_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
1e2845d5146466619dfd9bdb8e0795f90d952f2e249323ba288a601f1a54c9d8
akira08280/programming-in-haskell
compiler.hs
Compiler example from chapter 16 of Programming in Haskell , , Cambridge University Press , 2016 . data Expr = Val Int | Add Expr Expr eval :: Expr -> Int eval (Val n) = n eval (Add x y) = eval x + eval y type Stack = [Int] type Code = [Op] data Op = PUSH Int | ADD deriving Show exec :: Code -> Stack -> Stack exec [] s = s exec (PUSH n : c) s = exec c (n : s) exec (ADD : c) (m : n : s) = exec c (n+m : s) comp' :: Expr -> Code -> Code comp' (Val n) c = PUSH n : c comp' (Add x y) c = comp' x (comp' y (ADD : c)) comp :: Expr -> Code comp e = comp' e []
null
https://raw.githubusercontent.com/akira08280/programming-in-haskell/4067f729145429604aa7f3c8eee59b409addc685/Code/compiler.hs
haskell
Compiler example from chapter 16 of Programming in Haskell , , Cambridge University Press , 2016 . data Expr = Val Int | Add Expr Expr eval :: Expr -> Int eval (Val n) = n eval (Add x y) = eval x + eval y type Stack = [Int] type Code = [Op] data Op = PUSH Int | ADD deriving Show exec :: Code -> Stack -> Stack exec [] s = s exec (PUSH n : c) s = exec c (n : s) exec (ADD : c) (m : n : s) = exec c (n+m : s) comp' :: Expr -> Code -> Code comp' (Val n) c = PUSH n : c comp' (Add x y) c = comp' x (comp' y (ADD : c)) comp :: Expr -> Code comp e = comp' e []
f985827af6d52a6b323ab10f82e73b02cc46d3a77d11be4abec56b7288453c74
rajasegar/cl-djula-tailwind
main.lisp
(defpackage cl-djula-tailwind/tests/main (:use :cl :cl-djula-tailwind :rove)) (in-package :cl-djula-tailwind/tests/main) ;; NOTE: To run this test file, execute `(asdf:test-system :cl-djula-tailwind)' in your Lisp. (deftest test-plain-util (testing "should give css for mx-2" (ok (string= (cl-minify-css:minify-css (get-plain-class "mx-2")) ".mx-2{margin-left:0.5rem;margin-right:0.5rem;}")))) (deftest test-pseudo-util (testing "should give css for hover:text-red-500" (ok (string= (get-pseudo-class "hover:text-red-500") ".hover\\:text-red-500:hover { color: #ef4444; }")))) (deftest test-responsive-util (testing "should give css for md:w-32" (ok (string= (get-responsive-class "md:w-32") "@media (min-width: 768px) { .md\\:w-32 { width: 8rem; } }")))) (deftest test-darkmode-util (testing "should give css for dark:bg-black" (ok (string= (get-darkmode-class "dark:bg-black") "@media (prefers-color-scheme: dark) { .dark\\:bg-black { background-color: rgb(0 0 0); } }")))) (deftest test-peer-util (testing "should give css for peer-invalid:visible" (ok (string= (get-peer-class "peer-invalid:visible") ".peer:invalid ~ .peer-invalid\\:visible { visibility: visible; }")))) (deftest test-form-state-util (testing "should give css for required:text-red-500" (ok (string= (get-form-state-class "required:text-red-500") ".required\\:text-red-500:required { color: #ef4444; }")))) (deftest test-child-modifier-util (testing "should give css for first:pt-0" (ok (string= (get-child-modifier-class "first:pt-0") ".first\\:pt-0:first { padding-top: 0px; }")))) (deftest test-invalid-plain-util (testing "should give empty string for invalid util class" (ok (string= (get-plain-class "abc") ""))))
null
https://raw.githubusercontent.com/rajasegar/cl-djula-tailwind/f008ed11fa900a238580e6922cb94953eeda9b96/tests/main.lisp
lisp
NOTE: To run this test file, execute `(asdf:test-system :cl-djula-tailwind)' in your Lisp.
(defpackage cl-djula-tailwind/tests/main (:use :cl :cl-djula-tailwind :rove)) (in-package :cl-djula-tailwind/tests/main) (deftest test-plain-util (testing "should give css for mx-2" (ok (string= (cl-minify-css:minify-css (get-plain-class "mx-2")) ".mx-2{margin-left:0.5rem;margin-right:0.5rem;}")))) (deftest test-pseudo-util (testing "should give css for hover:text-red-500" (ok (string= (get-pseudo-class "hover:text-red-500") ".hover\\:text-red-500:hover { color: #ef4444; }")))) (deftest test-responsive-util (testing "should give css for md:w-32" (ok (string= (get-responsive-class "md:w-32") "@media (min-width: 768px) { .md\\:w-32 { width: 8rem; } }")))) (deftest test-darkmode-util (testing "should give css for dark:bg-black" (ok (string= (get-darkmode-class "dark:bg-black") "@media (prefers-color-scheme: dark) { .dark\\:bg-black { background-color: rgb(0 0 0); } }")))) (deftest test-peer-util (testing "should give css for peer-invalid:visible" (ok (string= (get-peer-class "peer-invalid:visible") ".peer:invalid ~ .peer-invalid\\:visible { visibility: visible; }")))) (deftest test-form-state-util (testing "should give css for required:text-red-500" (ok (string= (get-form-state-class "required:text-red-500") ".required\\:text-red-500:required { color: #ef4444; }")))) (deftest test-child-modifier-util (testing "should give css for first:pt-0" (ok (string= (get-child-modifier-class "first:pt-0") ".first\\:pt-0:first { padding-top: 0px; }")))) (deftest test-invalid-plain-util (testing "should give empty string for invalid util class" (ok (string= (get-plain-class "abc") ""))))
03d3807bb7a93a5a23e60efadfada8a287d2f604a10482cff3aa69a80149bd2e
braveclojure/training
core.clj
(ns blackjack.core (:gen-class) (:require [clojure.string :as str] [clojure.set :as set])) ;; Arbitrary amount of starting money (def starting-money 1000) ;; Use nested loops to iterate over suits and ranks to generate a deck (def deck "A deck of cards" (loop [suits ["β™ " "β™₯" "♦" "♣"] deck #{}] (if (empty? suits) deck (let [[suit & remaining-suits] suits] (recur remaining-suits (loop [ranks ["A" 2 3 4 5 6 7 8 9 10 "J" "Q" "K"] deck' deck] (if (empty? ranks) deck' (let [[rank & remaining-ranks] ranks] (recur remaining-ranks (conj deck' [suit rank])))))))))) (def initial-game "The starting state of the game" {:player {:money starting-money :bet 0 :hand []} :dealer {:hand []} :deck deck :outcome nil}) ;; This is used when calculating the value of a hand (def ten-cards "A card value in this set is worth 10 points" #{10 "J" "Q" "K"}) (defn get-input "Waits for user to enter text and hit enter, then cleans the input. If the user doesn't enter anything, it prompts again." [] (let [input (str/trim (read-line))] (if (empty? input) (do (println "Please enter some input") (recur)) (str/lower-case input)))) ;;===== ;; Bets ;;===== ;; Notice that we separate the impure function, prompt-bet, from the ;; pure function, place-bet. In functional programming languages, we ;; try to write pure functions as much as possible, and reduce the ;; footprint of impure functions. (defn place-bet "Transfer from player's money pile to bet pile" [game bet] (-> game (update-in [:player :money] - bet) (update-in [:player :bet] + bet))) (defn prompt-bet "Prompts user for a bet, then updates game state" [game] (println "Please place a bet by entering a number:") (place-bet game (Integer. (get-input)))) ;;===== ;; Dealing ;;===== (defn random-card "select a random card from the deck" [deck] (get (vec deck) (rand-int (count deck)))) (defn deal-to "Remove a card from the deck and give it to someone" [card-receiver-path {:keys [deck] :as game}] (let [card (random-card deck)] (-> game (update-in card-receiver-path conj card) (update :deck disj card)))) (def deal-player (partial deal-to [:player :hand])) (def deal-dealer (partial deal-to [:dealer :hand])) (defn deal [game] (-> game deal-player deal-dealer deal-player deal-dealer)) (defn player-hand [game] (get-in game [:player :hand])) (defn dealer-hand [game] (get-in game [:dealer :hand])) ;;===== ;; Hand outcomes ;;===== (defn outcome "Assign an outcome" [game x] (assoc game :outcome x)) ;;===== ;; Handling naturals ;;===== A natural is when the player or dealer has an ace and a 10 - card (defn natural-hand? "Does a hand contain an ace and a 10. Example hand: [[\"β™ \" 3] [\"β™ \" 10]]" [hand] ;; Remember that you can use sets as functions. When you apply a set ;; to a value, it returns that value if it contains that ;; value. Otherwise it returns nil. (let [ranks (set (map second hand))] (and (ranks "A") (not-empty (set/intersection ranks ten-cards))))) (defn handle-naturals "Assign outcome based on whether both have naturals, just one, or neither" [game] (let [player-natural? (natural-hand? (player-hand game)) dealer-natural? (natural-hand? (dealer-hand game))] (cond (and player-natural? dealer-natural?) (outcome game :tie) player-natural? (outcome game :player-won-natural) dealer-natural? (outcome game :player-lost) :else game))) ;;===== ;; Check for busts ;;===== (defn numberify-card-rank "Convert non-numeric cards to a number" [rank] (cond (ten-cards rank) 10 (= rank "A") 11 :else rank)) (defn best-hand-score "Gets as close as possible to 21 without going over" [hand] (let [ranks (map (comp numberify-card-rank second) hand) initial-sum (reduce + ranks)] (loop [sum initial-sum ranks ranks] ;; This bit checks if you've busted because you're treating an ace as 11 . If so , get the score with one ace converted to a 1 . (if (and (> sum 21) (contains? (set ranks) 11)) (recur (- sum 10) (conj (->> ranks sort reverse rest) 1)) sum)))) (defn busted? [hand] (> (best-hand-score hand) 21)) (defn check-player-bust [game] (if (busted? (player-hand game)) (outcome game :player-busted) game)) (defn check-dealer-bust [game] (if (busted? (dealer-hand game)) (outcome game :dealer-busted) game)) ;;===== ;; Displaying game ;;===== ;; Notice that all the format functions return strings and don't do ;; any printing. This is part of the general approach of separting out ;; impure functions as much as possible. (defn format-hand [hand] (->> hand (map #(str/join "" %)) (str/join ", "))) (defn format-dealer-hand "Special rules for the dealer hand - you don't want to reveal his hidden card or his score until after the player plays" [hand reveal-full] (if reveal-full (str (format-hand hand) " (" (best-hand-score hand) ")") (format-hand (rest hand)))) (defn format-game [game reveal-dealer] (let [ph (player-hand game)] (str "-----\n" "Your hand: " (format-hand ph) " (" (best-hand-score ph) ")\n" "Dealer hand: " (format-dealer-hand (dealer-hand game) reveal-dealer) "\n" "Bet: " (get-in game [:player :bet]) "\n" "-----\n"))) (defn print-game [game & [reveal-dealer]] (-> game (format-game reveal-dealer) println)) ;;===== ;; Play additional cards ;;===== (defn player-play "Prompt player to hit or stand, check for player bust" [game] ;; Check that there's no outcome from the natural check (when (not (:outcome game)) (loop [game game] (print-game game) (if (:outcome game) game (do (println "(h)it or (s)tand?") (let [response (get-input)] (if (= "h" response) (recur (check-player-bust (deal-player game))) (check-player-bust game)))))))) (defn dealer-play "Keep giving the dealer cards until his hand exceeds 17" [game] (if (not (:outcome game)) (loop [game game] (if (>= (best-hand-score (dealer-hand game)) 17) (check-dealer-bust game) (recur (deal-dealer game)))) game)) ;;===== ;; Final outcome ;;===== (defn determine-outcome "If the outcome wasn't already settled with naturals, compare scores" [game] (let [dealer-score (best-hand-score (dealer-hand game)) player-score (best-hand-score (player-hand game))] (cond (:outcome game) game (> dealer-score player-score) (outcome game :player-lost) (> player-score dealer-score) (outcome game :player-won) :else (outcome game :tie)))) (def outcomes {:player-busted "You busted! You lost!" :dealer-busted "The dealer busted! You won!" :tie "It was a tie!" :player-won-natural "You won a natural!" :player-lost "You lost!" :player-won "You won!"}) (defn print-outcome [game] (print-game game true) (println ((:outcome game) outcomes)) game) (defn print-money [game] (println "You have " (get-in game [:player :money]) " money") game) (defn pay-player [game multiplier] (update-in game [:player :money] + (* multiplier (get-in game [:player :bet])))) (defn tie "Return the player's bet" [game] (pay-player game 1)) (defn player-won-natural "Return the player's bet, plus 1.5x the bet" [game] (pay-player game 2.5)) (defn player-won "Return the player's 2x the player's bet" [game] (pay-player game 2)) (defn settle-outcome [{:keys [outcome] :as game}] (cond (#{:player-lost :player-busted} outcome) game (#{:player-won :dealer-busted} outcome) (player-won game) (= outcome :player-won-natural) (player-won-natural game) (= outcome :tie) (tie game))) (defn round [game] (-> game prompt-bet deal handle-naturals player-play dealer-play determine-outcome print-outcome settle-outcome print-money)) (defn game-loop "Wraps game rounds, prompting to continue after each round and resetting state such that players have no cards, the deck is full, and the player's money is retained" [game] (print-money game) (loop [game game] (let [game-result (round game)] (println "Continue? y/n") (if (= (get-input) "y") (recur (assoc-in game [:player :money] (get-in game-result [:player :money]))) (do (println "Bye!") (System/exit 0)))))) (defn -main [] (game-loop initial-game))
null
https://raw.githubusercontent.com/braveclojure/training/5b7fb9059c17b2166c2e66850094f424319e55eb/projects/blackjack/src/blackjack/core.clj
clojure
Arbitrary amount of starting money Use nested loops to iterate over suits and ranks to generate a deck This is used when calculating the value of a hand ===== Bets ===== Notice that we separate the impure function, prompt-bet, from the pure function, place-bet. In functional programming languages, we try to write pure functions as much as possible, and reduce the footprint of impure functions. ===== Dealing ===== ===== Hand outcomes ===== ===== Handling naturals ===== Remember that you can use sets as functions. When you apply a set to a value, it returns that value if it contains that value. Otherwise it returns nil. ===== Check for busts ===== This bit checks if you've busted because you're treating an ===== Displaying game ===== Notice that all the format functions return strings and don't do any printing. This is part of the general approach of separting out impure functions as much as possible. ===== Play additional cards ===== Check that there's no outcome from the natural check ===== Final outcome =====
(ns blackjack.core (:gen-class) (:require [clojure.string :as str] [clojure.set :as set])) (def starting-money 1000) (def deck "A deck of cards" (loop [suits ["β™ " "β™₯" "♦" "♣"] deck #{}] (if (empty? suits) deck (let [[suit & remaining-suits] suits] (recur remaining-suits (loop [ranks ["A" 2 3 4 5 6 7 8 9 10 "J" "Q" "K"] deck' deck] (if (empty? ranks) deck' (let [[rank & remaining-ranks] ranks] (recur remaining-ranks (conj deck' [suit rank])))))))))) (def initial-game "The starting state of the game" {:player {:money starting-money :bet 0 :hand []} :dealer {:hand []} :deck deck :outcome nil}) (def ten-cards "A card value in this set is worth 10 points" #{10 "J" "Q" "K"}) (defn get-input "Waits for user to enter text and hit enter, then cleans the input. If the user doesn't enter anything, it prompts again." [] (let [input (str/trim (read-line))] (if (empty? input) (do (println "Please enter some input") (recur)) (str/lower-case input)))) (defn place-bet "Transfer from player's money pile to bet pile" [game bet] (-> game (update-in [:player :money] - bet) (update-in [:player :bet] + bet))) (defn prompt-bet "Prompts user for a bet, then updates game state" [game] (println "Please place a bet by entering a number:") (place-bet game (Integer. (get-input)))) (defn random-card "select a random card from the deck" [deck] (get (vec deck) (rand-int (count deck)))) (defn deal-to "Remove a card from the deck and give it to someone" [card-receiver-path {:keys [deck] :as game}] (let [card (random-card deck)] (-> game (update-in card-receiver-path conj card) (update :deck disj card)))) (def deal-player (partial deal-to [:player :hand])) (def deal-dealer (partial deal-to [:dealer :hand])) (defn deal [game] (-> game deal-player deal-dealer deal-player deal-dealer)) (defn player-hand [game] (get-in game [:player :hand])) (defn dealer-hand [game] (get-in game [:dealer :hand])) (defn outcome "Assign an outcome" [game x] (assoc game :outcome x)) A natural is when the player or dealer has an ace and a 10 - card (defn natural-hand? "Does a hand contain an ace and a 10. Example hand: [[\"β™ \" 3] [\"β™ \" 10]]" [hand] (let [ranks (set (map second hand))] (and (ranks "A") (not-empty (set/intersection ranks ten-cards))))) (defn handle-naturals "Assign outcome based on whether both have naturals, just one, or neither" [game] (let [player-natural? (natural-hand? (player-hand game)) dealer-natural? (natural-hand? (dealer-hand game))] (cond (and player-natural? dealer-natural?) (outcome game :tie) player-natural? (outcome game :player-won-natural) dealer-natural? (outcome game :player-lost) :else game))) (defn numberify-card-rank "Convert non-numeric cards to a number" [rank] (cond (ten-cards rank) 10 (= rank "A") 11 :else rank)) (defn best-hand-score "Gets as close as possible to 21 without going over" [hand] (let [ranks (map (comp numberify-card-rank second) hand) initial-sum (reduce + ranks)] (loop [sum initial-sum ranks ranks] ace as 11 . If so , get the score with one ace converted to a 1 . (if (and (> sum 21) (contains? (set ranks) 11)) (recur (- sum 10) (conj (->> ranks sort reverse rest) 1)) sum)))) (defn busted? [hand] (> (best-hand-score hand) 21)) (defn check-player-bust [game] (if (busted? (player-hand game)) (outcome game :player-busted) game)) (defn check-dealer-bust [game] (if (busted? (dealer-hand game)) (outcome game :dealer-busted) game)) (defn format-hand [hand] (->> hand (map #(str/join "" %)) (str/join ", "))) (defn format-dealer-hand "Special rules for the dealer hand - you don't want to reveal his hidden card or his score until after the player plays" [hand reveal-full] (if reveal-full (str (format-hand hand) " (" (best-hand-score hand) ")") (format-hand (rest hand)))) (defn format-game [game reveal-dealer] (let [ph (player-hand game)] (str "-----\n" "Your hand: " (format-hand ph) " (" (best-hand-score ph) ")\n" "Dealer hand: " (format-dealer-hand (dealer-hand game) reveal-dealer) "\n" "Bet: " (get-in game [:player :bet]) "\n" "-----\n"))) (defn print-game [game & [reveal-dealer]] (-> game (format-game reveal-dealer) println)) (defn player-play "Prompt player to hit or stand, check for player bust" [game] (when (not (:outcome game)) (loop [game game] (print-game game) (if (:outcome game) game (do (println "(h)it or (s)tand?") (let [response (get-input)] (if (= "h" response) (recur (check-player-bust (deal-player game))) (check-player-bust game)))))))) (defn dealer-play "Keep giving the dealer cards until his hand exceeds 17" [game] (if (not (:outcome game)) (loop [game game] (if (>= (best-hand-score (dealer-hand game)) 17) (check-dealer-bust game) (recur (deal-dealer game)))) game)) (defn determine-outcome "If the outcome wasn't already settled with naturals, compare scores" [game] (let [dealer-score (best-hand-score (dealer-hand game)) player-score (best-hand-score (player-hand game))] (cond (:outcome game) game (> dealer-score player-score) (outcome game :player-lost) (> player-score dealer-score) (outcome game :player-won) :else (outcome game :tie)))) (def outcomes {:player-busted "You busted! You lost!" :dealer-busted "The dealer busted! You won!" :tie "It was a tie!" :player-won-natural "You won a natural!" :player-lost "You lost!" :player-won "You won!"}) (defn print-outcome [game] (print-game game true) (println ((:outcome game) outcomes)) game) (defn print-money [game] (println "You have " (get-in game [:player :money]) " money") game) (defn pay-player [game multiplier] (update-in game [:player :money] + (* multiplier (get-in game [:player :bet])))) (defn tie "Return the player's bet" [game] (pay-player game 1)) (defn player-won-natural "Return the player's bet, plus 1.5x the bet" [game] (pay-player game 2.5)) (defn player-won "Return the player's 2x the player's bet" [game] (pay-player game 2)) (defn settle-outcome [{:keys [outcome] :as game}] (cond (#{:player-lost :player-busted} outcome) game (#{:player-won :dealer-busted} outcome) (player-won game) (= outcome :player-won-natural) (player-won-natural game) (= outcome :tie) (tie game))) (defn round [game] (-> game prompt-bet deal handle-naturals player-play dealer-play determine-outcome print-outcome settle-outcome print-money)) (defn game-loop "Wraps game rounds, prompting to continue after each round and resetting state such that players have no cards, the deck is full, and the player's money is retained" [game] (print-money game) (loop [game game] (let [game-result (round game)] (println "Continue? y/n") (if (= (get-input) "y") (recur (assoc-in game [:player :money] (get-in game-result [:player :money]))) (do (println "Bye!") (System/exit 0)))))) (defn -main [] (game-loop initial-game))
87584386887328a7e96e69f2c5e18fa8570ded9d030a0cd88152a22055d12acf
minio/minio-hs
Time.hs
-- MinIO Haskell SDK , ( C ) 2017 MinIO , Inc. -- Licensed under the Apache License , Version 2.0 ( the " License " ) ; -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- -2.0 -- -- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- module Network.Minio.Data.Time ( awsTimeFormat, awsTimeFormatBS, awsDateFormat, awsDateFormatBS, awsParseTime, iso8601TimeFormat, UrlExpiry, ) where import Data.ByteString.Char8 (pack) import qualified Data.Time as Time import Data.Time.Format.ISO8601 (iso8601Show) import Lib.Prelude -- | Time to expire for a presigned URL. It interpreted as a number of seconds . The maximum duration that can be specified is 7 days . type UrlExpiry = Int awsTimeFormat :: UTCTime -> [Char] awsTimeFormat = Time.formatTime Time.defaultTimeLocale "%Y%m%dT%H%M%SZ" awsTimeFormatBS :: UTCTime -> ByteString awsTimeFormatBS = pack . awsTimeFormat awsDateFormat :: UTCTime -> [Char] awsDateFormat = Time.formatTime Time.defaultTimeLocale "%Y%m%d" awsDateFormatBS :: UTCTime -> ByteString awsDateFormatBS = pack . awsDateFormat awsParseTime :: [Char] -> Maybe UTCTime awsParseTime = Time.parseTimeM False Time.defaultTimeLocale "%Y%m%dT%H%M%SZ" iso8601TimeFormat :: UTCTime -> [Char] iso8601TimeFormat = iso8601Show
null
https://raw.githubusercontent.com/minio/minio-hs/0b3a5559fd95c4214a93545b1d602aa985c6f0c8/src/Network/Minio/Data/Time.hs
haskell
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | Time to expire for a presigned URL. It interpreted as a number of
MinIO Haskell SDK , ( C ) 2017 MinIO , Inc. Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , module Network.Minio.Data.Time ( awsTimeFormat, awsTimeFormatBS, awsDateFormat, awsDateFormatBS, awsParseTime, iso8601TimeFormat, UrlExpiry, ) where import Data.ByteString.Char8 (pack) import qualified Data.Time as Time import Data.Time.Format.ISO8601 (iso8601Show) import Lib.Prelude seconds . The maximum duration that can be specified is 7 days . type UrlExpiry = Int awsTimeFormat :: UTCTime -> [Char] awsTimeFormat = Time.formatTime Time.defaultTimeLocale "%Y%m%dT%H%M%SZ" awsTimeFormatBS :: UTCTime -> ByteString awsTimeFormatBS = pack . awsTimeFormat awsDateFormat :: UTCTime -> [Char] awsDateFormat = Time.formatTime Time.defaultTimeLocale "%Y%m%d" awsDateFormatBS :: UTCTime -> ByteString awsDateFormatBS = pack . awsDateFormat awsParseTime :: [Char] -> Maybe UTCTime awsParseTime = Time.parseTimeM False Time.defaultTimeLocale "%Y%m%dT%H%M%SZ" iso8601TimeFormat :: UTCTime -> [Char] iso8601TimeFormat = iso8601Show
866c3d73a64af971094ef6e807d6d57fd99c6caff1997c225398d2a16c83006f
LambdaHack/LambdaHack
MonadStateRead.hs
-- | Game state reading monad and basic operations. module Game.LambdaHack.Common.MonadStateRead ( MonadStateRead(..) , getState, getLevel , getGameMode, isNoConfirmsGame, getEntryArena, pickWeaponM, displayTaunt ) where import Prelude () import Game.LambdaHack.Core.Prelude import Data.Either import qualified Data.EnumMap.Strict as EM import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import Game.LambdaHack.Common.Kind import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.ReqFailure import Game.LambdaHack.Common.State import Game.LambdaHack.Common.Types import Game.LambdaHack.Content.ModeKind import Game.LambdaHack.Core.Frequency import Game.LambdaHack.Core.Random import qualified Game.LambdaHack.Definition.Ability as Ability -- | Monad for reading game state. A state monad with state modification -- disallowed (another constraint is needed to permit that). -- The basic server and client monads are like that, because server -- and clients freely modify their internal session data, but don't modify -- the main game state, except in very restricted and synchronized way. class (Monad m, Functor m, Applicative m) => MonadStateRead m where getsState :: (State -> a) -> m a getState :: MonadStateRead m => m State getState = getsState id getLevel :: MonadStateRead m => LevelId -> m Level getLevel lid = getsState $ (EM.! lid) . sdungeon getGameMode :: MonadStateRead m => m ModeKind getGameMode = do COps{comode} <- getsState scops gameModeId <- getsState sgameModeId return $! okind comode gameModeId isNoConfirmsGame :: MonadStateRead m => m Bool isNoConfirmsGame = do gameMode <- getGameMode return $! mattract gameMode getEntryArena :: MonadStateRead m => Faction -> m LevelId getEntryArena fact = do dungeon <- getsState sdungeon let (minD, maxD) = dungeonBounds dungeon f [] = 0 f ((ln, _, _) : _) = ln return $! max minD $ min maxD $ toEnum $ f $ ginitial fact pickWeaponM :: MonadStateRead m => Bool -> Maybe DiscoveryBenefit -> [(ItemId, ItemFullKit)] -> Ability.Skills -> ActorId -> m [(Double, Bool, Int, Int, ItemId, ItemFullKit)] pickWeaponM ignoreCharges mdiscoBenefit kitAss actorSk source = do sb <- getsState $ getActorBody source localTime <- getsState $ getLocalTime (blid sb) actorMaxSk <- getsState $ getActorMaxSkills source let calmE = calmEnough sb actorMaxSk forced = bproj sb permitted = permittedPrecious forced calmE preferredPrecious = fromRight False . permitted permAssocs = filter (preferredPrecious . fst . snd) kitAss strongest = strongestMelee ignoreCharges mdiscoBenefit localTime permAssocs return $! if | forced -> map (\(iid, itemFullKit) -> (-1, False, 0, 1, iid, itemFullKit)) kitAss | Ability.getSk Ability.SkMelee actorSk <= 0 -> [] | otherwise -> strongest displayTaunt :: MonadStateRead m => Bool -> (Rnd (Text, Text) -> m (Text, Text)) -> ActorId -> m (Text, Text) displayTaunt _voluntary rndToAction aid = do b <- getsState $ getActorBody aid actorMaxSk <- getsState $ getActorMaxSkills aid let canApply = Ability.getSk Ability.SkApply actorMaxSk > 2 && canHear -- if applies complex items, probably intelligent and can speak canHear = Ability.getSk Ability.SkHearing actorMaxSk > 0 && canBrace -- if hears, probably also emits sound vocally; -- disabled even by ushanka and rightly so canBrace = Ability.getSk Ability.SkWait actorMaxSk >= 2 -- not an insect, plant, geyser, faucet, fence, etc. -- so can emit sound by hitting something with body parts || Ability.getSk Ability.SkApply actorMaxSk > 2 -- and neither an impatient intelligent actor braceUneasy = [ (2, ("something", "flail around")) , (1, ("something", "toss blindly")) , (1, ("something", "squirm dizzily")) ] braceEasy = [ (2, ("something", "stretch")) , (1, ("something", "fidget")) , (1, ("something", "fret")) ] uneasy = deltasSerious (bcalmDelta b) || not (calmEnough b actorMaxSk) if bwatch b `elem` [WSleep, WWake] then rndToAction $ frequency $ toFreq "SfxTaunt" $ if uneasy then if | canApply -> (5, ("somebody", "yell")) : (3, ("somebody", "bellow")) : braceUneasy | canHear -> (5, ("somebody", "bellow")) : (3, ("something", "hiss")) : braceUneasy | canBrace -> braceUneasy | otherwise -> [(1, ("something", "drone enquiringly"))] else if | canApply -> (5, ("somebody", "yawn")) : (3, ("somebody", "grunt")) : braceEasy | canHear -> (5, ("somebody", "grunt")) : (3, ("something", "wheeze")) : braceEasy | canBrace -> braceEasy | otherwise -> [(1, ("something", "hum silently"))] else return $! if | bproj b -> ("something", "ping") | canApply -> ("somebody", "holler a taunt") | canHear -> ("somebody", "growl menacingly") | canBrace -> ("something", "stomp repeatedly") | otherwise -> ("something", "buzz angrily")
null
https://raw.githubusercontent.com/LambdaHack/LambdaHack/a3cd114410471b6a48c4f4bb746308fd4ee002b4/engine-src/Game/LambdaHack/Common/MonadStateRead.hs
haskell
| Game state reading monad and basic operations. | Monad for reading game state. A state monad with state modification disallowed (another constraint is needed to permit that). The basic server and client monads are like that, because server and clients freely modify their internal session data, but don't modify the main game state, except in very restricted and synchronized way. if applies complex items, probably intelligent and can speak if hears, probably also emits sound vocally; disabled even by ushanka and rightly so not an insect, plant, geyser, faucet, fence, etc. so can emit sound by hitting something with body parts and neither an impatient intelligent actor
module Game.LambdaHack.Common.MonadStateRead ( MonadStateRead(..) , getState, getLevel , getGameMode, isNoConfirmsGame, getEntryArena, pickWeaponM, displayTaunt ) where import Prelude () import Game.LambdaHack.Core.Prelude import Data.Either import qualified Data.EnumMap.Strict as EM import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import Game.LambdaHack.Common.Kind import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.ReqFailure import Game.LambdaHack.Common.State import Game.LambdaHack.Common.Types import Game.LambdaHack.Content.ModeKind import Game.LambdaHack.Core.Frequency import Game.LambdaHack.Core.Random import qualified Game.LambdaHack.Definition.Ability as Ability class (Monad m, Functor m, Applicative m) => MonadStateRead m where getsState :: (State -> a) -> m a getState :: MonadStateRead m => m State getState = getsState id getLevel :: MonadStateRead m => LevelId -> m Level getLevel lid = getsState $ (EM.! lid) . sdungeon getGameMode :: MonadStateRead m => m ModeKind getGameMode = do COps{comode} <- getsState scops gameModeId <- getsState sgameModeId return $! okind comode gameModeId isNoConfirmsGame :: MonadStateRead m => m Bool isNoConfirmsGame = do gameMode <- getGameMode return $! mattract gameMode getEntryArena :: MonadStateRead m => Faction -> m LevelId getEntryArena fact = do dungeon <- getsState sdungeon let (minD, maxD) = dungeonBounds dungeon f [] = 0 f ((ln, _, _) : _) = ln return $! max minD $ min maxD $ toEnum $ f $ ginitial fact pickWeaponM :: MonadStateRead m => Bool -> Maybe DiscoveryBenefit -> [(ItemId, ItemFullKit)] -> Ability.Skills -> ActorId -> m [(Double, Bool, Int, Int, ItemId, ItemFullKit)] pickWeaponM ignoreCharges mdiscoBenefit kitAss actorSk source = do sb <- getsState $ getActorBody source localTime <- getsState $ getLocalTime (blid sb) actorMaxSk <- getsState $ getActorMaxSkills source let calmE = calmEnough sb actorMaxSk forced = bproj sb permitted = permittedPrecious forced calmE preferredPrecious = fromRight False . permitted permAssocs = filter (preferredPrecious . fst . snd) kitAss strongest = strongestMelee ignoreCharges mdiscoBenefit localTime permAssocs return $! if | forced -> map (\(iid, itemFullKit) -> (-1, False, 0, 1, iid, itemFullKit)) kitAss | Ability.getSk Ability.SkMelee actorSk <= 0 -> [] | otherwise -> strongest displayTaunt :: MonadStateRead m => Bool -> (Rnd (Text, Text) -> m (Text, Text)) -> ActorId -> m (Text, Text) displayTaunt _voluntary rndToAction aid = do b <- getsState $ getActorBody aid actorMaxSk <- getsState $ getActorMaxSkills aid let canApply = Ability.getSk Ability.SkApply actorMaxSk > 2 && canHear canHear = Ability.getSk Ability.SkHearing actorMaxSk > 0 && canBrace canBrace = Ability.getSk Ability.SkWait actorMaxSk >= 2 || Ability.getSk Ability.SkApply actorMaxSk > 2 braceUneasy = [ (2, ("something", "flail around")) , (1, ("something", "toss blindly")) , (1, ("something", "squirm dizzily")) ] braceEasy = [ (2, ("something", "stretch")) , (1, ("something", "fidget")) , (1, ("something", "fret")) ] uneasy = deltasSerious (bcalmDelta b) || not (calmEnough b actorMaxSk) if bwatch b `elem` [WSleep, WWake] then rndToAction $ frequency $ toFreq "SfxTaunt" $ if uneasy then if | canApply -> (5, ("somebody", "yell")) : (3, ("somebody", "bellow")) : braceUneasy | canHear -> (5, ("somebody", "bellow")) : (3, ("something", "hiss")) : braceUneasy | canBrace -> braceUneasy | otherwise -> [(1, ("something", "drone enquiringly"))] else if | canApply -> (5, ("somebody", "yawn")) : (3, ("somebody", "grunt")) : braceEasy | canHear -> (5, ("somebody", "grunt")) : (3, ("something", "wheeze")) : braceEasy | canBrace -> braceEasy | otherwise -> [(1, ("something", "hum silently"))] else return $! if | bproj b -> ("something", "ping") | canApply -> ("somebody", "holler a taunt") | canHear -> ("somebody", "growl menacingly") | canBrace -> ("something", "stomp repeatedly") | otherwise -> ("something", "buzz angrily")
f43b87d7490b8e521ff07c840db2e9cd840651a701b52bc9d8c43ab33680673b
webyrd/untitled-relational-interpreter-book
slatex.scm
Configured for Scheme dialect petite by scmxlate , v 20120421 , ( c ) , ;/~dorai/scmxlate/scmxlate.html (define slatex::*slatex-version* "20090928") (define slatex::*operating-system* (if (getenv "COMSPEC") 'windows 'unix)) (define-syntax slatex::defenum (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let loop ([z (cdr so-d)] [i 0] [r '()]) (if (null? z) `(begin ,@r) (loop (cdr z) (+ i 1) (cons `(define (unquote (car z)) (integer->char ,i)) r))))))))) (define-syntax slatex::defrecord (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let ([name (cadr so-d)] [fields (cddr so-d)]) (let loop ([fields fields] [i 0] [r '()]) (if (null? fields) `(begin (define (unquote name) (lambda () (make-vector ,i))) ,@r) (loop (cdr fields) (+ i 1) (cons `(define (unquote (car fields)) ,i) r)))))))))) (define-syntax slatex::setf (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let ([l (cadr so-d)] [r (caddr so-d)]) (if (symbol? l) `(set! ,l ,r) (let ([a (car l)]) (if (eq? a 'list-ref) `(set-car! (list-tail ,@(cdr l)) ,r) `(,(cond [(eq? a 'string-ref) 'string-set!] [(eq? a 'vector-ref) 'vector-set!] [(eq? a 'slatex::of) 'slatex::the-setter-for-of] [else (slatex::slatex-error "setf is ill-formed" l r)]) ,@(cdr l) ,r)))))))))) (define-syntax slatex::the-setter-for-of (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let ([r (cadr so-d)] [i (caddr so-d)] [j (cadddr so-d)] [z (cddddr so-d)]) (cond [(null? z) `(vector-set! ,r ,i ,j)] [(and (eq? i '/) (= (length z) 1)) `(string-set! ,r ,j ,(car z))] [else `(slatex::the-setter-for-of (vector-ref ,r ,i) ,j ,@z)]))))))) (define-syntax slatex::of (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let ([r (cadr so-d)] [i (caddr so-d)] [z (cdddr so-d)]) (cond [(null? z) `(vector-ref ,r ,i)] [(and (eq? i '/) (= (length z) 1)) `(string-ref ,r ,(car z))] [else `(slatex::of (vector-ref ,r ,i) ,@z)]))))))) (define slatex::ormapcdr (lambda (f l) (let loop ([l l]) (if (null? l) #f (or (f l) (loop (cdr l))))))) (define slatex::list-prefix? (lambda (pfx l) (cond [(null? pfx) #t] [(null? l) #f] [(eqv? (car pfx) (car l)) (slatex::list-prefix? (cdr pfx) (cdr l))] [else #f]))) (define slatex::string-suffix? (lambda (sfx s) (let ([sfx-len (string-length sfx)] [s-len (string-length s)]) (if (> sfx-len s-len) #f (let loop ([i (- sfx-len 1)] [j (- s-len 1)]) (if (< i 0) #t (and (char=? (string-ref sfx i) (string-ref s j)) (loop (- i 1) (- j 1))))))))) (define slatex::mapcan (lambda (f l) (let loop ([l l]) (if (null? l) '() (append! (f (car l)) (loop (cdr l))))))) (define slatex::lassoc (lambda (x al eq) (let loop ([al al]) (if (null? al) #f (let ([c (car al)]) (if (eq (car c) x) c (loop (cdr al)))))))) (define slatex::lmember (lambda (x l eq) (let loop ([l l]) (if (null? l) #f (if (eq (car l) x) l (loop (cdr l))))))) (define slatex::delete (lambda (x l eq) (let loop ([l l]) (cond [(null? l) l] [(eq (car l) x) (loop (cdr l))] [else (set-cdr! l (loop (cdr l))) l])))) (define slatex::adjoin (lambda (x l eq) (if (slatex::lmember x l eq) l (cons x l)))) (define slatex::delete-if (lambda (p s) (let loop ([s s]) (cond [(null? s) s] [(p (car s)) (loop (cdr s))] [else (set-cdr! s (loop (cdr s))) s])))) (define slatex::string-prefix? (lambda (s1 s2 i) (let loop ([j 0]) (if (= j i) #t (and (char=? (string-ref s1 j) (string-ref s2 j)) (loop (+ j 1))))))) (define slatex::sublist (lambda (l i f) (let loop ([l (list-tail l i)] [k i] [r '()]) (cond [(>= k f) (reverse! r)] [(null? l) (slatex::slatex-error "sublist: List too small")] [else (loop (cdr l) (+ k 1) (cons (car l) r))])))) (define slatex::position-char (lambda (c l) (let loop ([l l] [i 0]) (cond [(null? l) #f] [(char=? (car l) c) i] [else (loop (cdr l) (+ i 1))])))) (define slatex::string-position-right (lambda (c s) (let ([n (string-length s)]) (let loop ([i (- n 1)]) (cond [(< i 0) #f] [(char=? (string-ref s i) c) i] [else (loop (- i 1))]))))) (define slatex::*return* (integer->char 13)) (define slatex::*tab* (integer->char 9)) (define slatex::slatex-error (lambda (where . what) (display "Error: ") (display where) (newline) (for-each (lambda (v) (write v) (newline)) what) (error "slatex-error"))) (define slatex::exit-slatex (lambda () (exit))) (define slatex::*slatex-case-sensitive?* #t) (define slatex::keyword-tokens (list "=>" "%" "abort" "and" "begin" "begin0" "case" "case-lambda" "cond" "define" "define!" "define-macro!" "define-syntax" "defmacro" "defrec!" "delay" "do" "else" "extend-syntax" "fluid-let" "if" "lambda" "let" "let*" "letrec" "let-syntax" "letrec-syntax" "or" "quasiquote" "quote" "rec" "record-case" "record-evcase" "recur" "set!" "sigma" "struct" "syntax" "syntax-rules" "trace" "trace-lambda" "trace-let" "trace-recur" "unless" "unquote" "unquote-splicing" "untrace" "when" "with")) (define slatex::variable-tokens '()) (define slatex::constant-tokens '()) (define slatex::data-tokens '()) (define slatex::special-symbols (reverse (reverse '(("." . ".") ("..." . "{\\dots}") ("-" . "$-$") ("1-" . "\\va{1$-$}") ("-1+" . "\\va{$-$1$+$}"))))) (define slatex::macro-definers '("define-syntax" "syntax-rules" "defmacro" "extend-syntax" "define-macro!")) (define slatex::case-and-ilk '("case" "record-case")) (define slatex::tex-analog (lambda (c) (case c [(#\$ #\& #\% #\# #\_) (string #\\ c)] [(#\{ #\}) (string #\$ #\\ c #\$)] [(#\\) "$\\backslash$"] [(#\+) "$+$"] [(#\*) "$\\ast$"] [(#\=) "$=$"] [(#\<) "$\\lt$"] [(#\>) "$\\gt$"] [(#\^) "\\^{}"] [(#\|) "$\\vert$"] [(#\~) "\\~{}"] [(#\@) "{\\atsign}"] [(#\") "{\\dq}"] [else (string c)]))) (define slatex::token=? (lambda (t1 t2) ((if slatex::*slatex-case-sensitive?* string=? string-ci=?) t1 t2))) (define slatex::*slatex-enabled?* #t) (define slatex::*slatex-reenabler* "UNDEFINED") (define slatex::*intext-triggerers* (list "scheme")) (define slatex::*resultintext-triggerers* (list "schemeresult")) (define slatex::*display-triggerers* (list "schemedisplay")) (define slatex::*response-triggerers* (list "schemeresponse")) (define slatex::*respbox-triggerers* (list "schemeresponsebox")) (define slatex::*box-triggerers* (list "schemebox")) (define slatex::*topbox-triggerers* (list "schemetopbox")) (define slatex::*input-triggerers* (list "schemeinput")) (define slatex::*region-triggerers* (list "schemeregion")) (define slatex::*math-triggerers* '()) (define slatex::*slatex-in-protected-region?* #f) (define slatex::*protected-files* '()) (define slatex::*include-onlys* 'all) (define slatex::*latex?* #t) (define slatex::*slatex-separate-includes?* #f) (define slatex::*tex-calling-directory* "") (define slatex::*max-line-length* 300) (slatex::defenum &void-space &plain-space &init-space &init-plain-space &paren-space &bracket-space &quote-space &inner-space) (slatex::defenum &void-tab &set-tab &move-tab &tabbed-crg-ret &plain-crg-ret) (slatex::defenum &void-notab &begin-comment &mid-comment &begin-string &mid-string &end-string &begin-math &mid-math &end-math) (slatex::defrecord slatex::make-raw-line slatex::=rtedge slatex::=char slatex::=space slatex::=tab slatex::=notab) (define slatex::make-line (lambda () (let ([l (slatex::make-raw-line)]) (slatex::setf (slatex::of l slatex::=rtedge) 0) (slatex::setf (slatex::of l slatex::=char) (make-string slatex::*max-line-length* #\space)) (slatex::setf (slatex::of l slatex::=space) (make-string slatex::*max-line-length* &void-space)) (slatex::setf (slatex::of l slatex::=tab) (make-string slatex::*max-line-length* &void-tab)) (slatex::setf (slatex::of l slatex::=notab) (make-string slatex::*max-line-length* &void-notab)) l))) (define slatex::*line1* (slatex::make-line)) (define slatex::*line2* (slatex::make-line)) (slatex::defrecord slatex::make-case-frame slatex::=in-ctag-tkn slatex::=in-bktd-ctag-exp slatex::=in-case-exp) (slatex::defrecord slatex::make-bq-frame slatex::=in-comma slatex::=in-bq-tkn slatex::=in-bktd-bq-exp) (define slatex::*latex-paragraph-mode?* 'fwd1) (define slatex::*intext?* 'fwd2) (define slatex::*code-env-spec* "UNDEFINED") (define slatex::*in* 'fwd3) (define slatex::*out* 'fwd4) (define slatex::*in-qtd-tkn* 'fwd5) (define slatex::*in-bktd-qtd-exp* 'fwd6) (define slatex::*in-mac-tkn* 'fwd7) (define slatex::*in-bktd-mac-exp* 'fwd8) (define slatex::*case-stack* 'fwd9) (define slatex::*bq-stack* 'fwd10) (define slatex::display-space (lambda (s p) (cond [(eq? s &plain-space) (display #\space p)] [(eq? s &init-plain-space) (display #\space p)] [(eq? s &init-space) (display "\\HL " p)] [(eq? s &paren-space) (display "\\PRN " p)] [(eq? s &bracket-space) (display "\\BKT " p)] [(eq? s &quote-space) (display "\\QUO " p)] [(eq? s &inner-space) (display "\\ " p)]))) (define slatex::display-tab (lambda (tab p) (cond [(eq? tab &set-tab) (display "\\=" p)] [(eq? tab &move-tab) (display "\\>" p)]))) (define slatex::display-notab (lambda (notab p) (cond [(eq? notab &begin-string) (display "\\dt{" p)] [(eq? notab &end-string) (display "}" p)]))) (define slatex::prim-data-token? (lambda (token) (or (char=? (string-ref token 0) #\#) (string->number token)))) (define slatex::set-keyword (lambda (x) (if (not (slatex::lmember x slatex::keyword-tokens slatex::token=?)) (begin (set! slatex::constant-tokens (slatex::delete x slatex::constant-tokens slatex::token=?)) (set! slatex::variable-tokens (slatex::delete x slatex::variable-tokens slatex::token=?)) (set! slatex::data-tokens (slatex::delete x slatex::data-tokens slatex::token=?)) (set! slatex::keyword-tokens (cons x slatex::keyword-tokens)))))) (define slatex::set-constant (lambda (x) (if (not (slatex::lmember x slatex::constant-tokens slatex::token=?)) (begin (set! slatex::keyword-tokens (slatex::delete x slatex::keyword-tokens slatex::token=?)) (set! slatex::variable-tokens (slatex::delete x slatex::variable-tokens slatex::token=?)) (set! slatex::data-tokens (slatex::delete x slatex::data-tokens slatex::token=?)) (set! slatex::constant-tokens (cons x slatex::constant-tokens)))))) (define slatex::set-variable (lambda (x) (if (not (slatex::lmember x slatex::variable-tokens slatex::token=?)) (begin (set! slatex::keyword-tokens (slatex::delete x slatex::keyword-tokens slatex::token=?)) (set! slatex::constant-tokens (slatex::delete x slatex::constant-tokens slatex::token=?)) (set! slatex::data-tokens (slatex::delete x slatex::data-tokens slatex::token=?)) (set! slatex::variable-tokens (cons x slatex::variable-tokens)))))) (define slatex::set-data (lambda (x) (if (not (slatex::lmember x slatex::data-tokens slatex::token=?)) (begin (set! slatex::keyword-tokens (slatex::delete x slatex::keyword-tokens slatex::token=?)) (set! slatex::constant-tokens (slatex::delete x slatex::constant-tokens slatex::token=?)) (set! slatex::variable-tokens (slatex::delete x slatex::variable-tokens slatex::token=?)) (set! slatex::data-tokens (cons x slatex::data-tokens)))))) (define slatex::set-special-symbol (lambda (x transl) (let ([c (slatex::lassoc x slatex::special-symbols slatex::token=?)]) (if c (set-cdr! c transl) (set! slatex::special-symbols (cons (cons x transl) slatex::special-symbols)))))) (define slatex::unset-special-symbol (lambda (x) (set! slatex::special-symbols (slatex::delete-if (lambda (c) (slatex::token=? (car c) x)) slatex::special-symbols)))) (define slatex::texify (lambda (s) (list->string (slatex::texify-aux s)))) (define slatex::texify-data (lambda (s) (let loop ([l (slatex::texify-aux s)] [r '()]) (if (null? l) (list->string (reverse! r)) (let ([c (car l)]) (loop (cdr l) (if (char=? c #\-) (append! (list #\$ c #\$) r) (cons c r)))))))) (define slatex::texify-aux (let ([arrow (string->list "-$>$")] [em-dash (string->list "---")] [en-dash (string->list "--")] [arrow2 (string->list "$\\to$")] [em-dash-2 (string->list "${-}{-}{-}$")] [en-dash-2 (string->list "${-}{-}$")]) (lambda (s) (let ([texified-sl (slatex::mapcan (lambda (c) (string->list (slatex::tex-analog c))) (string->list s))]) (let loop ([d texified-sl]) (cond [(null? d) #f] [(slatex::list-prefix? arrow d) (let ([d2 (list-tail d 4)]) (set-car! d (car arrow2)) (set-cdr! d (append (cdr arrow2) d2)) (loop d2))] [(slatex::list-prefix? em-dash d) (let ([d2 (list-tail d 3)]) (set-car! d (car em-dash-2)) (set-cdr! d (append (cdr em-dash-2) d2)) (loop d2))] [(slatex::list-prefix? en-dash d) (let ([d2 (list-tail d 2)]) (set-car! d (car en-dash-2)) (set-cdr! d (append (cdr en-dash-2) d2)) (loop d2))] [else (loop (cdr d))])) texified-sl)))) (define slatex::display-begin-sequence (lambda (out) (if (or slatex::*intext?* (not slatex::*latex?*)) (begin (display "\\" out) (display slatex::*code-env-spec* out) (newline out)) (begin (display "\\begin{" out) (display slatex::*code-env-spec* out) (display "}%" out) (newline out))))) (define slatex::display-end-sequence (lambda (out) (cond [slatex::*intext?* (display "\\end" out) (display slatex::*code-env-spec* out) (newline out)] [slatex::*latex?* (display "\\end{" out) (display slatex::*code-env-spec* out) (display "}" out) (newline out)] [else (display "\\end" out) (display slatex::*code-env-spec* out) (newline out)]))) (define slatex::display-tex-char (lambda (c p) (display (if (char? c) (slatex::tex-analog c) c) p))) (define slatex::display-token (lambda (s typ p) (cond [(eq? typ 'syntax) (display "\\sy{" p) (display (slatex::texify s) p) (display "}" p)] [(eq? typ 'variable) (display "\\va{" p) (display (slatex::texify s) p) (display "}" p)] [(eq? typ 'constant) (display "\\cn{" p) (display (slatex::texify s) p) (display "}" p)] [(eq? typ 'data) (display "\\dt{" p) (display (slatex::texify-data s) p) (display "}" p)] [else (slatex::slatex-error 'slatex::display-token "Unknown token type" typ)]))) (define slatex::get-line (let ([curr-notab &void-notab]) (lambda (line) (let ([graphic-char-seen? #f]) (let loop ([i 0]) (let ([c (read-char slatex::*in*)]) (cond [graphic-char-seen? (void)] [(or (eof-object? c) (char=? c slatex::*return*) (char=? c #\newline) (char=? c #\space) (char=? c slatex::*tab*)) (void)] [else (set! graphic-char-seen? #t)]) (cond [(eof-object? c) (cond [(eq? curr-notab &mid-string) (if (> i 0) (slatex::setf (slatex::of line slatex::=notab / (- i 1)) &end-string))] [(eq? curr-notab &mid-comment) (set! curr-notab &void-notab)] [(eq? curr-notab &mid-math) (slatex::slatex-error 'slatex::get-line "Found eof inside math")]) (slatex::setf (slatex::of line slatex::=char / i) #\newline) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (slatex::setf (slatex::of line slatex::=rtedge) i) (if (eq? (slatex::of line slatex::=notab / 0) &mid-string) (slatex::setf (slatex::of line slatex::=notab / 0) &begin-string)) (if (= i 0) #f #t)] [(or (char=? c slatex::*return*) (char=? c #\newline)) (if (and (memv slatex::*operating-system* '(dos windows os2 os2fat)) (char=? c slatex::*return*)) (if (char=? (peek-char slatex::*in*) #\newline) (read-char slatex::*in*))) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (cond [(eq? curr-notab &mid-string) (slatex::setf (slatex::of line slatex::=notab / i) &end-string)] [(eq? curr-notab &mid-comment) (set! curr-notab &void-notab)] [(eq? curr-notab &mid-math) (slatex::slatex-error 'slatex::get-line "Sorry, you can't split " "math formulas across lines in Scheme code")]) (slatex::setf (slatex::of line slatex::=char / i) #\newline) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) (cond [(eof-object? (peek-char slatex::*in*)) &plain-crg-ret] [slatex::*intext?* &plain-crg-ret] [else &tabbed-crg-ret])) (slatex::setf (slatex::of line slatex::=rtedge) i) (if (eq? (slatex::of line slatex::=notab / 0) &mid-string) (slatex::setf (slatex::of line slatex::=notab / 0) &begin-string)) #t] [(eq? curr-notab &mid-comment) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) (cond [(char=? c #\space) &plain-space] [(char=? c slatex::*tab*) &plain-space] [else &void-space])) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &mid-comment) (loop (+ i 1))] [(char=? c #\\) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) curr-notab) (let ([i+1 (+ i 1)] [c+1 (read-char slatex::*in*)]) (if (char=? c+1 slatex::*tab*) (set! c+1 #\space)) (slatex::setf (slatex::of line slatex::=char / i+1) c+1) (slatex::setf (slatex::of line slatex::=space / i+1) (if (char=? c+1 #\space) &plain-space &void-space)) (slatex::setf (slatex::of line slatex::=tab / i+1) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i+1) curr-notab) (loop (+ i+1 1)))] [(eq? curr-notab &mid-math) (if (char=? c slatex::*tab*) (set! c #\space)) (slatex::setf (slatex::of line slatex::=space / i) (if (char=? c #\space) &plain-space &void-space)) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (cond [(memv c slatex::*math-triggerers*) (slatex::setf (slatex::of line slatex::=char / i) #\$) (slatex::setf (slatex::of line slatex::=notab / i) &end-math) (slatex::setf curr-notab &void-notab)] [else (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=notab / i) &mid-math)]) (loop (+ i 1))] [(eq? curr-notab &mid-string) (if (char=? c slatex::*tab*) (set! c #\space)) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) (if (char=? c #\space) &inner-space &void-space)) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) (cond [(char=? c #\") (set! curr-notab &void-notab) &end-string] [else &mid-string])) (loop (+ i 1))] [(char=? c #\space) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) (cond [slatex::*intext?* &plain-space] [graphic-char-seen? &inner-space] [else &init-space])) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (loop (+ i 1))] [(char=? c slatex::*tab*) (let loop1 ([i i] [j 0]) (if (< j 8) (begin (slatex::setf (slatex::of line slatex::=char / i) #\space) (slatex::setf (slatex::of line slatex::=space / i) (cond [slatex::*intext?* &plain-space] [graphic-char-seen? &inner-space] [else &init-space])) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (loop1 (+ i 1) (+ j 1))))) (loop (+ i 8))] [(char=? c #\") (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &begin-string) (set! curr-notab &mid-string) (loop (+ i 1))] [(char=? c #\;) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &begin-comment) (set! curr-notab &mid-comment) (loop (+ i 1))] [(memv c slatex::*math-triggerers*) (slatex::setf (slatex::of line slatex::=char / i) #\$) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &begin-math) (set! curr-notab &mid-math) (loop (+ i 1))] [else (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (loop (+ i 1))]))))))) (define slatex::peephole-adjust (lambda (curr prev) (if (or (slatex::blank-line? curr) (slatex::flush-comment-line? curr)) (if (not slatex::*latex-paragraph-mode?*) (begin (set! slatex::*latex-paragraph-mode?* #t) (if (not slatex::*intext?*) (begin (slatex::remove-some-tabs prev 0) (let ([prev-rtedge (slatex::of prev slatex::=rtedge)]) (if (eq? (slatex::of prev slatex::=tab / prev-rtedge) &tabbed-crg-ret) (slatex::setf (slatex::of prev slatex::=tab / (slatex::of prev slatex::=rtedge)) &plain-crg-ret))))))) (begin (if slatex::*latex-paragraph-mode?* (set! slatex::*latex-paragraph-mode?* #f) (if (not slatex::*intext?*) (let ([remove-tabs-from #f]) (let loop ([i 0]) (cond [(char=? (slatex::of curr slatex::=char / i) #\newline) (set! remove-tabs-from i)] [(char=? (slatex::of prev slatex::=char / i) #\newline) (set! remove-tabs-from #f)] [(eq? (slatex::of curr slatex::=space / i) &init-space) (if (eq? (slatex::of prev slatex::=notab / i) &void-notab) (begin (cond [(or (char=? (slatex::of prev slatex::=char / i) #\() (eq? (slatex::of prev slatex::=space / i) &paren-space)) (slatex::setf (slatex::of curr slatex::=space / i) &paren-space)] [(or (char=? (slatex::of prev slatex::=char / i) #\[) (eq? (slatex::of prev slatex::=space / i) &bracket-space)) (slatex::setf (slatex::of curr slatex::=space / i) &bracket-space)] [(or (memv (slatex::of prev slatex::=char / i) '(#\' #\` #\,)) (eq? (slatex::of prev slatex::=space / i) &quote-space)) (slatex::setf (slatex::of curr slatex::=space / i) &quote-space)]) (if (memq (slatex::of prev slatex::=tab / i) (list &set-tab &move-tab)) (slatex::setf (slatex::of curr slatex::=tab / i) &move-tab)))) (loop (+ i 1))] [(= i 0) (set! remove-tabs-from 0)] [(not (eq? (slatex::of prev slatex::=tab / i) &void-tab)) (set! remove-tabs-from (+ i 1)) (if (memq (slatex::of prev slatex::=tab / i) (list &set-tab &move-tab)) (slatex::setf (slatex::of curr slatex::=tab / i) &move-tab))] [(memq (slatex::of prev slatex::=space / i) (list &init-space &init-plain-space &paren-space &bracket-space &quote-space)) (set! remove-tabs-from (+ i 1))] [(and (char=? (slatex::of prev slatex::=char / (- i 1)) #\space) (eq? (slatex::of prev slatex::=notab / (- i 1)) &void-notab)) (set! remove-tabs-from (+ i 1)) (slatex::setf (slatex::of prev slatex::=tab / i) &set-tab) (slatex::setf (slatex::of curr slatex::=tab / i) &move-tab)] [else (set! remove-tabs-from (+ i 1)) (let loop1 ([j (- i 1)]) (cond [(<= j 0) 'exit-loop1] [(not (eq? (slatex::of curr slatex::=tab / j) &void-tab)) 'exit-loop1] [(memq (slatex::of curr slatex::=space / j) (list &paren-space &bracket-space &quote-space)) (loop1 (- j 1))] [(or (not (eq? (slatex::of prev slatex::=notab / j) &void-notab)) (char=? (slatex::of prev slatex::=char / j) #\space)) (let ([k (+ j 1)]) (if (not (memq (slatex::of prev slatex::=notab / k) (list &mid-comment &mid-math &end-math &mid-string &end-string))) (begin (if (eq? (slatex::of prev slatex::=tab / k) &void-tab) (slatex::setf (slatex::of prev slatex::=tab / k) &set-tab)) (slatex::setf (slatex::of curr slatex::=tab / k) &move-tab))))] [else 'anything-else?]))])) (slatex::remove-some-tabs prev remove-tabs-from)))) (if (not slatex::*intext?*) (slatex::add-some-tabs curr)) (slatex::clean-init-spaces curr) (slatex::clean-inner-spaces curr))))) (define slatex::add-some-tabs (lambda (line) (let loop ([i 1] [succ-parens? #f]) (let ([c (slatex::of line slatex::=char / i)]) (cond [(char=? c #\newline) 'exit-loop] [(not (eq? (slatex::of line slatex::=notab / i) &void-notab)) (loop (+ i 1) #f)] [(char=? c #\[) (if (eq? (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=tab / i) &set-tab)) (loop (+ i 1) #f)] [(char=? c #\() (if (eq? (slatex::of line slatex::=tab / i) &void-tab) (if (not succ-parens?) (slatex::setf (slatex::of line slatex::=tab / i) &set-tab))) (loop (+ i 1) #t)] [else (loop (+ i 1) #f)]))))) (define slatex::remove-some-tabs (lambda (line i) (if i (let loop ([i i]) (cond [(char=? (slatex::of line slatex::=char / i) #\newline) 'exit] [(eq? (slatex::of line slatex::=tab / i) &set-tab) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (loop (+ i 1))] [else (loop (+ i 1))]))))) (define slatex::clean-init-spaces (lambda (line) (let loop ([i (slatex::of line slatex::=rtedge)]) (cond [(< i 0) 'exit-loop] [(eq? (slatex::of line slatex::=tab / i) &move-tab) (let loop1 ([i (- i 1)]) (cond [(< i 0) 'exit-loop1] [(memq (slatex::of line slatex::=space / i) (list &init-space &paren-space &bracket-space &quote-space)) (slatex::setf (slatex::of line slatex::=space / i) &init-plain-space) (loop1 (- i 1))] [else (loop1 (- i 1))]))] [else (loop (- i 1))])))) (define slatex::clean-inner-spaces (lambda (line) (let loop ([i 0] [succ-inner-spaces? #f]) (cond [(char=? (slatex::of line slatex::=char / i) #\newline) 'exit-loop] [(eq? (slatex::of line slatex::=space / i) &inner-space) (if (not succ-inner-spaces?) (slatex::setf (slatex::of line slatex::=space / i) &plain-space)) (loop (+ i 1) #t)] [else (loop (+ i 1) #f)])))) (define slatex::blank-line? (lambda (line) (let loop ([i 0]) (let ([c (slatex::of line slatex::=char / i)]) (cond [(char=? c #\space) (if (eq? (slatex::of line slatex::=notab / i) &void-notab) (loop (+ i 1)) #f)] [(char=? c #\newline) (let loop1 ([j (- i 1)]) (if (not (<= j 0)) (begin (slatex::setf (slatex::of line slatex::=space / i) &void-space) (loop1 (- j 1))))) #t] [else #f]))))) (define slatex::flush-comment-line? (lambda (line) (and (char=? (slatex::of line slatex::=char / 0) #\;) (eq? (slatex::of line slatex::=notab / 0) &begin-comment) (not (char=? (slatex::of line slatex::=char / 1) #\;))))) (define slatex::display-tex-line (lambda (line) (cond [else (let loop ([i (if (slatex::flush-comment-line? line) 1 0)]) (let ([c (slatex::of line slatex::=char / i)]) (if (char=? c #\newline) (if (not (eq? (slatex::of line slatex::=tab / i) &void-tab)) (newline slatex::*out*)) (begin (write-char c slatex::*out*) (loop (+ i 1))))))]))) (define slatex::display-scm-line (lambda (line) (let loop ([i 0]) (let ([c (slatex::of line slatex::=char / i)]) (cond [(char=? c #\newline) (let ([notab (slatex::of line slatex::=notab / i)] [tab (slatex::of line slatex::=tab / i)]) (if (eq? notab &end-string) (display "}" slatex::*out*)) (cond [(eq? tab &tabbed-crg-ret) (display "\\\\%" slatex::*out*) (newline slatex::*out*)] [(eq? tab &plain-crg-ret) (newline slatex::*out*)] [(eq? tab &void-tab) (write-char #\% slatex::*out*) (newline slatex::*out*)]))] [(eq? (slatex::of line slatex::=notab / i) &begin-comment) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &mid-comment) (write-char c slatex::*out*) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &begin-string) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (display "\\dt{" slatex::*out*) (if (char=? c #\space) (slatex::display-space (slatex::of line slatex::=space / i) slatex::*out*) (slatex::display-tex-char c slatex::*out*)) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &mid-string) (if (char=? c #\space) (slatex::display-space (slatex::of line slatex::=space / i) slatex::*out*) (slatex::display-tex-char c slatex::*out*)) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &end-string) (if (char=? c #\space) (slatex::display-space (slatex::of line slatex::=space / i) slatex::*out*) (slatex::display-tex-char c slatex::*out*)) (write-char #\} slatex::*out*) (if slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (if slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f))) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &begin-math) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &mid-math) (write-char c slatex::*out*) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &end-math) (write-char c slatex::*out*) (if slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (if slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f))) (loop (+ i 1))] [(char=? c #\space) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (slatex::display-space (slatex::of line slatex::=space / i) slatex::*out*) (loop (+ i 1))] [(char=? c #\') (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (if (or slatex::*in-qtd-tkn* (> slatex::*in-bktd-qtd-exp* 0) (and (pair? slatex::*bq-stack*) (not (slatex::of (car slatex::*bq-stack*) slatex::=in-comma)))) #f (set! slatex::*in-qtd-tkn* #t)) (loop (+ i 1))] [(char=? c #\`) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (if (or (null? slatex::*bq-stack*) (slatex::of (car slatex::*bq-stack*) slatex::=in-comma)) (set! slatex::*bq-stack* (cons (let ([f (slatex::make-bq-frame)]) (slatex::setf (slatex::of f slatex::=in-comma) #f) (slatex::setf (slatex::of f slatex::=in-bq-tkn) #t) (slatex::setf (slatex::of f slatex::=in-bktd-bq-exp) 0) f) slatex::*bq-stack*))) (loop (+ i 1))] [(char=? c #\,) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (if (not (or (null? slatex::*bq-stack*) (slatex::of (car slatex::*bq-stack*) slatex::=in-comma))) (set! slatex::*bq-stack* (cons (let ([f (slatex::make-bq-frame)]) (slatex::setf (slatex::of f slatex::=in-comma) #t) (slatex::setf (slatex::of f slatex::=in-bq-tkn) #t) (slatex::setf (slatex::of f slatex::=in-bktd-bq-exp) 0) f) slatex::*bq-stack*))) (if (char=? (slatex::of line slatex::=char / (+ i 1)) #\@) (begin (slatex::display-tex-char #\@ slatex::*out*) (loop (+ 2 i))) (loop (+ i 1)))] [(memv c '(#\( #\[)) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (cond [slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (set! slatex::*in-bktd-qtd-exp* 1)] [(> slatex::*in-bktd-qtd-exp* 0) (set! slatex::*in-bktd-qtd-exp* (+ slatex::*in-bktd-qtd-exp* 1))]) (cond [slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f) (set! slatex::*in-bktd-mac-exp* 1)] [(> slatex::*in-bktd-mac-exp* 0) (set! slatex::*in-bktd-mac-exp* (+ slatex::*in-bktd-mac-exp* 1))]) (if (not (null? slatex::*bq-stack*)) (let ([top (car slatex::*bq-stack*)]) (cond [(slatex::of top slatex::=in-bq-tkn) (slatex::setf (slatex::of top slatex::=in-bq-tkn) #f) (slatex::setf (slatex::of top slatex::=in-bktd-bq-exp) 1)] [(> (slatex::of top slatex::=in-bktd-bq-exp) 0) (slatex::setf (slatex::of top slatex::=in-bktd-bq-exp) (+ (slatex::of top slatex::=in-bktd-bq-exp) 1))]))) (if (not (null? slatex::*case-stack*)) (let ([top (car slatex::*case-stack*)]) (cond [(slatex::of top slatex::=in-ctag-tkn) (slatex::setf (slatex::of top slatex::=in-ctag-tkn) #f) (slatex::setf (slatex::of top slatex::=in-bktd-ctag-exp) 1)] [(> (slatex::of top slatex::=in-bktd-ctag-exp) 0) (slatex::setf (slatex::of top slatex::=in-bktd-ctag-exp) (+ (slatex::of top slatex::=in-bktd-ctag-exp) 1))] [(> (slatex::of top slatex::=in-case-exp) 0) (slatex::setf (slatex::of top slatex::=in-case-exp) (+ (slatex::of top slatex::=in-case-exp) 1)) (if (= (slatex::of top slatex::=in-case-exp) 2) (set! slatex::*in-qtd-tkn* #t))]))) (loop (+ i 1))] [(memv c '(#\) #\])) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (if (> slatex::*in-bktd-qtd-exp* 0) (set! slatex::*in-bktd-qtd-exp* (- slatex::*in-bktd-qtd-exp* 1))) (if (> slatex::*in-bktd-mac-exp* 0) (set! slatex::*in-bktd-mac-exp* (- slatex::*in-bktd-mac-exp* 1))) (if (not (null? slatex::*bq-stack*)) (let ([top (car slatex::*bq-stack*)]) (if (> (slatex::of top slatex::=in-bktd-bq-exp) 0) (begin (slatex::setf (slatex::of top slatex::=in-bktd-bq-exp) (- (slatex::of top slatex::=in-bktd-bq-exp) 1)) (if (= (slatex::of top slatex::=in-bktd-bq-exp) 0) (set! slatex::*bq-stack* (cdr slatex::*bq-stack*))))))) (let loop () (if (not (null? slatex::*case-stack*)) (let ([top (car slatex::*case-stack*)]) (cond [(> (slatex::of top slatex::=in-bktd-ctag-exp) 0) (slatex::setf (slatex::of top slatex::=in-bktd-ctag-exp) (- (slatex::of top slatex::=in-bktd-ctag-exp) 1)) (if (= (slatex::of top slatex::=in-bktd-ctag-exp) 0) (slatex::setf (slatex::of top slatex::=in-case-exp) 1))] [(> (slatex::of top slatex::=in-case-exp) 0) (slatex::setf (slatex::of top slatex::=in-case-exp) (- (slatex::of top slatex::=in-case-exp) 1)) (if (= (slatex::of top slatex::=in-case-exp) 0) (begin (set! slatex::*case-stack* (cdr slatex::*case-stack*)) (loop)))])))) (loop (+ i 1))] [else (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (loop (slatex::do-token line i))]))))) (define slatex::do-all-lines (lambda () (let loop ([line1 slatex::*line1*] [line2 slatex::*line2*]) (let* ([line2-paragraph? slatex::*latex-paragraph-mode?*] [more? (slatex::get-line line1)]) (slatex::peephole-adjust line1 line2) ((if line2-paragraph? slatex::display-tex-line slatex::display-scm-line) line2) (if (not (eq? line2-paragraph? slatex::*latex-paragraph-mode?*)) ((if slatex::*latex-paragraph-mode?* slatex::display-end-sequence slatex::display-begin-sequence) slatex::*out*)) (if more? (loop line2 line1)))))) (define slatex::scheme2tex (lambda (inport outport) (set! slatex::*in* inport) (set! slatex::*out* outport) (set! slatex::*latex-paragraph-mode?* #t) (set! slatex::*in-qtd-tkn* #f) (set! slatex::*in-bktd-qtd-exp* 0) (set! slatex::*in-mac-tkn* #f) (set! slatex::*in-bktd-mac-exp* 0) (set! slatex::*case-stack* '()) (set! slatex::*bq-stack* '()) (let ([flush-line (lambda (line) (slatex::setf (slatex::of line slatex::=rtedge) 0) (slatex::setf (slatex::of line slatex::=char / 0) #\newline) (slatex::setf (slatex::of line slatex::=space / 0) &void-space) (slatex::setf (slatex::of line slatex::=tab / 0) &void-tab) (slatex::setf (slatex::of line slatex::=notab / 0) &void-notab))]) (flush-line slatex::*line1*) (flush-line slatex::*line2*)) (slatex::do-all-lines))) (define slatex::do-token (let ([token-delims (list #\( #\) #\[ #\] #\space slatex::*return* #\" #\' #\` #\newline #\, #\;)]) (lambda (line i) (let loop ([buf '()] [i i]) (let ([c (slatex::of line slatex::=char / i)]) (cond [(char=? c #\\) (loop (cons (slatex::of line slatex::=char / (+ i 1)) (cons c buf)) (+ i 2))] [(or (memv c token-delims) (memv c slatex::*math-triggerers*)) (slatex::output-token (list->string (reverse! buf))) i] [(char? c) (loop (cons (slatex::of line slatex::=char / i) buf) (+ i 1))] [else (slatex::slatex-error 'slatex::do-token "token contains non-char?" c)])))))) (define slatex::output-token (lambda (token) (if (not (null? slatex::*case-stack*)) (let ([top (car slatex::*case-stack*)]) (if (slatex::of top slatex::=in-ctag-tkn) (begin (slatex::setf (slatex::of top slatex::=in-ctag-tkn) #f) (slatex::setf (slatex::of top slatex::=in-case-exp) 1))))) (if (slatex::lassoc token slatex::special-symbols slatex::token=?) (begin (if slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (if slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f))) (display (cdr (slatex::lassoc token slatex::special-symbols slatex::token=?)) slatex::*out*)) (slatex::display-token token (cond [slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (cond [(equal? token "else") 'syntax] [(slatex::lmember token slatex::data-tokens slatex::token=?) 'data] [(slatex::lmember token slatex::constant-tokens slatex::token=?) 'constant] [(slatex::lmember token slatex::variable-tokens slatex::token=?) 'constant] [(slatex::lmember token slatex::keyword-tokens slatex::token=?) 'constant] [(slatex::prim-data-token? token) 'data] [else 'constant])] [(> slatex::*in-bktd-qtd-exp* 0) 'constant] [(and (not (null? slatex::*bq-stack*)) (not (slatex::of (car slatex::*bq-stack*) slatex::=in-comma))) 'constant] [slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f) (slatex::set-keyword token) 'syntax] [(> slatex::*in-bktd-mac-exp* 0) (slatex::set-keyword token) 'syntax] [(slatex::lmember token slatex::data-tokens slatex::token=?) 'data] [(slatex::lmember token slatex::constant-tokens slatex::token=?) 'constant] [(slatex::lmember token slatex::variable-tokens slatex::token=?) 'variable] [(slatex::lmember token slatex::keyword-tokens slatex::token=?) (cond [(slatex::token=? token "quote") (set! slatex::*in-qtd-tkn* #t)] [(slatex::lmember token slatex::macro-definers slatex::token=?) (set! slatex::*in-mac-tkn* #t)] [(slatex::lmember token slatex::case-and-ilk slatex::token=?) (set! slatex::*case-stack* (cons (let ([f (slatex::make-case-frame)]) (slatex::setf (slatex::of f slatex::=in-ctag-tkn) #t) (slatex::setf (slatex::of f slatex::=in-bktd-ctag-exp) 0) (slatex::setf (slatex::of f slatex::=in-case-exp) 0) f) slatex::*case-stack*))]) 'syntax] [(slatex::prim-data-token? token) 'data] [else 'variable]) slatex::*out*)) (if (and (not (null? slatex::*bq-stack*)) (slatex::of (car slatex::*bq-stack*) slatex::=in-bq-tkn)) (set! slatex::*bq-stack* (cdr slatex::*bq-stack*))))) (define slatex::directory-namestring (lambda (f) (let ([p (slatex::string-position-right slatex::*directory-mark* f)]) (if p (substring f 0 (+ p 1)) "")))) (define slatex::basename (lambda (f) (let ([p (slatex::string-position-right slatex::*directory-mark* f)]) (if p (set! f (substring f (+ p 1) (string-length f)))) (let ([p (slatex::string-position-right #\. f)]) (if p (substring f 0 p) f))))) (define slatex::*texinputs* "") (define slatex::*texinputs-list* #f) (define slatex::*path-separator* (cond [(eq? slatex::*operating-system* 'unix) #\:] [(eq? slatex::*operating-system* 'mac-os) (integer->char 0)] [(memq slatex::*operating-system* '(windows os2 dos os2fat)) #\;] [else (slatex::slatex-error "Couldn't determine path separator character.")])) (define slatex::*directory-mark* (cond [(eq? slatex::*operating-system* 'unix) #\/] [(eq? slatex::*operating-system* 'mac-os) #\:] [(memq slatex::*operating-system* '(windows os2 dos os2fat)) #\\] [else (slatex::slatex-error "Couldn't determine directory mark.")])) (define slatex::*directory-mark-string* (list->string (list slatex::*directory-mark*))) (define slatex::*file-hider* (cond [(memq slatex::*operating-system* '(windows os2 unix mac-os)) "."] [(memq slatex::*operating-system* '(dos os2fat)) "x"] [else "."])) (define slatex::path-to-list (lambda (p) (let loop ([p (string->list p)] [r (list "")]) (let ([separator-pos (slatex::position-char slatex::*path-separator* p)]) (if separator-pos (loop (list-tail p (+ separator-pos 1)) (cons (list->string (slatex::sublist p 0 separator-pos)) r)) (reverse! (cons (list->string p) r))))))) (define slatex::find-some-file (lambda (path . files) (let loop ([path path]) (if (null? path) #f (let ([dir (car path)]) (let loop1 ([files (if (or (string=? dir "") (string=? dir ".")) files (map (lambda (file) (string-append dir slatex::*directory-mark-string* file)) files))]) (if (null? files) (loop (cdr path)) (let ([file (car files)]) (if (file-exists? file) file (loop1 (cdr files))))))))))) (define slatex::file-extension (lambda (filename) (let ([i (slatex::string-position-right #\. filename)]) (if i (substring filename i (string-length filename)) #f)))) (define slatex::full-texfile-name (lambda (filename) (let ([extn (slatex::file-extension filename)]) (if (and extn (or (string=? extn ".sty") (string=? extn ".tex"))) (slatex::find-some-file slatex::*texinputs-list* filename) (slatex::find-some-file slatex::*texinputs-list* (string-append filename ".tex") filename))))) (define slatex::full-styfile-name (lambda (filename) (slatex::find-some-file slatex::*texinputs-list* (string-append filename ".sty")))) (define slatex::full-clsfile-name (lambda (filename) (slatex::find-some-file slatex::*texinputs-list* (string-append filename ".cls")))) (define slatex::full-scmfile-name (lambda (filename) (apply slatex::find-some-file slatex::*texinputs-list* filename (map (lambda (extn) (string-append filename extn)) '(".scm" ".ss" ".s"))))) (define slatex::subjobname 'fwd) (define slatex::primary-aux-file-count -1) (define slatex::new-primary-aux-file (lambda (e) (set! slatex::primary-aux-file-count (+ slatex::primary-aux-file-count 1)) (string-append slatex::*tex-calling-directory* slatex::*file-hider* "Z" (number->string slatex::primary-aux-file-count) slatex::subjobname e))) (define slatex::new-secondary-aux-file (let ([n -1]) (lambda (e) (set! n (+ n 1)) (string-append slatex::*tex-calling-directory* slatex::*file-hider* "ZZ" (number->string n) slatex::subjobname e)))) (define slatex::new-aux-file (lambda e (let ([e (if (pair? e) (car e) "")]) ((if slatex::*slatex-in-protected-region?* slatex::new-secondary-aux-file slatex::new-primary-aux-file) e)))) (define slatex::eat-till-newline (lambda (in) (let loop () (let ([c (read-char in)]) (cond [(eof-object? c) 'done] [(char=? c #\newline) 'done] [else (loop)]))))) (define slatex::read-ctrl-seq (lambda (in) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-ctrl-exp: \\ followed by eof.")) (if (char-alphabetic? c) (list->string (reverse! (let loop ([s (list c)]) (let ([c (peek-char in)]) (cond [(eof-object? c) s] [(char-alphabetic? c) (read-char in) (loop (cons c s))] [(char=? c #\%) (slatex::eat-till-newline in) (loop s)] [else s]))))) (string c))))) (define slatex::eat-tabspace (lambda (in) (let loop () (let ([c (peek-char in)]) (cond [(eof-object? c) 'done] [(or (char=? c #\space) (char=? c slatex::*tab*)) (read-char in) (loop)] [else 'done]))))) (define slatex::eat-whitespace (lambda (in) (let loop () (let ([c (peek-char in)]) (cond [(eof-object? c) 'done] [(char-whitespace? c) (read-char in) (loop)] [else 'done]))))) (define slatex::eat-tex-whitespace (lambda (in) (let loop () (let ([c (peek-char in)]) (cond [(eof-object? c) 'done] [(char-whitespace? c) (read-char in) (loop)] [(char=? c #\%) (slatex::eat-till-newline in)] [else 'done]))))) (define slatex::chop-off-whitespace (lambda (l) (slatex::ormapcdr (lambda (d) (if (char-whitespace? (car d)) #f d)) l))) (define slatex::read-grouped-latexexp (lambda (in) (slatex::eat-tex-whitespace in) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-grouped-latexexp: ~\nExpected { but found eof.")) (if (not (char=? c #\{)) (slatex::slatex-error "read-grouped-latexexp: ~\nExpected { but found ~a." c)) (slatex::eat-tex-whitespace in) (list->string (reverse! (slatex::chop-off-whitespace (let loop ([s '()] [nesting 0] [escape? #f]) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-groupted-latexexp: ~\nFound eof inside {...}.")) (cond [escape? (loop (cons c s) nesting #f)] [(char=? c #\\) (loop (cons c s) nesting #t)] [(char=? c #\%) (slatex::eat-till-newline in) (loop s nesting #f)] [(char=? c #\{) (loop (cons c s) (+ nesting 1) #f)] [(char=? c #\}) (if (= nesting 0) s (loop (cons c s) (- nesting 1) #f))] [else (loop (cons c s) nesting #f)]))))))))) (define slatex::read-filename (let ([filename-delims (list #\{ #\} #\[ #\] #\( #\) #\# #\% #\\ #\, #\space slatex::*return* #\newline slatex::*tab* #\\)]) (lambda (in) (slatex::eat-tex-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "read-filename: ~\nExpected filename but found eof.")) (if (char=? c #\{) (slatex::read-grouped-latexexp in) (list->string (reverse! (let loop ([s '()] [escape? #f]) (let ([c (peek-char in)]) (cond [(eof-object? c) (if escape? (slatex::slatex-error "read-filename: ~\n\\ followed by eof.") s)] [escape? (read-char in) (loop (cons c s) #f)] [(char=? c #\\) (read-char in) (loop (cons c s) #t)] [(memv c filename-delims) s] [else (read-char in) (loop (cons c s) #f)])))))))))) (define slatex::read-schemeid (let ([schemeid-delims (list #\{ #\} #\[ #\] #\( #\) #\space slatex::*return* #\newline slatex::*tab*)]) (lambda (in) (slatex::eat-whitespace in) (list->string (reverse! (let loop ([s '()] [escape? #f]) (let ([c (peek-char in)]) (cond [(eof-object? c) s] [escape? (read-char in) (loop (cons c s) #f)] [(char=? c #\\) (read-char in) (loop (cons c s) #t)] [(memv c schemeid-delims) s] [else (read-char in) (loop (cons c s) #f)])))))))) (define slatex::read-delimed-commaed-filenames (lambda (in lft-delim rt-delim) (slatex::eat-tex-whitespace in) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-delimed-commaed-filenames: ~\nExpected filename(s) but found eof.")) (if (not (char=? c lft-delim)) (slatex::slatex-error "read-delimed-commaed-filenames: ~\nLeft delimiter ~a not found." lft-delim)) (let loop ([s '()]) (slatex::eat-tex-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "read-delimed-commaed-filenames: ~\nFound eof inside filename(s).")) (if (char=? c rt-delim) (begin (read-char in) (reverse! s)) (let ([s (cons (slatex::read-filename in) s)]) (slatex::eat-tex-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "read-delimed-commaed-filenames: ~\nFound eof inside filename(s).")) (cond [(char=? c #\,) (read-char in)] [(char=? c rt-delim) (void)] [else (slatex::slatex-error "read-delimed-commaed-filenames: ~\nBad filename(s) syntax.")]) (loop s))))))))) (define slatex::read-grouped-commaed-filenames (lambda (in) (slatex::read-delimed-commaed-filenames in #\{ #\}))) (define slatex::read-bktd-commaed-filenames (lambda (in) (slatex::read-delimed-commaed-filenames in #\[ #\]))) (define slatex::read-grouped-schemeids (lambda (in) (slatex::eat-tex-whitespace in) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-grouped-schemeids: ~\nExpected Scheme identifiers but found eof.")) (if (not (char=? c #\{)) (slatex::slatex-error "read-grouped-schemeids: ~\nExpected { but found ~a." c)) (let loop ([s '()]) (slatex::eat-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "read-grouped-schemeids:\nFound eof inside Scheme identifiers.")) (if (char=? c #\}) (begin (read-char in) (reverse! s)) (loop (cons (slatex::read-schemeid in) s)))))))) (define slatex::eat-delimed-text (lambda (in lft-delim rt-delim) (slatex::eat-tex-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) 'exit (if (char=? c lft-delim) (let loop () (let ([c (read-char in)]) (if (eof-object? c) 'exit (if (char=? c rt-delim) 'exit (loop)))))))))) (define slatex::eat-bktd-text (lambda (in) (slatex::eat-delimed-text in #\[ #\]))) (define slatex::eat-grouped-text (lambda (in) (slatex::eat-delimed-text in #\{ #\}))) (define slatex::ignore2 (lambda (i ii) 'void)) (define slatex::disable-slatex-temply (lambda (in) (set! slatex::*slatex-enabled?* #f) (set! slatex::*slatex-reenabler* (slatex::read-grouped-latexexp in)))) (define slatex::enable-slatex-again (lambda () (set! slatex::*slatex-enabled?* #t) (set! slatex::*slatex-reenabler* "UNDEFINED"))) (define slatex::add-to-slatex-db (lambda (in categ) (if (memq categ '(keyword constant variable)) (slatex::add-to-slatex-db-basic in categ) (slatex::add-to-slatex-db-special in categ)))) (define slatex::add-to-slatex-db-basic (lambda (in categ) (let ([setter (cond [(eq? categ 'keyword) slatex::set-keyword] [(eq? categ 'constant) slatex::set-constant] [(eq? categ 'variable) slatex::set-variable] [else (slatex::slatex-error "add-to-slatex-db-basic: ~\nUnknown category ~s." categ)])] [ids (slatex::read-grouped-schemeids in)]) (for-each setter ids)))) (define slatex::add-to-slatex-db-special (lambda (in what) (let ([ids (slatex::read-grouped-schemeids in)]) (cond [(eq? what 'unsetspecialsymbol) (for-each slatex::unset-special-symbol ids)] [(eq? what 'setspecialsymbol) (if (not (= (length ids) 1)) (slatex::slatex-error "add-to-slatex-db-special: ~\n\\setspecialsymbol takes one arg exactly.")) (let ([transl (slatex::read-grouped-latexexp in)]) (slatex::set-special-symbol (car ids) transl))] [else (slatex::slatex-error "add-to-slatex-db-special: ~\nUnknown command ~s." what)])))) (define slatex::process-slatex-alias (lambda (in what which) (let ([triggerer (slatex::read-grouped-latexexp in)]) (case which [(intext) (set! slatex::*intext-triggerers* (what triggerer slatex::*intext-triggerers* string=?))] [(resultintext) (set! slatex::*resultintext-triggerers* (what triggerer slatex::*resultintext-triggerers* string=?))] [(display) (set! slatex::*display-triggerers* (what triggerer slatex::*display-triggerers* string=?))] [(response) (set! slatex::*response-triggerers* (what triggerer slatex::*response-triggerers* string=?))] [(respbox) (set! slatex::*respbox-triggerers* (what triggerer slatex::*respbox-triggerers* string=?))] [(box) (set! slatex::*box-triggerers* (what triggerer slatex::*box-triggerers* string=?))] [(input) (set! slatex::*input-triggerers* (what triggerer slatex::*input-triggerers* string=?))] [(region) (set! slatex::*region-triggerers* (what triggerer slatex::*region-triggerers* string=?))] [(mathescape) (if (not (= (string-length triggerer) 1)) (slatex::slatex-error "process-slatex-alias: ~\nMath escape should be character.")) (set! slatex::*math-triggerers* (what (string-ref triggerer 0) slatex::*math-triggerers* char=?))] [else (slatex::slatex-error "process-slatex-alias:\nUnknown command ~s." which)])))) (define slatex::decide-latex-or-tex (lambda (latex?) (set! slatex::*latex?* latex?) (let ([pltexchk.jnk "pltexchk.jnk"]) (if (file-exists? pltexchk.jnk) (delete-file pltexchk.jnk)) (if (not slatex::*latex?*) (call-with-output-file pltexchk.jnk (lambda (outp) (display 'junk outp) (newline outp))))))) (define slatex::process-include-only (lambda (in) (set! slatex::*include-onlys* '()) (for-each (lambda (filename) (let ([filename (slatex::full-texfile-name filename)]) (if filename (set! slatex::*include-onlys* (slatex::adjoin filename slatex::*include-onlys* string=?))))) (slatex::read-grouped-commaed-filenames in)))) (define slatex::process-documentstyle (lambda (in) (slatex::eat-tex-whitespace in) (if (char=? (peek-char in) #\[) (for-each (lambda (filename) (fluid-let ([slatex::*slatex-in-protected-region?* #f]) (slatex::process-tex-file (string-append filename ".sty")))) (slatex::read-bktd-commaed-filenames in))))) (define slatex::process-documentclass (lambda (in) (slatex::eat-bktd-text in) (slatex::eat-grouped-text in))) (define slatex::process-case-info (lambda (in) (let ([bool (slatex::read-grouped-latexexp in)]) (set! slatex::*slatex-case-sensitive?* (cond [(string-ci=? bool "true") #t] [(string-ci=? bool "false") #f] [else (slatex::slatex-error "process-case-info: ~\n\\schemecasesensitive's arg should be true or false.")]))))) (define slatex::seen-first-command? #f) (define slatex::process-main-tex-file (lambda (filename) (display "SLaTeX v. ") (display slatex::*slatex-version*) (newline) (set! slatex::primary-aux-file-count -1) (set! slatex::*slatex-separate-includes?* #f) (if (or (not slatex::*texinputs-list*) (null? slatex::*texinputs-list*)) (set! slatex::*texinputs-list* (if slatex::*texinputs* (slatex::path-to-list slatex::*texinputs*) '("")))) (let ([file-hide-file "xZfilhid.tex"]) (if (file-exists? file-hide-file) (delete-file file-hide-file)) (if (memq slatex::*operating-system* '(dos os2fat)) (call-with-output-file file-hide-file (lambda (out) (display "\\def\\filehider{x}" out) (newline out))))) (display "typesetting code") (set! slatex::*tex-calling-directory* (slatex::directory-namestring filename)) (set! slatex::subjobname (slatex::basename filename)) (set! slatex::seen-first-command? #f) (slatex::process-tex-file filename) (display "done") (newline))) (define slatex::dump-intext (lambda (in out) (let* ([write-char (if out write-char slatex::ignore2)] [delim-char (begin (slatex::eat-whitespace in) (read-char in))] [delim-char (cond [(char=? delim-char #\{) #\}] [else delim-char])]) (if (eof-object? delim-char) (slatex::slatex-error "dump-intext: Expected delimiting character ~\nbut found eof.")) (let loop () (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "dump-intext: Found eof inside Scheme code.")) (if (char=? c delim-char) 'done (begin (write-char c out) (loop)))))))) (define slatex::dump-display (lambda (in out ender) (slatex::eat-tabspace in) (let ([write-char (if out write-char slatex::ignore2)] [ender-lh (string-length ender)] [c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "dump-display: Found eof inside displayed code.")) (if (char=? c #\newline) (read-char in)) (let loop ([i 0]) (if (= i ender-lh) 'done (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "dump-display: Found eof inside displayed code.")) (if (char=? c (string-ref ender i)) (loop (+ i 1)) (let loop2 ([j 0]) (if (< j i) (begin (write-char (string-ref ender j) out) (loop2 (+ j 1))) (begin (write-char c out) (loop 0))))))))))) (define slatex::debug? #f) (define slatex::process-tex-file (lambda (raw-filename) (if slatex::debug? (begin (display "begin ") (display raw-filename) (newline))) (let ([filename (slatex::full-texfile-name raw-filename)]) (if (not filename) (begin (display "[") (display raw-filename) (display "]") (flush-output-port)) (call-with-input-file filename (lambda (in) (let ([done? #f]) (let loop () (if done? 'exit-loop (begin (let ([c (read-char in)]) (cond [(eof-object? c) (set! done? #t)] [(char=? c #\%) (slatex::eat-till-newline in)] [(char=? c #\\) (let ([cs (slatex::read-ctrl-seq in)]) (if (not slatex::seen-first-command?) (begin (set! slatex::seen-first-command? #t) (slatex::decide-latex-or-tex (or (string=? cs "documentstyle") (string=? cs "documentclass") (string=? cs "NeedsTeXFormat"))))) (cond [(not slatex::*slatex-enabled?*) (if (string=? cs slatex::*slatex-reenabler*) (slatex::enable-slatex-again))] [(string=? cs "slatexignorecurrentfile") (set! done? #t)] [(string=? cs "slatexseparateincludes") (if slatex::*latex?* (set! slatex::*slatex-separate-includes?* #t))] [(string=? cs "slatexdisable") (slatex::disable-slatex-temply in)] [(string=? cs "begin") (slatex::eat-tex-whitespace in) (if (eqv? (peek-char in) #\{) (let ([cs (slatex::read-grouped-latexexp in)]) (cond [(member cs slatex::*display-triggerers*) (slatex::trigger-scheme2tex 'envdisplay in cs)] [(member cs slatex::*response-triggerers*) (slatex::trigger-scheme2tex 'envresponse in cs)] [(member cs slatex::*respbox-triggerers*) (slatex::trigger-scheme2tex 'envrespbox in cs)] [(member cs slatex::*box-triggerers*) (slatex::trigger-scheme2tex 'envbox in cs)] [(member cs slatex::*topbox-triggerers*) (slatex::trigger-scheme2tex 'envtopbox in cs)] [(member cs slatex::*region-triggerers*) (slatex::trigger-region 'envregion in cs)])))] [(member cs slatex::*intext-triggerers*) (slatex::trigger-scheme2tex 'intext in #f)] [(member cs slatex::*resultintext-triggerers*) (slatex::trigger-scheme2tex 'resultintext in #f)] [(member cs slatex::*display-triggerers*) (slatex::trigger-scheme2tex 'plaindisplay in cs)] [(member cs slatex::*response-triggerers*) (slatex::trigger-scheme2tex 'plainresponse in cs)] [(member cs slatex::*respbox-triggerers*) (slatex::trigger-scheme2tex 'plainrespbox in cs)] [(member cs slatex::*box-triggerers*) (slatex::trigger-scheme2tex 'plainbox in cs)] [(member cs slatex::*topbox-triggerers*) (slatex::trigger-scheme2tex 'plaintopbox in cs)] [(member cs slatex::*region-triggerers*) (slatex::trigger-region 'plainregion in cs)] [(member cs slatex::*input-triggerers*) (slatex::process-scheme-file (slatex::read-filename in))] [(string=? cs "input") (let ([f (slatex::read-filename in)]) (if (not (string=? f "")) (fluid-let ([slatex::*slatex-in-protected-region?* #f]) (slatex::process-tex-file f))))] [(string=? cs "usepackage") (fluid-let ([slatex::*slatex-in-protected-region?* #f]) (slatex::process-tex-file (string-append (slatex::read-filename in) ".sty")))] [(string=? cs "include") (if slatex::*latex?* (let ([f (slatex::full-texfile-name (slatex::read-filename in))]) (if (and f (or (eq? slatex::*include-onlys* 'all) (member f slatex::*include-onlys*))) (fluid-let ([slatex::*slatex-in-protected-region?* #f]) (if slatex::*slatex-separate-includes?* (fluid-let ([slatex::subjobname (slatex::basename f)] [slatex::primary-aux-file-count -1]) (slatex::process-tex-file f)) (slatex::process-tex-file f))))))] [(string=? cs "includeonly") (if slatex::*latex?* (slatex::process-include-only in))] [(string=? cs "documentstyle") (if slatex::*latex?* (slatex::process-documentstyle in))] [(string=? cs "documentclass") (if slatex::*latex?* (slatex::process-documentclass in))] [(string=? cs "schemecasesensitive") (slatex::process-case-info in)] [(string=? cs "defschemetoken") (slatex::process-slatex-alias in slatex::adjoin 'intext)] [(string=? cs "undefschemetoken") (slatex::process-slatex-alias in slatex::delete 'intext)] [(string=? cs "defschemeresulttoken") (slatex::process-slatex-alias in slatex::adjoin 'resultintext)] [(string=? cs "undefschemeresulttoken") (slatex::process-slatex-alias in slatex::delete 'resultintext)] [(string=? cs "defschemeresponsetoken") (slatex::process-slatex-alias in slatex::adjoin 'response)] [(string=? cs "undefschemeresponsetoken") (slatex::process-slatex-alias in slatex::delete 'response)] [(string=? cs "defschemeresponseboxtoken") (slatex::process-slatex-alias in slatex::adjoin 'respbox)] [(string=? cs "undefschemeresponseboxtoken") (slatex::process-slatex-alias in slatex::delete 'respbox)] [(string=? cs "defschemedisplaytoken") (slatex::process-slatex-alias in slatex::adjoin 'display)] [(string=? cs "undefschemedisplaytoken") (slatex::process-slatex-alias in slatex::delete 'display)] [(string=? cs "defschemeboxtoken") (slatex::process-slatex-alias in slatex::adjoin 'box)] [(string=? cs "undefschemeboxtoken") (slatex::process-slatex-alias in slatex::delete 'box)] [(string=? cs "defschemetopboxtoken") (slatex::process-slatex-alias in slatex::adjoin 'topbox)] [(string=? cs "undefschemetopboxtoken") (slatex::process-slatex-alias in slatex::delete 'topbox)] [(string=? cs "defschemeinputtoken") (slatex::process-slatex-alias in slatex::adjoin 'input)] [(string=? cs "undefschemeinputtoken") (slatex::process-slatex-alias in slatex::delete 'input)] [(string=? cs "defschemeregiontoken") (slatex::process-slatex-alias in slatex::adjoin 'region)] [(string=? cs "undefschemeregiontoken") (slatex::process-slatex-alias in slatex::delete 'region)] [(string=? cs "defschememathescape") (slatex::process-slatex-alias in slatex::adjoin 'mathescape)] [(string=? cs "undefschememathescape") (slatex::process-slatex-alias in slatex::delete 'mathescape)] [(string=? cs "setkeyword") (slatex::add-to-slatex-db in 'keyword)] [(string=? cs "setconstant") (slatex::add-to-slatex-db in 'constant)] [(string=? cs "setvariable") (slatex::add-to-slatex-db in 'variable)] [(string=? cs "setspecialsymbol") (slatex::add-to-slatex-db in 'setspecialsymbol)] [(string=? cs "unsetspecialsymbol") (slatex::add-to-slatex-db in 'unsetspecialsymbol)]))])) (loop))))))))) (if slatex::debug? (begin (display "end ") (display raw-filename) (newline))))) (define slatex::process-scheme-file (lambda (raw-filename) (let ([filename (slatex::full-scmfile-name raw-filename)]) (if (not filename) (begin (display "process-scheme-file: ") (display raw-filename) (display " doesn't exist") (newline)) (let ([aux.tex (slatex::new-aux-file ".tex")]) (display ".") (flush-output-port) (if (file-exists? aux.tex) (delete-file aux.tex)) (call-with-input-file filename (lambda (in) (call-with-output-file aux.tex (lambda (out) (fluid-let ([slatex::*intext?* #f] [slatex::*code-env-spec* "ZZZZschemedisplay"]) (slatex::scheme2tex in out)))))) (if slatex::*slatex-in-protected-region?* (set! slatex::*protected-files* (cons aux.tex slatex::*protected-files*))) (slatex::process-tex-file filename)))))) (define slatex::trigger-scheme2tex (lambda (typ in env) (let* ([aux (slatex::new-aux-file)] [aux.scm (string-append aux ".scm")] [aux.tex (string-append aux ".tex")]) (if (file-exists? aux.scm) (delete-file aux.scm)) (if (file-exists? aux.tex) (delete-file aux.tex)) (display ".") (flush-output-port) (call-with-output-file aux.scm (lambda (out) (cond [(memq typ '(intext resultintext)) (slatex::dump-intext in out)] [(memq typ '(envdisplay envresponse envrespbox envbox envtopbox)) (slatex::dump-display in out (string-append "\\end{" env "}"))] [(memq typ '(plaindisplay plainresponse plainrespbox plainbox plaintopbox)) (slatex::dump-display in out (string-append "\\end" env))] [else (slatex::slatex-error "trigger-scheme2tex: ~\n Unknown triggerer ~s." typ)]))) (call-with-input-file aux.scm (lambda (in) (call-with-output-file aux.tex (lambda (out) (fluid-let ([slatex::*intext?* (memq typ '(intext resultintext))] [slatex::*code-env-spec* (cond [(eq? typ 'intext) "ZZZZschemecodeintext"] [(eq? typ 'resultintext) "ZZZZschemeresultintext"] [(memq typ '(envdisplay plaindisplay)) "ZZZZschemedisplay"] [(memq typ '(envresponse plainresponse)) "ZZZZschemeresponse"] [(memq typ '(envrespbox plainrespbox)) "ZZZZschemeresponsebox"] [(memq typ '(envbox plainbox)) "ZZZZschemebox"] [(memq typ '(envtopbox plaintopbox)) "ZZZZschemetopbox"] [else (slatex::slatex-error "trigger-scheme2tex: ~\n Unknown triggerer ~s." typ)])]) (slatex::scheme2tex in out)))))) (if slatex::*slatex-in-protected-region?* (set! slatex::*protected-files* (cons aux.tex slatex::*protected-files*))) (if (memq typ '(envdisplay plaindisplay envbox plainbox envtopbox plaintopbox)) (slatex::process-tex-file aux.tex)) (delete-file aux.scm)))) (define slatex::trigger-region (lambda (typ in env) (let ([aux.tex (slatex::new-primary-aux-file ".tex")] [aux2.tex (slatex::new-secondary-aux-file ".tex")]) (if (file-exists? aux2.tex) (delete-file aux2.tex)) (if (file-exists? aux.tex) (delete-file aux.tex)) (display ".") (flush-output-port) (fluid-let ([slatex::*slatex-in-protected-region?* #t] [slatex::*protected-files* '()]) (call-with-output-file aux2.tex (lambda (out) (cond [(eq? typ 'envregion) (slatex::dump-display in out (string-append "\\end{" env "}"))] [(eq? typ 'plainregion) (slatex::dump-display in out (string-append "\\end" env))] [else (slatex::slatex-error "trigger-region: ~\nUnknown triggerer ~s." typ)]))) (slatex::process-tex-file aux2.tex) (set! slatex::*protected-files* (reverse! slatex::*protected-files*)) (call-with-input-file aux2.tex (lambda (in) (call-with-output-file aux.tex (lambda (out) (slatex::inline-protected-files in out))))) (delete-file aux2.tex))))) (define slatex::inline-protected-files (lambda (in out) (let ([done? #f]) (let loop () (if done? 'exit-loop (begin (let ([c (read-char in)]) (cond [(eof-object? c) (set! done? #t)] [(or (char=? c slatex::*return*) (char=? c #\newline)) (let ([c2 (peek-char in)]) (if (not (eof-object? c2)) (write-char c out)))] [(char=? c #\%) (write-char c out) (newline out) (slatex::eat-till-newline in)] [(char=? c #\\) (let ([cs (slatex::read-ctrl-seq in)]) (cond [(string=? cs "begin") (let ([cs (slatex::read-grouped-latexexp in)]) (cond [(member cs slatex::*display-triggerers*) (slatex::inline-protected 'envdisplay in out cs)] [(member cs slatex::*response-triggerers*) (slatex::inline-protected 'envresponse in out cs)] [(member cs slatex::*respbox-triggerers*) (slatex::inline-protected 'envrespbox in out cs)] [(member cs slatex::*box-triggerers*) (slatex::inline-protected 'envbox in out cs)] [(member cs slatex::*topbox-triggerers*) (slatex::inline-protected 'envtopbox in out cs)] [(member cs slatex::*region-triggerers*) (slatex::inline-protected 'envregion in out cs)] [else (display "\\begin{" out) (display cs out) (display "}" out)]))] [(member cs slatex::*intext-triggerers*) (slatex::inline-protected 'intext in out #f)] [(member cs slatex::*resultintext-triggerers*) (slatex::inline-protected 'resultintext in out #f)] [(member cs slatex::*display-triggerers*) (slatex::inline-protected 'plaindisplay in out cs)] [(member cs slatex::*response-triggerers*) (slatex::inline-protected 'plainresponse in out cs)] [(member cs slatex::*respbox-triggerers*) (slatex::inline-protected 'plainrespbox in out cs)] [(member cs slatex::*box-triggerers*) (slatex::inline-protected 'plainbox in out cs)] [(member cs slatex::*topbox-triggerers*) (slatex::inline-protected 'plaintopbox in out cs)] [(member cs slatex::*region-triggerers*) (slatex::inline-protected 'plainregion in out cs)] [(member cs slatex::*input-triggerers*) (slatex::inline-protected 'input in out cs)] [else (display "\\" out) (display cs out)]))] [else (write-char c out)])) (loop))))))) (define slatex::inline-protected (lambda (typ in out env) (cond [(eq? typ 'envregion) (display "\\begin{" out) (display env out) (display "}" out) (slatex::dump-display in out (string-append "\\end{" env "}")) (display "\\end{" out) (display env out) (display "}" out)] [(eq? typ 'plainregion) (display "\\" out) (display env out) (slatex::dump-display in out (string-append "\\end" env)) (display "\\end" out) (display env out)] [else (let ([f (car slatex::*protected-files*)]) (set! slatex::*protected-files* (cdr slatex::*protected-files*)) (call-with-input-file f (lambda (in) (slatex::inline-protected-files in out))) (delete-file f)) (cond [(memq typ '(intext resultintext)) (display "{}" out) (slatex::dump-intext in #f)] [(memq typ '(envrespbox envbox envtopbox)) (if (not slatex::*latex?*) (display "{}" out)) (slatex::dump-display in #f (string-append "\\end{" env "}"))] [(memq typ '(plainrespbox plainbox plaintopbox)) (display "{}" out) (slatex::dump-display in #f (string-append "\\end" env))] [(memq typ '(envdisplay envresponse)) (slatex::dump-display in #f (string-append "\\end{" env "}"))] [(memq typ '(plaindisplay plainresponse)) (slatex::dump-display in #f (string-append "\\end" env))] [(eq? typ 'input) (slatex::read-filename in)] [else (slatex::slatex-error "inline-protected: ~\nUnknown triggerer ~s." typ)])])))
null
https://raw.githubusercontent.com/webyrd/untitled-relational-interpreter-book/247e29afd224586c39c1983e042524c7cc9fe17b/latex/slatex/slatex.scm
scheme
/~dorai/scmxlate/scmxlate.html ) ) ))))) )]) ]
Configured for Scheme dialect petite by scmxlate , v 20120421 , ( c ) , (define slatex::*slatex-version* "20090928") (define slatex::*operating-system* (if (getenv "COMSPEC") 'windows 'unix)) (define-syntax slatex::defenum (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let loop ([z (cdr so-d)] [i 0] [r '()]) (if (null? z) `(begin ,@r) (loop (cdr z) (+ i 1) (cons `(define (unquote (car z)) (integer->char ,i)) r))))))))) (define-syntax slatex::defrecord (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let ([name (cadr so-d)] [fields (cddr so-d)]) (let loop ([fields fields] [i 0] [r '()]) (if (null? fields) `(begin (define (unquote name) (lambda () (make-vector ,i))) ,@r) (loop (cdr fields) (+ i 1) (cons `(define (unquote (car fields)) ,i) r)))))))))) (define-syntax slatex::setf (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let ([l (cadr so-d)] [r (caddr so-d)]) (if (symbol? l) `(set! ,l ,r) (let ([a (car l)]) (if (eq? a 'list-ref) `(set-car! (list-tail ,@(cdr l)) ,r) `(,(cond [(eq? a 'string-ref) 'string-set!] [(eq? a 'vector-ref) 'vector-set!] [(eq? a 'slatex::of) 'slatex::the-setter-for-of] [else (slatex::slatex-error "setf is ill-formed" l r)]) ,@(cdr l) ,r)))))))))) (define-syntax slatex::the-setter-for-of (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let ([r (cadr so-d)] [i (caddr so-d)] [j (cadddr so-d)] [z (cddddr so-d)]) (cond [(null? z) `(vector-set! ,r ,i ,j)] [(and (eq? i '/) (= (length z) 1)) `(string-set! ,r ,j ,(car z))] [else `(slatex::the-setter-for-of (vector-ref ,r ,i) ,j ,@z)]))))))) (define-syntax slatex::of (let* ([old-datum->syntax-object datum->syntax-object] [datum->syntax (lambda (so output) (old-datum->syntax-object (syntax-case so () [(k . stuff) #'k]) output))]) (lambda (so) (datum->syntax so (let ([so-d (syntax->datum so)]) (let ([r (cadr so-d)] [i (caddr so-d)] [z (cdddr so-d)]) (cond [(null? z) `(vector-ref ,r ,i)] [(and (eq? i '/) (= (length z) 1)) `(string-ref ,r ,(car z))] [else `(slatex::of (vector-ref ,r ,i) ,@z)]))))))) (define slatex::ormapcdr (lambda (f l) (let loop ([l l]) (if (null? l) #f (or (f l) (loop (cdr l))))))) (define slatex::list-prefix? (lambda (pfx l) (cond [(null? pfx) #t] [(null? l) #f] [(eqv? (car pfx) (car l)) (slatex::list-prefix? (cdr pfx) (cdr l))] [else #f]))) (define slatex::string-suffix? (lambda (sfx s) (let ([sfx-len (string-length sfx)] [s-len (string-length s)]) (if (> sfx-len s-len) #f (let loop ([i (- sfx-len 1)] [j (- s-len 1)]) (if (< i 0) #t (and (char=? (string-ref sfx i) (string-ref s j)) (loop (- i 1) (- j 1))))))))) (define slatex::mapcan (lambda (f l) (let loop ([l l]) (if (null? l) '() (append! (f (car l)) (loop (cdr l))))))) (define slatex::lassoc (lambda (x al eq) (let loop ([al al]) (if (null? al) #f (let ([c (car al)]) (if (eq (car c) x) c (loop (cdr al)))))))) (define slatex::lmember (lambda (x l eq) (let loop ([l l]) (if (null? l) #f (if (eq (car l) x) l (loop (cdr l))))))) (define slatex::delete (lambda (x l eq) (let loop ([l l]) (cond [(null? l) l] [(eq (car l) x) (loop (cdr l))] [else (set-cdr! l (loop (cdr l))) l])))) (define slatex::adjoin (lambda (x l eq) (if (slatex::lmember x l eq) l (cons x l)))) (define slatex::delete-if (lambda (p s) (let loop ([s s]) (cond [(null? s) s] [(p (car s)) (loop (cdr s))] [else (set-cdr! s (loop (cdr s))) s])))) (define slatex::string-prefix? (lambda (s1 s2 i) (let loop ([j 0]) (if (= j i) #t (and (char=? (string-ref s1 j) (string-ref s2 j)) (loop (+ j 1))))))) (define slatex::sublist (lambda (l i f) (let loop ([l (list-tail l i)] [k i] [r '()]) (cond [(>= k f) (reverse! r)] [(null? l) (slatex::slatex-error "sublist: List too small")] [else (loop (cdr l) (+ k 1) (cons (car l) r))])))) (define slatex::position-char (lambda (c l) (let loop ([l l] [i 0]) (cond [(null? l) #f] [(char=? (car l) c) i] [else (loop (cdr l) (+ i 1))])))) (define slatex::string-position-right (lambda (c s) (let ([n (string-length s)]) (let loop ([i (- n 1)]) (cond [(< i 0) #f] [(char=? (string-ref s i) c) i] [else (loop (- i 1))]))))) (define slatex::*return* (integer->char 13)) (define slatex::*tab* (integer->char 9)) (define slatex::slatex-error (lambda (where . what) (display "Error: ") (display where) (newline) (for-each (lambda (v) (write v) (newline)) what) (error "slatex-error"))) (define slatex::exit-slatex (lambda () (exit))) (define slatex::*slatex-case-sensitive?* #t) (define slatex::keyword-tokens (list "=>" "%" "abort" "and" "begin" "begin0" "case" "case-lambda" "cond" "define" "define!" "define-macro!" "define-syntax" "defmacro" "defrec!" "delay" "do" "else" "extend-syntax" "fluid-let" "if" "lambda" "let" "let*" "letrec" "let-syntax" "letrec-syntax" "or" "quasiquote" "quote" "rec" "record-case" "record-evcase" "recur" "set!" "sigma" "struct" "syntax" "syntax-rules" "trace" "trace-lambda" "trace-let" "trace-recur" "unless" "unquote" "unquote-splicing" "untrace" "when" "with")) (define slatex::variable-tokens '()) (define slatex::constant-tokens '()) (define slatex::data-tokens '()) (define slatex::special-symbols (reverse (reverse '(("." . ".") ("..." . "{\\dots}") ("-" . "$-$") ("1-" . "\\va{1$-$}") ("-1+" . "\\va{$-$1$+$}"))))) (define slatex::macro-definers '("define-syntax" "syntax-rules" "defmacro" "extend-syntax" "define-macro!")) (define slatex::case-and-ilk '("case" "record-case")) (define slatex::tex-analog (lambda (c) (case c [(#\$ #\& #\% #\# #\_) (string #\\ c)] [(#\{ #\}) (string #\$ #\\ c #\$)] [(#\\) "$\\backslash$"] [(#\+) "$+$"] [(#\*) "$\\ast$"] [(#\=) "$=$"] [(#\<) "$\\lt$"] [(#\>) "$\\gt$"] [(#\^) "\\^{}"] [(#\|) "$\\vert$"] [(#\~) "\\~{}"] [(#\@) "{\\atsign}"] [(#\") "{\\dq}"] [else (string c)]))) (define slatex::token=? (lambda (t1 t2) ((if slatex::*slatex-case-sensitive?* string=? string-ci=?) t1 t2))) (define slatex::*slatex-enabled?* #t) (define slatex::*slatex-reenabler* "UNDEFINED") (define slatex::*intext-triggerers* (list "scheme")) (define slatex::*resultintext-triggerers* (list "schemeresult")) (define slatex::*display-triggerers* (list "schemedisplay")) (define slatex::*response-triggerers* (list "schemeresponse")) (define slatex::*respbox-triggerers* (list "schemeresponsebox")) (define slatex::*box-triggerers* (list "schemebox")) (define slatex::*topbox-triggerers* (list "schemetopbox")) (define slatex::*input-triggerers* (list "schemeinput")) (define slatex::*region-triggerers* (list "schemeregion")) (define slatex::*math-triggerers* '()) (define slatex::*slatex-in-protected-region?* #f) (define slatex::*protected-files* '()) (define slatex::*include-onlys* 'all) (define slatex::*latex?* #t) (define slatex::*slatex-separate-includes?* #f) (define slatex::*tex-calling-directory* "") (define slatex::*max-line-length* 300) (slatex::defenum &void-space &plain-space &init-space &init-plain-space &paren-space &bracket-space &quote-space &inner-space) (slatex::defenum &void-tab &set-tab &move-tab &tabbed-crg-ret &plain-crg-ret) (slatex::defenum &void-notab &begin-comment &mid-comment &begin-string &mid-string &end-string &begin-math &mid-math &end-math) (slatex::defrecord slatex::make-raw-line slatex::=rtedge slatex::=char slatex::=space slatex::=tab slatex::=notab) (define slatex::make-line (lambda () (let ([l (slatex::make-raw-line)]) (slatex::setf (slatex::of l slatex::=rtedge) 0) (slatex::setf (slatex::of l slatex::=char) (make-string slatex::*max-line-length* #\space)) (slatex::setf (slatex::of l slatex::=space) (make-string slatex::*max-line-length* &void-space)) (slatex::setf (slatex::of l slatex::=tab) (make-string slatex::*max-line-length* &void-tab)) (slatex::setf (slatex::of l slatex::=notab) (make-string slatex::*max-line-length* &void-notab)) l))) (define slatex::*line1* (slatex::make-line)) (define slatex::*line2* (slatex::make-line)) (slatex::defrecord slatex::make-case-frame slatex::=in-ctag-tkn slatex::=in-bktd-ctag-exp slatex::=in-case-exp) (slatex::defrecord slatex::make-bq-frame slatex::=in-comma slatex::=in-bq-tkn slatex::=in-bktd-bq-exp) (define slatex::*latex-paragraph-mode?* 'fwd1) (define slatex::*intext?* 'fwd2) (define slatex::*code-env-spec* "UNDEFINED") (define slatex::*in* 'fwd3) (define slatex::*out* 'fwd4) (define slatex::*in-qtd-tkn* 'fwd5) (define slatex::*in-bktd-qtd-exp* 'fwd6) (define slatex::*in-mac-tkn* 'fwd7) (define slatex::*in-bktd-mac-exp* 'fwd8) (define slatex::*case-stack* 'fwd9) (define slatex::*bq-stack* 'fwd10) (define slatex::display-space (lambda (s p) (cond [(eq? s &plain-space) (display #\space p)] [(eq? s &init-plain-space) (display #\space p)] [(eq? s &init-space) (display "\\HL " p)] [(eq? s &paren-space) (display "\\PRN " p)] [(eq? s &bracket-space) (display "\\BKT " p)] [(eq? s &quote-space) (display "\\QUO " p)] [(eq? s &inner-space) (display "\\ " p)]))) (define slatex::display-tab (lambda (tab p) (cond [(eq? tab &set-tab) (display "\\=" p)] [(eq? tab &move-tab) (display "\\>" p)]))) (define slatex::display-notab (lambda (notab p) (cond [(eq? notab &begin-string) (display "\\dt{" p)] [(eq? notab &end-string) (display "}" p)]))) (define slatex::prim-data-token? (lambda (token) (or (char=? (string-ref token 0) #\#) (string->number token)))) (define slatex::set-keyword (lambda (x) (if (not (slatex::lmember x slatex::keyword-tokens slatex::token=?)) (begin (set! slatex::constant-tokens (slatex::delete x slatex::constant-tokens slatex::token=?)) (set! slatex::variable-tokens (slatex::delete x slatex::variable-tokens slatex::token=?)) (set! slatex::data-tokens (slatex::delete x slatex::data-tokens slatex::token=?)) (set! slatex::keyword-tokens (cons x slatex::keyword-tokens)))))) (define slatex::set-constant (lambda (x) (if (not (slatex::lmember x slatex::constant-tokens slatex::token=?)) (begin (set! slatex::keyword-tokens (slatex::delete x slatex::keyword-tokens slatex::token=?)) (set! slatex::variable-tokens (slatex::delete x slatex::variable-tokens slatex::token=?)) (set! slatex::data-tokens (slatex::delete x slatex::data-tokens slatex::token=?)) (set! slatex::constant-tokens (cons x slatex::constant-tokens)))))) (define slatex::set-variable (lambda (x) (if (not (slatex::lmember x slatex::variable-tokens slatex::token=?)) (begin (set! slatex::keyword-tokens (slatex::delete x slatex::keyword-tokens slatex::token=?)) (set! slatex::constant-tokens (slatex::delete x slatex::constant-tokens slatex::token=?)) (set! slatex::data-tokens (slatex::delete x slatex::data-tokens slatex::token=?)) (set! slatex::variable-tokens (cons x slatex::variable-tokens)))))) (define slatex::set-data (lambda (x) (if (not (slatex::lmember x slatex::data-tokens slatex::token=?)) (begin (set! slatex::keyword-tokens (slatex::delete x slatex::keyword-tokens slatex::token=?)) (set! slatex::constant-tokens (slatex::delete x slatex::constant-tokens slatex::token=?)) (set! slatex::variable-tokens (slatex::delete x slatex::variable-tokens slatex::token=?)) (set! slatex::data-tokens (cons x slatex::data-tokens)))))) (define slatex::set-special-symbol (lambda (x transl) (let ([c (slatex::lassoc x slatex::special-symbols slatex::token=?)]) (if c (set-cdr! c transl) (set! slatex::special-symbols (cons (cons x transl) slatex::special-symbols)))))) (define slatex::unset-special-symbol (lambda (x) (set! slatex::special-symbols (slatex::delete-if (lambda (c) (slatex::token=? (car c) x)) slatex::special-symbols)))) (define slatex::texify (lambda (s) (list->string (slatex::texify-aux s)))) (define slatex::texify-data (lambda (s) (let loop ([l (slatex::texify-aux s)] [r '()]) (if (null? l) (list->string (reverse! r)) (let ([c (car l)]) (loop (cdr l) (if (char=? c #\-) (append! (list #\$ c #\$) r) (cons c r)))))))) (define slatex::texify-aux (let ([arrow (string->list "-$>$")] [em-dash (string->list "---")] [en-dash (string->list "--")] [arrow2 (string->list "$\\to$")] [em-dash-2 (string->list "${-}{-}{-}$")] [en-dash-2 (string->list "${-}{-}$")]) (lambda (s) (let ([texified-sl (slatex::mapcan (lambda (c) (string->list (slatex::tex-analog c))) (string->list s))]) (let loop ([d texified-sl]) (cond [(null? d) #f] [(slatex::list-prefix? arrow d) (let ([d2 (list-tail d 4)]) (set-car! d (car arrow2)) (set-cdr! d (append (cdr arrow2) d2)) (loop d2))] [(slatex::list-prefix? em-dash d) (let ([d2 (list-tail d 3)]) (set-car! d (car em-dash-2)) (set-cdr! d (append (cdr em-dash-2) d2)) (loop d2))] [(slatex::list-prefix? en-dash d) (let ([d2 (list-tail d 2)]) (set-car! d (car en-dash-2)) (set-cdr! d (append (cdr en-dash-2) d2)) (loop d2))] [else (loop (cdr d))])) texified-sl)))) (define slatex::display-begin-sequence (lambda (out) (if (or slatex::*intext?* (not slatex::*latex?*)) (begin (display "\\" out) (display slatex::*code-env-spec* out) (newline out)) (begin (display "\\begin{" out) (display slatex::*code-env-spec* out) (display "}%" out) (newline out))))) (define slatex::display-end-sequence (lambda (out) (cond [slatex::*intext?* (display "\\end" out) (display slatex::*code-env-spec* out) (newline out)] [slatex::*latex?* (display "\\end{" out) (display slatex::*code-env-spec* out) (display "}" out) (newline out)] [else (display "\\end" out) (display slatex::*code-env-spec* out) (newline out)]))) (define slatex::display-tex-char (lambda (c p) (display (if (char? c) (slatex::tex-analog c) c) p))) (define slatex::display-token (lambda (s typ p) (cond [(eq? typ 'syntax) (display "\\sy{" p) (display (slatex::texify s) p) (display "}" p)] [(eq? typ 'variable) (display "\\va{" p) (display (slatex::texify s) p) (display "}" p)] [(eq? typ 'constant) (display "\\cn{" p) (display (slatex::texify s) p) (display "}" p)] [(eq? typ 'data) (display "\\dt{" p) (display (slatex::texify-data s) p) (display "}" p)] [else (slatex::slatex-error 'slatex::display-token "Unknown token type" typ)]))) (define slatex::get-line (let ([curr-notab &void-notab]) (lambda (line) (let ([graphic-char-seen? #f]) (let loop ([i 0]) (let ([c (read-char slatex::*in*)]) (cond [graphic-char-seen? (void)] [(or (eof-object? c) (char=? c slatex::*return*) (char=? c #\newline) (char=? c #\space) (char=? c slatex::*tab*)) (void)] [else (set! graphic-char-seen? #t)]) (cond [(eof-object? c) (cond [(eq? curr-notab &mid-string) (if (> i 0) (slatex::setf (slatex::of line slatex::=notab / (- i 1)) &end-string))] [(eq? curr-notab &mid-comment) (set! curr-notab &void-notab)] [(eq? curr-notab &mid-math) (slatex::slatex-error 'slatex::get-line "Found eof inside math")]) (slatex::setf (slatex::of line slatex::=char / i) #\newline) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (slatex::setf (slatex::of line slatex::=rtedge) i) (if (eq? (slatex::of line slatex::=notab / 0) &mid-string) (slatex::setf (slatex::of line slatex::=notab / 0) &begin-string)) (if (= i 0) #f #t)] [(or (char=? c slatex::*return*) (char=? c #\newline)) (if (and (memv slatex::*operating-system* '(dos windows os2 os2fat)) (char=? c slatex::*return*)) (if (char=? (peek-char slatex::*in*) #\newline) (read-char slatex::*in*))) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (cond [(eq? curr-notab &mid-string) (slatex::setf (slatex::of line slatex::=notab / i) &end-string)] [(eq? curr-notab &mid-comment) (set! curr-notab &void-notab)] [(eq? curr-notab &mid-math) (slatex::slatex-error 'slatex::get-line "Sorry, you can't split " "math formulas across lines in Scheme code")]) (slatex::setf (slatex::of line slatex::=char / i) #\newline) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) (cond [(eof-object? (peek-char slatex::*in*)) &plain-crg-ret] [slatex::*intext?* &plain-crg-ret] [else &tabbed-crg-ret])) (slatex::setf (slatex::of line slatex::=rtedge) i) (if (eq? (slatex::of line slatex::=notab / 0) &mid-string) (slatex::setf (slatex::of line slatex::=notab / 0) &begin-string)) #t] [(eq? curr-notab &mid-comment) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) (cond [(char=? c #\space) &plain-space] [(char=? c slatex::*tab*) &plain-space] [else &void-space])) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &mid-comment) (loop (+ i 1))] [(char=? c #\\) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) curr-notab) (let ([i+1 (+ i 1)] [c+1 (read-char slatex::*in*)]) (if (char=? c+1 slatex::*tab*) (set! c+1 #\space)) (slatex::setf (slatex::of line slatex::=char / i+1) c+1) (slatex::setf (slatex::of line slatex::=space / i+1) (if (char=? c+1 #\space) &plain-space &void-space)) (slatex::setf (slatex::of line slatex::=tab / i+1) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i+1) curr-notab) (loop (+ i+1 1)))] [(eq? curr-notab &mid-math) (if (char=? c slatex::*tab*) (set! c #\space)) (slatex::setf (slatex::of line slatex::=space / i) (if (char=? c #\space) &plain-space &void-space)) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (cond [(memv c slatex::*math-triggerers*) (slatex::setf (slatex::of line slatex::=char / i) #\$) (slatex::setf (slatex::of line slatex::=notab / i) &end-math) (slatex::setf curr-notab &void-notab)] [else (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=notab / i) &mid-math)]) (loop (+ i 1))] [(eq? curr-notab &mid-string) (if (char=? c slatex::*tab*) (set! c #\space)) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) (if (char=? c #\space) &inner-space &void-space)) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) (cond [(char=? c #\") (set! curr-notab &void-notab) &end-string] [else &mid-string])) (loop (+ i 1))] [(char=? c #\space) (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) (cond [slatex::*intext?* &plain-space] [graphic-char-seen? &inner-space] [else &init-space])) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (loop (+ i 1))] [(char=? c slatex::*tab*) (let loop1 ([i i] [j 0]) (if (< j 8) (begin (slatex::setf (slatex::of line slatex::=char / i) #\space) (slatex::setf (slatex::of line slatex::=space / i) (cond [slatex::*intext?* &plain-space] [graphic-char-seen? &inner-space] [else &init-space])) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (loop1 (+ i 1) (+ j 1))))) (loop (+ i 8))] [(char=? c #\") (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &begin-string) (set! curr-notab &mid-string) (loop (+ i 1))] (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &begin-comment) (set! curr-notab &mid-comment) (loop (+ i 1))] [(memv c slatex::*math-triggerers*) (slatex::setf (slatex::of line slatex::=char / i) #\$) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &begin-math) (set! curr-notab &mid-math) (loop (+ i 1))] [else (slatex::setf (slatex::of line slatex::=char / i) c) (slatex::setf (slatex::of line slatex::=space / i) &void-space) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=notab / i) &void-notab) (loop (+ i 1))]))))))) (define slatex::peephole-adjust (lambda (curr prev) (if (or (slatex::blank-line? curr) (slatex::flush-comment-line? curr)) (if (not slatex::*latex-paragraph-mode?*) (begin (set! slatex::*latex-paragraph-mode?* #t) (if (not slatex::*intext?*) (begin (slatex::remove-some-tabs prev 0) (let ([prev-rtedge (slatex::of prev slatex::=rtedge)]) (if (eq? (slatex::of prev slatex::=tab / prev-rtedge) &tabbed-crg-ret) (slatex::setf (slatex::of prev slatex::=tab / (slatex::of prev slatex::=rtedge)) &plain-crg-ret))))))) (begin (if slatex::*latex-paragraph-mode?* (set! slatex::*latex-paragraph-mode?* #f) (if (not slatex::*intext?*) (let ([remove-tabs-from #f]) (let loop ([i 0]) (cond [(char=? (slatex::of curr slatex::=char / i) #\newline) (set! remove-tabs-from i)] [(char=? (slatex::of prev slatex::=char / i) #\newline) (set! remove-tabs-from #f)] [(eq? (slatex::of curr slatex::=space / i) &init-space) (if (eq? (slatex::of prev slatex::=notab / i) &void-notab) (begin (cond [(or (char=? (slatex::of prev slatex::=char / i) #\() (eq? (slatex::of prev slatex::=space / i) &paren-space)) (slatex::setf (slatex::of curr slatex::=space / i) &paren-space)] [(or (char=? (slatex::of prev slatex::=char / i) #\[) (eq? (slatex::of prev slatex::=space / i) &bracket-space)) (slatex::setf (slatex::of curr slatex::=space / i) &bracket-space)] [(or (memv (slatex::of prev slatex::=char / i) '(#\' #\` #\,)) (eq? (slatex::of prev slatex::=space / i) &quote-space)) (slatex::setf (slatex::of curr slatex::=space / i) &quote-space)]) (if (memq (slatex::of prev slatex::=tab / i) (list &set-tab &move-tab)) (slatex::setf (slatex::of curr slatex::=tab / i) &move-tab)))) (loop (+ i 1))] [(= i 0) (set! remove-tabs-from 0)] [(not (eq? (slatex::of prev slatex::=tab / i) &void-tab)) (set! remove-tabs-from (+ i 1)) (if (memq (slatex::of prev slatex::=tab / i) (list &set-tab &move-tab)) (slatex::setf (slatex::of curr slatex::=tab / i) &move-tab))] [(memq (slatex::of prev slatex::=space / i) (list &init-space &init-plain-space &paren-space &bracket-space &quote-space)) (set! remove-tabs-from (+ i 1))] [(and (char=? (slatex::of prev slatex::=char / (- i 1)) #\space) (eq? (slatex::of prev slatex::=notab / (- i 1)) &void-notab)) (set! remove-tabs-from (+ i 1)) (slatex::setf (slatex::of prev slatex::=tab / i) &set-tab) (slatex::setf (slatex::of curr slatex::=tab / i) &move-tab)] [else (set! remove-tabs-from (+ i 1)) (let loop1 ([j (- i 1)]) (cond [(<= j 0) 'exit-loop1] [(not (eq? (slatex::of curr slatex::=tab / j) &void-tab)) 'exit-loop1] [(memq (slatex::of curr slatex::=space / j) (list &paren-space &bracket-space &quote-space)) (loop1 (- j 1))] [(or (not (eq? (slatex::of prev slatex::=notab / j) &void-notab)) (char=? (slatex::of prev slatex::=char / j) #\space)) (let ([k (+ j 1)]) (if (not (memq (slatex::of prev slatex::=notab / k) (list &mid-comment &mid-math &end-math &mid-string &end-string))) (begin (if (eq? (slatex::of prev slatex::=tab / k) &void-tab) (slatex::setf (slatex::of prev slatex::=tab / k) &set-tab)) (slatex::setf (slatex::of curr slatex::=tab / k) &move-tab))))] [else 'anything-else?]))])) (slatex::remove-some-tabs prev remove-tabs-from)))) (if (not slatex::*intext?*) (slatex::add-some-tabs curr)) (slatex::clean-init-spaces curr) (slatex::clean-inner-spaces curr))))) (define slatex::add-some-tabs (lambda (line) (let loop ([i 1] [succ-parens? #f]) (let ([c (slatex::of line slatex::=char / i)]) (cond [(char=? c #\newline) 'exit-loop] [(not (eq? (slatex::of line slatex::=notab / i) &void-notab)) (loop (+ i 1) #f)] [(char=? c #\[) (if (eq? (slatex::of line slatex::=tab / i) &void-tab) (slatex::setf (slatex::of line slatex::=tab / i) &set-tab)) (loop (+ i 1) #f)] [(char=? c #\() (if (eq? (slatex::of line slatex::=tab / i) &void-tab) (if (not succ-parens?) (slatex::setf (slatex::of line slatex::=tab / i) &set-tab))) (loop (+ i 1) #t)] [else (loop (+ i 1) #f)]))))) (define slatex::remove-some-tabs (lambda (line i) (if i (let loop ([i i]) (cond [(char=? (slatex::of line slatex::=char / i) #\newline) 'exit] [(eq? (slatex::of line slatex::=tab / i) &set-tab) (slatex::setf (slatex::of line slatex::=tab / i) &void-tab) (loop (+ i 1))] [else (loop (+ i 1))]))))) (define slatex::clean-init-spaces (lambda (line) (let loop ([i (slatex::of line slatex::=rtedge)]) (cond [(< i 0) 'exit-loop] [(eq? (slatex::of line slatex::=tab / i) &move-tab) (let loop1 ([i (- i 1)]) (cond [(< i 0) 'exit-loop1] [(memq (slatex::of line slatex::=space / i) (list &init-space &paren-space &bracket-space &quote-space)) (slatex::setf (slatex::of line slatex::=space / i) &init-plain-space) (loop1 (- i 1))] [else (loop1 (- i 1))]))] [else (loop (- i 1))])))) (define slatex::clean-inner-spaces (lambda (line) (let loop ([i 0] [succ-inner-spaces? #f]) (cond [(char=? (slatex::of line slatex::=char / i) #\newline) 'exit-loop] [(eq? (slatex::of line slatex::=space / i) &inner-space) (if (not succ-inner-spaces?) (slatex::setf (slatex::of line slatex::=space / i) &plain-space)) (loop (+ i 1) #t)] [else (loop (+ i 1) #f)])))) (define slatex::blank-line? (lambda (line) (let loop ([i 0]) (let ([c (slatex::of line slatex::=char / i)]) (cond [(char=? c #\space) (if (eq? (slatex::of line slatex::=notab / i) &void-notab) (loop (+ i 1)) #f)] [(char=? c #\newline) (let loop1 ([j (- i 1)]) (if (not (<= j 0)) (begin (slatex::setf (slatex::of line slatex::=space / i) &void-space) (loop1 (- j 1))))) #t] [else #f]))))) (define slatex::flush-comment-line? (lambda (line) (eq? (slatex::of line slatex::=notab / 0) &begin-comment) (define slatex::display-tex-line (lambda (line) (cond [else (let loop ([i (if (slatex::flush-comment-line? line) 1 0)]) (let ([c (slatex::of line slatex::=char / i)]) (if (char=? c #\newline) (if (not (eq? (slatex::of line slatex::=tab / i) &void-tab)) (newline slatex::*out*)) (begin (write-char c slatex::*out*) (loop (+ i 1))))))]))) (define slatex::display-scm-line (lambda (line) (let loop ([i 0]) (let ([c (slatex::of line slatex::=char / i)]) (cond [(char=? c #\newline) (let ([notab (slatex::of line slatex::=notab / i)] [tab (slatex::of line slatex::=tab / i)]) (if (eq? notab &end-string) (display "}" slatex::*out*)) (cond [(eq? tab &tabbed-crg-ret) (display "\\\\%" slatex::*out*) (newline slatex::*out*)] [(eq? tab &plain-crg-ret) (newline slatex::*out*)] [(eq? tab &void-tab) (write-char #\% slatex::*out*) (newline slatex::*out*)]))] [(eq? (slatex::of line slatex::=notab / i) &begin-comment) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &mid-comment) (write-char c slatex::*out*) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &begin-string) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (display "\\dt{" slatex::*out*) (if (char=? c #\space) (slatex::display-space (slatex::of line slatex::=space / i) slatex::*out*) (slatex::display-tex-char c slatex::*out*)) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &mid-string) (if (char=? c #\space) (slatex::display-space (slatex::of line slatex::=space / i) slatex::*out*) (slatex::display-tex-char c slatex::*out*)) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &end-string) (if (char=? c #\space) (slatex::display-space (slatex::of line slatex::=space / i) slatex::*out*) (slatex::display-tex-char c slatex::*out*)) (write-char #\} slatex::*out*) (if slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (if slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f))) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &begin-math) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &mid-math) (write-char c slatex::*out*) (loop (+ i 1))] [(eq? (slatex::of line slatex::=notab / i) &end-math) (write-char c slatex::*out*) (if slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (if slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f))) (loop (+ i 1))] [(char=? c #\space) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (slatex::display-space (slatex::of line slatex::=space / i) slatex::*out*) (loop (+ i 1))] [(char=? c #\') (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (if (or slatex::*in-qtd-tkn* (> slatex::*in-bktd-qtd-exp* 0) (and (pair? slatex::*bq-stack*) (not (slatex::of (car slatex::*bq-stack*) slatex::=in-comma)))) #f (set! slatex::*in-qtd-tkn* #t)) (loop (+ i 1))] [(char=? c #\`) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (if (or (null? slatex::*bq-stack*) (slatex::of (car slatex::*bq-stack*) slatex::=in-comma)) (set! slatex::*bq-stack* (cons (let ([f (slatex::make-bq-frame)]) (slatex::setf (slatex::of f slatex::=in-comma) #f) (slatex::setf (slatex::of f slatex::=in-bq-tkn) #t) (slatex::setf (slatex::of f slatex::=in-bktd-bq-exp) 0) f) slatex::*bq-stack*))) (loop (+ i 1))] [(char=? c #\,) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (if (not (or (null? slatex::*bq-stack*) (slatex::of (car slatex::*bq-stack*) slatex::=in-comma))) (set! slatex::*bq-stack* (cons (let ([f (slatex::make-bq-frame)]) (slatex::setf (slatex::of f slatex::=in-comma) #t) (slatex::setf (slatex::of f slatex::=in-bq-tkn) #t) (slatex::setf (slatex::of f slatex::=in-bktd-bq-exp) 0) f) slatex::*bq-stack*))) (if (char=? (slatex::of line slatex::=char / (+ i 1)) #\@) (begin (slatex::display-tex-char #\@ slatex::*out*) (loop (+ 2 i))) (loop (+ i 1)))] [(memv c '(#\( #\[)) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (cond [slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (set! slatex::*in-bktd-qtd-exp* 1)] [(> slatex::*in-bktd-qtd-exp* 0) (set! slatex::*in-bktd-qtd-exp* (+ slatex::*in-bktd-qtd-exp* 1))]) (cond [slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f) (set! slatex::*in-bktd-mac-exp* 1)] [(> slatex::*in-bktd-mac-exp* 0) (set! slatex::*in-bktd-mac-exp* (+ slatex::*in-bktd-mac-exp* 1))]) (if (not (null? slatex::*bq-stack*)) (let ([top (car slatex::*bq-stack*)]) (cond [(slatex::of top slatex::=in-bq-tkn) (slatex::setf (slatex::of top slatex::=in-bq-tkn) #f) (slatex::setf (slatex::of top slatex::=in-bktd-bq-exp) 1)] [(> (slatex::of top slatex::=in-bktd-bq-exp) 0) (slatex::setf (slatex::of top slatex::=in-bktd-bq-exp) (+ (slatex::of top slatex::=in-bktd-bq-exp) 1))]))) (if (not (null? slatex::*case-stack*)) (let ([top (car slatex::*case-stack*)]) (cond [(slatex::of top slatex::=in-ctag-tkn) (slatex::setf (slatex::of top slatex::=in-ctag-tkn) #f) (slatex::setf (slatex::of top slatex::=in-bktd-ctag-exp) 1)] [(> (slatex::of top slatex::=in-bktd-ctag-exp) 0) (slatex::setf (slatex::of top slatex::=in-bktd-ctag-exp) (+ (slatex::of top slatex::=in-bktd-ctag-exp) 1))] [(> (slatex::of top slatex::=in-case-exp) 0) (slatex::setf (slatex::of top slatex::=in-case-exp) (+ (slatex::of top slatex::=in-case-exp) 1)) (if (= (slatex::of top slatex::=in-case-exp) 2) (set! slatex::*in-qtd-tkn* #t))]))) (loop (+ i 1))] [(memv c '(#\) #\])) (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (write-char c slatex::*out*) (if (> slatex::*in-bktd-qtd-exp* 0) (set! slatex::*in-bktd-qtd-exp* (- slatex::*in-bktd-qtd-exp* 1))) (if (> slatex::*in-bktd-mac-exp* 0) (set! slatex::*in-bktd-mac-exp* (- slatex::*in-bktd-mac-exp* 1))) (if (not (null? slatex::*bq-stack*)) (let ([top (car slatex::*bq-stack*)]) (if (> (slatex::of top slatex::=in-bktd-bq-exp) 0) (begin (slatex::setf (slatex::of top slatex::=in-bktd-bq-exp) (- (slatex::of top slatex::=in-bktd-bq-exp) 1)) (if (= (slatex::of top slatex::=in-bktd-bq-exp) 0) (set! slatex::*bq-stack* (cdr slatex::*bq-stack*))))))) (let loop () (if (not (null? slatex::*case-stack*)) (let ([top (car slatex::*case-stack*)]) (cond [(> (slatex::of top slatex::=in-bktd-ctag-exp) 0) (slatex::setf (slatex::of top slatex::=in-bktd-ctag-exp) (- (slatex::of top slatex::=in-bktd-ctag-exp) 1)) (if (= (slatex::of top slatex::=in-bktd-ctag-exp) 0) (slatex::setf (slatex::of top slatex::=in-case-exp) 1))] [(> (slatex::of top slatex::=in-case-exp) 0) (slatex::setf (slatex::of top slatex::=in-case-exp) (- (slatex::of top slatex::=in-case-exp) 1)) (if (= (slatex::of top slatex::=in-case-exp) 0) (begin (set! slatex::*case-stack* (cdr slatex::*case-stack*)) (loop)))])))) (loop (+ i 1))] [else (slatex::display-tab (slatex::of line slatex::=tab / i) slatex::*out*) (loop (slatex::do-token line i))]))))) (define slatex::do-all-lines (lambda () (let loop ([line1 slatex::*line1*] [line2 slatex::*line2*]) (let* ([line2-paragraph? slatex::*latex-paragraph-mode?*] [more? (slatex::get-line line1)]) (slatex::peephole-adjust line1 line2) ((if line2-paragraph? slatex::display-tex-line slatex::display-scm-line) line2) (if (not (eq? line2-paragraph? slatex::*latex-paragraph-mode?*)) ((if slatex::*latex-paragraph-mode?* slatex::display-end-sequence slatex::display-begin-sequence) slatex::*out*)) (if more? (loop line2 line1)))))) (define slatex::scheme2tex (lambda (inport outport) (set! slatex::*in* inport) (set! slatex::*out* outport) (set! slatex::*latex-paragraph-mode?* #t) (set! slatex::*in-qtd-tkn* #f) (set! slatex::*in-bktd-qtd-exp* 0) (set! slatex::*in-mac-tkn* #f) (set! slatex::*in-bktd-mac-exp* 0) (set! slatex::*case-stack* '()) (set! slatex::*bq-stack* '()) (let ([flush-line (lambda (line) (slatex::setf (slatex::of line slatex::=rtedge) 0) (slatex::setf (slatex::of line slatex::=char / 0) #\newline) (slatex::setf (slatex::of line slatex::=space / 0) &void-space) (slatex::setf (slatex::of line slatex::=tab / 0) &void-tab) (slatex::setf (slatex::of line slatex::=notab / 0) &void-notab))]) (flush-line slatex::*line1*) (flush-line slatex::*line2*)) (slatex::do-all-lines))) (define slatex::do-token (let ([token-delims (list #\( #\) #\[ #\] #\space (lambda (line i) (let loop ([buf '()] [i i]) (let ([c (slatex::of line slatex::=char / i)]) (cond [(char=? c #\\) (loop (cons (slatex::of line slatex::=char / (+ i 1)) (cons c buf)) (+ i 2))] [(or (memv c token-delims) (memv c slatex::*math-triggerers*)) (slatex::output-token (list->string (reverse! buf))) i] [(char? c) (loop (cons (slatex::of line slatex::=char / i) buf) (+ i 1))] [else (slatex::slatex-error 'slatex::do-token "token contains non-char?" c)])))))) (define slatex::output-token (lambda (token) (if (not (null? slatex::*case-stack*)) (let ([top (car slatex::*case-stack*)]) (if (slatex::of top slatex::=in-ctag-tkn) (begin (slatex::setf (slatex::of top slatex::=in-ctag-tkn) #f) (slatex::setf (slatex::of top slatex::=in-case-exp) 1))))) (if (slatex::lassoc token slatex::special-symbols slatex::token=?) (begin (if slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (if slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f))) (display (cdr (slatex::lassoc token slatex::special-symbols slatex::token=?)) slatex::*out*)) (slatex::display-token token (cond [slatex::*in-qtd-tkn* (set! slatex::*in-qtd-tkn* #f) (cond [(equal? token "else") 'syntax] [(slatex::lmember token slatex::data-tokens slatex::token=?) 'data] [(slatex::lmember token slatex::constant-tokens slatex::token=?) 'constant] [(slatex::lmember token slatex::variable-tokens slatex::token=?) 'constant] [(slatex::lmember token slatex::keyword-tokens slatex::token=?) 'constant] [(slatex::prim-data-token? token) 'data] [else 'constant])] [(> slatex::*in-bktd-qtd-exp* 0) 'constant] [(and (not (null? slatex::*bq-stack*)) (not (slatex::of (car slatex::*bq-stack*) slatex::=in-comma))) 'constant] [slatex::*in-mac-tkn* (set! slatex::*in-mac-tkn* #f) (slatex::set-keyword token) 'syntax] [(> slatex::*in-bktd-mac-exp* 0) (slatex::set-keyword token) 'syntax] [(slatex::lmember token slatex::data-tokens slatex::token=?) 'data] [(slatex::lmember token slatex::constant-tokens slatex::token=?) 'constant] [(slatex::lmember token slatex::variable-tokens slatex::token=?) 'variable] [(slatex::lmember token slatex::keyword-tokens slatex::token=?) (cond [(slatex::token=? token "quote") (set! slatex::*in-qtd-tkn* #t)] [(slatex::lmember token slatex::macro-definers slatex::token=?) (set! slatex::*in-mac-tkn* #t)] [(slatex::lmember token slatex::case-and-ilk slatex::token=?) (set! slatex::*case-stack* (cons (let ([f (slatex::make-case-frame)]) (slatex::setf (slatex::of f slatex::=in-ctag-tkn) #t) (slatex::setf (slatex::of f slatex::=in-bktd-ctag-exp) 0) (slatex::setf (slatex::of f slatex::=in-case-exp) 0) f) slatex::*case-stack*))]) 'syntax] [(slatex::prim-data-token? token) 'data] [else 'variable]) slatex::*out*)) (if (and (not (null? slatex::*bq-stack*)) (slatex::of (car slatex::*bq-stack*) slatex::=in-bq-tkn)) (set! slatex::*bq-stack* (cdr slatex::*bq-stack*))))) (define slatex::directory-namestring (lambda (f) (let ([p (slatex::string-position-right slatex::*directory-mark* f)]) (if p (substring f 0 (+ p 1)) "")))) (define slatex::basename (lambda (f) (let ([p (slatex::string-position-right slatex::*directory-mark* f)]) (if p (set! f (substring f (+ p 1) (string-length f)))) (let ([p (slatex::string-position-right #\. f)]) (if p (substring f 0 p) f))))) (define slatex::*texinputs* "") (define slatex::*texinputs-list* #f) (define slatex::*path-separator* (cond [(eq? slatex::*operating-system* 'unix) #\:] [(eq? slatex::*operating-system* 'mac-os) (integer->char 0)] [(memq slatex::*operating-system* '(windows os2 dos os2fat)) [else (slatex::slatex-error "Couldn't determine path separator character.")])) (define slatex::*directory-mark* (cond [(eq? slatex::*operating-system* 'unix) #\/] [(eq? slatex::*operating-system* 'mac-os) #\:] [(memq slatex::*operating-system* '(windows os2 dos os2fat)) #\\] [else (slatex::slatex-error "Couldn't determine directory mark.")])) (define slatex::*directory-mark-string* (list->string (list slatex::*directory-mark*))) (define slatex::*file-hider* (cond [(memq slatex::*operating-system* '(windows os2 unix mac-os)) "."] [(memq slatex::*operating-system* '(dos os2fat)) "x"] [else "."])) (define slatex::path-to-list (lambda (p) (let loop ([p (string->list p)] [r (list "")]) (let ([separator-pos (slatex::position-char slatex::*path-separator* p)]) (if separator-pos (loop (list-tail p (+ separator-pos 1)) (cons (list->string (slatex::sublist p 0 separator-pos)) r)) (reverse! (cons (list->string p) r))))))) (define slatex::find-some-file (lambda (path . files) (let loop ([path path]) (if (null? path) #f (let ([dir (car path)]) (let loop1 ([files (if (or (string=? dir "") (string=? dir ".")) files (map (lambda (file) (string-append dir slatex::*directory-mark-string* file)) files))]) (if (null? files) (loop (cdr path)) (let ([file (car files)]) (if (file-exists? file) file (loop1 (cdr files))))))))))) (define slatex::file-extension (lambda (filename) (let ([i (slatex::string-position-right #\. filename)]) (if i (substring filename i (string-length filename)) #f)))) (define slatex::full-texfile-name (lambda (filename) (let ([extn (slatex::file-extension filename)]) (if (and extn (or (string=? extn ".sty") (string=? extn ".tex"))) (slatex::find-some-file slatex::*texinputs-list* filename) (slatex::find-some-file slatex::*texinputs-list* (string-append filename ".tex") filename))))) (define slatex::full-styfile-name (lambda (filename) (slatex::find-some-file slatex::*texinputs-list* (string-append filename ".sty")))) (define slatex::full-clsfile-name (lambda (filename) (slatex::find-some-file slatex::*texinputs-list* (string-append filename ".cls")))) (define slatex::full-scmfile-name (lambda (filename) (apply slatex::find-some-file slatex::*texinputs-list* filename (map (lambda (extn) (string-append filename extn)) '(".scm" ".ss" ".s"))))) (define slatex::subjobname 'fwd) (define slatex::primary-aux-file-count -1) (define slatex::new-primary-aux-file (lambda (e) (set! slatex::primary-aux-file-count (+ slatex::primary-aux-file-count 1)) (string-append slatex::*tex-calling-directory* slatex::*file-hider* "Z" (number->string slatex::primary-aux-file-count) slatex::subjobname e))) (define slatex::new-secondary-aux-file (let ([n -1]) (lambda (e) (set! n (+ n 1)) (string-append slatex::*tex-calling-directory* slatex::*file-hider* "ZZ" (number->string n) slatex::subjobname e)))) (define slatex::new-aux-file (lambda e (let ([e (if (pair? e) (car e) "")]) ((if slatex::*slatex-in-protected-region?* slatex::new-secondary-aux-file slatex::new-primary-aux-file) e)))) (define slatex::eat-till-newline (lambda (in) (let loop () (let ([c (read-char in)]) (cond [(eof-object? c) 'done] [(char=? c #\newline) 'done] [else (loop)]))))) (define slatex::read-ctrl-seq (lambda (in) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-ctrl-exp: \\ followed by eof.")) (if (char-alphabetic? c) (list->string (reverse! (let loop ([s (list c)]) (let ([c (peek-char in)]) (cond [(eof-object? c) s] [(char-alphabetic? c) (read-char in) (loop (cons c s))] [(char=? c #\%) (slatex::eat-till-newline in) (loop s)] [else s]))))) (string c))))) (define slatex::eat-tabspace (lambda (in) (let loop () (let ([c (peek-char in)]) (cond [(eof-object? c) 'done] [(or (char=? c #\space) (char=? c slatex::*tab*)) (read-char in) (loop)] [else 'done]))))) (define slatex::eat-whitespace (lambda (in) (let loop () (let ([c (peek-char in)]) (cond [(eof-object? c) 'done] [(char-whitespace? c) (read-char in) (loop)] [else 'done]))))) (define slatex::eat-tex-whitespace (lambda (in) (let loop () (let ([c (peek-char in)]) (cond [(eof-object? c) 'done] [(char-whitespace? c) (read-char in) (loop)] [(char=? c #\%) (slatex::eat-till-newline in)] [else 'done]))))) (define slatex::chop-off-whitespace (lambda (l) (slatex::ormapcdr (lambda (d) (if (char-whitespace? (car d)) #f d)) l))) (define slatex::read-grouped-latexexp (lambda (in) (slatex::eat-tex-whitespace in) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-grouped-latexexp: ~\nExpected { but found eof.")) (if (not (char=? c #\{)) (slatex::slatex-error "read-grouped-latexexp: ~\nExpected { but found ~a." c)) (slatex::eat-tex-whitespace in) (list->string (reverse! (slatex::chop-off-whitespace (let loop ([s '()] [nesting 0] [escape? #f]) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-groupted-latexexp: ~\nFound eof inside {...}.")) (cond [escape? (loop (cons c s) nesting #f)] [(char=? c #\\) (loop (cons c s) nesting #t)] [(char=? c #\%) (slatex::eat-till-newline in) (loop s nesting #f)] [(char=? c #\{) (loop (cons c s) (+ nesting 1) #f)] [(char=? c #\}) (if (= nesting 0) s (loop (cons c s) (- nesting 1) #f))] [else (loop (cons c s) nesting #f)]))))))))) (define slatex::read-filename (let ([filename-delims (list #\{ #\} #\[ #\] #\( #\) #\# #\% #\\ #\, #\space slatex::*return* #\newline slatex::*tab* #\\)]) (lambda (in) (slatex::eat-tex-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "read-filename: ~\nExpected filename but found eof.")) (if (char=? c #\{) (slatex::read-grouped-latexexp in) (list->string (reverse! (let loop ([s '()] [escape? #f]) (let ([c (peek-char in)]) (cond [(eof-object? c) (if escape? (slatex::slatex-error "read-filename: ~\n\\ followed by eof.") s)] [escape? (read-char in) (loop (cons c s) #f)] [(char=? c #\\) (read-char in) (loop (cons c s) #t)] [(memv c filename-delims) s] [else (read-char in) (loop (cons c s) #f)])))))))))) (define slatex::read-schemeid (let ([schemeid-delims (list #\{ #\} #\[ #\] #\( #\) #\space slatex::*return* #\newline slatex::*tab*)]) (lambda (in) (slatex::eat-whitespace in) (list->string (reverse! (let loop ([s '()] [escape? #f]) (let ([c (peek-char in)]) (cond [(eof-object? c) s] [escape? (read-char in) (loop (cons c s) #f)] [(char=? c #\\) (read-char in) (loop (cons c s) #t)] [(memv c schemeid-delims) s] [else (read-char in) (loop (cons c s) #f)])))))))) (define slatex::read-delimed-commaed-filenames (lambda (in lft-delim rt-delim) (slatex::eat-tex-whitespace in) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-delimed-commaed-filenames: ~\nExpected filename(s) but found eof.")) (if (not (char=? c lft-delim)) (slatex::slatex-error "read-delimed-commaed-filenames: ~\nLeft delimiter ~a not found." lft-delim)) (let loop ([s '()]) (slatex::eat-tex-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "read-delimed-commaed-filenames: ~\nFound eof inside filename(s).")) (if (char=? c rt-delim) (begin (read-char in) (reverse! s)) (let ([s (cons (slatex::read-filename in) s)]) (slatex::eat-tex-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "read-delimed-commaed-filenames: ~\nFound eof inside filename(s).")) (cond [(char=? c #\,) (read-char in)] [(char=? c rt-delim) (void)] [else (slatex::slatex-error "read-delimed-commaed-filenames: ~\nBad filename(s) syntax.")]) (loop s))))))))) (define slatex::read-grouped-commaed-filenames (lambda (in) (slatex::read-delimed-commaed-filenames in #\{ #\}))) (define slatex::read-bktd-commaed-filenames (lambda (in) (slatex::read-delimed-commaed-filenames in #\[ #\]))) (define slatex::read-grouped-schemeids (lambda (in) (slatex::eat-tex-whitespace in) (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "read-grouped-schemeids: ~\nExpected Scheme identifiers but found eof.")) (if (not (char=? c #\{)) (slatex::slatex-error "read-grouped-schemeids: ~\nExpected { but found ~a." c)) (let loop ([s '()]) (slatex::eat-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "read-grouped-schemeids:\nFound eof inside Scheme identifiers.")) (if (char=? c #\}) (begin (read-char in) (reverse! s)) (loop (cons (slatex::read-schemeid in) s)))))))) (define slatex::eat-delimed-text (lambda (in lft-delim rt-delim) (slatex::eat-tex-whitespace in) (let ([c (peek-char in)]) (if (eof-object? c) 'exit (if (char=? c lft-delim) (let loop () (let ([c (read-char in)]) (if (eof-object? c) 'exit (if (char=? c rt-delim) 'exit (loop)))))))))) (define slatex::eat-bktd-text (lambda (in) (slatex::eat-delimed-text in #\[ #\]))) (define slatex::eat-grouped-text (lambda (in) (slatex::eat-delimed-text in #\{ #\}))) (define slatex::ignore2 (lambda (i ii) 'void)) (define slatex::disable-slatex-temply (lambda (in) (set! slatex::*slatex-enabled?* #f) (set! slatex::*slatex-reenabler* (slatex::read-grouped-latexexp in)))) (define slatex::enable-slatex-again (lambda () (set! slatex::*slatex-enabled?* #t) (set! slatex::*slatex-reenabler* "UNDEFINED"))) (define slatex::add-to-slatex-db (lambda (in categ) (if (memq categ '(keyword constant variable)) (slatex::add-to-slatex-db-basic in categ) (slatex::add-to-slatex-db-special in categ)))) (define slatex::add-to-slatex-db-basic (lambda (in categ) (let ([setter (cond [(eq? categ 'keyword) slatex::set-keyword] [(eq? categ 'constant) slatex::set-constant] [(eq? categ 'variable) slatex::set-variable] [else (slatex::slatex-error "add-to-slatex-db-basic: ~\nUnknown category ~s." categ)])] [ids (slatex::read-grouped-schemeids in)]) (for-each setter ids)))) (define slatex::add-to-slatex-db-special (lambda (in what) (let ([ids (slatex::read-grouped-schemeids in)]) (cond [(eq? what 'unsetspecialsymbol) (for-each slatex::unset-special-symbol ids)] [(eq? what 'setspecialsymbol) (if (not (= (length ids) 1)) (slatex::slatex-error "add-to-slatex-db-special: ~\n\\setspecialsymbol takes one arg exactly.")) (let ([transl (slatex::read-grouped-latexexp in)]) (slatex::set-special-symbol (car ids) transl))] [else (slatex::slatex-error "add-to-slatex-db-special: ~\nUnknown command ~s." what)])))) (define slatex::process-slatex-alias (lambda (in what which) (let ([triggerer (slatex::read-grouped-latexexp in)]) (case which [(intext) (set! slatex::*intext-triggerers* (what triggerer slatex::*intext-triggerers* string=?))] [(resultintext) (set! slatex::*resultintext-triggerers* (what triggerer slatex::*resultintext-triggerers* string=?))] [(display) (set! slatex::*display-triggerers* (what triggerer slatex::*display-triggerers* string=?))] [(response) (set! slatex::*response-triggerers* (what triggerer slatex::*response-triggerers* string=?))] [(respbox) (set! slatex::*respbox-triggerers* (what triggerer slatex::*respbox-triggerers* string=?))] [(box) (set! slatex::*box-triggerers* (what triggerer slatex::*box-triggerers* string=?))] [(input) (set! slatex::*input-triggerers* (what triggerer slatex::*input-triggerers* string=?))] [(region) (set! slatex::*region-triggerers* (what triggerer slatex::*region-triggerers* string=?))] [(mathescape) (if (not (= (string-length triggerer) 1)) (slatex::slatex-error "process-slatex-alias: ~\nMath escape should be character.")) (set! slatex::*math-triggerers* (what (string-ref triggerer 0) slatex::*math-triggerers* char=?))] [else (slatex::slatex-error "process-slatex-alias:\nUnknown command ~s." which)])))) (define slatex::decide-latex-or-tex (lambda (latex?) (set! slatex::*latex?* latex?) (let ([pltexchk.jnk "pltexchk.jnk"]) (if (file-exists? pltexchk.jnk) (delete-file pltexchk.jnk)) (if (not slatex::*latex?*) (call-with-output-file pltexchk.jnk (lambda (outp) (display 'junk outp) (newline outp))))))) (define slatex::process-include-only (lambda (in) (set! slatex::*include-onlys* '()) (for-each (lambda (filename) (let ([filename (slatex::full-texfile-name filename)]) (if filename (set! slatex::*include-onlys* (slatex::adjoin filename slatex::*include-onlys* string=?))))) (slatex::read-grouped-commaed-filenames in)))) (define slatex::process-documentstyle (lambda (in) (slatex::eat-tex-whitespace in) (if (char=? (peek-char in) #\[) (for-each (lambda (filename) (fluid-let ([slatex::*slatex-in-protected-region?* #f]) (slatex::process-tex-file (string-append filename ".sty")))) (slatex::read-bktd-commaed-filenames in))))) (define slatex::process-documentclass (lambda (in) (slatex::eat-bktd-text in) (slatex::eat-grouped-text in))) (define slatex::process-case-info (lambda (in) (let ([bool (slatex::read-grouped-latexexp in)]) (set! slatex::*slatex-case-sensitive?* (cond [(string-ci=? bool "true") #t] [(string-ci=? bool "false") #f] [else (slatex::slatex-error "process-case-info: ~\n\\schemecasesensitive's arg should be true or false.")]))))) (define slatex::seen-first-command? #f) (define slatex::process-main-tex-file (lambda (filename) (display "SLaTeX v. ") (display slatex::*slatex-version*) (newline) (set! slatex::primary-aux-file-count -1) (set! slatex::*slatex-separate-includes?* #f) (if (or (not slatex::*texinputs-list*) (null? slatex::*texinputs-list*)) (set! slatex::*texinputs-list* (if slatex::*texinputs* (slatex::path-to-list slatex::*texinputs*) '("")))) (let ([file-hide-file "xZfilhid.tex"]) (if (file-exists? file-hide-file) (delete-file file-hide-file)) (if (memq slatex::*operating-system* '(dos os2fat)) (call-with-output-file file-hide-file (lambda (out) (display "\\def\\filehider{x}" out) (newline out))))) (display "typesetting code") (set! slatex::*tex-calling-directory* (slatex::directory-namestring filename)) (set! slatex::subjobname (slatex::basename filename)) (set! slatex::seen-first-command? #f) (slatex::process-tex-file filename) (display "done") (newline))) (define slatex::dump-intext (lambda (in out) (let* ([write-char (if out write-char slatex::ignore2)] [delim-char (begin (slatex::eat-whitespace in) (read-char in))] [delim-char (cond [(char=? delim-char #\{) #\}] [else delim-char])]) (if (eof-object? delim-char) (slatex::slatex-error "dump-intext: Expected delimiting character ~\nbut found eof.")) (let loop () (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "dump-intext: Found eof inside Scheme code.")) (if (char=? c delim-char) 'done (begin (write-char c out) (loop)))))))) (define slatex::dump-display (lambda (in out ender) (slatex::eat-tabspace in) (let ([write-char (if out write-char slatex::ignore2)] [ender-lh (string-length ender)] [c (peek-char in)]) (if (eof-object? c) (slatex::slatex-error "dump-display: Found eof inside displayed code.")) (if (char=? c #\newline) (read-char in)) (let loop ([i 0]) (if (= i ender-lh) 'done (let ([c (read-char in)]) (if (eof-object? c) (slatex::slatex-error "dump-display: Found eof inside displayed code.")) (if (char=? c (string-ref ender i)) (loop (+ i 1)) (let loop2 ([j 0]) (if (< j i) (begin (write-char (string-ref ender j) out) (loop2 (+ j 1))) (begin (write-char c out) (loop 0))))))))))) (define slatex::debug? #f) (define slatex::process-tex-file (lambda (raw-filename) (if slatex::debug? (begin (display "begin ") (display raw-filename) (newline))) (let ([filename (slatex::full-texfile-name raw-filename)]) (if (not filename) (begin (display "[") (display raw-filename) (display "]") (flush-output-port)) (call-with-input-file filename (lambda (in) (let ([done? #f]) (let loop () (if done? 'exit-loop (begin (let ([c (read-char in)]) (cond [(eof-object? c) (set! done? #t)] [(char=? c #\%) (slatex::eat-till-newline in)] [(char=? c #\\) (let ([cs (slatex::read-ctrl-seq in)]) (if (not slatex::seen-first-command?) (begin (set! slatex::seen-first-command? #t) (slatex::decide-latex-or-tex (or (string=? cs "documentstyle") (string=? cs "documentclass") (string=? cs "NeedsTeXFormat"))))) (cond [(not slatex::*slatex-enabled?*) (if (string=? cs slatex::*slatex-reenabler*) (slatex::enable-slatex-again))] [(string=? cs "slatexignorecurrentfile") (set! done? #t)] [(string=? cs "slatexseparateincludes") (if slatex::*latex?* (set! slatex::*slatex-separate-includes?* #t))] [(string=? cs "slatexdisable") (slatex::disable-slatex-temply in)] [(string=? cs "begin") (slatex::eat-tex-whitespace in) (if (eqv? (peek-char in) #\{) (let ([cs (slatex::read-grouped-latexexp in)]) (cond [(member cs slatex::*display-triggerers*) (slatex::trigger-scheme2tex 'envdisplay in cs)] [(member cs slatex::*response-triggerers*) (slatex::trigger-scheme2tex 'envresponse in cs)] [(member cs slatex::*respbox-triggerers*) (slatex::trigger-scheme2tex 'envrespbox in cs)] [(member cs slatex::*box-triggerers*) (slatex::trigger-scheme2tex 'envbox in cs)] [(member cs slatex::*topbox-triggerers*) (slatex::trigger-scheme2tex 'envtopbox in cs)] [(member cs slatex::*region-triggerers*) (slatex::trigger-region 'envregion in cs)])))] [(member cs slatex::*intext-triggerers*) (slatex::trigger-scheme2tex 'intext in #f)] [(member cs slatex::*resultintext-triggerers*) (slatex::trigger-scheme2tex 'resultintext in #f)] [(member cs slatex::*display-triggerers*) (slatex::trigger-scheme2tex 'plaindisplay in cs)] [(member cs slatex::*response-triggerers*) (slatex::trigger-scheme2tex 'plainresponse in cs)] [(member cs slatex::*respbox-triggerers*) (slatex::trigger-scheme2tex 'plainrespbox in cs)] [(member cs slatex::*box-triggerers*) (slatex::trigger-scheme2tex 'plainbox in cs)] [(member cs slatex::*topbox-triggerers*) (slatex::trigger-scheme2tex 'plaintopbox in cs)] [(member cs slatex::*region-triggerers*) (slatex::trigger-region 'plainregion in cs)] [(member cs slatex::*input-triggerers*) (slatex::process-scheme-file (slatex::read-filename in))] [(string=? cs "input") (let ([f (slatex::read-filename in)]) (if (not (string=? f "")) (fluid-let ([slatex::*slatex-in-protected-region?* #f]) (slatex::process-tex-file f))))] [(string=? cs "usepackage") (fluid-let ([slatex::*slatex-in-protected-region?* #f]) (slatex::process-tex-file (string-append (slatex::read-filename in) ".sty")))] [(string=? cs "include") (if slatex::*latex?* (let ([f (slatex::full-texfile-name (slatex::read-filename in))]) (if (and f (or (eq? slatex::*include-onlys* 'all) (member f slatex::*include-onlys*))) (fluid-let ([slatex::*slatex-in-protected-region?* #f]) (if slatex::*slatex-separate-includes?* (fluid-let ([slatex::subjobname (slatex::basename f)] [slatex::primary-aux-file-count -1]) (slatex::process-tex-file f)) (slatex::process-tex-file f))))))] [(string=? cs "includeonly") (if slatex::*latex?* (slatex::process-include-only in))] [(string=? cs "documentstyle") (if slatex::*latex?* (slatex::process-documentstyle in))] [(string=? cs "documentclass") (if slatex::*latex?* (slatex::process-documentclass in))] [(string=? cs "schemecasesensitive") (slatex::process-case-info in)] [(string=? cs "defschemetoken") (slatex::process-slatex-alias in slatex::adjoin 'intext)] [(string=? cs "undefschemetoken") (slatex::process-slatex-alias in slatex::delete 'intext)] [(string=? cs "defschemeresulttoken") (slatex::process-slatex-alias in slatex::adjoin 'resultintext)] [(string=? cs "undefschemeresulttoken") (slatex::process-slatex-alias in slatex::delete 'resultintext)] [(string=? cs "defschemeresponsetoken") (slatex::process-slatex-alias in slatex::adjoin 'response)] [(string=? cs "undefschemeresponsetoken") (slatex::process-slatex-alias in slatex::delete 'response)] [(string=? cs "defschemeresponseboxtoken") (slatex::process-slatex-alias in slatex::adjoin 'respbox)] [(string=? cs "undefschemeresponseboxtoken") (slatex::process-slatex-alias in slatex::delete 'respbox)] [(string=? cs "defschemedisplaytoken") (slatex::process-slatex-alias in slatex::adjoin 'display)] [(string=? cs "undefschemedisplaytoken") (slatex::process-slatex-alias in slatex::delete 'display)] [(string=? cs "defschemeboxtoken") (slatex::process-slatex-alias in slatex::adjoin 'box)] [(string=? cs "undefschemeboxtoken") (slatex::process-slatex-alias in slatex::delete 'box)] [(string=? cs "defschemetopboxtoken") (slatex::process-slatex-alias in slatex::adjoin 'topbox)] [(string=? cs "undefschemetopboxtoken") (slatex::process-slatex-alias in slatex::delete 'topbox)] [(string=? cs "defschemeinputtoken") (slatex::process-slatex-alias in slatex::adjoin 'input)] [(string=? cs "undefschemeinputtoken") (slatex::process-slatex-alias in slatex::delete 'input)] [(string=? cs "defschemeregiontoken") (slatex::process-slatex-alias in slatex::adjoin 'region)] [(string=? cs "undefschemeregiontoken") (slatex::process-slatex-alias in slatex::delete 'region)] [(string=? cs "defschememathescape") (slatex::process-slatex-alias in slatex::adjoin 'mathescape)] [(string=? cs "undefschememathescape") (slatex::process-slatex-alias in slatex::delete 'mathescape)] [(string=? cs "setkeyword") (slatex::add-to-slatex-db in 'keyword)] [(string=? cs "setconstant") (slatex::add-to-slatex-db in 'constant)] [(string=? cs "setvariable") (slatex::add-to-slatex-db in 'variable)] [(string=? cs "setspecialsymbol") (slatex::add-to-slatex-db in 'setspecialsymbol)] [(string=? cs "unsetspecialsymbol") (slatex::add-to-slatex-db in 'unsetspecialsymbol)]))])) (loop))))))))) (if slatex::debug? (begin (display "end ") (display raw-filename) (newline))))) (define slatex::process-scheme-file (lambda (raw-filename) (let ([filename (slatex::full-scmfile-name raw-filename)]) (if (not filename) (begin (display "process-scheme-file: ") (display raw-filename) (display " doesn't exist") (newline)) (let ([aux.tex (slatex::new-aux-file ".tex")]) (display ".") (flush-output-port) (if (file-exists? aux.tex) (delete-file aux.tex)) (call-with-input-file filename (lambda (in) (call-with-output-file aux.tex (lambda (out) (fluid-let ([slatex::*intext?* #f] [slatex::*code-env-spec* "ZZZZschemedisplay"]) (slatex::scheme2tex in out)))))) (if slatex::*slatex-in-protected-region?* (set! slatex::*protected-files* (cons aux.tex slatex::*protected-files*))) (slatex::process-tex-file filename)))))) (define slatex::trigger-scheme2tex (lambda (typ in env) (let* ([aux (slatex::new-aux-file)] [aux.scm (string-append aux ".scm")] [aux.tex (string-append aux ".tex")]) (if (file-exists? aux.scm) (delete-file aux.scm)) (if (file-exists? aux.tex) (delete-file aux.tex)) (display ".") (flush-output-port) (call-with-output-file aux.scm (lambda (out) (cond [(memq typ '(intext resultintext)) (slatex::dump-intext in out)] [(memq typ '(envdisplay envresponse envrespbox envbox envtopbox)) (slatex::dump-display in out (string-append "\\end{" env "}"))] [(memq typ '(plaindisplay plainresponse plainrespbox plainbox plaintopbox)) (slatex::dump-display in out (string-append "\\end" env))] [else (slatex::slatex-error "trigger-scheme2tex: ~\n Unknown triggerer ~s." typ)]))) (call-with-input-file aux.scm (lambda (in) (call-with-output-file aux.tex (lambda (out) (fluid-let ([slatex::*intext?* (memq typ '(intext resultintext))] [slatex::*code-env-spec* (cond [(eq? typ 'intext) "ZZZZschemecodeintext"] [(eq? typ 'resultintext) "ZZZZschemeresultintext"] [(memq typ '(envdisplay plaindisplay)) "ZZZZschemedisplay"] [(memq typ '(envresponse plainresponse)) "ZZZZschemeresponse"] [(memq typ '(envrespbox plainrespbox)) "ZZZZschemeresponsebox"] [(memq typ '(envbox plainbox)) "ZZZZschemebox"] [(memq typ '(envtopbox plaintopbox)) "ZZZZschemetopbox"] [else (slatex::slatex-error "trigger-scheme2tex: ~\n Unknown triggerer ~s." typ)])]) (slatex::scheme2tex in out)))))) (if slatex::*slatex-in-protected-region?* (set! slatex::*protected-files* (cons aux.tex slatex::*protected-files*))) (if (memq typ '(envdisplay plaindisplay envbox plainbox envtopbox plaintopbox)) (slatex::process-tex-file aux.tex)) (delete-file aux.scm)))) (define slatex::trigger-region (lambda (typ in env) (let ([aux.tex (slatex::new-primary-aux-file ".tex")] [aux2.tex (slatex::new-secondary-aux-file ".tex")]) (if (file-exists? aux2.tex) (delete-file aux2.tex)) (if (file-exists? aux.tex) (delete-file aux.tex)) (display ".") (flush-output-port) (fluid-let ([slatex::*slatex-in-protected-region?* #t] [slatex::*protected-files* '()]) (call-with-output-file aux2.tex (lambda (out) (cond [(eq? typ 'envregion) (slatex::dump-display in out (string-append "\\end{" env "}"))] [(eq? typ 'plainregion) (slatex::dump-display in out (string-append "\\end" env))] [else (slatex::slatex-error "trigger-region: ~\nUnknown triggerer ~s." typ)]))) (slatex::process-tex-file aux2.tex) (set! slatex::*protected-files* (reverse! slatex::*protected-files*)) (call-with-input-file aux2.tex (lambda (in) (call-with-output-file aux.tex (lambda (out) (slatex::inline-protected-files in out))))) (delete-file aux2.tex))))) (define slatex::inline-protected-files (lambda (in out) (let ([done? #f]) (let loop () (if done? 'exit-loop (begin (let ([c (read-char in)]) (cond [(eof-object? c) (set! done? #t)] [(or (char=? c slatex::*return*) (char=? c #\newline)) (let ([c2 (peek-char in)]) (if (not (eof-object? c2)) (write-char c out)))] [(char=? c #\%) (write-char c out) (newline out) (slatex::eat-till-newline in)] [(char=? c #\\) (let ([cs (slatex::read-ctrl-seq in)]) (cond [(string=? cs "begin") (let ([cs (slatex::read-grouped-latexexp in)]) (cond [(member cs slatex::*display-triggerers*) (slatex::inline-protected 'envdisplay in out cs)] [(member cs slatex::*response-triggerers*) (slatex::inline-protected 'envresponse in out cs)] [(member cs slatex::*respbox-triggerers*) (slatex::inline-protected 'envrespbox in out cs)] [(member cs slatex::*box-triggerers*) (slatex::inline-protected 'envbox in out cs)] [(member cs slatex::*topbox-triggerers*) (slatex::inline-protected 'envtopbox in out cs)] [(member cs slatex::*region-triggerers*) (slatex::inline-protected 'envregion in out cs)] [else (display "\\begin{" out) (display cs out) (display "}" out)]))] [(member cs slatex::*intext-triggerers*) (slatex::inline-protected 'intext in out #f)] [(member cs slatex::*resultintext-triggerers*) (slatex::inline-protected 'resultintext in out #f)] [(member cs slatex::*display-triggerers*) (slatex::inline-protected 'plaindisplay in out cs)] [(member cs slatex::*response-triggerers*) (slatex::inline-protected 'plainresponse in out cs)] [(member cs slatex::*respbox-triggerers*) (slatex::inline-protected 'plainrespbox in out cs)] [(member cs slatex::*box-triggerers*) (slatex::inline-protected 'plainbox in out cs)] [(member cs slatex::*topbox-triggerers*) (slatex::inline-protected 'plaintopbox in out cs)] [(member cs slatex::*region-triggerers*) (slatex::inline-protected 'plainregion in out cs)] [(member cs slatex::*input-triggerers*) (slatex::inline-protected 'input in out cs)] [else (display "\\" out) (display cs out)]))] [else (write-char c out)])) (loop))))))) (define slatex::inline-protected (lambda (typ in out env) (cond [(eq? typ 'envregion) (display "\\begin{" out) (display env out) (display "}" out) (slatex::dump-display in out (string-append "\\end{" env "}")) (display "\\end{" out) (display env out) (display "}" out)] [(eq? typ 'plainregion) (display "\\" out) (display env out) (slatex::dump-display in out (string-append "\\end" env)) (display "\\end" out) (display env out)] [else (let ([f (car slatex::*protected-files*)]) (set! slatex::*protected-files* (cdr slatex::*protected-files*)) (call-with-input-file f (lambda (in) (slatex::inline-protected-files in out))) (delete-file f)) (cond [(memq typ '(intext resultintext)) (display "{}" out) (slatex::dump-intext in #f)] [(memq typ '(envrespbox envbox envtopbox)) (if (not slatex::*latex?*) (display "{}" out)) (slatex::dump-display in #f (string-append "\\end{" env "}"))] [(memq typ '(plainrespbox plainbox plaintopbox)) (display "{}" out) (slatex::dump-display in #f (string-append "\\end" env))] [(memq typ '(envdisplay envresponse)) (slatex::dump-display in #f (string-append "\\end{" env "}"))] [(memq typ '(plaindisplay plainresponse)) (slatex::dump-display in #f (string-append "\\end" env))] [(eq? typ 'input) (slatex::read-filename in)] [else (slatex::slatex-error "inline-protected: ~\nUnknown triggerer ~s." typ)])])))
4571e6e1fe0f1c69bc075d58818606277e23b4722c4b30e75f883d3d2f69e121
chameco/reliquary
AST.hs
module Reliquary.Core.AST where import Text.Parsec import Reliquary.AST data Name = Integer data CoreTerm = CStar | CUnitType | CUnit | CRelTermType | CRelTerm Term | CVar Int | CApply CoreTerm CoreTerm | CLambda CoreTerm CoreTerm | CCons CoreTerm CoreTerm | CFst CoreTerm | CSnd CoreTerm | CPi CoreTerm CoreTerm | CSigma CoreTerm CoreTerm type CoreEnv = [(CoreTerm, Int)] data GenError = Mismatch CoreTerm CoreTerm | NotInScope | NotType CoreTerm | NotFunction CoreTerm | NotPair CoreTerm | NameNotInScope String | Redefinition String | SyntaxError ParseError | EmptyStack | InternalError CoreTerm isType :: CoreTerm -> Bool isType CStar = True isType _ = False matchTerm :: CoreTerm -> CoreTerm -> Bool matchTerm CStar CStar = True matchTerm CUnitType CUnitType = True matchTerm CUnit CUnit = True matchTerm CRelTermType CRelTermType = True matchTerm (CRelTerm t) (CRelTerm t') = t == t' matchTerm (CVar i) (CVar j) = i == j matchTerm (CApply f t) (CApply f' t') = matchTerm f f' && matchTerm t t' matchTerm (CLambda ty t) (CLambda ty' t') = matchTerm ty ty' && matchTerm t t' matchTerm (CCons t1 t2) (CCons t1' t2') = matchTerm t1 t1' && matchTerm t2 t2' matchTerm (CFst t) (CFst t') = matchTerm t t' matchTerm (CSnd t) (CSnd t') = matchTerm t t' matchTerm (CPi ty t) (CPi ty' t') = matchTerm ty ty' && matchTerm t t' matchTerm (CSigma ty t) (CSigma ty' t') = matchTerm ty ty' && matchTerm t t' matchTerm _ _ = False displayTerm :: CoreTerm -> String displayTerm CStar = "*" displayTerm CUnitType = "Unit" displayTerm CUnit = "()" displayTerm CRelTermType = "RelTerm" displayTerm (CRelTerm t) = show t displayTerm (CVar i) = show i displayTerm (CApply f t) = "(" ++ displayTerm f ++ " " ++ displayTerm t ++ ")" displayTerm (CLambda ty t) = "Ξ»" ++ displayTerm ty ++ "." ++ displayTerm t displayTerm (CCons t t') = "[" ++ displayTerm t ++ "," ++ displayTerm t' ++ "]" displayTerm (CFst t) = "fst " ++ displayTerm t displayTerm (CSnd t) = "snd " ++ displayTerm t displayTerm (CPi ty t) = "Ξ " ++ displayTerm ty ++ "." ++ displayTerm t displayTerm (CSigma ty t) = "Ξ£" ++ displayTerm ty ++ "." ++ displayTerm t displayError :: GenError -> String displayError (Mismatch t t') = "Type mismatch: " ++ displayTerm t' ++ " is not expected type " ++ displayTerm t displayError NotInScope = "Type checker failure: de Bruijn index not in scope" displayError (NotType t) = displayTerm t ++ " is not a type" displayError (NotFunction t) = displayTerm t ++ " is not a function" displayError (NotPair t) = displayTerm t ++ " is not a pair" displayError (NameNotInScope n) = "Name " ++ n ++ " is not in scope" displayError (Redefinition n) = "Attempt to redefine name " ++ n displayError (SyntaxError parseError) = "Syntax error: " ++ show parseError displayError EmptyStack = "Empty stack" displayError (InternalError t) = "Internal error: " ++ displayTerm t
null
https://raw.githubusercontent.com/chameco/reliquary/0af1bc89b6e37d790e460d6119ded3bcfaa85b07/src/Reliquary/Core/AST.hs
haskell
module Reliquary.Core.AST where import Text.Parsec import Reliquary.AST data Name = Integer data CoreTerm = CStar | CUnitType | CUnit | CRelTermType | CRelTerm Term | CVar Int | CApply CoreTerm CoreTerm | CLambda CoreTerm CoreTerm | CCons CoreTerm CoreTerm | CFst CoreTerm | CSnd CoreTerm | CPi CoreTerm CoreTerm | CSigma CoreTerm CoreTerm type CoreEnv = [(CoreTerm, Int)] data GenError = Mismatch CoreTerm CoreTerm | NotInScope | NotType CoreTerm | NotFunction CoreTerm | NotPair CoreTerm | NameNotInScope String | Redefinition String | SyntaxError ParseError | EmptyStack | InternalError CoreTerm isType :: CoreTerm -> Bool isType CStar = True isType _ = False matchTerm :: CoreTerm -> CoreTerm -> Bool matchTerm CStar CStar = True matchTerm CUnitType CUnitType = True matchTerm CUnit CUnit = True matchTerm CRelTermType CRelTermType = True matchTerm (CRelTerm t) (CRelTerm t') = t == t' matchTerm (CVar i) (CVar j) = i == j matchTerm (CApply f t) (CApply f' t') = matchTerm f f' && matchTerm t t' matchTerm (CLambda ty t) (CLambda ty' t') = matchTerm ty ty' && matchTerm t t' matchTerm (CCons t1 t2) (CCons t1' t2') = matchTerm t1 t1' && matchTerm t2 t2' matchTerm (CFst t) (CFst t') = matchTerm t t' matchTerm (CSnd t) (CSnd t') = matchTerm t t' matchTerm (CPi ty t) (CPi ty' t') = matchTerm ty ty' && matchTerm t t' matchTerm (CSigma ty t) (CSigma ty' t') = matchTerm ty ty' && matchTerm t t' matchTerm _ _ = False displayTerm :: CoreTerm -> String displayTerm CStar = "*" displayTerm CUnitType = "Unit" displayTerm CUnit = "()" displayTerm CRelTermType = "RelTerm" displayTerm (CRelTerm t) = show t displayTerm (CVar i) = show i displayTerm (CApply f t) = "(" ++ displayTerm f ++ " " ++ displayTerm t ++ ")" displayTerm (CLambda ty t) = "Ξ»" ++ displayTerm ty ++ "." ++ displayTerm t displayTerm (CCons t t') = "[" ++ displayTerm t ++ "," ++ displayTerm t' ++ "]" displayTerm (CFst t) = "fst " ++ displayTerm t displayTerm (CSnd t) = "snd " ++ displayTerm t displayTerm (CPi ty t) = "Ξ " ++ displayTerm ty ++ "." ++ displayTerm t displayTerm (CSigma ty t) = "Ξ£" ++ displayTerm ty ++ "." ++ displayTerm t displayError :: GenError -> String displayError (Mismatch t t') = "Type mismatch: " ++ displayTerm t' ++ " is not expected type " ++ displayTerm t displayError NotInScope = "Type checker failure: de Bruijn index not in scope" displayError (NotType t) = displayTerm t ++ " is not a type" displayError (NotFunction t) = displayTerm t ++ " is not a function" displayError (NotPair t) = displayTerm t ++ " is not a pair" displayError (NameNotInScope n) = "Name " ++ n ++ " is not in scope" displayError (Redefinition n) = "Attempt to redefine name " ++ n displayError (SyntaxError parseError) = "Syntax error: " ++ show parseError displayError EmptyStack = "Empty stack" displayError (InternalError t) = "Internal error: " ++ displayTerm t
922fc9a6e94e2e6c5775aac8c63cb536ccc16298a684b994388c580672a14d87
codereport/SICP-2020
cezarb_solutions.rkt
#lang racket (require rackunit) (require racket/list) Ex . 2.77 , 2.78 and 2.79 (define table (make-hash)) (define (put key1 key2 value) (hash-set! table (list key1 key2) value)) (define (get key1 key2) (hash-ref table (list key1 key2) #f)) (define (attach-tag tag value) (cons tag value)) (define (type-tag datum) (cond ((pair? datum) (car datum)) ((number? datum) 'scheme-number) (error "Bad tagged datum: TYPE-TAG" datum))) (define (contents datum) (cond ((pair? datum) (cdr datum)) ((number? datum) datum) (error "Bad tagged datum: TYPE-TAG" datum))) (define square *) (define (apply-generic op . args) (let ((type-tags (map type-tag args)) (values (map contents args)) ) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) ; can we convert ? (if (member op (list 'add 'sub 'mul 'div 'equ?)) ; try to find a common type (assume only binary ops ...) (let ((root-type (common-supertype type-tags))) (if (not (null? root-type)) ; convert all values to supertype (let ((values (map (lambda (arg) (convert-from-to-value (type-tag arg) root-type (contents arg))) args))) ; apply operation to (apply (get op (build-list (length type-tags) (lambda (x) root-type))) values)) (error "No conversion: APPLY-GENERIC" (list op type-tags))) ) (error "No method for these types: APPLY-GENERIC" (list op type-tags)) ))))) (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (equ? x y) (apply-generic 'equ? x y)) ; -- scheme-number -- (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'make 'scheme-number (lambda (x) (tag x))) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (= x y))) 'done) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) ; -- rational -- (define (install-rational-package) ;; internal procedures (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) ;; interface to rest of the system (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) (put 'equ? '(rational rational) (lambda (x y) (and (= (* (numer x) (denom y)) (* (numer y) (denom x)))))) (put 'numer '(rational) (lambda (q) (numer q))) (put 'denom '(rational) (lambda (q) (denom q))) 'done) (define (numer q) (apply-generic 'numer q)) (define (denom q) (apply-generic 'denom q)) ; --complex -- (define (install-rectangular-package) ;; internal procedures (define (real-part z) (car z)) (define (imag-part z) (cdr z)) (define (make-from-real-imag x y) (cons x y)) (define (magnitude z) (sqrt (+ (square (real-part z)) (square (imag-part z))))) (define (angle z) (atan (imag-part z) (real-part z))) (define (make-from-mag-ang r a) (cons (* r (cos a)) (* r (sin a)))) ;; interface to the rest of the system (define (tag x) (attach-tag 'rectangular x)) (put 'real-part '(rectangular) real-part) (put 'imag-part '(rectangular) imag-part) (put 'magnitude '(rectangular) magnitude) (put 'angle '(rectangular) angle) (put 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'equ? '(rectangular rectangular) (lambda (z1 z2) (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2))))) 'done) (define (install-polar-package) ;; internal procedures (define (magnitude z) (car z)) (define (angle z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) (define (real-part z) (* (magnitude z) (cos (angle z)))) (define (imag-part z) (* (magnitude z) (sin (angle z)))) (define (make-from-real-imag x y) (cons (sqrt (+ (square x) (square y))) (atan y x))) ;; interface to the rest of the system (define (tag x) (attach-tag 'polar x)) (put 'real-part '(polar) real-part) (put 'imag-part '(polar) imag-part) (put 'magnitude '(polar) magnitude) (put 'angle '(polar) angle) (put 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'equ? '(polar polar) (lambda (z1 z2) (and (= (magnitude z1) (magnitude z2)) (= (angle z1) (angle z2))))) 'done) (define (real-part z) (apply-generic 'real-part z)) (define (imag-part z) (apply-generic 'imag-part z)) (define (magnitude z) (apply-generic 'magnitude z)) (define (angle z) (apply-generic 'angle z)) (define (complex-equ? z1 z2) (apply-generic 'equ? z1 z2)) (define (install-complex-package) ;; imported procedures from rectangular and polar packages (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) ;; internal procedures (define (add-complex z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) ;; interface to rest of the system (define (tag z) (attach-tag 'complex z)) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'real-part '(complex) real-part) (put 'imag-part '(complex) imag-part) (put 'magnitude '(complex) magnitude) (put 'angle '(complex) angle) (put 'equ? '(complex complex) (lambda (z1 z2) (complex-equ? z1 z2))) 'done) (define (make-complex-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) (define (make-rational n d) ((get 'make 'rational) n d)) (define (install-all) (install-scheme-number-package) (install-rational-package) (install-rectangular-package) (install-polar-package) (install-complex-package) ) (module+ test (begin (install-all) (check-equal? (add 1 2) (make-scheme-number 3)) (check-equal? (equ? 1 1) #t) (check-equal? (equ? (make-rational 1 2) (make-rational 6 12)) #t) (check-equal? (equ? (make-complex-from-real-imag 1 2) (make-complex-from-real-imag 1 2)) #t) )) Ex . 2.83 and 2.84 (define (raise-scheme-number-to-rational n) (make-rational (contents n) 1)) (define (raise-rational-to-complex n) (make-complex-from-real-imag (/ (numer n) (denom n)) 0)) ; supertypes is a list of pairs (supertype . raiser) (define (raise from supertypes) (put 'raise from supertypes)) (define (install-raise) (raise 'scheme-number (list (cons 'rational raise-scheme-number-to-rational))) (raise 'rational (list (cons 'complex raise-rational-to-complex))) ) (define (install-geometry-raise) (define (dummy a) (println (format "[~a]" a)) a) (raise 'triangle (list (cons 'polygon dummy))) (raise 'isosceles-triangle (list (cons 'triangle dummy))) (raise 'quadrilateral-triangle (list (cons 'isosceles-triangle dummy))) (raise 'isosceles-right-triangle (list (cons 'isosceles-triangle dummy) (cons 'right-triangle dummy))) (raise 'right-triangle (list (cons 'triangle dummy))) (raise 'quadrilateral (list (cons 'polygon dummy))) (raise 'trapezoid (list (cons 'quadrilateral dummy))) (raise 'parallelogram (list (cons 'trapezoid dummy))) (raise 'rectangle (list (cons 'parallelogram dummy))) (raise 'square (list (cons 'rhombus dummy) (cons 'rectangle dummy))) (raise 'rhombus (list (cons 'parallelogram dummy) (cons 'kite dummy))) (raise 'kite (list (cons 'quadrilateral dummy))) ) (define (id x) x) (define (zip-with fn a b) (cond ((null? a) '()) (else (cons (fn (car a) (car b)) (zip-with fn (cdr a) (cdr b)))))) (define (flatmap fn a) (foldl (lambda (elem init) (append init elem)) '() (map fn a))) ; return a list of paths from type A to the root type (define (supertype-chains A) (define (try-extend-chains chains) (define uptypes (map (lambda (path) (let ((uptype (get 'raise (car (last path))))) (if uptype uptype '()))) chains)) (define extended-chains (zip-with (lambda (path uptypes) (if (not (null? uptypes)) (map (lambda (uptype) (append path (list uptype))) uptypes) (list path))) chains uptypes)) (define next-chains (flatmap id extended-chains)) (if (null? (foldl append '() uptypes)) chains (try-extend-chains next-chains))) (try-extend-chains (list (list (cons A id))))) (define (is-subtype a b) (not (null? (flatmap (lambda (path) (if (member b (map car path)) (list b) '())) (supertype-chains a))))) (define (common-supertype types) (define (common-type A B) (define pa (supertype-chains A)) (define pb (supertype-chains B)) (define (common-chain-node a b) (cond ((or (null? a) (null? b)) '()) ((eq? (caar a) (caar b)) (list (caar a))) (else (let ((xa (common-chain-node (cdr a) b)) (xb (common-chain-node a (cdr b)))) (append xa xb))))) (define types (sort (remove-duplicates (flatmap (lambda (a) (flatmap (lambda (b) (common-chain-node a b)) pb)) pa)) is-subtype)) (if (not (null? types)) (car types) '())) (foldl common-type (car types) (cdr types))) (define (convert-from-to-value from to value) (define (convert-chain path value) (define next-value ((cdar path) value)) (if (eq? (caar path) to) next-value (convert-chain (cdr path) next-value))) (car (flatmap (lambda (path) (if (member to (map car path)) (list (convert-chain path value)) '())) (supertype-chains from)))) (module+ test (begin (install-all) (install-raise) (check-equal? (equ? (raise-scheme-number-to-rational 3) (make-rational 6 2)) #t) (check-equal? (equ? (convert-from-to-value 'scheme-number 'complex 2) (make-complex-from-real-imag 2 0)) #t ) (check-equal? (equ? (add (make-complex-from-real-imag 2 3) (make-scheme-number 4)) (make-complex-from-real-imag 6 3)) #t) )) (module+ test (begin (install-geometry-raise) (check-equal? (common-supertype (list 'rectangle 'kite 'trapezoid)) 'quadrilateral) ))
null
https://raw.githubusercontent.com/codereport/SICP-2020/2d1e60048db89678830d93fcc558a846b7f57b76/Chapter%202.5%20Solutions/cezarb_solutions.rkt
racket
can we convert ? try to find a common type (assume only binary ops ...) convert all values to supertype apply operation to -- scheme-number -- -- rational -- internal procedures interface to rest of the system --complex -- internal procedures interface to the rest of the system internal procedures interface to the rest of the system imported procedures from rectangular and polar packages internal procedures interface to rest of the system supertypes is a list of pairs (supertype . raiser) return a list of paths from type A to the root type
#lang racket (require rackunit) (require racket/list) Ex . 2.77 , 2.78 and 2.79 (define table (make-hash)) (define (put key1 key2 value) (hash-set! table (list key1 key2) value)) (define (get key1 key2) (hash-ref table (list key1 key2) #f)) (define (attach-tag tag value) (cons tag value)) (define (type-tag datum) (cond ((pair? datum) (car datum)) ((number? datum) 'scheme-number) (error "Bad tagged datum: TYPE-TAG" datum))) (define (contents datum) (cond ((pair? datum) (cdr datum)) ((number? datum) datum) (error "Bad tagged datum: TYPE-TAG" datum))) (define square *) (define (apply-generic op . args) (let ((type-tags (map type-tag args)) (values (map contents args)) ) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (if (member op (list 'add 'sub 'mul 'div 'equ?)) (let ((root-type (common-supertype type-tags))) (if (not (null? root-type)) (let ((values (map (lambda (arg) (convert-from-to-value (type-tag arg) root-type (contents arg))) args))) (apply (get op (build-list (length type-tags) (lambda (x) root-type))) values)) (error "No conversion: APPLY-GENERIC" (list op type-tags))) ) (error "No method for these types: APPLY-GENERIC" (list op type-tags)) ))))) (define (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (equ? x y) (apply-generic 'equ? x y)) (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'make 'scheme-number (lambda (x) (tag x))) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (= x y))) 'done) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) (define (install-rational-package) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) (put 'equ? '(rational rational) (lambda (x y) (and (= (* (numer x) (denom y)) (* (numer y) (denom x)))))) (put 'numer '(rational) (lambda (q) (numer q))) (put 'denom '(rational) (lambda (q) (denom q))) 'done) (define (numer q) (apply-generic 'numer q)) (define (denom q) (apply-generic 'denom q)) (define (install-rectangular-package) (define (real-part z) (car z)) (define (imag-part z) (cdr z)) (define (make-from-real-imag x y) (cons x y)) (define (magnitude z) (sqrt (+ (square (real-part z)) (square (imag-part z))))) (define (angle z) (atan (imag-part z) (real-part z))) (define (make-from-mag-ang r a) (cons (* r (cos a)) (* r (sin a)))) (define (tag x) (attach-tag 'rectangular x)) (put 'real-part '(rectangular) real-part) (put 'imag-part '(rectangular) imag-part) (put 'magnitude '(rectangular) magnitude) (put 'angle '(rectangular) angle) (put 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'equ? '(rectangular rectangular) (lambda (z1 z2) (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2))))) 'done) (define (install-polar-package) (define (magnitude z) (car z)) (define (angle z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) (define (real-part z) (* (magnitude z) (cos (angle z)))) (define (imag-part z) (* (magnitude z) (sin (angle z)))) (define (make-from-real-imag x y) (cons (sqrt (+ (square x) (square y))) (atan y x))) (define (tag x) (attach-tag 'polar x)) (put 'real-part '(polar) real-part) (put 'imag-part '(polar) imag-part) (put 'magnitude '(polar) magnitude) (put 'angle '(polar) angle) (put 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'equ? '(polar polar) (lambda (z1 z2) (and (= (magnitude z1) (magnitude z2)) (= (angle z1) (angle z2))))) 'done) (define (real-part z) (apply-generic 'real-part z)) (define (imag-part z) (apply-generic 'imag-part z)) (define (magnitude z) (apply-generic 'magnitude z)) (define (angle z) (apply-generic 'angle z)) (define (complex-equ? z1 z2) (apply-generic 'equ? z1 z2)) (define (install-complex-package) (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) (define (add-complex z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) (define (tag z) (attach-tag 'complex z)) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'real-part '(complex) real-part) (put 'imag-part '(complex) imag-part) (put 'magnitude '(complex) magnitude) (put 'angle '(complex) angle) (put 'equ? '(complex complex) (lambda (z1 z2) (complex-equ? z1 z2))) 'done) (define (make-complex-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) (define (make-rational n d) ((get 'make 'rational) n d)) (define (install-all) (install-scheme-number-package) (install-rational-package) (install-rectangular-package) (install-polar-package) (install-complex-package) ) (module+ test (begin (install-all) (check-equal? (add 1 2) (make-scheme-number 3)) (check-equal? (equ? 1 1) #t) (check-equal? (equ? (make-rational 1 2) (make-rational 6 12)) #t) (check-equal? (equ? (make-complex-from-real-imag 1 2) (make-complex-from-real-imag 1 2)) #t) )) Ex . 2.83 and 2.84 (define (raise-scheme-number-to-rational n) (make-rational (contents n) 1)) (define (raise-rational-to-complex n) (make-complex-from-real-imag (/ (numer n) (denom n)) 0)) (define (raise from supertypes) (put 'raise from supertypes)) (define (install-raise) (raise 'scheme-number (list (cons 'rational raise-scheme-number-to-rational))) (raise 'rational (list (cons 'complex raise-rational-to-complex))) ) (define (install-geometry-raise) (define (dummy a) (println (format "[~a]" a)) a) (raise 'triangle (list (cons 'polygon dummy))) (raise 'isosceles-triangle (list (cons 'triangle dummy))) (raise 'quadrilateral-triangle (list (cons 'isosceles-triangle dummy))) (raise 'isosceles-right-triangle (list (cons 'isosceles-triangle dummy) (cons 'right-triangle dummy))) (raise 'right-triangle (list (cons 'triangle dummy))) (raise 'quadrilateral (list (cons 'polygon dummy))) (raise 'trapezoid (list (cons 'quadrilateral dummy))) (raise 'parallelogram (list (cons 'trapezoid dummy))) (raise 'rectangle (list (cons 'parallelogram dummy))) (raise 'square (list (cons 'rhombus dummy) (cons 'rectangle dummy))) (raise 'rhombus (list (cons 'parallelogram dummy) (cons 'kite dummy))) (raise 'kite (list (cons 'quadrilateral dummy))) ) (define (id x) x) (define (zip-with fn a b) (cond ((null? a) '()) (else (cons (fn (car a) (car b)) (zip-with fn (cdr a) (cdr b)))))) (define (flatmap fn a) (foldl (lambda (elem init) (append init elem)) '() (map fn a))) (define (supertype-chains A) (define (try-extend-chains chains) (define uptypes (map (lambda (path) (let ((uptype (get 'raise (car (last path))))) (if uptype uptype '()))) chains)) (define extended-chains (zip-with (lambda (path uptypes) (if (not (null? uptypes)) (map (lambda (uptype) (append path (list uptype))) uptypes) (list path))) chains uptypes)) (define next-chains (flatmap id extended-chains)) (if (null? (foldl append '() uptypes)) chains (try-extend-chains next-chains))) (try-extend-chains (list (list (cons A id))))) (define (is-subtype a b) (not (null? (flatmap (lambda (path) (if (member b (map car path)) (list b) '())) (supertype-chains a))))) (define (common-supertype types) (define (common-type A B) (define pa (supertype-chains A)) (define pb (supertype-chains B)) (define (common-chain-node a b) (cond ((or (null? a) (null? b)) '()) ((eq? (caar a) (caar b)) (list (caar a))) (else (let ((xa (common-chain-node (cdr a) b)) (xb (common-chain-node a (cdr b)))) (append xa xb))))) (define types (sort (remove-duplicates (flatmap (lambda (a) (flatmap (lambda (b) (common-chain-node a b)) pb)) pa)) is-subtype)) (if (not (null? types)) (car types) '())) (foldl common-type (car types) (cdr types))) (define (convert-from-to-value from to value) (define (convert-chain path value) (define next-value ((cdar path) value)) (if (eq? (caar path) to) next-value (convert-chain (cdr path) next-value))) (car (flatmap (lambda (path) (if (member to (map car path)) (list (convert-chain path value)) '())) (supertype-chains from)))) (module+ test (begin (install-all) (install-raise) (check-equal? (equ? (raise-scheme-number-to-rational 3) (make-rational 6 2)) #t) (check-equal? (equ? (convert-from-to-value 'scheme-number 'complex 2) (make-complex-from-real-imag 2 0)) #t ) (check-equal? (equ? (add (make-complex-from-real-imag 2 3) (make-scheme-number 4)) (make-complex-from-real-imag 6 3)) #t) )) (module+ test (begin (install-geometry-raise) (check-equal? (common-supertype (list 'rectangle 'kite 'trapezoid)) 'quadrilateral) ))
fdad9cc0b91fde7eee7b759d371ebafa86941700ad8ffe885043d89dfd4c19ad
janestreet/merlin-jst
type_enclosing.ml
open Std let log_section = "type-enclosing" let {Logger.log} = Logger.for_section log_section type type_info = | Modtype of Env.t * Types.module_type | Type of Env.t * Types.type_expr | Type_decl of Env.t * Ident.t * Types.type_declaration | String of string type typed_enclosings = (Location.t * type_info * Query_protocol.is_tail_position) list let from_nodes ~path = let aux (env, node, tail) = let open Browse_raw in let ret x = Some (Mbrowse.node_loc node, x, tail) in match[@ocaml.warning "-9"] node with | Expression {exp_type = t} | Pattern {pat_type = t} | Core_type {ctyp_type = t} | Value_description { val_desc = { ctyp_type = t } } -> ret (Type (env, t)) | Type_declaration { typ_id = id; typ_type = t} -> ret (Type_decl (env, id, t)) | Module_expr {mod_type = Types.Mty_for_hole} -> None | Module_expr {mod_type = m} | Module_type {mty_type = m} | Module_binding {mb_expr = {mod_type = m}} | Module_declaration {md_type = {mty_type = m}} | Module_type_declaration {mtd_type = Some {mty_type = m}} | Module_binding_name {mb_expr = {mod_type = m}} | Module_declaration_name {md_type = {mty_type = m}} | Module_type_declaration_name {mtd_type = Some {mty_type = m}} -> ret (Modtype (env, m)) | Class_field { cf_desc = Tcf_method (_, _, Tcfk_concrete (_, {exp_type})) } -> begin match Types.get_desc exp_type with | Tarrow (_, _, t, _) -> ret (Type (env, t)) | _ -> None end | Class_field { cf_desc = Tcf_val (_, _, _, Tcfk_concrete (_, {exp_type = t }), _) } -> ret (Type (env, t)) | Class_field { cf_desc = Tcf_method (_, _, Tcfk_virtual {ctyp_type = t }) } -> ret (Type (env, t)) | Class_field { cf_desc = Tcf_val (_, _, _, Tcfk_virtual {ctyp_type = t }, _) } -> ret (Type (env, t)) | _ -> None in List.filter_map ~f:aux path let from_reconstructed ~nodes ~cursor ~verbosity exprs = let open Browse_raw in let env, node = Mbrowse.leaf_node nodes in log ~title:"from_reconstructed" "node = %s\nexprs = [%s]" (Browse_raw.string_of_node node) (String.concat ~sep:";" (List.map exprs ~f:(fun l -> l.Location.txt)) ); let include_lident = match node with | Pattern _ -> false | _ -> true in let include_uident = match node with | Module_binding _ | Module_binding_name _ | Module_declaration _ | Module_declaration_name _ | Module_type_declaration _ | Module_type_declaration_name _ -> false | _ -> true in let get_context lident = Context.inspect_browse_tree ~cursor (Longident.parse lident) [nodes] in let f = fun {Location. txt = source; loc} -> let context = get_context source in Option.iter context ~f:(fun ctx -> log ~title:"from_reconstructed" "source = %s; context = %s" source (Context.to_string ctx)); match context with Retrieve the type from the AST when it is possible | Some (Context.Constructor (cd, loc)) -> log ~title:"from_reconstructed" "ctx: constructor %s" cd.cstr_name; let ppf, to_string = Format.to_string () in Type_utils.print_constr ~verbosity env ppf cd; Some (loc, String (to_string ()), `No) | Some (Context.Label { lbl_name; lbl_arg; _ }) -> log ~title:"from_reconstructed" "ctx: label %s" lbl_name; let ppf, to_string = Format.to_string () in Type_utils.print_type_with_decl ~verbosity env ppf lbl_arg; Some (loc, String (to_string ()), `No) | Some Context.Constant -> None | _ -> let context = Option.value ~default:Context.Expr context in (* Else use the reconstructed identifier *) match source with | "" -> log ~title:"from_reconstructed" "no reconstructed identifier"; None | source when not include_lident && Char.is_lowercase source.[0] -> log ~title:"from_reconstructed" "skipping lident"; None | source when not include_uident && Char.is_uppercase source.[0] -> log ~title:"from_reconstructed" "skipping uident"; None | source -> try let ppf, to_string = Format.to_string () in if Type_utils.type_in_env ~verbosity ~context env ppf source then ( log ~title:"from_reconstructed" "typed %s" source; Some (loc, String (to_string ()), `No) ) else ( log ~title:"from_reconstructed" "FAILED to type %s" source; None ) with _ -> None in List.filter_map exprs ~f
null
https://raw.githubusercontent.com/janestreet/merlin-jst/9c3b60c98d80b56af18ea95c27a0902f0244659a/src/analysis/type_enclosing.ml
ocaml
Else use the reconstructed identifier
open Std let log_section = "type-enclosing" let {Logger.log} = Logger.for_section log_section type type_info = | Modtype of Env.t * Types.module_type | Type of Env.t * Types.type_expr | Type_decl of Env.t * Ident.t * Types.type_declaration | String of string type typed_enclosings = (Location.t * type_info * Query_protocol.is_tail_position) list let from_nodes ~path = let aux (env, node, tail) = let open Browse_raw in let ret x = Some (Mbrowse.node_loc node, x, tail) in match[@ocaml.warning "-9"] node with | Expression {exp_type = t} | Pattern {pat_type = t} | Core_type {ctyp_type = t} | Value_description { val_desc = { ctyp_type = t } } -> ret (Type (env, t)) | Type_declaration { typ_id = id; typ_type = t} -> ret (Type_decl (env, id, t)) | Module_expr {mod_type = Types.Mty_for_hole} -> None | Module_expr {mod_type = m} | Module_type {mty_type = m} | Module_binding {mb_expr = {mod_type = m}} | Module_declaration {md_type = {mty_type = m}} | Module_type_declaration {mtd_type = Some {mty_type = m}} | Module_binding_name {mb_expr = {mod_type = m}} | Module_declaration_name {md_type = {mty_type = m}} | Module_type_declaration_name {mtd_type = Some {mty_type = m}} -> ret (Modtype (env, m)) | Class_field { cf_desc = Tcf_method (_, _, Tcfk_concrete (_, {exp_type})) } -> begin match Types.get_desc exp_type with | Tarrow (_, _, t, _) -> ret (Type (env, t)) | _ -> None end | Class_field { cf_desc = Tcf_val (_, _, _, Tcfk_concrete (_, {exp_type = t }), _) } -> ret (Type (env, t)) | Class_field { cf_desc = Tcf_method (_, _, Tcfk_virtual {ctyp_type = t }) } -> ret (Type (env, t)) | Class_field { cf_desc = Tcf_val (_, _, _, Tcfk_virtual {ctyp_type = t }, _) } -> ret (Type (env, t)) | _ -> None in List.filter_map ~f:aux path let from_reconstructed ~nodes ~cursor ~verbosity exprs = let open Browse_raw in let env, node = Mbrowse.leaf_node nodes in log ~title:"from_reconstructed" "node = %s\nexprs = [%s]" (Browse_raw.string_of_node node) (String.concat ~sep:";" (List.map exprs ~f:(fun l -> l.Location.txt)) ); let include_lident = match node with | Pattern _ -> false | _ -> true in let include_uident = match node with | Module_binding _ | Module_binding_name _ | Module_declaration _ | Module_declaration_name _ | Module_type_declaration _ | Module_type_declaration_name _ -> false | _ -> true in let get_context lident = Context.inspect_browse_tree ~cursor (Longident.parse lident) [nodes] in let f = fun {Location. txt = source; loc} -> let context = get_context source in Option.iter context ~f:(fun ctx -> log ~title:"from_reconstructed" "source = %s; context = %s" source (Context.to_string ctx)); match context with Retrieve the type from the AST when it is possible | Some (Context.Constructor (cd, loc)) -> log ~title:"from_reconstructed" "ctx: constructor %s" cd.cstr_name; let ppf, to_string = Format.to_string () in Type_utils.print_constr ~verbosity env ppf cd; Some (loc, String (to_string ()), `No) | Some (Context.Label { lbl_name; lbl_arg; _ }) -> log ~title:"from_reconstructed" "ctx: label %s" lbl_name; let ppf, to_string = Format.to_string () in Type_utils.print_type_with_decl ~verbosity env ppf lbl_arg; Some (loc, String (to_string ()), `No) | Some Context.Constant -> None | _ -> let context = Option.value ~default:Context.Expr context in match source with | "" -> log ~title:"from_reconstructed" "no reconstructed identifier"; None | source when not include_lident && Char.is_lowercase source.[0] -> log ~title:"from_reconstructed" "skipping lident"; None | source when not include_uident && Char.is_uppercase source.[0] -> log ~title:"from_reconstructed" "skipping uident"; None | source -> try let ppf, to_string = Format.to_string () in if Type_utils.type_in_env ~verbosity ~context env ppf source then ( log ~title:"from_reconstructed" "typed %s" source; Some (loc, String (to_string ()), `No) ) else ( log ~title:"from_reconstructed" "FAILED to type %s" source; None ) with _ -> None in List.filter_map exprs ~f
2971daa83c5a12e0eee28b48eb73617e03cf4ba3bb54e12fecc84db8df210f57
silky/quipper
Example4.hs
This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the -- file COPYRIGHT for a list of authors, copyright holders, licensing, -- and other details. All rights reserved. -- -- ====================================================================== import Quipper example4 :: (Qubit, Qubit, Qubit) -> Circ (Qubit, Qubit, Qubit) example4(q, a, b) = do with_ancilla $ \c -> do qnot_at c `controlled` [a, b] hadamard q `controlled` [c] qnot_at c `controlled` [a, b] return (q, a, b) main = print_simple Preview example4
null
https://raw.githubusercontent.com/silky/quipper/1ef6d031984923d8b7ded1c14f05db0995791633/tests/Example4.hs
haskell
file COPYRIGHT for a list of authors, copyright holders, licensing, and other details. All rights reserved. ======================================================================
This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the import Quipper example4 :: (Qubit, Qubit, Qubit) -> Circ (Qubit, Qubit, Qubit) example4(q, a, b) = do with_ancilla $ \c -> do qnot_at c `controlled` [a, b] hadamard q `controlled` [c] qnot_at c `controlled` [a, b] return (q, a, b) main = print_simple Preview example4
4364998876ee04337dbd8319440cd60f91ee9a4be99558c8a152e4fabc967423
reborg/clojure-essential-reference
10.clj
< 1 > #(nthrest lines %)) < 2 > #(take-while (some-fn header? metric?) %)) (defn filter-pattern [lines] ; <3> (sequence (comp (map (all-except-first lines)) (keep if-header-or-metric) (filter pattern?)) (range (count lines)))) (filter-pattern device-output) ;; ((["Wireless" "MXD" ""] [ " ClassA " " 34.97 " " " " 34.5 " ] [ " ClassB " " 11.7 " " 11.4 " ] ) ;; (["Wired" "QXD"] [ " ClassA " " 34.97 " " 33.6 " " 34.5 " ] [ " ClassC " " 11.0 " " 11.4 " ] ) )
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Sequences/SequentialCollections/seqandsequence/10.clj
clojure
<3> ((["Wireless" "MXD" ""] (["Wired" "QXD"]
< 1 > #(nthrest lines %)) < 2 > #(take-while (some-fn header? metric?) %)) (sequence (comp (map (all-except-first lines)) (keep if-header-or-metric) (filter pattern?)) (range (count lines)))) (filter-pattern device-output) [ " ClassA " " 34.97 " " " " 34.5 " ] [ " ClassB " " 11.7 " " 11.4 " ] ) [ " ClassA " " 34.97 " " 33.6 " " 34.5 " ] [ " ClassC " " 11.0 " " 11.4 " ] ) )
3ac6abdb5fcb9bfb68170e8fa7e62998b5a79ce9196a2135a197b21f0194614e
Elastifile/git-sling
Main.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TupleSections # module Main where import Control.Monad (when, void, forM_) import Control.Monad.IO.Class (liftIO) import Data.IORef import Data.Maybe (fromMaybe, mapMaybe) import Data.Text (Text) import qualified Data.Text as T import Data.Time.Clock.POSIX (getPOSIXTime) import Sling.Git (Branch (..), Ref (..), Remote (..), mkBranchName) import qualified Sling.Git as Git import Sling.Lib (EShell, abort, Hash(..), eprocsL, formatEmail, eprint, ignoreError, runEShell) import qualified Sling import Sling.Options (parseOpts, OptServerId(..), PrepushCmd(..), CommandType(..), PrepushMode(..), FilterOptions(..), Options(..), PollOptions(..), PollMode(..),) import Sling.Path (encodeFP) import Sling.Prepush (PrepushLogs(..)) import Sling.Proposal import qualified Sling.Proposal as Proposal import Sling.Email (sendProposalEmail, EmailType(..)) import Sling.Web (forkServer, CurrentState(..), emptyCurrentState) import Text.Regex.Posix ((=~)) import Turtle (ExitCode, (&)) import qualified Data.List as List import Network.BSD (getHostName) import qualified Filesystem.Path.CurrentOS as FP import System.IO.Temp (createTempDirectory) import qualified Text.Blaze.Html5 as H import Control.Concurrent (threadDelay) import Options.Applicative import Prelude hiding (FilePath) pollingInterval :: Int pollingInterval = 1000000 * 10 origin :: Remote origin = Remote "origin" resetLocalOnto :: Proposal -> EShell () resetLocalOnto proposal = do let ontoBranchName = proposalBranchOnto proposal localOntoBranch = RefBranch $ LocalBranch ontoBranchName remoteOntoBranch = RefBranch $ RemoteBranch origin ontoBranchName localExists <- Git.exists localOntoBranch remoteExists <- Git.exists remoteOntoBranch when (localExists && remoteExists) $ do Git.checkout localOntoBranch Git.reset Git.ResetHard remoteOntoBranch cleanupGit :: Proposal -> EShell () cleanupGit proposal = do Git.rebaseAbort & ignoreError Git.reset Git.ResetHard RefHead resetLocalOnto proposal ---------------------------------------------------------------------- clearCurrentProposal :: IORef CurrentState -> IO () clearCurrentProposal currentState = modifyIORef currentState $ \state -> state { csCurrentProposal = Nothing , csCurrentLogFile = Nothing } setStateProposal :: (Show a, Foldable t) => IORef CurrentState -> Proposal -> t a -> EShell () setStateProposal currentState proposal commits = do time <- liftIO getPOSIXTime liftIO $ modifyIORef currentState $ \state -> state { csCurrentProposal = Just (proposal, time) } eprint $ "Attempting proposal: " <> formatProposal proposal eprint "Commits: " mapM_ (eprint . T.pack . show) commits setCurrentLogFile :: IORef CurrentState -> Text -> EShell () setCurrentLogFile currentState logFileName = liftIO $ modifyIORef currentState $ \state -> state { csCurrentLogFile = Just $ T.unpack logFileName } setCurrentJob :: IORef CurrentState -> Text -> Sling.Job -> EShell () setCurrentJob currentState logFileName (Sling.Job proposal baseRef headRef) = do commits <- Git.log baseRef headRef setStateProposal currentState proposal commits setCurrentLogFile currentState logFileName ---------------------------------------------------------------------- abortAttempt :: IORef CurrentState -> Options -> Proposal -> (Text, ExitCode) -> EShell a abortAttempt currentState options proposal (msg, _err) = do eprint . T.pack $ "ABORTING: " ++ show msg sendProposalEmail options proposal "Aborting" (H.html $ H.text msg) Nothing ProposalFailureEmail cleanupGit proposal liftIO $ clearCurrentProposal currentState abort "Aborted" slingBranchName :: Maybe Prefix -> Text -> Git.BranchName slingBranchName Nothing suffix = mkBranchName suffix slingBranchName (Just prefix) suffix = mkBranchName $ prefixToText prefix <> suffix ---------------------------------------------------------------------- tryTakeJob :: ServerId -> Options -> (Branch, Proposal) -> EShell (Maybe Sling.Job) tryTakeJob serverId options (branch, proposal) = do cleanupBranches -- remove leftover branches Git.fetch -- cleanup leftover state from previous runs cleanupGit proposal Sling.tryTakeJob serverId options origin (branch, proposal) attemptBranchOrAbort :: ServerId -> IORef CurrentState -> Options -> PrepushCmd -> Branch -> Proposal -> EShell () attemptBranchOrAbort serverId currentState options prepushCmd branch proposal = do job' <- tryTakeJob serverId options (branch, proposal) case job' of Nothing -> return () -- ignore Just job -> do dirPath <- FP.decodeString <$> liftIO (createTempDirectory "/tmp" "sling.log") logFileName <- head <$> eprocsL "mktemp" ["-p", encodeFP dirPath, "prepush.XXXXXXX.txt"] let prepushLogs = PrepushLogs dirPath (FP.fromText logFileName) setCurrentJob currentState logFileName job -- DO IT! Sling.runPrepush options origin prepushCmd prepushLogs job Sling.transitionProposal options origin job (Just prepushLogs) eprint $ "Finished handling proposal " <> formatProposal proposal ---------------------------------------------------------------------- usage :: String usage = List.intercalate "\n" [ "Usage: sling-server COMMAND" , "" , "where COMMAND is the prepush command to run on each attempted branch." ] filterByStatus :: FilterOptions -> Proposal -> Bool filterByStatus filterOptions proposal = case proposalStatus proposal of ProposalProposed{} -> True ProposalInProgress{} -> not $ optNoInProgress filterOptions ProposalRejected -> False shouldConsiderProposal :: FilterOptions -> Proposal -> Bool shouldConsiderProposal filterOptions proposal = (filterByStatus filterOptions proposal) && (optSourcePrefix filterOptions == proposalPrefix proposal) && fromMaybe True (checkFilter <$> optBranchFilterAll filterOptions) && fromMaybe True (not . checkFilter <$> optBranchExcludeFilterAll filterOptions) && fromMaybe True (((not $ proposalDryRun proposal) ||) . checkFilter <$> optBranchFilterDryRun filterOptions) && fromMaybe True ((proposalDryRun proposal ||) . checkFilter <$> optBranchFilterNoDryRun filterOptions) where checkFilter pat = (T.unpack . Git.fromBranchName $ proposalBranchOnto proposal) =~ pat handleSpecificProposal :: ServerId -> IORef CurrentState -> Options -> PrepushCmd -> Proposal -> EShell () handleSpecificProposal serverId state options prepushCmd proposal = do Git.fetch allProposals <- getProposals let matchingBranches = filter (\(_b, p) -> proposal == p) allProposals branch <- case matchingBranches of [] -> abort $ "Failed to find branch for proposal: " <> formatProposal proposal [(b, _p)] -> return b _ -> abort $ "Assertion failed: multiple branches matching the same proposal: " <> formatProposal proposal attemptBranchOrAbort serverId state options prepushCmd branch proposal parseProposals :: [Branch] -> [(Branch, Proposal)] parseProposals remoteBranches = List.sortOn (proposalQueueIndex . snd) $ mapMaybe (\branch -> (branch,) <$> Proposal.fromBranchName (Git.branchName branch)) remoteBranches getProposals :: EShell [(Branch, Proposal)] getProposals = parseProposals . map (uncurry Git.RemoteBranch) <$> Git.remoteBranches getFilteredProposals :: ServerId -> FilterOptions -> EShell [(Branch, Proposal)] getFilteredProposals serverId filterOptions = do allProposals <- getProposals let filteredProposals = filter (shouldConsiderProposal filterOptions . snd) allProposals isInProgress proposal = case proposalStatus proposal of ProposalInProgress{} -> True _ -> False forThisServer proposal = case proposalStatus proposal of ProposalProposed{} -> True ProposalInProgress proposalServerId -> proposalServerId == serverId ProposalRejected -> False proposalsForThisServer = filter (forThisServer . snd) filteredProposals if optNoConcurrent filterOptions && any (isInProgress . snd) filteredProposals then return [] else return $ if optInProgressFromAnyServer filterOptions then filteredProposals else proposalsForThisServer cleanupBranches :: EShell () cleanupBranches = do slingLocalBranches <- map fst . mapMaybe (\b -> fmap (b,) . parseProposal . Git.fromBranchName $ b) <$> Git.localBranches mapM_ (\x -> Git.deleteLocalBranch x & ignoreError) slingLocalBranches serverPoll :: ServerId -> IORef CurrentState -> Options -> PrepushCmd -> PollOptions -> EShell Bool serverPoll serverId currentState options prepushCmd pollOptions = do let filterOptions = optFilterOptions pollOptions allProposals <- getProposals proposals <- getFilteredProposals serverId filterOptions eprint . T.pack $ mconcat $ List.intersperse "\n\t" [ "Filters: " , maybe "" ("match filter: " <> ) (optBranchFilterAll filterOptions) , maybe "" ("exclude filter: " <> ) (optBranchExcludeFilterAll filterOptions) , maybe "" ("dry run branch filter: " <> ) (optBranchFilterDryRun filterOptions) , maybe "" ("non-dry-run branch filter: " <> ) (optBranchFilterNoDryRun filterOptions) ] eprint . T.pack $ "Allow concurrent: " <> if optNoConcurrent filterOptions then "No" else "Yes" eprint . T.pack $ mconcat $ List.intersperse "\n\t" [ "Prefixes: " , "Source: " <> maybe "" (T.unpack . prefixToText) (optSourcePrefix filterOptions) , "Target: " <> maybe "" (T.unpack . prefixToText) (optTargetPrefix options) ] let showProposals ps = List.intercalate "\n\t" (map (show . Git.branchName . fst) ps) eprint . T.pack $ "All proposals (before filtering):\n\t" <> showProposals allProposals eprint . T.pack $ "Going to attempt proposals:\n\t" <> showProposals proposals liftIO $ modifyIORef currentState $ \state -> state { csPendingProposals = map snd proposals } case proposals of [] -> do eprint "Done - have nothing to do." return False (topProposal:_) -> do (uncurry $ attemptBranchOrAbort serverId currentState options prepushCmd) topProposal liftIO $ clearCurrentProposal currentState eprint . T.pack $ "Done proposal: " ++ show topProposal return True serverLoop :: ServerId -> IORef CurrentState -> Options -> PrepushCmd -> PollOptions -> EShell () serverLoop serverId currentState options prepushCmd pollOptions = do void $ liftIO $ forkServer (optWebServerPort options) (readIORef currentState) let go = do havePending <- serverPoll serverId currentState options prepushCmd pollOptions case optPollMode pollOptions of PollModeOneShot -> return () PollModeAllQueued -> when havePending go PollModeDaemon interval -> do liftIO $ threadDelay $ interval*1000000 go go notInProgress :: Proposal -> Bool notInProgress proposal = case Proposal.proposalStatus proposal of Proposal.ProposalInProgress{} -> False _ -> True main :: IO () main = runEShell $ do options <- liftIO parseOpts currentState <- liftIO $ newIORef emptyCurrentState hostName <- liftIO getHostName let serverId = ServerId $ case optServerId options of OptServerIdHostName -> T.pack hostName OptServerIdName serverIdName -> serverIdName Git.configRemoteFetch origin Git.fetch case optCommandType options of CommandTypePropose (ProposalModePoll pollOptions) prepushCmd -> serverLoop serverId currentState options prepushCmd pollOptions CommandTypePropose (ProposalModeSingle proposal) prepushCmd -> handleSpecificProposal serverId currentState options prepushCmd proposal CommandTypeList pollOptions -> do proposals <- getFilteredProposals serverId pollOptions forM_ proposals $ \(branch, proposal) -> liftIO $ putStrLn $ T.unpack $ (Git.fromBranchName (Git.branchName branch) <> " " <> formatEmail (proposalEmail proposal)) CommandTypeRebase pollOptions -> do proposals <- getFilteredProposals serverId pollOptions forM_ proposals $ Sling.updateProposal options origin CommandTypeTakeJob pollOptions -> do proposals <- getFilteredProposals serverId pollOptions case proposals of (topProposal:_) -> do mjob <- tryTakeJob serverId options topProposal case mjob of Nothing -> return () Just (Sling.Job proposal baseRef headRef) -> do baseHash <- Git.refToHash baseRef headHash <- Git.refToHash headRef liftIO $ mapM_ putStrLn $ [ T.unpack (Proposal.formatProposal proposal) , T.unpack $ fromHash baseHash , T.unpack $ fromHash headHash , T.unpack $ formatEmail $ Proposal.proposalEmail proposal , T.unpack $ Git.fromBranchName $ Proposal.proposalBranchOnto proposal ] _ -> return () CommandTypeTransition proposal -> do case Proposal.proposalType proposal of Proposal.ProposalTypeRebase{} -> abort "Can't transition a rebase proposal" Proposal.ProposalTypeMerge _mergeType baseHash -> do headRef <- Git.RefHash <$> Git.refToHash (Git.RefBranch $ Git.RemoteBranch origin (Proposal.toBranchName proposal)) Sling.transitionProposal options origin (Sling.Job proposal (Git.RefHash baseHash) headRef) Nothing CommandTypeReject proposal reason -> do Sling.rejectProposal options origin proposal reason Nothing Nothing
null
https://raw.githubusercontent.com/Elastifile/git-sling/a92f1836910c0a4d8105ca0dff9d1bd08e9bb181/server/app/Main.hs
haskell
# LANGUAGE OverloadedStrings # -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- remove leftover branches cleanup leftover state from previous runs ignore DO IT! --------------------------------------------------------------------
# LANGUAGE FlexibleContexts # # LANGUAGE TupleSections # module Main where import Control.Monad (when, void, forM_) import Control.Monad.IO.Class (liftIO) import Data.IORef import Data.Maybe (fromMaybe, mapMaybe) import Data.Text (Text) import qualified Data.Text as T import Data.Time.Clock.POSIX (getPOSIXTime) import Sling.Git (Branch (..), Ref (..), Remote (..), mkBranchName) import qualified Sling.Git as Git import Sling.Lib (EShell, abort, Hash(..), eprocsL, formatEmail, eprint, ignoreError, runEShell) import qualified Sling import Sling.Options (parseOpts, OptServerId(..), PrepushCmd(..), CommandType(..), PrepushMode(..), FilterOptions(..), Options(..), PollOptions(..), PollMode(..),) import Sling.Path (encodeFP) import Sling.Prepush (PrepushLogs(..)) import Sling.Proposal import qualified Sling.Proposal as Proposal import Sling.Email (sendProposalEmail, EmailType(..)) import Sling.Web (forkServer, CurrentState(..), emptyCurrentState) import Text.Regex.Posix ((=~)) import Turtle (ExitCode, (&)) import qualified Data.List as List import Network.BSD (getHostName) import qualified Filesystem.Path.CurrentOS as FP import System.IO.Temp (createTempDirectory) import qualified Text.Blaze.Html5 as H import Control.Concurrent (threadDelay) import Options.Applicative import Prelude hiding (FilePath) pollingInterval :: Int pollingInterval = 1000000 * 10 origin :: Remote origin = Remote "origin" resetLocalOnto :: Proposal -> EShell () resetLocalOnto proposal = do let ontoBranchName = proposalBranchOnto proposal localOntoBranch = RefBranch $ LocalBranch ontoBranchName remoteOntoBranch = RefBranch $ RemoteBranch origin ontoBranchName localExists <- Git.exists localOntoBranch remoteExists <- Git.exists remoteOntoBranch when (localExists && remoteExists) $ do Git.checkout localOntoBranch Git.reset Git.ResetHard remoteOntoBranch cleanupGit :: Proposal -> EShell () cleanupGit proposal = do Git.rebaseAbort & ignoreError Git.reset Git.ResetHard RefHead resetLocalOnto proposal clearCurrentProposal :: IORef CurrentState -> IO () clearCurrentProposal currentState = modifyIORef currentState $ \state -> state { csCurrentProposal = Nothing , csCurrentLogFile = Nothing } setStateProposal :: (Show a, Foldable t) => IORef CurrentState -> Proposal -> t a -> EShell () setStateProposal currentState proposal commits = do time <- liftIO getPOSIXTime liftIO $ modifyIORef currentState $ \state -> state { csCurrentProposal = Just (proposal, time) } eprint $ "Attempting proposal: " <> formatProposal proposal eprint "Commits: " mapM_ (eprint . T.pack . show) commits setCurrentLogFile :: IORef CurrentState -> Text -> EShell () setCurrentLogFile currentState logFileName = liftIO $ modifyIORef currentState $ \state -> state { csCurrentLogFile = Just $ T.unpack logFileName } setCurrentJob :: IORef CurrentState -> Text -> Sling.Job -> EShell () setCurrentJob currentState logFileName (Sling.Job proposal baseRef headRef) = do commits <- Git.log baseRef headRef setStateProposal currentState proposal commits setCurrentLogFile currentState logFileName abortAttempt :: IORef CurrentState -> Options -> Proposal -> (Text, ExitCode) -> EShell a abortAttempt currentState options proposal (msg, _err) = do eprint . T.pack $ "ABORTING: " ++ show msg sendProposalEmail options proposal "Aborting" (H.html $ H.text msg) Nothing ProposalFailureEmail cleanupGit proposal liftIO $ clearCurrentProposal currentState abort "Aborted" slingBranchName :: Maybe Prefix -> Text -> Git.BranchName slingBranchName Nothing suffix = mkBranchName suffix slingBranchName (Just prefix) suffix = mkBranchName $ prefixToText prefix <> suffix tryTakeJob :: ServerId -> Options -> (Branch, Proposal) -> EShell (Maybe Sling.Job) tryTakeJob serverId options (branch, proposal) = do Git.fetch cleanupGit proposal Sling.tryTakeJob serverId options origin (branch, proposal) attemptBranchOrAbort :: ServerId -> IORef CurrentState -> Options -> PrepushCmd -> Branch -> Proposal -> EShell () attemptBranchOrAbort serverId currentState options prepushCmd branch proposal = do job' <- tryTakeJob serverId options (branch, proposal) case job' of Just job -> do dirPath <- FP.decodeString <$> liftIO (createTempDirectory "/tmp" "sling.log") logFileName <- head <$> eprocsL "mktemp" ["-p", encodeFP dirPath, "prepush.XXXXXXX.txt"] let prepushLogs = PrepushLogs dirPath (FP.fromText logFileName) setCurrentJob currentState logFileName job Sling.runPrepush options origin prepushCmd prepushLogs job Sling.transitionProposal options origin job (Just prepushLogs) eprint $ "Finished handling proposal " <> formatProposal proposal usage :: String usage = List.intercalate "\n" [ "Usage: sling-server COMMAND" , "" , "where COMMAND is the prepush command to run on each attempted branch." ] filterByStatus :: FilterOptions -> Proposal -> Bool filterByStatus filterOptions proposal = case proposalStatus proposal of ProposalProposed{} -> True ProposalInProgress{} -> not $ optNoInProgress filterOptions ProposalRejected -> False shouldConsiderProposal :: FilterOptions -> Proposal -> Bool shouldConsiderProposal filterOptions proposal = (filterByStatus filterOptions proposal) && (optSourcePrefix filterOptions == proposalPrefix proposal) && fromMaybe True (checkFilter <$> optBranchFilterAll filterOptions) && fromMaybe True (not . checkFilter <$> optBranchExcludeFilterAll filterOptions) && fromMaybe True (((not $ proposalDryRun proposal) ||) . checkFilter <$> optBranchFilterDryRun filterOptions) && fromMaybe True ((proposalDryRun proposal ||) . checkFilter <$> optBranchFilterNoDryRun filterOptions) where checkFilter pat = (T.unpack . Git.fromBranchName $ proposalBranchOnto proposal) =~ pat handleSpecificProposal :: ServerId -> IORef CurrentState -> Options -> PrepushCmd -> Proposal -> EShell () handleSpecificProposal serverId state options prepushCmd proposal = do Git.fetch allProposals <- getProposals let matchingBranches = filter (\(_b, p) -> proposal == p) allProposals branch <- case matchingBranches of [] -> abort $ "Failed to find branch for proposal: " <> formatProposal proposal [(b, _p)] -> return b _ -> abort $ "Assertion failed: multiple branches matching the same proposal: " <> formatProposal proposal attemptBranchOrAbort serverId state options prepushCmd branch proposal parseProposals :: [Branch] -> [(Branch, Proposal)] parseProposals remoteBranches = List.sortOn (proposalQueueIndex . snd) $ mapMaybe (\branch -> (branch,) <$> Proposal.fromBranchName (Git.branchName branch)) remoteBranches getProposals :: EShell [(Branch, Proposal)] getProposals = parseProposals . map (uncurry Git.RemoteBranch) <$> Git.remoteBranches getFilteredProposals :: ServerId -> FilterOptions -> EShell [(Branch, Proposal)] getFilteredProposals serverId filterOptions = do allProposals <- getProposals let filteredProposals = filter (shouldConsiderProposal filterOptions . snd) allProposals isInProgress proposal = case proposalStatus proposal of ProposalInProgress{} -> True _ -> False forThisServer proposal = case proposalStatus proposal of ProposalProposed{} -> True ProposalInProgress proposalServerId -> proposalServerId == serverId ProposalRejected -> False proposalsForThisServer = filter (forThisServer . snd) filteredProposals if optNoConcurrent filterOptions && any (isInProgress . snd) filteredProposals then return [] else return $ if optInProgressFromAnyServer filterOptions then filteredProposals else proposalsForThisServer cleanupBranches :: EShell () cleanupBranches = do slingLocalBranches <- map fst . mapMaybe (\b -> fmap (b,) . parseProposal . Git.fromBranchName $ b) <$> Git.localBranches mapM_ (\x -> Git.deleteLocalBranch x & ignoreError) slingLocalBranches serverPoll :: ServerId -> IORef CurrentState -> Options -> PrepushCmd -> PollOptions -> EShell Bool serverPoll serverId currentState options prepushCmd pollOptions = do let filterOptions = optFilterOptions pollOptions allProposals <- getProposals proposals <- getFilteredProposals serverId filterOptions eprint . T.pack $ mconcat $ List.intersperse "\n\t" [ "Filters: " , maybe "" ("match filter: " <> ) (optBranchFilterAll filterOptions) , maybe "" ("exclude filter: " <> ) (optBranchExcludeFilterAll filterOptions) , maybe "" ("dry run branch filter: " <> ) (optBranchFilterDryRun filterOptions) , maybe "" ("non-dry-run branch filter: " <> ) (optBranchFilterNoDryRun filterOptions) ] eprint . T.pack $ "Allow concurrent: " <> if optNoConcurrent filterOptions then "No" else "Yes" eprint . T.pack $ mconcat $ List.intersperse "\n\t" [ "Prefixes: " , "Source: " <> maybe "" (T.unpack . prefixToText) (optSourcePrefix filterOptions) , "Target: " <> maybe "" (T.unpack . prefixToText) (optTargetPrefix options) ] let showProposals ps = List.intercalate "\n\t" (map (show . Git.branchName . fst) ps) eprint . T.pack $ "All proposals (before filtering):\n\t" <> showProposals allProposals eprint . T.pack $ "Going to attempt proposals:\n\t" <> showProposals proposals liftIO $ modifyIORef currentState $ \state -> state { csPendingProposals = map snd proposals } case proposals of [] -> do eprint "Done - have nothing to do." return False (topProposal:_) -> do (uncurry $ attemptBranchOrAbort serverId currentState options prepushCmd) topProposal liftIO $ clearCurrentProposal currentState eprint . T.pack $ "Done proposal: " ++ show topProposal return True serverLoop :: ServerId -> IORef CurrentState -> Options -> PrepushCmd -> PollOptions -> EShell () serverLoop serverId currentState options prepushCmd pollOptions = do void $ liftIO $ forkServer (optWebServerPort options) (readIORef currentState) let go = do havePending <- serverPoll serverId currentState options prepushCmd pollOptions case optPollMode pollOptions of PollModeOneShot -> return () PollModeAllQueued -> when havePending go PollModeDaemon interval -> do liftIO $ threadDelay $ interval*1000000 go go notInProgress :: Proposal -> Bool notInProgress proposal = case Proposal.proposalStatus proposal of Proposal.ProposalInProgress{} -> False _ -> True main :: IO () main = runEShell $ do options <- liftIO parseOpts currentState <- liftIO $ newIORef emptyCurrentState hostName <- liftIO getHostName let serverId = ServerId $ case optServerId options of OptServerIdHostName -> T.pack hostName OptServerIdName serverIdName -> serverIdName Git.configRemoteFetch origin Git.fetch case optCommandType options of CommandTypePropose (ProposalModePoll pollOptions) prepushCmd -> serverLoop serverId currentState options prepushCmd pollOptions CommandTypePropose (ProposalModeSingle proposal) prepushCmd -> handleSpecificProposal serverId currentState options prepushCmd proposal CommandTypeList pollOptions -> do proposals <- getFilteredProposals serverId pollOptions forM_ proposals $ \(branch, proposal) -> liftIO $ putStrLn $ T.unpack $ (Git.fromBranchName (Git.branchName branch) <> " " <> formatEmail (proposalEmail proposal)) CommandTypeRebase pollOptions -> do proposals <- getFilteredProposals serverId pollOptions forM_ proposals $ Sling.updateProposal options origin CommandTypeTakeJob pollOptions -> do proposals <- getFilteredProposals serverId pollOptions case proposals of (topProposal:_) -> do mjob <- tryTakeJob serverId options topProposal case mjob of Nothing -> return () Just (Sling.Job proposal baseRef headRef) -> do baseHash <- Git.refToHash baseRef headHash <- Git.refToHash headRef liftIO $ mapM_ putStrLn $ [ T.unpack (Proposal.formatProposal proposal) , T.unpack $ fromHash baseHash , T.unpack $ fromHash headHash , T.unpack $ formatEmail $ Proposal.proposalEmail proposal , T.unpack $ Git.fromBranchName $ Proposal.proposalBranchOnto proposal ] _ -> return () CommandTypeTransition proposal -> do case Proposal.proposalType proposal of Proposal.ProposalTypeRebase{} -> abort "Can't transition a rebase proposal" Proposal.ProposalTypeMerge _mergeType baseHash -> do headRef <- Git.RefHash <$> Git.refToHash (Git.RefBranch $ Git.RemoteBranch origin (Proposal.toBranchName proposal)) Sling.transitionProposal options origin (Sling.Job proposal (Git.RefHash baseHash) headRef) Nothing CommandTypeReject proposal reason -> do Sling.rejectProposal options origin proposal reason Nothing Nothing
8284afd96ff412b89005b426f9c5d022653ac53f242bebb8f6ee3069aabf49cf
jyh/metaprl
kat_terms.mli
extends Base_theory extends Support_algebra extends Base_select extends Itt_struct2 (************************************************************************ * TERMS * ************************************************************************) 1 and 0 declare prod{'x;'y} (* 'x * 'y *) declare union{'x;'y} (* 'x + 'y *) declare minus{'x} (* ~'x *) ' x^ * declare bool declare kleene declare le{'x; 'y} declare ge{'x; 'y}
null
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/kat/kat_terms.mli
ocaml
*********************************************************************** * TERMS * *********************************************************************** 'x * 'y 'x + 'y ~'x
extends Base_theory extends Support_algebra extends Base_select extends Itt_struct2 1 and 0 ' x^ * declare bool declare kleene declare le{'x; 'y} declare ge{'x; 'y}
c723cc5712180e44aaff12be5370c50419eb6290971edf05b7a99604747b2b76
input-output-hk/ouroboros-network
TrackUpdates.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE LambdaCase # {-# LANGUAGE MultiWayIf #-} # LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # module Test.ThreadNet.Infra.Byron.TrackUpdates ( ProtocolVersionUpdateLabel (..) , SoftwareVersionUpdateLabel (..) , mkProtocolByronAndHardForkTxs , mkUpdateLabels ) where import Control.Exception (assert) import Control.Monad (guard) import Data.ByteString (ByteString) import Data.Coerce (coerce) import Data.Functor.Identity import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe) import Data.Set (Set) import qualified Data.Set as Set import Data.Word (Word64) import GHC.Stack (HasCallStack) import qualified Cardano.Chain.Block as Block import qualified Cardano.Chain.Byron.API as ByronAPI import qualified Cardano.Chain.Genesis as Genesis import qualified Cardano.Chain.MempoolPayload as MempoolPayload import Cardano.Chain.Slotting (EpochSlots (..), SlotNumber (..)) import qualified Cardano.Chain.Update as Update import Cardano.Chain.Update.Proposal (AProposal) import qualified Cardano.Chain.Update.Proposal as Proposal import qualified Cardano.Chain.Update.Validation.Interface as Update import qualified Cardano.Chain.Update.Validation.Registration as Registration import Cardano.Chain.Update.Vote (AVote) import qualified Cardano.Chain.Update.Vote as Vote import qualified Cardano.Crypto as Crypto import Cardano.Ledger.Binary (ByteSpan, DecCBOR (..), EncCBOR (..)) import Ouroboros.Consensus.Block import Ouroboros.Consensus.Config import Ouroboros.Consensus.Node.ProtocolInfo (NumCoreNodes (..), ProtocolInfo (..)) import Ouroboros.Consensus.NodeId (CoreNodeId (..)) import Ouroboros.Consensus.Protocol.PBFT import qualified Ouroboros.Consensus.Byron.Crypto.DSIGN as Crypto import Ouroboros.Consensus.Byron.Ledger (ByronBlock) import qualified Ouroboros.Consensus.Byron.Ledger as Byron import Test.ThreadNet.Network (TestNodeInitialization (..)) import qualified Test.ThreadNet.Ref.PBFT as Ref import Test.ThreadNet.Util.NodeJoinPlan import Test.ThreadNet.Util.NodeTopology import Test.ThreadNet.Infra.Byron.ProtocolInfo import Test.Util.Slots (NumSlots (..)) -- | The expectation and observation regarding whether the hard-fork proposal -- successfully updated the protocol version -- data ProtocolVersionUpdateLabel = ProtocolVersionUpdateLabel { pvuObserved :: Bool -- ^ whether the proposed protocol version is adopted or not adopted by the -- end of the test , pvuRequired :: Maybe Bool -- ^ @Just b@ indicates whether the final chains must have adopted or must -- have not adopted the proposed protocol version. @Nothing@ means there is -- no requirement. } deriving (Show) -- | As 'ProtocolVersionUpdateLabel', but for software version updates -- -- Note that software version updates are adopted sooner than and perhaps -- independently of protocol version updates, even when they are introduced by -- the same proposal transaction. -- data SoftwareVersionUpdateLabel = SoftwareVersionUpdateLabel { svuObserved :: Bool , svuRequired :: Maybe Bool } deriving (Show) -- | Classify the a @QuickCheck@ test's input and output with respect to whether the protocol\/software version should have been\/was updated -- mkUpdateLabels :: PBftParams -> NumSlots -> Genesis.Config -> NodeJoinPlan -> NodeTopology -> Ref.Result -> Byron.LedgerState ByronBlock -- ^ from 'nodeOutputFinalLedger' -> (ProtocolVersionUpdateLabel, SoftwareVersionUpdateLabel) mkUpdateLabels params numSlots genesisConfig nodeJoinPlan topology result ldgr = (pvuLabel, svuLabel) where PBftParams{pbftNumNodes, pbftSecurityParam} = params -- the slot immediately after the end of the simulation sentinel :: SlotNumber sentinel = SlotNumber t where NumSlots t = numSlots a block forged in slot @s@ becomes immutable / stable in slot @s + twoK@ -- according to the Byron Chain Density invariant twoK :: SlotNo twoK = SlotNo $ 2 * maxRollbacks pbftSecurityParam -- the number of slots in an epoch epochSlots :: SlotNo epochSlots = coerce $ Genesis.configEpochSlots genesisConfig -- the protocol parameters -- -- ASSUMPTION: These do not change during the test. pp0 :: Update.ProtocolParameters pp0 = Genesis.configProtocolParameters genesisConfig -- how many votes/endorsements the proposal needs to gain quorum :: Word64 quorum = (\x -> assert (x > 0) x) $ fromIntegral $ Update.upAdptThd (fromIntegral n) pp0 where NumCoreNodes n = pbftNumNodes -- how many slots the proposal has to gain sufficient votes before it -- expires ttl :: SlotNo ttl = coerce $ Update.ppUpdateProposalTTL pp0 the first slot of the epoch after the epoch containing the given slot ebbSlotAfter :: SlotNo -> SlotNo ebbSlotAfter (SlotNo s) = SlotNo (denom * div s denom) + epochSlots where SlotNo denom = epochSlots finalState :: [Ref.Outcome] -> ProposalState finalState outcomes = go Proposing (SlotNo 0) outcomes -- compute the @Just@ case of 'pvuRequired' from the simulated outcomes go :: ProposalState -- ^ the state before the next outcome -> SlotNo -- ^ the slot described by the next outcome -> [Ref.Outcome] -> ProposalState go !st !s = \case [] -> assert (coerce sentinel == s) st o:os -> case o of Ref.Absent -> continueWith st Ref.Unable -> continueWith st Ref.Wasted -> continueWith st Ref.Nominal -> case st of -- the proposal is in this slot Proposing -> let -- if this leader just joined, it will forge before the -- proposal reaches its mempool, unless it's node 0 lostRace = s == leaderJoinSlot && leader /= CoreNodeId 0 in if lostRace then continueWith st else votes can be valid immediately and at least one should -- also be in this block go (Voting s Set.empty) s (o:os) Voting proposalSlot votes -> let votesInTheNewBlock = -- an exception to the rule: the proposal and c0's -- own vote always has time to reach its mempool (if leader == c0 then Set.insert c0 else id) $ -- if the leader is joining in this slot, then no -- votes will reach its mempool before it forges: -- other nodes' votes will be delayed via -- communication and its own vote is not valid -- because it will forge before its ledger/mempool -- contains the proposal if s == leaderJoinSlot then Set.empty else -- only votes from nodes that joined prior to this slot can reach the leader 's before it -- forges Map.keysSet $ Map.filter (< s) m where NodeJoinPlan m = nodeJoinPlan c0 = CoreNodeId 0 votes' = Set.union votesInTheNewBlock votes confirmed = fromIntegral (Set.size votes') >= quorum expired = proposalSlot + ttl < s in if -- TODO cardano-ledger-byron checks for quorum before it checks -- for expiry, so we do mimick that here. But is that -- correct? | confirmed -> continueWith $ Endorsing s Set.empty -- c0 will re-propose the same proposal again at the next -- opportunity | expired -> continueWith $ Proposing | otherwise -> continueWith $ Voting proposalSlot votes' Endorsing finalVoteSlot ends -> continueWith $ if s < finalVoteSlot + twoK then st -- ignore endorsements until final vote is stable else let ends' = Set.insert (Ref.mkLeaderOf params s) ends in if fromIntegral (Set.size ends) < quorum then Endorsing finalVoteSlot ends' else Adopting s -- enough endorsements Adopting{} -> continueWith st where leader = Ref.mkLeaderOf params s leaderJoinSlot = coreNodeIdJoinSlot nodeJoinPlan leader continueWith st' = go st' (succ s) os pvuLabel = ProtocolVersionUpdateLabel { pvuObserved = (== theProposedProtocolVersion) $ Update.adoptedProtocolVersion $ Block.cvsUpdateState $ -- tick the chain over into the slot after the final simulated slot ByronAPI.applyChainTick genesisConfig sentinel $ Byron.byronLedgerState ldgr , pvuRequired = case result of ' Ref . Forked ' means there 's only 1 - block chains , and that 's not enough -- for a proposal to succeed Ref.Forked{} -> Just False -- we wouldn't necessarily be able to anticipate when the last -- endorsement happens, so give up Ref.Nondeterministic{} -> Nothing Ref.Outcomes outcomes -> do checkTopo params topology Just $ case finalState outcomes of Proposing{} -> False Voting{} -> False Endorsing{} -> False Adopting finalEndorsementSlot -> ebbSlotAfter (finalEndorsementSlot + twoK) <= s where s = coerce sentinel } svuLabel = SoftwareVersionUpdateLabel { svuObserved = fromMaybe False $ do let nm = Update.svAppName theProposedSoftwareVersion (Registration.ApplicationVersion vn _slot _metadata) <- Map.lookup nm $ Update.appVersions $ Block.cvsUpdateState $ -- unlike for protocol version updates, there is no need to tick -- since the passage of time isn't a prerequisite Byron.byronLedgerState ldgr pure $ vn == Update.svNumber theProposedSoftwareVersion , svuRequired = case result of ' Ref . Forked ' means all blocks except perhaps the first were -- forged in the slot in which the forging node joined, which means -- nodes other than c0 never forged after receiving the proposal. A -- block forged by node c0 will have proposed and might have -- confirmed it (depending on quorum), but the other nodes will not -- have. This is very much a corner case, so we ignore it. Ref.Forked{} -> Nothing -- We wouldn't necessarily be able to anticipate if the proposal is -- confirmed or even in all of the final chains, so we ignore it. Ref.Nondeterministic{} -> Nothing Ref.Outcomes outcomes -> do checkTopo params topology Just $ case finalState outcomes of Proposing{} -> False Voting{} -> False Endorsing{} -> True Adopting{} -> True } -- if the topology is not mesh, then some assumptions in 'finalState' about -- races maybe be wrong -- -- In particular, if the proposal is already on the chain, and the leader of -- the next slot, call it node L, is joining and is only directly connected to -- other nodes that are also joining, then those other node's votes will not reach L 's before it forges in the next slot . In fact , those votes will arrive to node L via TxSub during the current slot but /before/ the block containing the proposal does , so node L 's will reject the -- votes as invalid. The votes are not resent (at least not before node L -- leads). checkTopo :: PBftParams -> NodeTopology -> Maybe () checkTopo params topology = do let PBftParams{pbftNumNodes} = params guard $ topology == meshNodeTopology pbftNumNodes -- | The state of a proposal within a linear timeline -- data ProposalState = Proposing ^ submitting the proposal ( possibly not for the first time , if it has -- previously expired) | Voting !SlotNo !(Set CoreNodeId) -- ^ accumulating sufficient votes -- -- The slot is when the proposal was submitted; it might expire during -- voting. The set is who has voted. | Endorsing !SlotNo !(Set CoreNodeId) -- ^ accumulating sufficient endorsements -- The slot is when the first sufficient vote was submitted . The set is the -- endorsements seen so far. | Adopting !SlotNo -- ^ waiting for epoch transition -- The slot is when the first sufficient endorsement was submitted . deriving (Show) {------------------------------------------------------------------------------- ProtocolVersion update proposals -------------------------------------------------------------------------------} -- | The protocol info for a node as well as some initial transactions -- The transactions implement a smoke test for the hard - fork from Byron to . See PR # 1741 for details on how that hard - fork will work . The key fact is that last thing the nodes will ever do while running the -- protocol is adopt a specific (but as of yet to-be-determined) protocol -- version. So this smoke test ensures that the nodes can in fact adopt a new -- protocol version. -- Adopting a new protocol version requires four kinds of event in . -- Again, see PR #1741 for more details. -- -- * Proposal transaction. A protocol parameter update proposal transaction -- makes it onto the chain (it doesn't have to actually change any -- parameters, just increase the protocol version). Proposals are ' MempoolPayload . MempoolUpdateProposal ' transactions ; one is included in -- the return value of this function. In the smoke test, we immediately and repeatedly throughout the test add the proposal to @CoreNodeId 0@ 's ; this seems realistic . -- * Vote transactions . A sufficient number of nodes ( @floor ( 0.6 * -- 'pbftNumNodes')@ as of this writing) must vote for the proposal. Votes are ' MempoolPayload . MempoolUpdateVote ' transactions ; one per node is -- included in the return value of this function. In the smoke test, we -- immediately and repeatedly throughout the test add each node's vote to -- its own mempool; this seems realistic. -- * Endorsement header field . After enough votes are 2k slots old , a -- sufficient number of nodes (@floor (0.6 * 'pbftNumNodes')@ as of this -- writing) must then endorse the proposal. Endorsements are not transactions . Instead , every header includes a field that specifies -- a protocol version to endorse. At a particular stage of a corresponding -- proposal's lifetime, that field constitutes an endorsement. At all other -- times, it is essentially ignored. In the smoke test, we take advantage of -- that to avoid having to restart our nodes: the nodes' initial -- configuration causes them to immediately and always attempt to endorse -- the proposed protocol version; this seems only slightly unrealistic. -- * Epoch transition . After enough endorsements are 2k slots old , the -- protocol version will be adopted at the next epoch transition, unless -- something else prevents it. In the smoke test, we check the validation -- state of the final chains for the new protocol version when we detect no -- mitigating circumstances, such as the test not even being scheduled to reach the second epoch . -- mkProtocolByronAndHardForkTxs :: forall m. (Monad m, HasCallStack) => PBftParams -> CoreNodeId -> Genesis.Config -> Genesis.GeneratedSecrets -> Update.ProtocolVersion -- ^ the protocol version that triggers the hard fork -> TestNodeInitialization m ByronBlock mkProtocolByronAndHardForkTxs params cid genesisConfig genesisSecrets propPV = TestNodeInitialization { tniCrucialTxs = proposals ++ votes , tniProtocolInfo = pInfo } where ProtocolInfo{pInfoConfig} = pInfo bcfg = configBlock pInfoConfig pInfo :: ProtocolInfo m ByronBlock opKey :: Crypto.SigningKey (pInfo, Crypto.SignKeyByronDSIGN opKey) = mkProtocolByron params cid genesisConfig genesisSecrets proposals :: [Byron.GenTx ByronBlock] proposals = if cid /= CoreNodeId 0 then [] else (:[]) $ Byron.fromMempoolPayload $ MempoolPayload.MempoolUpdateProposal proposal votes :: [Byron.GenTx ByronBlock] votes = (:[]) $ Byron.fromMempoolPayload $ MempoolPayload.MempoolUpdateVote vote vote :: AVote ByteString vote = loopbackAnnotations $ -- signed by delegate SK Vote.signVote (Byron.byronProtocolMagicId bcfg) (Update.recoverUpId proposal) True -- the serialization hardwires this value anyway (Crypto.noPassSafeSigner opKey) proposal :: AProposal ByteString proposal = loopbackAnnotations $ mkHardForkProposal params genesisConfig genesisSecrets propPV -- | A protocol parameter update proposal that doesn't actually change any -- parameter value but does propose 'theProposedProtocolVersion' -- -- Without loss of generality, the proposal is signed by @'CoreNodeId' 0@. -- mkHardForkProposal :: HasCallStack => PBftParams -> Genesis.Config -> Genesis.GeneratedSecrets -> Update.ProtocolVersion -> AProposal () mkHardForkProposal params genesisConfig genesisSecrets propPV = -- signed by delegate SK Proposal.signProposal (Byron.byronProtocolMagicId bcfg) propBody (Crypto.noPassSafeSigner opKey) where pInfo :: ProtocolInfo Identity ByronBlock opKey :: Crypto.SigningKey (pInfo, Crypto.SignKeyByronDSIGN opKey) = mkProtocolByron params (CoreNodeId 0) genesisConfig genesisSecrets ProtocolInfo{pInfoConfig} = pInfo bcfg = configBlock pInfoConfig propBody :: Proposal.ProposalBody propBody = Proposal.ProposalBody { Proposal.protocolVersion = propPV , Proposal.protocolParametersUpdate = Update.ProtocolParametersUpdate { Update.ppuScriptVersion = Nothing , Update.ppuSlotDuration = Nothing , Update.ppuMaxBlockSize = Nothing , Update.ppuMaxHeaderSize = Nothing , Update.ppuMaxTxSize = Nothing , Update.ppuMaxProposalSize = Nothing , Update.ppuMpcThd = Nothing , Update.ppuHeavyDelThd = Nothing , Update.ppuUpdateVoteThd = Nothing , Update.ppuUpdateProposalThd = Nothing , Update.ppuUpdateProposalTTL = Nothing , Update.ppuSoftforkRule = Nothing , Update.ppuTxFeePolicy = Nothing , Update.ppuUnlockStakeEpoch = Nothing } , Proposal.softwareVersion = theProposedSoftwareVersion , Proposal.metadata = Map.empty } -- | Add the bytestring annotations that would be present if we were to -- serialize the argument, send it to ourselves, receive it, and deserialize it -- -- The mempool payloads require the serialized bytes as annotations. It's -- tricky to get right, and this function lets use reuse the existing CBOR -- instances. -- loopbackAnnotations :: ( DecCBOR (f ByteSpan) , EncCBOR (f ()) , Functor f ) => f () -> f ByteString loopbackAnnotations = ByronAPI.reAnnotateUsing encCBOR decCBOR
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/17889be3e1b6d9b5ee86022b91729837051e6fbb/ouroboros-consensus-byron-test/src/Test/ThreadNet/Infra/Byron/TrackUpdates.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE MultiWayIf # | The expectation and observation regarding whether the hard-fork proposal successfully updated the protocol version ^ whether the proposed protocol version is adopted or not adopted by the end of the test ^ @Just b@ indicates whether the final chains must have adopted or must have not adopted the proposed protocol version. @Nothing@ means there is no requirement. | As 'ProtocolVersionUpdateLabel', but for software version updates Note that software version updates are adopted sooner than and perhaps independently of protocol version updates, even when they are introduced by the same proposal transaction. | Classify the a @QuickCheck@ test's input and output with respect to ^ from 'nodeOutputFinalLedger' the slot immediately after the end of the simulation according to the Byron Chain Density invariant the number of slots in an epoch the protocol parameters ASSUMPTION: These do not change during the test. how many votes/endorsements the proposal needs to gain how many slots the proposal has to gain sufficient votes before it expires compute the @Just@ case of 'pvuRequired' from the simulated outcomes ^ the state before the next outcome ^ the slot described by the next outcome the proposal is in this slot if this leader just joined, it will forge before the proposal reaches its mempool, unless it's node 0 also be in this block an exception to the rule: the proposal and c0's own vote always has time to reach its mempool if the leader is joining in this slot, then no votes will reach its mempool before it forges: other nodes' votes will be delayed via communication and its own vote is not valid because it will forge before its ledger/mempool contains the proposal only votes from nodes that joined prior to this forges TODO cardano-ledger-byron checks for quorum before it checks for expiry, so we do mimick that here. But is that correct? c0 will re-propose the same proposal again at the next opportunity ignore endorsements until final vote is stable enough endorsements tick the chain over into the slot after the final simulated slot for a proposal to succeed we wouldn't necessarily be able to anticipate when the last endorsement happens, so give up unlike for protocol version updates, there is no need to tick since the passage of time isn't a prerequisite forged in the slot in which the forging node joined, which means nodes other than c0 never forged after receiving the proposal. A block forged by node c0 will have proposed and might have confirmed it (depending on quorum), but the other nodes will not have. This is very much a corner case, so we ignore it. We wouldn't necessarily be able to anticipate if the proposal is confirmed or even in all of the final chains, so we ignore it. if the topology is not mesh, then some assumptions in 'finalState' about races maybe be wrong In particular, if the proposal is already on the chain, and the leader of the next slot, call it node L, is joining and is only directly connected to other nodes that are also joining, then those other node's votes will not votes as invalid. The votes are not resent (at least not before node L leads). | The state of a proposal within a linear timeline previously expired) ^ accumulating sufficient votes The slot is when the proposal was submitted; it might expire during voting. The set is who has voted. ^ accumulating sufficient endorsements endorsements seen so far. ^ waiting for epoch transition ------------------------------------------------------------------------------ ProtocolVersion update proposals ------------------------------------------------------------------------------ | The protocol info for a node as well as some initial transactions protocol is adopt a specific (but as of yet to-be-determined) protocol version. So this smoke test ensures that the nodes can in fact adopt a new protocol version. Again, see PR #1741 for more details. * Proposal transaction. A protocol parameter update proposal transaction makes it onto the chain (it doesn't have to actually change any parameters, just increase the protocol version). Proposals are the return value of this function. In the smoke test, we immediately and 'pbftNumNodes')@ as of this writing) must vote for the proposal. Votes included in the return value of this function. In the smoke test, we immediately and repeatedly throughout the test add each node's vote to its own mempool; this seems realistic. sufficient number of nodes (@floor (0.6 * 'pbftNumNodes')@ as of this writing) must then endorse the proposal. Endorsements are not a protocol version to endorse. At a particular stage of a corresponding proposal's lifetime, that field constitutes an endorsement. At all other times, it is essentially ignored. In the smoke test, we take advantage of that to avoid having to restart our nodes: the nodes' initial configuration causes them to immediately and always attempt to endorse the proposed protocol version; this seems only slightly unrealistic. protocol version will be adopted at the next epoch transition, unless something else prevents it. In the smoke test, we check the validation state of the final chains for the new protocol version when we detect no mitigating circumstances, such as the test not even being scheduled to ^ the protocol version that triggers the hard fork signed by delegate SK the serialization hardwires this value anyway | A protocol parameter update proposal that doesn't actually change any parameter value but does propose 'theProposedProtocolVersion' Without loss of generality, the proposal is signed by @'CoreNodeId' 0@. signed by delegate SK | Add the bytestring annotations that would be present if we were to serialize the argument, send it to ourselves, receive it, and deserialize it The mempool payloads require the serialized bytes as annotations. It's tricky to get right, and this function lets use reuse the existing CBOR instances.
# LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # module Test.ThreadNet.Infra.Byron.TrackUpdates ( ProtocolVersionUpdateLabel (..) , SoftwareVersionUpdateLabel (..) , mkProtocolByronAndHardForkTxs , mkUpdateLabels ) where import Control.Exception (assert) import Control.Monad (guard) import Data.ByteString (ByteString) import Data.Coerce (coerce) import Data.Functor.Identity import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe) import Data.Set (Set) import qualified Data.Set as Set import Data.Word (Word64) import GHC.Stack (HasCallStack) import qualified Cardano.Chain.Block as Block import qualified Cardano.Chain.Byron.API as ByronAPI import qualified Cardano.Chain.Genesis as Genesis import qualified Cardano.Chain.MempoolPayload as MempoolPayload import Cardano.Chain.Slotting (EpochSlots (..), SlotNumber (..)) import qualified Cardano.Chain.Update as Update import Cardano.Chain.Update.Proposal (AProposal) import qualified Cardano.Chain.Update.Proposal as Proposal import qualified Cardano.Chain.Update.Validation.Interface as Update import qualified Cardano.Chain.Update.Validation.Registration as Registration import Cardano.Chain.Update.Vote (AVote) import qualified Cardano.Chain.Update.Vote as Vote import qualified Cardano.Crypto as Crypto import Cardano.Ledger.Binary (ByteSpan, DecCBOR (..), EncCBOR (..)) import Ouroboros.Consensus.Block import Ouroboros.Consensus.Config import Ouroboros.Consensus.Node.ProtocolInfo (NumCoreNodes (..), ProtocolInfo (..)) import Ouroboros.Consensus.NodeId (CoreNodeId (..)) import Ouroboros.Consensus.Protocol.PBFT import qualified Ouroboros.Consensus.Byron.Crypto.DSIGN as Crypto import Ouroboros.Consensus.Byron.Ledger (ByronBlock) import qualified Ouroboros.Consensus.Byron.Ledger as Byron import Test.ThreadNet.Network (TestNodeInitialization (..)) import qualified Test.ThreadNet.Ref.PBFT as Ref import Test.ThreadNet.Util.NodeJoinPlan import Test.ThreadNet.Util.NodeTopology import Test.ThreadNet.Infra.Byron.ProtocolInfo import Test.Util.Slots (NumSlots (..)) data ProtocolVersionUpdateLabel = ProtocolVersionUpdateLabel { pvuObserved :: Bool , pvuRequired :: Maybe Bool } deriving (Show) data SoftwareVersionUpdateLabel = SoftwareVersionUpdateLabel { svuObserved :: Bool , svuRequired :: Maybe Bool } deriving (Show) whether the protocol\/software version should have been\/was updated mkUpdateLabels :: PBftParams -> NumSlots -> Genesis.Config -> NodeJoinPlan -> NodeTopology -> Ref.Result -> Byron.LedgerState ByronBlock -> (ProtocolVersionUpdateLabel, SoftwareVersionUpdateLabel) mkUpdateLabels params numSlots genesisConfig nodeJoinPlan topology result ldgr = (pvuLabel, svuLabel) where PBftParams{pbftNumNodes, pbftSecurityParam} = params sentinel :: SlotNumber sentinel = SlotNumber t where NumSlots t = numSlots a block forged in slot @s@ becomes immutable / stable in slot @s + twoK@ twoK :: SlotNo twoK = SlotNo $ 2 * maxRollbacks pbftSecurityParam epochSlots :: SlotNo epochSlots = coerce $ Genesis.configEpochSlots genesisConfig pp0 :: Update.ProtocolParameters pp0 = Genesis.configProtocolParameters genesisConfig quorum :: Word64 quorum = (\x -> assert (x > 0) x) $ fromIntegral $ Update.upAdptThd (fromIntegral n) pp0 where NumCoreNodes n = pbftNumNodes ttl :: SlotNo ttl = coerce $ Update.ppUpdateProposalTTL pp0 the first slot of the epoch after the epoch containing the given slot ebbSlotAfter :: SlotNo -> SlotNo ebbSlotAfter (SlotNo s) = SlotNo (denom * div s denom) + epochSlots where SlotNo denom = epochSlots finalState :: [Ref.Outcome] -> ProposalState finalState outcomes = go Proposing (SlotNo 0) outcomes go :: ProposalState -> SlotNo -> [Ref.Outcome] -> ProposalState go !st !s = \case [] -> assert (coerce sentinel == s) st o:os -> case o of Ref.Absent -> continueWith st Ref.Unable -> continueWith st Ref.Wasted -> continueWith st Ref.Nominal -> case st of Proposing -> lostRace = s == leaderJoinSlot && leader /= CoreNodeId 0 in if lostRace then continueWith st else votes can be valid immediately and at least one should go (Voting s Set.empty) s (o:os) Voting proposalSlot votes -> let votesInTheNewBlock = (if leader == c0 then Set.insert c0 else id) $ if s == leaderJoinSlot then Set.empty else slot can reach the leader 's before it Map.keysSet $ Map.filter (< s) m where NodeJoinPlan m = nodeJoinPlan c0 = CoreNodeId 0 votes' = Set.union votesInTheNewBlock votes confirmed = fromIntegral (Set.size votes') >= quorum expired = proposalSlot + ttl < s in | confirmed -> continueWith $ Endorsing s Set.empty | expired -> continueWith $ Proposing | otherwise -> continueWith $ Voting proposalSlot votes' Endorsing finalVoteSlot ends -> continueWith $ if s < finalVoteSlot + twoK else let ends' = Set.insert (Ref.mkLeaderOf params s) ends in if fromIntegral (Set.size ends) < quorum then Endorsing finalVoteSlot ends' Adopting{} -> continueWith st where leader = Ref.mkLeaderOf params s leaderJoinSlot = coreNodeIdJoinSlot nodeJoinPlan leader continueWith st' = go st' (succ s) os pvuLabel = ProtocolVersionUpdateLabel { pvuObserved = (== theProposedProtocolVersion) $ Update.adoptedProtocolVersion $ Block.cvsUpdateState $ ByronAPI.applyChainTick genesisConfig sentinel $ Byron.byronLedgerState ldgr , pvuRequired = case result of ' Ref . Forked ' means there 's only 1 - block chains , and that 's not enough Ref.Forked{} -> Just False Ref.Nondeterministic{} -> Nothing Ref.Outcomes outcomes -> do checkTopo params topology Just $ case finalState outcomes of Proposing{} -> False Voting{} -> False Endorsing{} -> False Adopting finalEndorsementSlot -> ebbSlotAfter (finalEndorsementSlot + twoK) <= s where s = coerce sentinel } svuLabel = SoftwareVersionUpdateLabel { svuObserved = fromMaybe False $ do let nm = Update.svAppName theProposedSoftwareVersion (Registration.ApplicationVersion vn _slot _metadata) <- Map.lookup nm $ Update.appVersions $ Block.cvsUpdateState $ Byron.byronLedgerState ldgr pure $ vn == Update.svNumber theProposedSoftwareVersion , svuRequired = case result of ' Ref . Forked ' means all blocks except perhaps the first were Ref.Forked{} -> Nothing Ref.Nondeterministic{} -> Nothing Ref.Outcomes outcomes -> do checkTopo params topology Just $ case finalState outcomes of Proposing{} -> False Voting{} -> False Endorsing{} -> True Adopting{} -> True } reach L 's before it forges in the next slot . In fact , those votes will arrive to node L via TxSub during the current slot but /before/ the block containing the proposal does , so node L 's will reject the checkTopo :: PBftParams -> NodeTopology -> Maybe () checkTopo params topology = do let PBftParams{pbftNumNodes} = params guard $ topology == meshNodeTopology pbftNumNodes data ProposalState = Proposing ^ submitting the proposal ( possibly not for the first time , if it has | Voting !SlotNo !(Set CoreNodeId) | Endorsing !SlotNo !(Set CoreNodeId) The slot is when the first sufficient vote was submitted . The set is the | Adopting !SlotNo The slot is when the first sufficient endorsement was submitted . deriving (Show) The transactions implement a smoke test for the hard - fork from Byron to . See PR # 1741 for details on how that hard - fork will work . The key fact is that last thing the nodes will ever do while running the Adopting a new protocol version requires four kinds of event in . ' MempoolPayload . MempoolUpdateProposal ' transactions ; one is included in repeatedly throughout the test add the proposal to @CoreNodeId 0@ 's ; this seems realistic . * Vote transactions . A sufficient number of nodes ( @floor ( 0.6 * are ' MempoolPayload . MempoolUpdateVote ' transactions ; one per node is * Endorsement header field . After enough votes are 2k slots old , a transactions . Instead , every header includes a field that specifies * Epoch transition . After enough endorsements are 2k slots old , the reach the second epoch . mkProtocolByronAndHardForkTxs :: forall m. (Monad m, HasCallStack) => PBftParams -> CoreNodeId -> Genesis.Config -> Genesis.GeneratedSecrets -> Update.ProtocolVersion -> TestNodeInitialization m ByronBlock mkProtocolByronAndHardForkTxs params cid genesisConfig genesisSecrets propPV = TestNodeInitialization { tniCrucialTxs = proposals ++ votes , tniProtocolInfo = pInfo } where ProtocolInfo{pInfoConfig} = pInfo bcfg = configBlock pInfoConfig pInfo :: ProtocolInfo m ByronBlock opKey :: Crypto.SigningKey (pInfo, Crypto.SignKeyByronDSIGN opKey) = mkProtocolByron params cid genesisConfig genesisSecrets proposals :: [Byron.GenTx ByronBlock] proposals = if cid /= CoreNodeId 0 then [] else (:[]) $ Byron.fromMempoolPayload $ MempoolPayload.MempoolUpdateProposal proposal votes :: [Byron.GenTx ByronBlock] votes = (:[]) $ Byron.fromMempoolPayload $ MempoolPayload.MempoolUpdateVote vote vote :: AVote ByteString vote = loopbackAnnotations $ Vote.signVote (Byron.byronProtocolMagicId bcfg) (Update.recoverUpId proposal) (Crypto.noPassSafeSigner opKey) proposal :: AProposal ByteString proposal = loopbackAnnotations $ mkHardForkProposal params genesisConfig genesisSecrets propPV mkHardForkProposal :: HasCallStack => PBftParams -> Genesis.Config -> Genesis.GeneratedSecrets -> Update.ProtocolVersion -> AProposal () mkHardForkProposal params genesisConfig genesisSecrets propPV = Proposal.signProposal (Byron.byronProtocolMagicId bcfg) propBody (Crypto.noPassSafeSigner opKey) where pInfo :: ProtocolInfo Identity ByronBlock opKey :: Crypto.SigningKey (pInfo, Crypto.SignKeyByronDSIGN opKey) = mkProtocolByron params (CoreNodeId 0) genesisConfig genesisSecrets ProtocolInfo{pInfoConfig} = pInfo bcfg = configBlock pInfoConfig propBody :: Proposal.ProposalBody propBody = Proposal.ProposalBody { Proposal.protocolVersion = propPV , Proposal.protocolParametersUpdate = Update.ProtocolParametersUpdate { Update.ppuScriptVersion = Nothing , Update.ppuSlotDuration = Nothing , Update.ppuMaxBlockSize = Nothing , Update.ppuMaxHeaderSize = Nothing , Update.ppuMaxTxSize = Nothing , Update.ppuMaxProposalSize = Nothing , Update.ppuMpcThd = Nothing , Update.ppuHeavyDelThd = Nothing , Update.ppuUpdateVoteThd = Nothing , Update.ppuUpdateProposalThd = Nothing , Update.ppuUpdateProposalTTL = Nothing , Update.ppuSoftforkRule = Nothing , Update.ppuTxFeePolicy = Nothing , Update.ppuUnlockStakeEpoch = Nothing } , Proposal.softwareVersion = theProposedSoftwareVersion , Proposal.metadata = Map.empty } loopbackAnnotations :: ( DecCBOR (f ByteSpan) , EncCBOR (f ()) , Functor f ) => f () -> f ByteString loopbackAnnotations = ByronAPI.reAnnotateUsing encCBOR decCBOR
76a6ea0f3aceaef5cdf0c855848643d112fa5910fa621c9800eea4eab5d7d4cb
racket/compiler
zo-test.rkt
#!/bin/sh #| exec racket -t "$0" -- -s -t 60 -v -R $* |# #lang racket (require setup/dirs racket/runtime-path racket/future compiler/find-exe "zo-test-util.rkt") (define ((make-recorder! ht) file phase) (hash-update! ht phase (curry list* file) empty)) (define stop-on-first-error (make-parameter #f)) (define verbose-mode (make-parameter #f)) (define care-about-nonserious? (make-parameter #t)) (define invariant-output (make-parameter #f)) (define time-limit (make-parameter +inf.0)) (define randomize (make-parameter #f)) (define num-processes (make-parameter (processor-count))) (define errors (make-hash)) (define (record-common-error! exn-msg) (hash-update! errors (common-message exn-msg) add1 0)) (define (common-message exn-msg) (define given-messages (regexp-match #rx".*given" exn-msg)) (if (and given-messages (not (empty? given-messages))) (first given-messages) exn-msg)) (define success-ht (make-hasheq)) (define success! (make-recorder! success-ht)) (define failure-ht (make-hasheq)) (define failure! (make-recorder! failure-ht)) (define debugging? (make-parameter #f)) (define (randomize-list l) (define ll (length l)) (define seen? (make-hasheq)) (let loop ([t 0]) (if (= t ll) empty (let ([i (random ll)]) (if (hash-has-key? seen? i) (loop t) (begin (hash-set! seen? i #t) (list* (list-ref l i) (loop (add1 t))))))))) (define (maybe-randomize-list l) (if (randomize) (randomize-list l) l)) (define (for-zos ! p) (define p-str (if (path? p) (path->string p) p)) (cond [(directory-exists? p) (for ([sp (in-list (maybe-randomize-list (directory-list p)))]) (for-zos ! (build-path p sp)))] [(regexp-match #rx"\\.zo$" p-str) (! p-str)])) (define-runtime-path zo-test-worker-path "zo-test-worker.rkt") (define racket-path (path->string (find-exe))) (define p (command-line #:program "zo-test" #:once-each [("-D") "Enable debugging output" (debugging? #t)] [("-s" "--stop-on-first-error") "Stop testing when first error is encountered" (stop-on-first-error #t)] [("-S") "Don't take some errors seriously" (care-about-nonserious? #f)] [("-v" "--verbose") "Display verbose error messages" (verbose-mode #t)] [("-I") "Invariant output" (invariant-output #t)] [("-R") "Randomize" (randomize #t)] [("-t") number "Limit the run to a given amount of time" (time-limit (string->number number))] [("-j") n "Run <n> in parallel" (num-processes (string->number n))] #:args p (if (empty? p) (list (find-collects-dir)) p))) (define to-worker-ch (make-channel)) (define stop-ch (make-channel)) (define from-worker-ch (make-channel)) (define worker-threads (for/list ([i (in-range (num-processes))]) (thread (Ξ» () (let loop () (sync (handle-evt to-worker-ch (Ξ» (p) (when (debugging?) (printf "~a\n" p)) (define-values (sp stdout stdin stderr) (subprocess #f #f #f racket-path (path->string zo-test-worker-path) p)) (define r (dynamic-wind void (Ξ» () (read stdout)) (Ξ» () (close-input-port stdout) (close-input-port stderr) (close-output-port stdin) (subprocess-kill sp #t)))) (channel-put from-worker-ch (cons p r)) (loop))) (handle-evt stop-ch (Ξ» (die) (void))))))))) (define (process-result p r) (match r [(success phase) (success! p phase)] [(failure phase serious? exn-msg) (record-common-error! exn-msg) (failure! p phase) (unless (and (not (care-about-nonserious?)) (not serious?)) (when (or (verbose-mode) (stop-on-first-error)) (eprintf "~a -- ~a: ~a\n" p phase exn-msg)) (when (stop-on-first-error) (stop!)))])) (define timing-thread (thread (Ξ» () (sync (alarm-evt (+ (current-inexact-milliseconds) (* 1000 (time-limit))))) (stop!)))) (define server-thread (thread (Ξ» () (let loop ([ts worker-threads]) (if (empty? ts) (stop!) (apply sync (handle-evt from-worker-ch (match-lambda [(cons p rs) (for-each (curry process-result p) rs) (loop ts)])) (for/list ([t (in-list ts)]) (handle-evt t (Ξ» _ (loop (remq t ts))))))))))) (define (spawn-worker p) (channel-put to-worker-ch p)) (define (zo-test paths) (for-each (curry for-zos spawn-worker) paths) (for ([i (in-range (processor-count))]) (channel-put stop-ch #t))) (define root-thread (thread (Ξ» () (zo-test p)))) (define final-sema (make-semaphore 0)) (define (stop!) (semaphore-post final-sema)) (define (hash-keys ht) (hash-map ht (Ξ» (k v) k))) (define final-thread (thread (Ξ» () (semaphore-wait final-sema) (for-each kill-thread (list* root-thread server-thread worker-threads)) (unless (invariant-output) (newline) (for ([kind-name (remove-duplicates (append (hash-keys failure-ht) (hash-keys success-ht)))]) (define fails (length (hash-ref failure-ht kind-name empty))) (define succs (length (hash-ref success-ht kind-name empty))) (define all (+ fails succs)) (unless (zero? all) (printf "~S\n" `(,kind-name (#f ,fails) (#t ,succs) ,all)))) (newline) (printf "~a tests passed\n" (length (hash-ref success-ht 'everything empty))) (let ([common-errors (sort (filter (Ξ» (p) ((car p) . > . 10)) (hash-map errors (Ξ» (k v) (cons v k)))) > #:key car)]) (unless (empty? common-errors) (printf "Common Errors:\n") (for ([p (in-list common-errors)]) (printf "~a:\n~a\n\n" (car p) (cdr p))))))))) (thread-wait final-thread) ;; Test mode: (module test racket/base (require syntax/location) (parameterize ([current-command-line-arguments (vector "-I" "-S" "-t" "60" "-v" "-R")]) (dynamic-require (quote-module-path "..") #f)))
null
https://raw.githubusercontent.com/racket/compiler/88acf8a1ec81fec0fbcb6035af1d994d2fec4154/compiler-test/tests/compiler/zo-test.rkt
racket
exec racket -t "$0" -- -s -t 60 -v -R $* Test mode:
#!/bin/sh #lang racket (require setup/dirs racket/runtime-path racket/future compiler/find-exe "zo-test-util.rkt") (define ((make-recorder! ht) file phase) (hash-update! ht phase (curry list* file) empty)) (define stop-on-first-error (make-parameter #f)) (define verbose-mode (make-parameter #f)) (define care-about-nonserious? (make-parameter #t)) (define invariant-output (make-parameter #f)) (define time-limit (make-parameter +inf.0)) (define randomize (make-parameter #f)) (define num-processes (make-parameter (processor-count))) (define errors (make-hash)) (define (record-common-error! exn-msg) (hash-update! errors (common-message exn-msg) add1 0)) (define (common-message exn-msg) (define given-messages (regexp-match #rx".*given" exn-msg)) (if (and given-messages (not (empty? given-messages))) (first given-messages) exn-msg)) (define success-ht (make-hasheq)) (define success! (make-recorder! success-ht)) (define failure-ht (make-hasheq)) (define failure! (make-recorder! failure-ht)) (define debugging? (make-parameter #f)) (define (randomize-list l) (define ll (length l)) (define seen? (make-hasheq)) (let loop ([t 0]) (if (= t ll) empty (let ([i (random ll)]) (if (hash-has-key? seen? i) (loop t) (begin (hash-set! seen? i #t) (list* (list-ref l i) (loop (add1 t))))))))) (define (maybe-randomize-list l) (if (randomize) (randomize-list l) l)) (define (for-zos ! p) (define p-str (if (path? p) (path->string p) p)) (cond [(directory-exists? p) (for ([sp (in-list (maybe-randomize-list (directory-list p)))]) (for-zos ! (build-path p sp)))] [(regexp-match #rx"\\.zo$" p-str) (! p-str)])) (define-runtime-path zo-test-worker-path "zo-test-worker.rkt") (define racket-path (path->string (find-exe))) (define p (command-line #:program "zo-test" #:once-each [("-D") "Enable debugging output" (debugging? #t)] [("-s" "--stop-on-first-error") "Stop testing when first error is encountered" (stop-on-first-error #t)] [("-S") "Don't take some errors seriously" (care-about-nonserious? #f)] [("-v" "--verbose") "Display verbose error messages" (verbose-mode #t)] [("-I") "Invariant output" (invariant-output #t)] [("-R") "Randomize" (randomize #t)] [("-t") number "Limit the run to a given amount of time" (time-limit (string->number number))] [("-j") n "Run <n> in parallel" (num-processes (string->number n))] #:args p (if (empty? p) (list (find-collects-dir)) p))) (define to-worker-ch (make-channel)) (define stop-ch (make-channel)) (define from-worker-ch (make-channel)) (define worker-threads (for/list ([i (in-range (num-processes))]) (thread (Ξ» () (let loop () (sync (handle-evt to-worker-ch (Ξ» (p) (when (debugging?) (printf "~a\n" p)) (define-values (sp stdout stdin stderr) (subprocess #f #f #f racket-path (path->string zo-test-worker-path) p)) (define r (dynamic-wind void (Ξ» () (read stdout)) (Ξ» () (close-input-port stdout) (close-input-port stderr) (close-output-port stdin) (subprocess-kill sp #t)))) (channel-put from-worker-ch (cons p r)) (loop))) (handle-evt stop-ch (Ξ» (die) (void))))))))) (define (process-result p r) (match r [(success phase) (success! p phase)] [(failure phase serious? exn-msg) (record-common-error! exn-msg) (failure! p phase) (unless (and (not (care-about-nonserious?)) (not serious?)) (when (or (verbose-mode) (stop-on-first-error)) (eprintf "~a -- ~a: ~a\n" p phase exn-msg)) (when (stop-on-first-error) (stop!)))])) (define timing-thread (thread (Ξ» () (sync (alarm-evt (+ (current-inexact-milliseconds) (* 1000 (time-limit))))) (stop!)))) (define server-thread (thread (Ξ» () (let loop ([ts worker-threads]) (if (empty? ts) (stop!) (apply sync (handle-evt from-worker-ch (match-lambda [(cons p rs) (for-each (curry process-result p) rs) (loop ts)])) (for/list ([t (in-list ts)]) (handle-evt t (Ξ» _ (loop (remq t ts))))))))))) (define (spawn-worker p) (channel-put to-worker-ch p)) (define (zo-test paths) (for-each (curry for-zos spawn-worker) paths) (for ([i (in-range (processor-count))]) (channel-put stop-ch #t))) (define root-thread (thread (Ξ» () (zo-test p)))) (define final-sema (make-semaphore 0)) (define (stop!) (semaphore-post final-sema)) (define (hash-keys ht) (hash-map ht (Ξ» (k v) k))) (define final-thread (thread (Ξ» () (semaphore-wait final-sema) (for-each kill-thread (list* root-thread server-thread worker-threads)) (unless (invariant-output) (newline) (for ([kind-name (remove-duplicates (append (hash-keys failure-ht) (hash-keys success-ht)))]) (define fails (length (hash-ref failure-ht kind-name empty))) (define succs (length (hash-ref success-ht kind-name empty))) (define all (+ fails succs)) (unless (zero? all) (printf "~S\n" `(,kind-name (#f ,fails) (#t ,succs) ,all)))) (newline) (printf "~a tests passed\n" (length (hash-ref success-ht 'everything empty))) (let ([common-errors (sort (filter (Ξ» (p) ((car p) . > . 10)) (hash-map errors (Ξ» (k v) (cons v k)))) > #:key car)]) (unless (empty? common-errors) (printf "Common Errors:\n") (for ([p (in-list common-errors)]) (printf "~a:\n~a\n\n" (car p) (cdr p))))))))) (thread-wait final-thread) (module test racket/base (require syntax/location) (parameterize ([current-command-line-arguments (vector "-I" "-S" "-t" "60" "-v" "-R")]) (dynamic-require (quote-module-path "..") #f)))
15d227e5127e2445154c5fd0a92d241fe9e5ae32646a77302efdb5838ad507ef
sealchain-project/sealchain
DB.hs
-- | Higher-level DB functionality. module Pos.DB.DB ( initNodeDBs , gsAdoptedBVDataDefault ) where import Universum import Pos.Chain.Block (genesisBlock0, headerHash) import Pos.Chain.Genesis as Genesis (Config (..)) import Pos.Chain.Lrc (genesisLeaders) import Pos.Chain.Update (BlockVersionData) import Pos.DB.Block (prepareBlockDB) import Pos.DB.Class (MonadDB, MonadDBRead (..)) import Pos.DB.Lrc (prepareLrcDB) import Pos.DB.Update (getAdoptedBVData) import Pos.GState.GState (prepareGStateDB) # INLINE initNodeDBs # | Initialize DBs if necessary . initNodeDBs :: forall m . (MonadIO m, MonadDB m) => Genesis.Config -> m () initNodeDBs genesisConfig = do let initialTip = headerHash gb prepareBlockDB gb prepareGStateDB genesisConfig initialTip prepareLrcDB genesisConfig where gb = genesisBlock0 (configProtocolMagic genesisConfig) (configGenesisHash genesisConfig) (genesisLeaders genesisConfig) ---------------------------------------------------------------------------- -- MonadGState instance ---------------------------------------------------------------------------- gsAdoptedBVDataDefault :: MonadDBRead m => m BlockVersionData gsAdoptedBVDataDefault = getAdoptedBVData
null
https://raw.githubusercontent.com/sealchain-project/sealchain/e97b4bac865fb147979cb14723a12c716a62e51e/lib/src/Pos/DB/DB.hs
haskell
| Higher-level DB functionality. -------------------------------------------------------------------------- MonadGState instance --------------------------------------------------------------------------
module Pos.DB.DB ( initNodeDBs , gsAdoptedBVDataDefault ) where import Universum import Pos.Chain.Block (genesisBlock0, headerHash) import Pos.Chain.Genesis as Genesis (Config (..)) import Pos.Chain.Lrc (genesisLeaders) import Pos.Chain.Update (BlockVersionData) import Pos.DB.Block (prepareBlockDB) import Pos.DB.Class (MonadDB, MonadDBRead (..)) import Pos.DB.Lrc (prepareLrcDB) import Pos.DB.Update (getAdoptedBVData) import Pos.GState.GState (prepareGStateDB) # INLINE initNodeDBs # | Initialize DBs if necessary . initNodeDBs :: forall m . (MonadIO m, MonadDB m) => Genesis.Config -> m () initNodeDBs genesisConfig = do let initialTip = headerHash gb prepareBlockDB gb prepareGStateDB genesisConfig initialTip prepareLrcDB genesisConfig where gb = genesisBlock0 (configProtocolMagic genesisConfig) (configGenesisHash genesisConfig) (genesisLeaders genesisConfig) gsAdoptedBVDataDefault :: MonadDBRead m => m BlockVersionData gsAdoptedBVDataDefault = getAdoptedBVData
85df4d63d3b63186ce30ef85c4a7563f5c58f0f498e02403e3432b18b89be65e
soegaard/sketching
text-rotation.rkt
#lang sketching ; -docs/blob/master/content/examples/Basics/Typography/TextRotation/TextRotation.pde ; Text Rotation. ; Draws letters to the screen and rotates them at different angles. (define angle 0.0) ; the rotation angle (define (setup) (size 640 360) (frame-rate 10) (text-size 18) (background 0)) (define (draw) (background 0) ; (smoothing 'unsmoothed) ; (text-smoothing 'unsmoothed) (stroke-weight 1) (stroke 153) (push-matrix) (define angle1 (radians 45)) (translate 100 180) (rotate angle1) (text "45 DEGREES" 0 0) (line 0 0 150 0) (pop-matrix) (push-matrix) (define angle2 (radians 270)) (translate 200 180) (rotate angle2) (text "270 DEGREES" 0 0) (line 0 0 150 0) (pop-matrix) (push-matrix) (translate 440 180) (rotate (radians angle)) (text (~a (modulo (int angle) 360) " DEGREES") 0 0) (line 0 0 150 0) (pop-matrix) (+= angle 0.25) (stroke 255 0 0) (stroke-weight 4) (point 100 180) (point 200 180) (point 440 180))
null
https://raw.githubusercontent.com/soegaard/sketching/94e114ac6e92ede3b85481df755b673be24b226e/sketching-doc/sketching-doc/manual-examples/basics/typography/text-rotation.rkt
racket
-docs/blob/master/content/examples/Basics/Typography/TextRotation/TextRotation.pde Text Rotation. Draws letters to the screen and rotates them at different angles. the rotation angle (smoothing 'unsmoothed) (text-smoothing 'unsmoothed)
#lang sketching (define (setup) (size 640 360) (frame-rate 10) (text-size 18) (background 0)) (define (draw) (background 0) (stroke-weight 1) (stroke 153) (push-matrix) (define angle1 (radians 45)) (translate 100 180) (rotate angle1) (text "45 DEGREES" 0 0) (line 0 0 150 0) (pop-matrix) (push-matrix) (define angle2 (radians 270)) (translate 200 180) (rotate angle2) (text "270 DEGREES" 0 0) (line 0 0 150 0) (pop-matrix) (push-matrix) (translate 440 180) (rotate (radians angle)) (text (~a (modulo (int angle) 360) " DEGREES") 0 0) (line 0 0 150 0) (pop-matrix) (+= angle 0.25) (stroke 255 0 0) (stroke-weight 4) (point 100 180) (point 200 180) (point 440 180))
09203a82432cc6781c1f1d04cf5648e44acef526f5ebfc8d0e1316ec00405a6d
mbenke/zpf2012
PlusMinusUU.hs
# LANGUAGE FlexibleContexts , RankNTypes # import Data.Char(digitToInt) import Criterion.Main import Text.ParserCombinators.UU import Text.ParserCombinators.UU.Utils import Text.ParserCombinators.UU.BasicInstances hiding(Parser) type Parser a = P (Str Char String LineColPos) a digit :: Parser Char digit = pSym ( ' 0 ' , ' 9 ' ) digit = pDigit char :: Char -> Parser Char char = pSym gen 0 = "1" gen n = ('1':'+':'1':'-':gen (n-1)) pNum :: Parser Int pNum = fmap digitToInt digit chainl1 = flip pChainl pExp = pNum `chainl1` addop addop = (+) <$ char '+' <<|> (-) <$ char '-' : : [ Error ] doparse :: Parser a -> String -> String -> a doparse p name input = let extp = ( (,) <$> p <*> pEnd) str = (createStr (LineColPos 0 0 0) input) (a, errors) = parse extp str in a {-case errors of [] -> a (e:_) -> error $ show e -} test n = doparse pExp "gen" (gen n) main = defaultMain [ bench "gen 10000" $ whnf test 10000 , bench "gen 100000" $ whnf test 100000 ]
null
https://raw.githubusercontent.com/mbenke/zpf2012/faad6468f9400059de1c0735e12a84a2fdf24bb4/Code/Parse2/PlusMinusUU.hs
haskell
case errors of [] -> a (e:_) -> error $ show e
# LANGUAGE FlexibleContexts , RankNTypes # import Data.Char(digitToInt) import Criterion.Main import Text.ParserCombinators.UU import Text.ParserCombinators.UU.Utils import Text.ParserCombinators.UU.BasicInstances hiding(Parser) type Parser a = P (Str Char String LineColPos) a digit :: Parser Char digit = pSym ( ' 0 ' , ' 9 ' ) digit = pDigit char :: Char -> Parser Char char = pSym gen 0 = "1" gen n = ('1':'+':'1':'-':gen (n-1)) pNum :: Parser Int pNum = fmap digitToInt digit chainl1 = flip pChainl pExp = pNum `chainl1` addop addop = (+) <$ char '+' <<|> (-) <$ char '-' : : [ Error ] doparse :: Parser a -> String -> String -> a doparse p name input = let extp = ( (,) <$> p <*> pEnd) str = (createStr (LineColPos 0 0 0) input) (a, errors) = parse extp str test n = doparse pExp "gen" (gen n) main = defaultMain [ bench "gen 10000" $ whnf test 10000 , bench "gen 100000" $ whnf test 100000 ]
455bd09428df9d49443968b98bb18277b645eac1aa421cc67089d82a16c3444c
UMM-CSci/edsger
unification_test.cljs
(ns edsger.unification-test (:require [edsger.unification :as u] [edsger.parsing :as p] [cljs.test :as t :refer-macros [deftest is] :include-macros true])) ;; ==== Unit tests for `wrap` (deftest wrap-with-symbol (is (= '(:a) (u/wrap :a)))) (deftest wrap-with-list (is (= '(2) (u/wrap '(2))))) ;; ==== Unit tests for `check-match` (deftest a-test (is (true? (u/check-match '(:not (:equiv u (:or w y))) '(:equiv (:not u) (:or w y)) '(:not (:equiv ?a ?b)) '(:equiv (:not ?a) ?b))))) (deftest completely-inapplicable-rule (is (not (u/check-match '(:equiv (:and p q) p q) '(:or p q) '(:equiv (:and ?p ?q) ?p) '(:equiv ?q (:or ?p ?q)))))) (deftest proving-3_4-step-1 (is (true? (u/check-match '(true) '(:equiv q q) '(true) '(:equiv ?q ?q))) "Empty `start-matches` map case")) (deftest proving-3_4-step-1-naming (is (true? (u/check-match '(true) '(:equiv p p) '(true) '(:equiv ?q ?q))) "The exact symbols don't need to match")) (deftest proving-3_4-step-1-badv1 (is (not (u/check-match '(true) '(:equiv p q) '(true) '(:equiv ?q ?q))))) (deftest proving-3_4-step-1-badv2 (is (not (u/check-match '(false) '(:equiv q q) '(true) '(:equiv ?q ?q))))) (deftest proving-3_39-step-1 (is (true? (u/check-match '(:equiv (:and p true) p) '(:equiv (:or p true) true) '(:equiv (:and ?p ?q) ?p) '(:equiv (:or ?p ?q) ?q))))) (deftest proving-3_39-step-1-ordering (is (not (u/check-match '(:equiv (:and p true) p) '(:equiv (:or p true) true) '(:equiv (:and ?p ?q) ?p) '(:equiv ?q (:or ?p ?q)))) "Ordering is crucial for matching with `binding-map`")) (deftest start-matches-and-end-requires-no-substitution (is (true? (u/check-match '(:a-keyword q) '(true) '(:a-keyword ?p) '(true))) "Empty `end-matches` case")) (deftest constants-can-match (is (true? (u/check-match ':a ':b ':a ':b)))) (deftest constants-can-fail (is (not (u/check-match ':a ':c ':a ':b)))) ;; ==== Unit tests for `check-match-recursive` (deftest non-recursive-case (is (true? (u/check-match-recursive '(:not (:equiv u (:or w y))) '(:equiv (:not u) (:or w y)) '(:not (:equiv ?a ?b)) '(:equiv (:not ?a) ?b))))) (deftest simple-recursive-case (is (true? (u/check-match-recursive '(:and p (:equiv true true)) '(:and p true) '(:equiv ?q ?q) '(true))))) (deftest rule-applies-but-not-actually-equal (is (not (u/check-match-recursive '(:and p (:equiv true true)) '(:or p true) '(:equiv ?q ?q) '(true))))) (deftest rule-applies-but-not-actually-equal-v2 (is (not (u/check-match-recursive '(:and p (:equiv true true) false) '(:and p true true) '(:equiv ?q ?q) '(true))))) (deftest diff-length-exps (is (not (u/check-match-recursive '(:and p (:equiv true true) false) '(:and p true) '(:equiv ?q ?q) '(true))) "Different lengths of expressions are handled correctly")) (deftest non-seqable-start-or-end-expr (is (true? (u/check-match-recursive '(:and a a) 'a '(:and ?p ?p) '?p))) (is (not (u/check-match-recursive '(:and a a) 'b '(:and ?p ?p) '?p)))) ;; The following tests are to test recursive-validate Test on empty lists , should return true if both are empty , false if only one (deftest empty-list-recurse-val Trying it on two empty lists should throw an error (try (doall (u/recursive-validate '() '() '()) (is false)) (catch js/Error e (is true))) (is (empty? (u/recursive-validate '("anything, just one thing") '() '()))) (try (doall (u/recursive-validate (list '(:and a a) 'a) '() '()) (is false)) (catch js/Error e (is true)))) ;; Test on recursive-validate on non-empty lists (def rules-list (list '(:and ?a ?b) '(:and ?b ?a) '(:or ?a ?b) '(:or ?b ?a) '(:implies ?z ?q) '(:implies '(:not ?q) '(:not ?z)))) (def exps-list (list '(:implies '(:and a b) '(:or p q)) '(:implies '(:and b a) '(:or p q)) '(:implies '(:and b a) '(:or q p)) '(:implies '(:not '(:or q p)) '(:not '(:and b a))))) (deftest recursive-validate-non-empty (is (every? true? (u/recursive-validate exps-list rules-list (list "≑" "≑" "≑")))) (is (not (every? true? (u/recursive-validate exps-list (cons '(:or ?a ?b) (rest rules-list)) (list "≑" "≑" "≑")))))) Tests capturing the problem for bug # 62 ;; The problem was an (unnecessary) check that used ;; `list?`, which returned `false` when passed vectors. ;; Our parser generates nested vectors, so this failed ;; on more complex expressions. (deftest check-bug-62 ' (: not (: and (: and ) q ) ) bug-rule-left (p/rulify (p/parse "a ∧ a")) ; '(:and ?a ?a) bug-rule-right (p/rulify (p/parse "a")) ; '?a bug-exp-right (p/parse "Β¬(p ∧ q)")] ; '(:not (:and p q)) (is (not (u/check-match bug-exp-left bug-exp-right bug-rule-left bug-rule-right))) (is (u/check-match (second (second bug-exp-left)) (second (second bug-exp-right)) bug-rule-left bug-rule-right)) (is (u/check-match-recursive (second (second bug-exp-left)) (second (second bug-exp-right)) bug-rule-left bug-rule-right)) (is (u/check-match-recursive (second bug-exp-left) (second bug-exp-right) bug-rule-left bug-rule-right)) (is (u/check-match-recursive bug-exp-left bug-exp-right bug-rule-left bug-rule-right)) ; check that it works when everything is a vector (is (u/check-match-recursive [:not [:and [:and 'p 'p] 'q]] [:not [:and 'p 'q]] [:and '?a '?a] '?a)) ; check that it works when everything is a list (is (u/check-match-recursive '(:not (:and (:and p p) q)) '(:not (:and p q)) '(:and ?a ?a) '?a)) (is (first (u/recursive-validate (list bug-exp-left bug-exp-right) (list bug-rule-left bug-rule-right) ["≑"]))))) (deftest check-bug-91 (let [exp-left (p/parse "(m ≑ (n ∧ p)) β‡’ q") rule-left (p/rulify (p/parse "a ∧ b")) rule-right (p/rulify (p/parse "b ∧ a")) exp-right (p/parse "(m ≑ (p ∧ n)) β‡’ q")] (is (u/recursive-validate [exp-left exp-right] [rule-left rule-right] ["≑"]))) )
null
https://raw.githubusercontent.com/UMM-CSci/edsger/60910e70274f03c169a503826f095049bda5944a/test/edsger/unification_test.cljs
clojure
==== Unit tests for `wrap` ==== Unit tests for `check-match` ==== Unit tests for `check-match-recursive` The following tests are to test recursive-validate Test on recursive-validate on non-empty lists The problem was an (unnecessary) check that used `list?`, which returned `false` when passed vectors. Our parser generates nested vectors, so this failed on more complex expressions. '(:and ?a ?a) '?a '(:not (:and p q)) check that it works when everything is a vector check that it works when everything is a list
(ns edsger.unification-test (:require [edsger.unification :as u] [edsger.parsing :as p] [cljs.test :as t :refer-macros [deftest is] :include-macros true])) (deftest wrap-with-symbol (is (= '(:a) (u/wrap :a)))) (deftest wrap-with-list (is (= '(2) (u/wrap '(2))))) (deftest a-test (is (true? (u/check-match '(:not (:equiv u (:or w y))) '(:equiv (:not u) (:or w y)) '(:not (:equiv ?a ?b)) '(:equiv (:not ?a) ?b))))) (deftest completely-inapplicable-rule (is (not (u/check-match '(:equiv (:and p q) p q) '(:or p q) '(:equiv (:and ?p ?q) ?p) '(:equiv ?q (:or ?p ?q)))))) (deftest proving-3_4-step-1 (is (true? (u/check-match '(true) '(:equiv q q) '(true) '(:equiv ?q ?q))) "Empty `start-matches` map case")) (deftest proving-3_4-step-1-naming (is (true? (u/check-match '(true) '(:equiv p p) '(true) '(:equiv ?q ?q))) "The exact symbols don't need to match")) (deftest proving-3_4-step-1-badv1 (is (not (u/check-match '(true) '(:equiv p q) '(true) '(:equiv ?q ?q))))) (deftest proving-3_4-step-1-badv2 (is (not (u/check-match '(false) '(:equiv q q) '(true) '(:equiv ?q ?q))))) (deftest proving-3_39-step-1 (is (true? (u/check-match '(:equiv (:and p true) p) '(:equiv (:or p true) true) '(:equiv (:and ?p ?q) ?p) '(:equiv (:or ?p ?q) ?q))))) (deftest proving-3_39-step-1-ordering (is (not (u/check-match '(:equiv (:and p true) p) '(:equiv (:or p true) true) '(:equiv (:and ?p ?q) ?p) '(:equiv ?q (:or ?p ?q)))) "Ordering is crucial for matching with `binding-map`")) (deftest start-matches-and-end-requires-no-substitution (is (true? (u/check-match '(:a-keyword q) '(true) '(:a-keyword ?p) '(true))) "Empty `end-matches` case")) (deftest constants-can-match (is (true? (u/check-match ':a ':b ':a ':b)))) (deftest constants-can-fail (is (not (u/check-match ':a ':c ':a ':b)))) (deftest non-recursive-case (is (true? (u/check-match-recursive '(:not (:equiv u (:or w y))) '(:equiv (:not u) (:or w y)) '(:not (:equiv ?a ?b)) '(:equiv (:not ?a) ?b))))) (deftest simple-recursive-case (is (true? (u/check-match-recursive '(:and p (:equiv true true)) '(:and p true) '(:equiv ?q ?q) '(true))))) (deftest rule-applies-but-not-actually-equal (is (not (u/check-match-recursive '(:and p (:equiv true true)) '(:or p true) '(:equiv ?q ?q) '(true))))) (deftest rule-applies-but-not-actually-equal-v2 (is (not (u/check-match-recursive '(:and p (:equiv true true) false) '(:and p true true) '(:equiv ?q ?q) '(true))))) (deftest diff-length-exps (is (not (u/check-match-recursive '(:and p (:equiv true true) false) '(:and p true) '(:equiv ?q ?q) '(true))) "Different lengths of expressions are handled correctly")) (deftest non-seqable-start-or-end-expr (is (true? (u/check-match-recursive '(:and a a) 'a '(:and ?p ?p) '?p))) (is (not (u/check-match-recursive '(:and a a) 'b '(:and ?p ?p) '?p)))) Test on empty lists , should return true if both are empty , false if only one (deftest empty-list-recurse-val Trying it on two empty lists should throw an error (try (doall (u/recursive-validate '() '() '()) (is false)) (catch js/Error e (is true))) (is (empty? (u/recursive-validate '("anything, just one thing") '() '()))) (try (doall (u/recursive-validate (list '(:and a a) 'a) '() '()) (is false)) (catch js/Error e (is true)))) (def rules-list (list '(:and ?a ?b) '(:and ?b ?a) '(:or ?a ?b) '(:or ?b ?a) '(:implies ?z ?q) '(:implies '(:not ?q) '(:not ?z)))) (def exps-list (list '(:implies '(:and a b) '(:or p q)) '(:implies '(:and b a) '(:or p q)) '(:implies '(:and b a) '(:or q p)) '(:implies '(:not '(:or q p)) '(:not '(:and b a))))) (deftest recursive-validate-non-empty (is (every? true? (u/recursive-validate exps-list rules-list (list "≑" "≑" "≑")))) (is (not (every? true? (u/recursive-validate exps-list (cons '(:or ?a ?b) (rest rules-list)) (list "≑" "≑" "≑")))))) Tests capturing the problem for bug # 62 (deftest check-bug-62 ' (: not (: and (: and ) q ) ) (is (not (u/check-match bug-exp-left bug-exp-right bug-rule-left bug-rule-right))) (is (u/check-match (second (second bug-exp-left)) (second (second bug-exp-right)) bug-rule-left bug-rule-right)) (is (u/check-match-recursive (second (second bug-exp-left)) (second (second bug-exp-right)) bug-rule-left bug-rule-right)) (is (u/check-match-recursive (second bug-exp-left) (second bug-exp-right) bug-rule-left bug-rule-right)) (is (u/check-match-recursive bug-exp-left bug-exp-right bug-rule-left bug-rule-right)) (is (u/check-match-recursive [:not [:and [:and 'p 'p] 'q]] [:not [:and 'p 'q]] [:and '?a '?a] '?a)) (is (u/check-match-recursive '(:not (:and (:and p p) q)) '(:not (:and p q)) '(:and ?a ?a) '?a)) (is (first (u/recursive-validate (list bug-exp-left bug-exp-right) (list bug-rule-left bug-rule-right) ["≑"]))))) (deftest check-bug-91 (let [exp-left (p/parse "(m ≑ (n ∧ p)) β‡’ q") rule-left (p/rulify (p/parse "a ∧ b")) rule-right (p/rulify (p/parse "b ∧ a")) exp-right (p/parse "(m ≑ (p ∧ n)) β‡’ q")] (is (u/recursive-validate [exp-left exp-right] [rule-left rule-right] ["≑"]))) )
a0ab48f4a3814975dd56ad960e4752747a98c126a8a223cfddd1bc309205fcd8
jacekschae/learn-pedestal-course-files
user.clj
(ns user (:require [io.pedestal.http :as http] [clojure.edn :as edn] [cheffy.routes :as routes])) (defonce system-ref (atom nil)) (defn start-dev [] (let [config (-> "src/config/cheffy/development.edn" slurp edn/read-string)] (reset! system-ref (-> config (assoc ::http/routes routes/routes) (http/create-server) (http/start)))) :started) (defn stop-dev [] (http/stop @system-ref) :stopped) (defn restart-dev [] (stop-dev) (start-dev) :restarted) (comment (start-dev) (restart-dev) (stop-dev) )
null
https://raw.githubusercontent.com/jacekschae/learn-pedestal-course-files/fa60a8f208e80658a4c55f0c094b66f68a2d3c6a/increments/11-system-setup/src/dev/user.clj
clojure
(ns user (:require [io.pedestal.http :as http] [clojure.edn :as edn] [cheffy.routes :as routes])) (defonce system-ref (atom nil)) (defn start-dev [] (let [config (-> "src/config/cheffy/development.edn" slurp edn/read-string)] (reset! system-ref (-> config (assoc ::http/routes routes/routes) (http/create-server) (http/start)))) :started) (defn stop-dev [] (http/stop @system-ref) :stopped) (defn restart-dev [] (stop-dev) (start-dev) :restarted) (comment (start-dev) (restart-dev) (stop-dev) )
1afe5d54998cd7d8fef6ff6f96865f09f5d3922264982099b38dd849bde3df50
gedge-platform/gedge-platform
rabbit_exchange_type_headers.erl
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %% Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . %% -module(rabbit_exchange_type_headers). -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit_common/include/rabbit_framing.hrl"). -behaviour(rabbit_exchange_type). -export([description/0, serialise_events/0, route/2]). -export([validate/1, validate_binding/2, create/2, delete/3, policy_changed/2, add_binding/3, remove_bindings/3, assert_args_equivalence/2]). -export([info/1, info/2]). -rabbit_boot_step({?MODULE, [{description, "exchange type headers"}, {mfa, {rabbit_registry, register, [exchange, <<"headers">>, ?MODULE]}}, {requires, rabbit_registry}, {enables, kernel_ready}]}). info(_X) -> []. info(_X, _) -> []. description() -> [{description, <<"AMQP headers exchange, as per the AMQP specification">>}]. serialise_events() -> false. route(#exchange{name = Name}, #delivery{message = #basic_message{content = Content}}) -> Headers = case (Content#content.properties)#'P_basic'.headers of undefined -> []; H -> rabbit_misc:sort_field_table(H) end, rabbit_router:match_bindings( Name, fun (#binding{args = Spec}) -> headers_match(Spec, Headers) end). validate_binding(_X, #binding{args = Args}) -> case rabbit_misc:table_lookup(Args, <<"x-match">>) of {longstr, <<"all">>} -> ok; {longstr, <<"any">>} -> ok; {longstr, Other} -> {error, {binding_invalid, "Invalid x-match field value ~p; " "expected all or any", [Other]}}; {Type, Other} -> {error, {binding_invalid, "Invalid x-match field type ~p (value ~p); " "expected longstr", [Type, Other]}}; undefined -> ok %% [0] end. %% [0] spec is vague on whether it can be omitted but in practice it's %% useful to allow people to do this parse_x_match({longstr, <<"all">>}) -> all; parse_x_match({longstr, <<"any">>}) -> any; parse_x_match(_) -> all. %% legacy; we didn't validate Horrendous matching algorithm . Depends for its merge - like %% (linear-time) behaviour on the lists:keysort %% (rabbit_misc:sort_field_table) that route/1 and %% rabbit_binding:{add,remove}/2 do. %% %% !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! %% In other words: REQUIRES BOTH PATTERN AND DATA TO BE SORTED ASCENDING BY KEY. %% !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! %% -spec headers_match (rabbit_framing:amqp_table(), rabbit_framing:amqp_table()) -> boolean(). headers_match(Args, Data) -> MK = parse_x_match(rabbit_misc:table_lookup(Args, <<"x-match">>)), headers_match(Args, Data, true, false, MK). % A bit less horrendous algorithm :) headers_match(_, _, false, _, all) -> false; headers_match(_, _, _, true, any) -> true; % No more bindings, return current state headers_match([], _Data, AllMatch, _AnyMatch, all) -> AllMatch; headers_match([], _Data, _AllMatch, AnyMatch, any) -> AnyMatch; % Delete bindings starting with x- headers_match([{<<"x-", _/binary>>, _PT, _PV} | PRest], Data, AllMatch, AnyMatch, MatchKind) -> headers_match(PRest, Data, AllMatch, AnyMatch, MatchKind); % No more data, but still bindings, false with all headers_match(_Pattern, [], _AllMatch, AnyMatch, MatchKind) -> headers_match([], [], false, AnyMatch, MatchKind); % Data key header not in binding, go next data headers_match(Pattern = [{PK, _PT, _PV} | _], [{DK, _DT, _DV} | DRest], AllMatch, AnyMatch, MatchKind) when PK > DK -> headers_match(Pattern, DRest, AllMatch, AnyMatch, MatchKind); % Binding key header not in data, false with all, go next binding headers_match([{PK, _PT, _PV} | PRest], Data = [{DK, _DT, _DV} | _], _AllMatch, AnyMatch, MatchKind) when PK < DK -> headers_match(PRest, Data, false, AnyMatch, MatchKind); %% It's not properly specified, but a "no value" in a %% pattern field is supposed to mean simple presence of %% the corresponding data field. I've interpreted that to %% mean a type of "void" for the pattern field. headers_match([{PK, void, _PV} | PRest], [{DK, _DT, _DV} | DRest], AllMatch, _AnyMatch, MatchKind) when PK == DK -> headers_match(PRest, DRest, AllMatch, true, MatchKind); Complete match , true with any , go next headers_match([{PK, _PT, PV} | PRest], [{DK, _DT, DV} | DRest], AllMatch, _AnyMatch, MatchKind) when PK == DK andalso PV == DV -> headers_match(PRest, DRest, AllMatch, true, MatchKind); % Value does not match, false with all, go next headers_match([{PK, _PT, _PV} | PRest], [{DK, _DT, _DV} | DRest], _AllMatch, AnyMatch, MatchKind) when PK == DK -> headers_match(PRest, DRest, false, AnyMatch, MatchKind). validate(_X) -> ok. create(_Tx, _X) -> ok. delete(_Tx, _X, _Bs) -> ok. policy_changed(_X1, _X2) -> ok. add_binding(_Tx, _X, _B) -> ok. remove_bindings(_Tx, _X, _Bs) -> ok. assert_args_equivalence(X, Args) -> rabbit_exchange:assert_args_equivalence(X, Args).
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbit/src/rabbit_exchange_type_headers.erl
erlang
[0] [0] spec is vague on whether it can be omitted but in practice it's useful to allow people to do this legacy; we didn't validate (linear-time) behaviour on the lists:keysort (rabbit_misc:sort_field_table) that route/1 and rabbit_binding:{add,remove}/2 do. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In other words: REQUIRES BOTH PATTERN AND DATA TO BE SORTED ASCENDING BY KEY. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! A bit less horrendous algorithm :) No more bindings, return current state Delete bindings starting with x- No more data, but still bindings, false with all Data key header not in binding, go next data Binding key header not in data, false with all, go next binding It's not properly specified, but a "no value" in a pattern field is supposed to mean simple presence of the corresponding data field. I've interpreted that to mean a type of "void" for the pattern field. Value does not match, false with all, go next
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . -module(rabbit_exchange_type_headers). -include_lib("rabbit_common/include/rabbit.hrl"). -include_lib("rabbit_common/include/rabbit_framing.hrl"). -behaviour(rabbit_exchange_type). -export([description/0, serialise_events/0, route/2]). -export([validate/1, validate_binding/2, create/2, delete/3, policy_changed/2, add_binding/3, remove_bindings/3, assert_args_equivalence/2]). -export([info/1, info/2]). -rabbit_boot_step({?MODULE, [{description, "exchange type headers"}, {mfa, {rabbit_registry, register, [exchange, <<"headers">>, ?MODULE]}}, {requires, rabbit_registry}, {enables, kernel_ready}]}). info(_X) -> []. info(_X, _) -> []. description() -> [{description, <<"AMQP headers exchange, as per the AMQP specification">>}]. serialise_events() -> false. route(#exchange{name = Name}, #delivery{message = #basic_message{content = Content}}) -> Headers = case (Content#content.properties)#'P_basic'.headers of undefined -> []; H -> rabbit_misc:sort_field_table(H) end, rabbit_router:match_bindings( Name, fun (#binding{args = Spec}) -> headers_match(Spec, Headers) end). validate_binding(_X, #binding{args = Args}) -> case rabbit_misc:table_lookup(Args, <<"x-match">>) of {longstr, <<"all">>} -> ok; {longstr, <<"any">>} -> ok; {longstr, Other} -> {error, {binding_invalid, "Invalid x-match field value ~p; " "expected all or any", [Other]}}; {Type, Other} -> {error, {binding_invalid, "Invalid x-match field type ~p (value ~p); " "expected longstr", [Type, Other]}}; end. parse_x_match({longstr, <<"all">>}) -> all; parse_x_match({longstr, <<"any">>}) -> any; Horrendous matching algorithm . Depends for its merge - like -spec headers_match (rabbit_framing:amqp_table(), rabbit_framing:amqp_table()) -> boolean(). headers_match(Args, Data) -> MK = parse_x_match(rabbit_misc:table_lookup(Args, <<"x-match">>)), headers_match(Args, Data, true, false, MK). headers_match(_, _, false, _, all) -> false; headers_match(_, _, _, true, any) -> true; headers_match([], _Data, AllMatch, _AnyMatch, all) -> AllMatch; headers_match([], _Data, _AllMatch, AnyMatch, any) -> AnyMatch; headers_match([{<<"x-", _/binary>>, _PT, _PV} | PRest], Data, AllMatch, AnyMatch, MatchKind) -> headers_match(PRest, Data, AllMatch, AnyMatch, MatchKind); headers_match(_Pattern, [], _AllMatch, AnyMatch, MatchKind) -> headers_match([], [], false, AnyMatch, MatchKind); headers_match(Pattern = [{PK, _PT, _PV} | _], [{DK, _DT, _DV} | DRest], AllMatch, AnyMatch, MatchKind) when PK > DK -> headers_match(Pattern, DRest, AllMatch, AnyMatch, MatchKind); headers_match([{PK, _PT, _PV} | PRest], Data = [{DK, _DT, _DV} | _], _AllMatch, AnyMatch, MatchKind) when PK < DK -> headers_match(PRest, Data, false, AnyMatch, MatchKind); headers_match([{PK, void, _PV} | PRest], [{DK, _DT, _DV} | DRest], AllMatch, _AnyMatch, MatchKind) when PK == DK -> headers_match(PRest, DRest, AllMatch, true, MatchKind); Complete match , true with any , go next headers_match([{PK, _PT, PV} | PRest], [{DK, _DT, DV} | DRest], AllMatch, _AnyMatch, MatchKind) when PK == DK andalso PV == DV -> headers_match(PRest, DRest, AllMatch, true, MatchKind); headers_match([{PK, _PT, _PV} | PRest], [{DK, _DT, _DV} | DRest], _AllMatch, AnyMatch, MatchKind) when PK == DK -> headers_match(PRest, DRest, false, AnyMatch, MatchKind). validate(_X) -> ok. create(_Tx, _X) -> ok. delete(_Tx, _X, _Bs) -> ok. policy_changed(_X1, _X2) -> ok. add_binding(_Tx, _X, _B) -> ok. remove_bindings(_Tx, _X, _Bs) -> ok. assert_args_equivalence(X, Args) -> rabbit_exchange:assert_args_equivalence(X, Args).
cf63dba01d7f1059ce693cd61c765b117abe3b535a4870f9f7a8b217bf646665
sneerteam/sneer
rx_test_util.clj
(ns sneer.rx-test-util (:require [clojure.core.async :refer [>!! <!! close! chan]] [rx.lang.clojure.core :as rx] [sneer.async :refer [decode-nil]] [sneer.commons :refer [nvl]] [sneer.rx :refer [observe-for-io subscribe-on-io]] [sneer.test-util :refer [<wait-trace! <!!? closes]] ) (:import [rx Observable])) (defn subscribe-chan [c observable] (rx/subscribe observable #(>!! c (nvl % :nil)) ; Channels cannot take nil #(do #_(.printStackTrace %) (>!! c {:sneer.test-util/error %}) (close! c)) #(close! c))) (defn observable->chan ([obs] (doto (chan) (subscribe-chan obs))) ([obs xform] (doto (chan 1 xform) (subscribe-chan obs)))) (defn ->chan2 ([obs] (observable->chan (subscribe-on-io obs))) ([obs xform] (observable->chan (subscribe-on-io obs) xform))) (defn ->chan [^Observable o] (->> o observe-for-io observable->chan)) (defn emits [expected] (fn [obs] (let [ch (->chan obs)] (<wait-trace! ch expected)))) (defn emits-error [exception-type] (emits #(instance? exception-type (:sneer.test-util/error %)))) (defn <next [obs] (decode-nil (<!!? (->chan obs)))) (defn completes [obs] (closes (->chan2 obs))) ( do ( require ' midje.repl ) ( midje.repl/autotest ) )
null
https://raw.githubusercontent.com/sneerteam/sneer/b093c46321a5a42ae9418df427dbb237489b7bcb/core/src/main/clojure/sneer/rx_test_util.clj
clojure
Channels cannot take nil
(ns sneer.rx-test-util (:require [clojure.core.async :refer [>!! <!! close! chan]] [rx.lang.clojure.core :as rx] [sneer.async :refer [decode-nil]] [sneer.commons :refer [nvl]] [sneer.rx :refer [observe-for-io subscribe-on-io]] [sneer.test-util :refer [<wait-trace! <!!? closes]] ) (:import [rx Observable])) (defn subscribe-chan [c observable] (rx/subscribe observable #(do #_(.printStackTrace %) (>!! c {:sneer.test-util/error %}) (close! c)) #(close! c))) (defn observable->chan ([obs] (doto (chan) (subscribe-chan obs))) ([obs xform] (doto (chan 1 xform) (subscribe-chan obs)))) (defn ->chan2 ([obs] (observable->chan (subscribe-on-io obs))) ([obs xform] (observable->chan (subscribe-on-io obs) xform))) (defn ->chan [^Observable o] (->> o observe-for-io observable->chan)) (defn emits [expected] (fn [obs] (let [ch (->chan obs)] (<wait-trace! ch expected)))) (defn emits-error [exception-type] (emits #(instance? exception-type (:sneer.test-util/error %)))) (defn <next [obs] (decode-nil (<!!? (->chan obs)))) (defn completes [obs] (closes (->chan2 obs))) ( do ( require ' midje.repl ) ( midje.repl/autotest ) )
251c287edc3c6f09345a2dce0e3bcff2f67781b5457718ceed1897bc93ea7ccf
javalib-team/javalib
jSignature.mli
* This file is part of Javalib * Copyright ( c)2008 ( CNRS ) * * This software is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 , with the special exception on linking described in file * LICENSE . * * This program is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this program . If not , see * < / > . * This file is part of Javalib * Copyright (c)2008 Laurent Hubert (CNRS) * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1, with the special exception on linking described in file * LICENSE. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * </>. *) * This module describe the signatures used with generics . It defines the data types used to represent information extracted from the Signature attribute defined in Java 5 ( chapter 4.4.4 ) . the data types used to represent information extracted from the Signature attribute defined in Java 5 (chapter 4.4.4). *) open JBasics (** {1 Types used in type declarations of generic signatures} *) (** This is the type used for type variables as P in Collection<P>.*) type typeVariable = TypeVariable of string type typeArgument = | ArgumentExtends of fieldTypeSignature (** e.g. <?+Object> *) | ArgumentInherits of fieldTypeSignature (** e.g. <?-Object> *) | ArgumentIs of fieldTypeSignature (** e.g. <Object>*) | ArgumentIsAny (** <*> *) and simpleClassTypeSignature = { scts_name : string; scts_type_arguments : typeArgument list; } and classTypeSignature = { cts_package : string list; cts_enclosing_classes : simpleClassTypeSignature list; cts_simple_class_type_signature : simpleClassTypeSignature; } and formalTypeParameter = { ftp_name : string; ftp_class_bound : fieldTypeSignature option; ftp_interface_bounds : fieldTypeSignature list; } and throwsSignature = | ThrowsClass of classTypeSignature | ThrowsTypeVariable of typeVariable (** [typeSignature] is used for method parameters and return values of generic methods. *) and typeSignature = | GBasic of java_basic_type | GObject of fieldTypeSignature (** {1 Types of generic signatures} *) and classSignature = { cs_formal_type_parameters : formalTypeParameter list; cs_super_class : classTypeSignature; cs_super_interfaces : classTypeSignature list; } (** This type is for references. Generic fields are of this type (it cannot be of a basic type as it would not be generic anymore) but method arguments or even generic parameters are also of this type. *) and fieldTypeSignature = | GClass of classTypeSignature | GArray of typeSignature | GVariable of typeVariable type methodTypeSignature ={ mts_formal_type_parameters : formalTypeParameter list; mts_type_signature : typeSignature list; mts_return_type : typeSignature option; mts_throws : throwsSignature list; }
null
https://raw.githubusercontent.com/javalib-team/javalib/0699f904dbb17e87ec0ad6ed0c258a1737e60329/src/jSignature.mli
ocaml
* {1 Types used in type declarations of generic signatures} * This is the type used for type variables as P in Collection<P>. * e.g. <?+Object> * e.g. <?-Object> * e.g. <Object> * <*> * [typeSignature] is used for method parameters and return values of generic methods. * {1 Types of generic signatures} * This type is for references. Generic fields are of this type (it cannot be of a basic type as it would not be generic anymore) but method arguments or even generic parameters are also of this type.
* This file is part of Javalib * Copyright ( c)2008 ( CNRS ) * * This software is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 , with the special exception on linking described in file * LICENSE . * * This program is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this program . If not , see * < / > . * This file is part of Javalib * Copyright (c)2008 Laurent Hubert (CNRS) * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1, with the special exception on linking described in file * LICENSE. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * </>. *) * This module describe the signatures used with generics . It defines the data types used to represent information extracted from the Signature attribute defined in Java 5 ( chapter 4.4.4 ) . the data types used to represent information extracted from the Signature attribute defined in Java 5 (chapter 4.4.4). *) open JBasics type typeVariable = TypeVariable of string type typeArgument = and simpleClassTypeSignature = { scts_name : string; scts_type_arguments : typeArgument list; } and classTypeSignature = { cts_package : string list; cts_enclosing_classes : simpleClassTypeSignature list; cts_simple_class_type_signature : simpleClassTypeSignature; } and formalTypeParameter = { ftp_name : string; ftp_class_bound : fieldTypeSignature option; ftp_interface_bounds : fieldTypeSignature list; } and throwsSignature = | ThrowsClass of classTypeSignature | ThrowsTypeVariable of typeVariable and typeSignature = | GBasic of java_basic_type | GObject of fieldTypeSignature and classSignature = { cs_formal_type_parameters : formalTypeParameter list; cs_super_class : classTypeSignature; cs_super_interfaces : classTypeSignature list; } and fieldTypeSignature = | GClass of classTypeSignature | GArray of typeSignature | GVariable of typeVariable type methodTypeSignature ={ mts_formal_type_parameters : formalTypeParameter list; mts_type_signature : typeSignature list; mts_return_type : typeSignature option; mts_throws : throwsSignature list; }
03042194d029a681ed238bbadce71cc6e43561842ff4fe5a96d6a26397ff39ec
OCamlPro/ezjs_min
js.ml
include Js_of_ocaml.Js module Url = Js_of_ocaml.Url module Dom_html = Js_of_ocaml.Dom_html module Firebug = Js_of_ocaml.Firebug module File = Js_of_ocaml.File module Dom = Js_of_ocaml.Dom module Typed_array = Js_of_ocaml.Typed_array module Regexp = Js_of_ocaml.Regexp type ('a, 'b) result = ('a, 'b) Stdlib.result = Ok of 'a | Error of 'b type window = Dom_html.window let to_arrayf f a = Array.map f (to_array a) let of_arrayf f a = array (Array.map f a) let to_list a = Array.to_list @@ to_array a let of_list l = array @@ Array.of_list @@ l let to_listf f a = Array.to_list @@ to_arrayf f a let of_listf f a = of_arrayf f @@ Array.of_list a let optdef f = function None -> undefined | Some x -> def (f x) let to_optdef f x = match Optdef.to_option x with None -> None | Some x -> Some (f x) let unoptdef_f def f x = match Optdef.to_option x with None -> def | Some x -> f x let unoptdef def x = match Optdef.to_option x with None -> def | Some x -> x let convdef f x = match Optdef.to_option x with None -> undefined | Some x -> def (f x) let to_opt f x = match Opt.to_option x with None -> None | Some x -> Some (f x) let opt f = function None -> null | Some x -> some (f x) let convopt f x = match Opt.to_option x with None -> null | Some x -> some (f x) let js_log o = Firebug.console##log o let log_str s = Firebug.console##log (string s) let log fmt = Format.kfprintf (fun _fmt -> js_log (string (Format.flush_str_formatter ()))) Format.str_formatter fmt let error_of_string s = new%js error_constr (string s) let catch_exn f = function | Js_error.Exn e -> f (Js_error.to_error e) | exn -> f @@ error_of_string @@ Printexc.to_string exn module AOpt = struct type +'a t let null : 'a t = Unsafe.pure_js_expr "null" external some : 'a -> 'a t = "%identity" let undefined : 'a t = Unsafe.pure_js_expr "undefined" external def : 'a -> 'a t = "%identity" external return : 'a -> 'a t = "%identity" external coerce : 'a t -> 'a = "%identity" external js_equals : 'a -> 'b -> bool = "caml_js_equals" let is_none (x : 'a t) : bool = x == undefined || js_equals x null let map ?(none=undefined) (x : 'a t) (f : 'a -> 'b) : 'b t = if is_none x then none else return (f (coerce x)) let bind ?(none=undefined) (x : 'a t) (f : 'a -> 'b t) : 'b t = if is_none x then none else f (coerce x) let test (x : 'a t) : bool = not (is_none x) let iter (x : 'a t) (f : 'a -> unit) : unit = if not (is_none x) then f (coerce x) let case (x : 'a t) (f : unit -> 'b) (g : 'a -> 'b) : 'b = if is_none x then f () else g (coerce x) let get (x : 'a t) (f : unit -> 'a) : 'a = if is_none x then f () else (coerce x) let option ?(none=undefined) (x : 'a option) : 'a t = match x with | None -> none | Some x -> return x let to_option (x : 'a t) : 'a option = case x (fun () -> None) (fun x -> Some x) let aopt ?(none=(undefined : 'b t)) (f : 'a -> 'b) : 'a option -> 'b t = function | None -> none | Some x -> return (f x) let to_aopt (f : 'a -> 'b) (x : 'a t) : 'b option = case x (fun () -> None) (fun x -> Some (f x)) end type 'a aopt = 'a AOpt.t type 'a case_prop = < get : 'a optdef > gen_prop let rec choose_case_opt = function | [] -> undefined | h :: t -> match Optdef.to_option h with None -> choose_case_opt t | Some _ -> h let choose_case l = choose_case_opt (List.map Optdef.return l) let object_cs = Unsafe.global##._Object let assign (o1 : _ t) (o2 : _ t) = Unsafe.coerce (object_cs##assign o1 o2) let assign_list l = Unsafe.coerce (Unsafe.meth_call object_cs "assign" (Array.of_list l)) let remove_undefined o = let keys = object_keys o in keys##forEach (wrap_callback (fun k _ _ -> if not (Optdef.test (Unsafe.get o k)) then Unsafe.delete o k))
null
https://raw.githubusercontent.com/OCamlPro/ezjs_min/dd35adc11f54c4678cd39902893ecc45e07036ee/src/js.ml
ocaml
include Js_of_ocaml.Js module Url = Js_of_ocaml.Url module Dom_html = Js_of_ocaml.Dom_html module Firebug = Js_of_ocaml.Firebug module File = Js_of_ocaml.File module Dom = Js_of_ocaml.Dom module Typed_array = Js_of_ocaml.Typed_array module Regexp = Js_of_ocaml.Regexp type ('a, 'b) result = ('a, 'b) Stdlib.result = Ok of 'a | Error of 'b type window = Dom_html.window let to_arrayf f a = Array.map f (to_array a) let of_arrayf f a = array (Array.map f a) let to_list a = Array.to_list @@ to_array a let of_list l = array @@ Array.of_list @@ l let to_listf f a = Array.to_list @@ to_arrayf f a let of_listf f a = of_arrayf f @@ Array.of_list a let optdef f = function None -> undefined | Some x -> def (f x) let to_optdef f x = match Optdef.to_option x with None -> None | Some x -> Some (f x) let unoptdef_f def f x = match Optdef.to_option x with None -> def | Some x -> f x let unoptdef def x = match Optdef.to_option x with None -> def | Some x -> x let convdef f x = match Optdef.to_option x with None -> undefined | Some x -> def (f x) let to_opt f x = match Opt.to_option x with None -> None | Some x -> Some (f x) let opt f = function None -> null | Some x -> some (f x) let convopt f x = match Opt.to_option x with None -> null | Some x -> some (f x) let js_log o = Firebug.console##log o let log_str s = Firebug.console##log (string s) let log fmt = Format.kfprintf (fun _fmt -> js_log (string (Format.flush_str_formatter ()))) Format.str_formatter fmt let error_of_string s = new%js error_constr (string s) let catch_exn f = function | Js_error.Exn e -> f (Js_error.to_error e) | exn -> f @@ error_of_string @@ Printexc.to_string exn module AOpt = struct type +'a t let null : 'a t = Unsafe.pure_js_expr "null" external some : 'a -> 'a t = "%identity" let undefined : 'a t = Unsafe.pure_js_expr "undefined" external def : 'a -> 'a t = "%identity" external return : 'a -> 'a t = "%identity" external coerce : 'a t -> 'a = "%identity" external js_equals : 'a -> 'b -> bool = "caml_js_equals" let is_none (x : 'a t) : bool = x == undefined || js_equals x null let map ?(none=undefined) (x : 'a t) (f : 'a -> 'b) : 'b t = if is_none x then none else return (f (coerce x)) let bind ?(none=undefined) (x : 'a t) (f : 'a -> 'b t) : 'b t = if is_none x then none else f (coerce x) let test (x : 'a t) : bool = not (is_none x) let iter (x : 'a t) (f : 'a -> unit) : unit = if not (is_none x) then f (coerce x) let case (x : 'a t) (f : unit -> 'b) (g : 'a -> 'b) : 'b = if is_none x then f () else g (coerce x) let get (x : 'a t) (f : unit -> 'a) : 'a = if is_none x then f () else (coerce x) let option ?(none=undefined) (x : 'a option) : 'a t = match x with | None -> none | Some x -> return x let to_option (x : 'a t) : 'a option = case x (fun () -> None) (fun x -> Some x) let aopt ?(none=(undefined : 'b t)) (f : 'a -> 'b) : 'a option -> 'b t = function | None -> none | Some x -> return (f x) let to_aopt (f : 'a -> 'b) (x : 'a t) : 'b option = case x (fun () -> None) (fun x -> Some (f x)) end type 'a aopt = 'a AOpt.t type 'a case_prop = < get : 'a optdef > gen_prop let rec choose_case_opt = function | [] -> undefined | h :: t -> match Optdef.to_option h with None -> choose_case_opt t | Some _ -> h let choose_case l = choose_case_opt (List.map Optdef.return l) let object_cs = Unsafe.global##._Object let assign (o1 : _ t) (o2 : _ t) = Unsafe.coerce (object_cs##assign o1 o2) let assign_list l = Unsafe.coerce (Unsafe.meth_call object_cs "assign" (Array.of_list l)) let remove_undefined o = let keys = object_keys o in keys##forEach (wrap_callback (fun k _ _ -> if not (Optdef.test (Unsafe.get o k)) then Unsafe.delete o k))
1b0c3bc8b4265380b4c4e5dd9241e5c16520e1fc80ab20718207897dbb62019d
CryptoKami/cryptokami-core
Genesis.hs
-- | Computation of LRC genesis data. module Pos.Lrc.Genesis ( genesisLeaders ) where import Pos.Core (GenesisData (..), HasConfiguration, SlotLeaders, genesisData) import Pos.Lrc.FtsPure (followTheSatoshiUtxo) import Pos.Txp.GenesisUtxo (genesisUtxo) import Pos.Txp.Toil (GenesisUtxo (..)) -- | Compute leaders of the 0-th epoch from initial shared seed and stake distribution. genesisLeaders :: HasConfiguration => SlotLeaders genesisLeaders = followTheSatoshiUtxo (gdFtsSeed genesisData) utxo where GenesisUtxo utxo = genesisUtxo
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/block/src/Pos/Lrc/Genesis.hs
haskell
| Computation of LRC genesis data. | Compute leaders of the 0-th epoch from initial shared seed and stake distribution.
module Pos.Lrc.Genesis ( genesisLeaders ) where import Pos.Core (GenesisData (..), HasConfiguration, SlotLeaders, genesisData) import Pos.Lrc.FtsPure (followTheSatoshiUtxo) import Pos.Txp.GenesisUtxo (genesisUtxo) import Pos.Txp.Toil (GenesisUtxo (..)) genesisLeaders :: HasConfiguration => SlotLeaders genesisLeaders = followTheSatoshiUtxo (gdFtsSeed genesisData) utxo where GenesisUtxo utxo = genesisUtxo
8b8e0512be4d163e254536434caa4fe32ab439cb866b0a4b1eae6a02ee022981
thlack/surfs
spec.clj
(ns ^:no-doc thlack.surfs.props.spec "Contains specs for convenience props included via thlack.surfs" (:require [clojure.spec.alpha :as s] [thlack.surfs.composition.spec :as comp.spec] [thlack.surfs.strings.spec :as strings.spec])) (s/def ::selected? boolean?) (s/def ::disable_emoji_for (s/coll-of keyword? :kind set?)) (s/def ::text (s/or :string ::strings.spec/string :map ::comp.spec/text)) (s/def ::plain-text (s/or :string ::strings.spec/string :map ::comp.spec/plain-text))
null
https://raw.githubusercontent.com/thlack/surfs/e03d137d6d43c4b73a45a71984cf084d2904c4b0/src/thlack/surfs/props/spec.clj
clojure
(ns ^:no-doc thlack.surfs.props.spec "Contains specs for convenience props included via thlack.surfs" (:require [clojure.spec.alpha :as s] [thlack.surfs.composition.spec :as comp.spec] [thlack.surfs.strings.spec :as strings.spec])) (s/def ::selected? boolean?) (s/def ::disable_emoji_for (s/coll-of keyword? :kind set?)) (s/def ::text (s/or :string ::strings.spec/string :map ::comp.spec/text)) (s/def ::plain-text (s/or :string ::strings.spec/string :map ::comp.spec/plain-text))
96a963accbee37bb5105f5b1a09888f62e64dfd6376b22e0c02e6c20eeb2919a
FundingCircle/jackdaw
base.clj
(ns jackdaw.test.commands.base (:require [clojure.pprint :as pprint])) (set! *warn-on-reflection* true) (def command-map {:stop (constantly true) :sleep (fn [_machine [sleep-ms]] (Thread/sleep sleep-ms)) :println (fn [_machine params] (println (apply str params))) :pprint (fn [_machine params] (pprint/pprint params)) :do (fn [machine [do-fn]] (do-fn @(:journal machine))) :do! (fn [machine [do-fn]] (do-fn (:journal machine))) :inspect (fn [machine [inspect-fn]] (inspect-fn machine))})
null
https://raw.githubusercontent.com/FundingCircle/jackdaw/e0c66d386277282219e070cfbd0fe2ffa3c9dca5/src/jackdaw/test/commands/base.clj
clojure
(ns jackdaw.test.commands.base (:require [clojure.pprint :as pprint])) (set! *warn-on-reflection* true) (def command-map {:stop (constantly true) :sleep (fn [_machine [sleep-ms]] (Thread/sleep sleep-ms)) :println (fn [_machine params] (println (apply str params))) :pprint (fn [_machine params] (pprint/pprint params)) :do (fn [machine [do-fn]] (do-fn @(:journal machine))) :do! (fn [machine [do-fn]] (do-fn (:journal machine))) :inspect (fn [machine [inspect-fn]] (inspect-fn machine))})
85eaceba30b5007bd53c4410949e8d3ac15b9c0e1f5c35cccbbe841551c2053a
ucsd-progsys/dsolve
lazy.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Para , INRIA Rocquencourt (* *) Copyright 1997 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ I d : lazy.mli , v 1.10 2002/07/30 13:02:56 xleroy Exp $ (** Deferred computations. *) type 'a t = 'a lazy_t;; (** A value of type ['a Lazy.t] is a deferred computation, called a suspension, that has a result of type ['a]. The special expression syntax [lazy (expr)] makes a suspension of the computation of [expr], without computing [expr] itself yet. "Forcing" the suspension will then compute [expr] and return its result. Note: [lazy_t] is the built-in type constructor used by the compiler for the [lazy] keyword. You should not use it directly. Always use [Lazy.t] instead. Note: if the program is compiled with the [-rectypes] option, ill-founded recursive definitions of the form [let rec x = lazy x] or [let rec x = lazy(lazy(...(lazy x)))] are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the [-rectypes] option, such ill-founded recursive definitions are rejected by the type-checker. *) exception Undefined;; val force : 'a t -> 'a;; * [ force x ] forces the suspension [ x ] and returns its result . If [ x ] has already been forced , [ Lazy.force x ] returns the same value again without recomputing it . If it raised an exception , the same exception is raised again . Raise [ Undefined ] if the forcing of [ x ] tries to force [ x ] itself recursively . If [x] has already been forced, [Lazy.force x] returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. Raise [Undefined] if the forcing of [x] tries to force [x] itself recursively. *) val force_val : 'a t -> 'a;; (** [force_val x] forces the suspension [x] and returns its result. If [x] has already been forced, [force_val x] returns the same value again without recomputing it. Raise [Undefined] if the forcing of [x] tries to force [x] itself recursively. If the computation of [x] raises an exception, it is unspecified whether [force_val x] raises the same exception or [Undefined]. *) val lazy_from_fun : (unit -> 'a) -> 'a t;; (** [lazy_from_fun f] is the same as [lazy (f ())] but slightly more efficient. *) val lazy_from_val : 'a -> 'a t;; (** [lazy_from_val v] returns an already-forced suspension of [v] This is for special purposes only and should not be confused with [lazy (v)]. *) val lazy_is_val : 'a t -> bool;; (** [lazy_is_val x] returns [true] if [x] has already been forced and did not raise an exception. *)
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/stdlib/lazy.mli
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* * Deferred computations. * A value of type ['a Lazy.t] is a deferred computation, called a suspension, that has a result of type ['a]. The special expression syntax [lazy (expr)] makes a suspension of the computation of [expr], without computing [expr] itself yet. "Forcing" the suspension will then compute [expr] and return its result. Note: [lazy_t] is the built-in type constructor used by the compiler for the [lazy] keyword. You should not use it directly. Always use [Lazy.t] instead. Note: if the program is compiled with the [-rectypes] option, ill-founded recursive definitions of the form [let rec x = lazy x] or [let rec x = lazy(lazy(...(lazy x)))] are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the [-rectypes] option, such ill-founded recursive definitions are rejected by the type-checker. * [force_val x] forces the suspension [x] and returns its result. If [x] has already been forced, [force_val x] returns the same value again without recomputing it. Raise [Undefined] if the forcing of [x] tries to force [x] itself recursively. If the computation of [x] raises an exception, it is unspecified whether [force_val x] raises the same exception or [Undefined]. * [lazy_from_fun f] is the same as [lazy (f ())] but slightly more efficient. * [lazy_from_val v] returns an already-forced suspension of [v] This is for special purposes only and should not be confused with [lazy (v)]. * [lazy_is_val x] returns [true] if [x] has already been forced and did not raise an exception.
, projet Para , INRIA Rocquencourt Copyright 1997 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ I d : lazy.mli , v 1.10 2002/07/30 13:02:56 xleroy Exp $ type 'a t = 'a lazy_t;; exception Undefined;; val force : 'a t -> 'a;; * [ force x ] forces the suspension [ x ] and returns its result . If [ x ] has already been forced , [ Lazy.force x ] returns the same value again without recomputing it . If it raised an exception , the same exception is raised again . Raise [ Undefined ] if the forcing of [ x ] tries to force [ x ] itself recursively . If [x] has already been forced, [Lazy.force x] returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. Raise [Undefined] if the forcing of [x] tries to force [x] itself recursively. *) val force_val : 'a t -> 'a;; val lazy_from_fun : (unit -> 'a) -> 'a t;; val lazy_from_val : 'a -> 'a t;; val lazy_is_val : 'a t -> bool;;
ea7c6d4bfb3d2f048bd2db6ff9406579a3ed106bfcfb2e6ad6087f23a96bef2d
Dasudian/DSDIN
dsdo_txs_eqc.erl
-module(dsdo_txs_eqc). -compile(export_all). -compile(nowarn_export_all). -include_lib("eqc/include/eqc.hrl"). -include_lib("eqc/include/eqc_component.hrl"). -record(state, { oracles = [] , queries = [] , responses = [] , accounts = [] , patron , height = 0 }). -record(account, { pubkey, balance, height, privkey, nonce = 0 }). -record(oracle, { fee, address, ttl, height }). -record(query, { oracle, query, fee, answered = false, query_owner, query_ttl, response_ttl, height, id }). initial_state() -> #state{}. %% -- Generators ------------------------------------------------------------- gen_oracle() -> #oracle{ fee = choose(1, 10) , ttl = {delta, frequency([{1, choose(3, 15)}, {9, choose(15, 50)}])} }. gen_query(O) -> #query{ fee = O#oracle.fee, query = "Bla, bla...", oracle = O#oracle.address, query_ttl = gen_ttl(), response_ttl = gen_ttl() }. gen_response() -> ?LET(N, nat(), list_to_binary(integer_to_list(N))). %% TODO: fixed block gen_ttl() -> {delta, choose(3, 10)}. gen_key_pair() -> return(crypto:generate_key(ecdh, crypto:ec_curve(secp256k1))). gen_account(AtHeight) -> ?LET({PubKey, PrivKey}, gen_key_pair(), #account{ pubkey = PubKey, privkey = PrivKey, balance = choose(5, 200), height = AtHeight }). %% -- Operations ------------------------------------------------------------- %% --- init --- init_pre(S) -> S#state.patron == undefined. init_args(_S) -> ?LET({PubKey, PrivKey}, gen_key_pair(), [#account{ pubkey = PubKey, balance = 1000000, height = 0, privkey = PrivKey }]). init(#account{ pubkey = PK, balance = B }) -> {Genesis, Trees} = dsdc_block_genesis:genesis_block_with_state(#{ preset_accounts => [{PK, B}] }), {ok, GenesisHash} = dsdc_blocks:hash_internal_representation(Genesis), Chain = dsdc_chain_state:new_from_persistance([Genesis], [{GenesisHash, Trees}]), state_start(Chain). init_next(S, _V, [Patron]) -> S#state{ patron = Patron }. %% --- add_account --- add_account_args(S) -> [S#state.patron, gen_account(S#state.height + 1)]. add_account_pre(S, [_Patron, NewAccount]) -> S#state.height + 1 == NewAccount#account.height. add_account_adapt(S, [Patron, NewAccount]) -> [Patron, NewAccount#account{ height = S#state.height + 1}]. add_account(Patron, NewAccount) -> apply_tx(mk_spend_tx(Patron, NewAccount)). add_account_next(S, _V, [Patron = #account{ balance = PB, nonce = PN }, NewAccount = #account{ balance = NB }]) -> S#state{ patron = Patron#account{ balance = PB - NB - 1, nonce = PN + 1 }, accounts = S#state.accounts ++ [NewAccount], height = S#state.height + 1 }. add_account_post(_S, [_Patron, _NewAccount], Res) -> eq(Res, ok). --- register_oracle --- register_oracle_pre(S) -> non_oracle_accounts(S) =/= []. register_oracle_args(S) -> [elements(non_oracle_accounts(S)), gen_oracle()]. register_oracle_pre(S, [Account, _Oracle]) -> lists:member(Account, non_oracle_accounts(S)). register_oracle(Account, Oracle) -> apply_tx(mk_oracle_register_tx(Account, Oracle)). register_oracle_next(S, _V, [A = #account{ nonce = N, balance = B, pubkey = PK }, O = #oracle { ttl = TTL }]) -> case balance(PK, S) >= 4 + ttl_fee(TTL) of true -> S1 = update_account(A#account{ nonce = N+1, balance = B - (4 + ttl_fee(TTL)) }, S), S2 = update_oracle(O#oracle{ address = PK, height = S#state.height + 1 }, S1), S2#state{ height = S#state.height + 1 }; false -> S end. register_oracle_post(S, [#account{ pubkey = A }, #oracle{ ttl = TTL }], Res) -> case Res of ok -> true; {bad_tx, _Tx, _} -> case balance(A, S) < 4 + ttl_fee(TTL) of true -> true; false -> eq(Res, ok) end end. register_oracle_features(S, [#account{ pubkey = A }, #oracle{ ttl = TTL }], _V) -> case balance(A, S) < 4 + ttl_fee(TTL) of true -> [{register_oracle, false}]; false -> [{register_oracle, true}] end. %% --- query_oracle --- query_oracle_pre(S) -> S#state.oracles =/= []. query_oracle_args(S) -> ?LET(O, elements(S#state.oracles), [elements(S#state.accounts), gen_query(O)]). query_oracle_pre(S, [Account, Query]) -> lists:member(Account, S#state.accounts) andalso lists:keymember(Query#query.oracle, #oracle.address, S#state.oracles). query_oracle_adapt(S, [Account, Query]) -> case lists:keymember(Query#query.oracle, #oracle.address, S#state.oracles) andalso lists:keymember(Account#account.pubkey, #account.pubkey, S#state.accounts) of true -> [lists:keyfind(Account#account.pubkey, #account.pubkey, S#state.accounts), Query]; false -> false end. query_oracle(Account, Query) -> QueryTx = mk_oracle_query_tx(Account, Query), Id = dsdo_query:id(dsdo_query:new(QueryTx, 0)), {apply_tx(QueryTx), Id}. query_oracle_next(S, Id, [A = #account{ balance = B, nonce = N, pubkey = PK }, Q = #query{ fee = Fee, query_ttl = TTL }]) -> case query_tx_status(S, A, Q) of ok -> S1 = update_account(A#account{ nonce = N+1, balance = B - (2 + Fee + ttl_fee(TTL)) }, S), S2 = update_query(Q#query{ query_owner = PK, height = S#state.height + 1, id = {call, erlang, element, [2, Id]} }, S1), S2#state{ height = S#state.height + 1 }; _ -> S end. query_oracle_post(S, [A, Q], {Res, _}) -> QueryStatus = query_tx_status(S, A, Q), case Res of ok -> eq(ok, QueryStatus); {bad_tx, _Tx, _} when QueryStatus == ok -> eq(bad_tx, ok); _ -> true end. query_oracle_features(S, [A, Q], _V) -> [{query_oracle, query_tx_status(S, A, Q)}]. query_tx_status(S, #account{ pubkey = APK }, #query{ fee = QF, query_ttl = TTL, response_ttl = RTTL, oracle = OPK }) -> Oracle = lists:keyfind(OPK, #oracle.address, S#state.oracles), check([check_balance(balance(APK, S), QF + 2 + ttl_fee(TTL)), check_query_ttl(Oracle, TTL, RTTL, S#state.height+1), check_expire(oracle_expired(Oracle, S#state.height+1))]). check_query_ttl(O, QTTL, RTTL, Height) -> OracleExpire = dsdo_utils:ttl_expiry(O#oracle.height, O#oracle.ttl), QueryMaxExpire = dsdo_utils:ttl_expiry(Height + dsdo_utils:ttl_delta(Height, QTTL), RTTL), case OracleExpire < QueryMaxExpire of false -> ok; true -> {error, query_ttl_too_long} end. %% --- oracle_response --- oracle_response_pre(S) -> S#state.queries =/= []. oracle_response_args(S) -> ?LET(Q, elements(S#state.queries), [lists:keyfind(Q#query.oracle, #account.pubkey, S#state.accounts), Q, gen_response()]). oracle_response_pre(S, [A, Q, _R]) -> A#account.pubkey == Q#query.oracle andalso lists:member(A, S#state.accounts) andalso lists:member(Q, S#state.queries). oracle_response_adapt(S, [A, Q, R]) -> case lists:keymember(A#account.pubkey, #account.pubkey, S#state.accounts) andalso lists:keymember(Q#query.id, #query.id, S#state.queries) of true -> [lists:keyfind(A#account.pubkey, #account.pubkey, S#state.accounts), lists:keyfind(Q#query.id, #query.id, S#state.queries), R]; false -> false end. oracle_response(Account, Query, Response) -> ResponseTx = mk_oracle_response_tx(Account, Query, Response), apply_tx(ResponseTx). oracle_response_next(S, _V, [A = #account{ balance = B, nonce = N }, Q = #query{ fee = QF, response_ttl = TTL }, _]) -> case response_tx_status(S, A, Q) of ok -> S1 = update_account(A#account{ nonce = N+1, balance = B - (2 + ttl_fee(TTL)) + QF }, S), S2 = update_query(Q#query{ answered = true }, S1), S2#state{ height = S#state.height + 1 }; _ -> S end. oracle_response_post(S, [A, Q, _R], Res) -> ResponseStatus = response_tx_status(S, A, Q), case Res of ok -> eq(ok, ResponseStatus); {bad_tx, _Tx, _} when ResponseStatus == ok -> eq(bad_tx, ok); _ -> true end. oracle_response_features(S, [A, Q, _Response], _V) -> [{oracle_response, response_tx_status(S, A, Q)}]. response_tx_status(S, #account{ pubkey = APK }, Q = #query{ fee = QF, response_ttl = TTL }) -> Oracle = lists:keyfind(APK, #oracle.address, S#state.oracles), check([check_balance(balance(APK, S), (2 + ttl_fee(TTL)) - QF), check_expire(query_expired(Q, S#state.height+1)), check_expire(oracle_expired(Oracle, S#state.height+1)), check_answered(Q)]). check_balance(B1, B2) when B1 >= B2 -> ok; check_balance(_B1, _B2) -> {error, insufficient_funds}. check_expire(true) -> {error, expired}; check_expire(false) -> ok. check_answered(#query{ answered = true }) -> {error, already_answered}; check_answered(_) -> ok. check([]) -> ok; check([ok | Xs]) -> check(Xs); check([E | _]) -> E. %% -- Common pre-/post-conditions -------------------------------------------- command_precondition_common(S, Cmd) -> S#state.patron =/= undefined orelse Cmd == init. invariant(#state{ patron = undefined }) -> true; invariant(S) -> Chain = state_get(), {_LastBlock, Trees} = top_block_with_state(Chain), eqc_statem:conj([tag(accounts, check_accounts(S#state.accounts, Trees)), tag(oracles, check_oracles(S#state.oracles, Trees, S#state.height)), tag(queries, check_queries(S#state.queries, Trees, S#state.height))]). oracle_expired(#oracle{ height = H0, ttl = TTL }, H) -> expired(H0, TTL, H). query_expired(#query{ height = H0, query_ttl = TTL }, H) -> expired(H0, TTL, H). expired(H0, TTL, H) -> H > dsdo_utils:ttl_expiry(H0, TTL). check_accounts(As, Trees) -> ATree = dsdc_trees:accounts(Trees), case lists:usort([ check_account(A, ATree) || A <- As ]) -- [true] of [] -> true; Err -> Err end. check_oracles(ModelOs, Trees, Height) -> OTree = dsdc_trees:oracles(Trees), ExpectedOs = [ O#oracle.address || O <- ModelOs, not oracle_expired(O, Height) ], ActualOs = [ dsdo_oracles:owner(O) || O <- dsdo_state_tree:oracle_list(OTree)], case {ExpectedOs -- ActualOs, ActualOs -- ExpectedOs} of {[], []} -> true; {[], Os} -> {extra_oracles_in_state_tree, Os}; {Os, []} -> {premature_pruning, Os}; {Os1, Os2} -> {extra, Os1, missing, Os2} end. check_queries(ModelQs, Trees, Height) -> OTree = dsdc_trees:oracles(Trees), ExpectedQs = [ Q#query.id || Q <- ModelQs, not query_expired(Q, Height) ], ActualQs = [ dsdo_query:id(Q) || Q <- dsdo_state_tree:query_list(OTree)], case {ExpectedQs -- ActualQs, ActualQs -- ExpectedQs} of {[], []} -> true; {[], Qs} -> {extra_queries_in_state_tree, Qs}; {Qs, []} -> {premature_pruning, Qs}; {Qs1, Qs2} -> {extra, Qs1, missing, Qs2} end. check_account(#account{ pubkey = PK, balance = B, nonce = N }, ATree) -> case dsdc_accounts_trees:lookup(PK, ATree) of none -> {account_missing, PK}; {value, Account} -> tag(PK, eqc_statem:conj([tag(balance, eq(dsdc_accounts:balance(Account), B)), tag(nonce, eq(dsdc_accounts:nonce(Account), N))])) end. %% -- Property --------------------------------------------------------------- weight(_S, oracle_response) -> 2; weight(_S, query_oracle) -> 2; weight(_S, _Cmd) -> 1. prop_ok() -> ?SETUP(fun() -> setup(), fun() -> teardown() end end, ?FORALL(Cmds, commands(?MODULE), %% eqc_statem:show_states( begin HSR = {H, _S, Res} = run_commands(Cmds), check_command_names(Cmds, measure(length, commands_length(Cmds), aggregate(call_features(H), pretty_commands(?MODULE, Cmds, HSR, Res == ok)))) end)). setup() -> eqc_mocking:start_mocking(api_spec()). teardown() -> eqc_mocking:stop_mocking(). tag(_, true) -> true; tag(Tag, X) -> {Tag, X}. api_spec() -> #api_spec{ modules = [dsdc_tx_sign(), dsdc_target()] }. dsdc_target() -> #api_module{ name = dsdc_target, fallback = dsdo_oracles_mock }. dsdc_tx_sign() -> #api_module{ name = dsdc_tx_sign, fallback = dsdo_oracles_mock }. %% -- Transaction helpers ---------------------------------------------------- apply_tx(Tx) -> Chain = state_get(), {LastBlock, Trees0} = top_block_with_state(Chain), try NewBlock = dsdc_blocks:new(LastBlock, [Tx], Trees0), {ok, Chain1} = dsdc_chain_state:insert_block(NewBlock, Chain), state_put(Chain1), ok catch E:R -> {bad_tx, Tx, {E, R, erlang:get_stacktrace()}} end. mk_spend_tx(Sender, Receiver) -> {ok, Tx} = dsdc_spend_tx:new(#{ sender => Sender#account.pubkey, recipient => Receiver#account.pubkey, amount => Receiver#account.balance, fee => 1, nonce => Sender#account.nonce + 1 }), Tx. mk_oracle_register_tx(#account{ pubkey = PK, nonce = N }, #oracle{ fee = QF, ttl = TTL }) -> {ok, Tx} = dsdo_register_tx:new(#{account => PK, nonce => N + 1, query_spec => <<"string()">>, response_spec => <<"boolean() | integer()">>, query_fee => QF, ttl => TTL, fee => 4 + ttl_fee(TTL)}), Tx. mk_oracle_query_tx(#account{ pubkey = PK, nonce = N }, #query{ fee = QF, query_ttl = TTL, response_ttl = RTTL, oracle = O, query = Q }) -> {ok, Tx} = dsdo_query_tx:new(#{sender => PK, nonce => N + 1, oracle => O, query => list_to_binary(Q), query_fee => QF, query_ttl => TTL, response_ttl => RTTL, fee => 2 + ttl_fee(TTL)}), Tx. mk_oracle_response_tx(#account{ pubkey = PK, nonce = N }, #query{ response_ttl = TTL, id = Id }, R) -> {ok, Tx} = dsdo_response_tx:new(#{oracle => PK, nonce => N + 1, query_id => Id, response => R, fee => 2 + ttl_fee(TTL)}), Tx. ttl_fee(_) -> 1. %% -- State operations ------------------------------------------------------- update_oracle(O = #oracle{ address = PK }, S = #state{ oracles = Os }) -> S#state{ oracles = lists:keystore(PK, #oracle.address, Os, O) }. update_query(Q = #query{ id = Id }, S = #state{ queries = Qs }) -> S#state{ queries = lists:keystore(Id, #query.id, Qs, Q) }. add_response(Response, S) -> S#state{ responses = S#state.responses ++ [Response] }. update_account(A, S = #state{ accounts = As }) -> S#state{ accounts = lists:keystore(A#account.pubkey, #account.pubkey, As, A) }. non_oracle_accounts(#state{ accounts = As, oracles = Os, height = H }) -> lists:filter(fun(#account{ pubkey = PK }) -> case lists:keyfind(PK, #oracle.address, Os) of false -> true; O -> oracle_expired(O, H) end end, As). balance(PK, #state{ accounts = As }) -> #account{ balance = B } = lists:keyfind(PK, #account.pubkey, As), B. %% -- State service ---------------------------------------------------------- -define(SERVER, epoch_eqc). state_start(Chain) -> (catch erlang:exit(whereis(?SERVER), kill)), timer:sleep(1), register(?SERVER, spawn(fun() -> loop(Chain) end)). state_get() -> state_rpc(get). state_put(Chain) -> state_rpc({put, Chain}). state_rpc(Cmd) -> Ref = make_ref(), ?SERVER ! {epoch, self(), Ref, Cmd}, receive {epoch, Ref, Res} -> Res after 200 -> error({rpc_timeout, Cmd}) end. loop(Chain) -> receive {epoch, From, Ref, get} -> From ! {epoch, Ref, Chain}, loop(Chain); {epoch, From, Ref, {put, NewChain}} -> From ! {epoch, Ref, ok}, loop(NewChain) end. top_block_with_state(Chain) -> Block = dsdc_chain_state:top_block(Chain), {ok, BlockHash} = dsdc_blocks:hash_internal_representation(Block), {ok, Trees} = dsdc_chain_state:get_block_state(BlockHash, Chain), {Block, Trees}.
null
https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/dsdoracle/eqc/dsdo_txs_eqc.erl
erlang
-- Generators ------------------------------------------------------------- TODO: fixed block -- Operations ------------------------------------------------------------- --- init --- --- add_account --- --- query_oracle --- --- oracle_response --- -- Common pre-/post-conditions -------------------------------------------- -- Property --------------------------------------------------------------- eqc_statem:show_states( -- Transaction helpers ---------------------------------------------------- -- State operations ------------------------------------------------------- -- State service ----------------------------------------------------------
-module(dsdo_txs_eqc). -compile(export_all). -compile(nowarn_export_all). -include_lib("eqc/include/eqc.hrl"). -include_lib("eqc/include/eqc_component.hrl"). -record(state, { oracles = [] , queries = [] , responses = [] , accounts = [] , patron , height = 0 }). -record(account, { pubkey, balance, height, privkey, nonce = 0 }). -record(oracle, { fee, address, ttl, height }). -record(query, { oracle, query, fee, answered = false, query_owner, query_ttl, response_ttl, height, id }). initial_state() -> #state{}. gen_oracle() -> #oracle{ fee = choose(1, 10) , ttl = {delta, frequency([{1, choose(3, 15)}, {9, choose(15, 50)}])} }. gen_query(O) -> #query{ fee = O#oracle.fee, query = "Bla, bla...", oracle = O#oracle.address, query_ttl = gen_ttl(), response_ttl = gen_ttl() }. gen_response() -> ?LET(N, nat(), list_to_binary(integer_to_list(N))). gen_ttl() -> {delta, choose(3, 10)}. gen_key_pair() -> return(crypto:generate_key(ecdh, crypto:ec_curve(secp256k1))). gen_account(AtHeight) -> ?LET({PubKey, PrivKey}, gen_key_pair(), #account{ pubkey = PubKey, privkey = PrivKey, balance = choose(5, 200), height = AtHeight }). init_pre(S) -> S#state.patron == undefined. init_args(_S) -> ?LET({PubKey, PrivKey}, gen_key_pair(), [#account{ pubkey = PubKey, balance = 1000000, height = 0, privkey = PrivKey }]). init(#account{ pubkey = PK, balance = B }) -> {Genesis, Trees} = dsdc_block_genesis:genesis_block_with_state(#{ preset_accounts => [{PK, B}] }), {ok, GenesisHash} = dsdc_blocks:hash_internal_representation(Genesis), Chain = dsdc_chain_state:new_from_persistance([Genesis], [{GenesisHash, Trees}]), state_start(Chain). init_next(S, _V, [Patron]) -> S#state{ patron = Patron }. add_account_args(S) -> [S#state.patron, gen_account(S#state.height + 1)]. add_account_pre(S, [_Patron, NewAccount]) -> S#state.height + 1 == NewAccount#account.height. add_account_adapt(S, [Patron, NewAccount]) -> [Patron, NewAccount#account{ height = S#state.height + 1}]. add_account(Patron, NewAccount) -> apply_tx(mk_spend_tx(Patron, NewAccount)). add_account_next(S, _V, [Patron = #account{ balance = PB, nonce = PN }, NewAccount = #account{ balance = NB }]) -> S#state{ patron = Patron#account{ balance = PB - NB - 1, nonce = PN + 1 }, accounts = S#state.accounts ++ [NewAccount], height = S#state.height + 1 }. add_account_post(_S, [_Patron, _NewAccount], Res) -> eq(Res, ok). --- register_oracle --- register_oracle_pre(S) -> non_oracle_accounts(S) =/= []. register_oracle_args(S) -> [elements(non_oracle_accounts(S)), gen_oracle()]. register_oracle_pre(S, [Account, _Oracle]) -> lists:member(Account, non_oracle_accounts(S)). register_oracle(Account, Oracle) -> apply_tx(mk_oracle_register_tx(Account, Oracle)). register_oracle_next(S, _V, [A = #account{ nonce = N, balance = B, pubkey = PK }, O = #oracle { ttl = TTL }]) -> case balance(PK, S) >= 4 + ttl_fee(TTL) of true -> S1 = update_account(A#account{ nonce = N+1, balance = B - (4 + ttl_fee(TTL)) }, S), S2 = update_oracle(O#oracle{ address = PK, height = S#state.height + 1 }, S1), S2#state{ height = S#state.height + 1 }; false -> S end. register_oracle_post(S, [#account{ pubkey = A }, #oracle{ ttl = TTL }], Res) -> case Res of ok -> true; {bad_tx, _Tx, _} -> case balance(A, S) < 4 + ttl_fee(TTL) of true -> true; false -> eq(Res, ok) end end. register_oracle_features(S, [#account{ pubkey = A }, #oracle{ ttl = TTL }], _V) -> case balance(A, S) < 4 + ttl_fee(TTL) of true -> [{register_oracle, false}]; false -> [{register_oracle, true}] end. query_oracle_pre(S) -> S#state.oracles =/= []. query_oracle_args(S) -> ?LET(O, elements(S#state.oracles), [elements(S#state.accounts), gen_query(O)]). query_oracle_pre(S, [Account, Query]) -> lists:member(Account, S#state.accounts) andalso lists:keymember(Query#query.oracle, #oracle.address, S#state.oracles). query_oracle_adapt(S, [Account, Query]) -> case lists:keymember(Query#query.oracle, #oracle.address, S#state.oracles) andalso lists:keymember(Account#account.pubkey, #account.pubkey, S#state.accounts) of true -> [lists:keyfind(Account#account.pubkey, #account.pubkey, S#state.accounts), Query]; false -> false end. query_oracle(Account, Query) -> QueryTx = mk_oracle_query_tx(Account, Query), Id = dsdo_query:id(dsdo_query:new(QueryTx, 0)), {apply_tx(QueryTx), Id}. query_oracle_next(S, Id, [A = #account{ balance = B, nonce = N, pubkey = PK }, Q = #query{ fee = Fee, query_ttl = TTL }]) -> case query_tx_status(S, A, Q) of ok -> S1 = update_account(A#account{ nonce = N+1, balance = B - (2 + Fee + ttl_fee(TTL)) }, S), S2 = update_query(Q#query{ query_owner = PK, height = S#state.height + 1, id = {call, erlang, element, [2, Id]} }, S1), S2#state{ height = S#state.height + 1 }; _ -> S end. query_oracle_post(S, [A, Q], {Res, _}) -> QueryStatus = query_tx_status(S, A, Q), case Res of ok -> eq(ok, QueryStatus); {bad_tx, _Tx, _} when QueryStatus == ok -> eq(bad_tx, ok); _ -> true end. query_oracle_features(S, [A, Q], _V) -> [{query_oracle, query_tx_status(S, A, Q)}]. query_tx_status(S, #account{ pubkey = APK }, #query{ fee = QF, query_ttl = TTL, response_ttl = RTTL, oracle = OPK }) -> Oracle = lists:keyfind(OPK, #oracle.address, S#state.oracles), check([check_balance(balance(APK, S), QF + 2 + ttl_fee(TTL)), check_query_ttl(Oracle, TTL, RTTL, S#state.height+1), check_expire(oracle_expired(Oracle, S#state.height+1))]). check_query_ttl(O, QTTL, RTTL, Height) -> OracleExpire = dsdo_utils:ttl_expiry(O#oracle.height, O#oracle.ttl), QueryMaxExpire = dsdo_utils:ttl_expiry(Height + dsdo_utils:ttl_delta(Height, QTTL), RTTL), case OracleExpire < QueryMaxExpire of false -> ok; true -> {error, query_ttl_too_long} end. oracle_response_pre(S) -> S#state.queries =/= []. oracle_response_args(S) -> ?LET(Q, elements(S#state.queries), [lists:keyfind(Q#query.oracle, #account.pubkey, S#state.accounts), Q, gen_response()]). oracle_response_pre(S, [A, Q, _R]) -> A#account.pubkey == Q#query.oracle andalso lists:member(A, S#state.accounts) andalso lists:member(Q, S#state.queries). oracle_response_adapt(S, [A, Q, R]) -> case lists:keymember(A#account.pubkey, #account.pubkey, S#state.accounts) andalso lists:keymember(Q#query.id, #query.id, S#state.queries) of true -> [lists:keyfind(A#account.pubkey, #account.pubkey, S#state.accounts), lists:keyfind(Q#query.id, #query.id, S#state.queries), R]; false -> false end. oracle_response(Account, Query, Response) -> ResponseTx = mk_oracle_response_tx(Account, Query, Response), apply_tx(ResponseTx). oracle_response_next(S, _V, [A = #account{ balance = B, nonce = N }, Q = #query{ fee = QF, response_ttl = TTL }, _]) -> case response_tx_status(S, A, Q) of ok -> S1 = update_account(A#account{ nonce = N+1, balance = B - (2 + ttl_fee(TTL)) + QF }, S), S2 = update_query(Q#query{ answered = true }, S1), S2#state{ height = S#state.height + 1 }; _ -> S end. oracle_response_post(S, [A, Q, _R], Res) -> ResponseStatus = response_tx_status(S, A, Q), case Res of ok -> eq(ok, ResponseStatus); {bad_tx, _Tx, _} when ResponseStatus == ok -> eq(bad_tx, ok); _ -> true end. oracle_response_features(S, [A, Q, _Response], _V) -> [{oracle_response, response_tx_status(S, A, Q)}]. response_tx_status(S, #account{ pubkey = APK }, Q = #query{ fee = QF, response_ttl = TTL }) -> Oracle = lists:keyfind(APK, #oracle.address, S#state.oracles), check([check_balance(balance(APK, S), (2 + ttl_fee(TTL)) - QF), check_expire(query_expired(Q, S#state.height+1)), check_expire(oracle_expired(Oracle, S#state.height+1)), check_answered(Q)]). check_balance(B1, B2) when B1 >= B2 -> ok; check_balance(_B1, _B2) -> {error, insufficient_funds}. check_expire(true) -> {error, expired}; check_expire(false) -> ok. check_answered(#query{ answered = true }) -> {error, already_answered}; check_answered(_) -> ok. check([]) -> ok; check([ok | Xs]) -> check(Xs); check([E | _]) -> E. command_precondition_common(S, Cmd) -> S#state.patron =/= undefined orelse Cmd == init. invariant(#state{ patron = undefined }) -> true; invariant(S) -> Chain = state_get(), {_LastBlock, Trees} = top_block_with_state(Chain), eqc_statem:conj([tag(accounts, check_accounts(S#state.accounts, Trees)), tag(oracles, check_oracles(S#state.oracles, Trees, S#state.height)), tag(queries, check_queries(S#state.queries, Trees, S#state.height))]). oracle_expired(#oracle{ height = H0, ttl = TTL }, H) -> expired(H0, TTL, H). query_expired(#query{ height = H0, query_ttl = TTL }, H) -> expired(H0, TTL, H). expired(H0, TTL, H) -> H > dsdo_utils:ttl_expiry(H0, TTL). check_accounts(As, Trees) -> ATree = dsdc_trees:accounts(Trees), case lists:usort([ check_account(A, ATree) || A <- As ]) -- [true] of [] -> true; Err -> Err end. check_oracles(ModelOs, Trees, Height) -> OTree = dsdc_trees:oracles(Trees), ExpectedOs = [ O#oracle.address || O <- ModelOs, not oracle_expired(O, Height) ], ActualOs = [ dsdo_oracles:owner(O) || O <- dsdo_state_tree:oracle_list(OTree)], case {ExpectedOs -- ActualOs, ActualOs -- ExpectedOs} of {[], []} -> true; {[], Os} -> {extra_oracles_in_state_tree, Os}; {Os, []} -> {premature_pruning, Os}; {Os1, Os2} -> {extra, Os1, missing, Os2} end. check_queries(ModelQs, Trees, Height) -> OTree = dsdc_trees:oracles(Trees), ExpectedQs = [ Q#query.id || Q <- ModelQs, not query_expired(Q, Height) ], ActualQs = [ dsdo_query:id(Q) || Q <- dsdo_state_tree:query_list(OTree)], case {ExpectedQs -- ActualQs, ActualQs -- ExpectedQs} of {[], []} -> true; {[], Qs} -> {extra_queries_in_state_tree, Qs}; {Qs, []} -> {premature_pruning, Qs}; {Qs1, Qs2} -> {extra, Qs1, missing, Qs2} end. check_account(#account{ pubkey = PK, balance = B, nonce = N }, ATree) -> case dsdc_accounts_trees:lookup(PK, ATree) of none -> {account_missing, PK}; {value, Account} -> tag(PK, eqc_statem:conj([tag(balance, eq(dsdc_accounts:balance(Account), B)), tag(nonce, eq(dsdc_accounts:nonce(Account), N))])) end. weight(_S, oracle_response) -> 2; weight(_S, query_oracle) -> 2; weight(_S, _Cmd) -> 1. prop_ok() -> ?SETUP(fun() -> setup(), fun() -> teardown() end end, ?FORALL(Cmds, commands(?MODULE), begin HSR = {H, _S, Res} = run_commands(Cmds), check_command_names(Cmds, measure(length, commands_length(Cmds), aggregate(call_features(H), pretty_commands(?MODULE, Cmds, HSR, Res == ok)))) end)). setup() -> eqc_mocking:start_mocking(api_spec()). teardown() -> eqc_mocking:stop_mocking(). tag(_, true) -> true; tag(Tag, X) -> {Tag, X}. api_spec() -> #api_spec{ modules = [dsdc_tx_sign(), dsdc_target()] }. dsdc_target() -> #api_module{ name = dsdc_target, fallback = dsdo_oracles_mock }. dsdc_tx_sign() -> #api_module{ name = dsdc_tx_sign, fallback = dsdo_oracles_mock }. apply_tx(Tx) -> Chain = state_get(), {LastBlock, Trees0} = top_block_with_state(Chain), try NewBlock = dsdc_blocks:new(LastBlock, [Tx], Trees0), {ok, Chain1} = dsdc_chain_state:insert_block(NewBlock, Chain), state_put(Chain1), ok catch E:R -> {bad_tx, Tx, {E, R, erlang:get_stacktrace()}} end. mk_spend_tx(Sender, Receiver) -> {ok, Tx} = dsdc_spend_tx:new(#{ sender => Sender#account.pubkey, recipient => Receiver#account.pubkey, amount => Receiver#account.balance, fee => 1, nonce => Sender#account.nonce + 1 }), Tx. mk_oracle_register_tx(#account{ pubkey = PK, nonce = N }, #oracle{ fee = QF, ttl = TTL }) -> {ok, Tx} = dsdo_register_tx:new(#{account => PK, nonce => N + 1, query_spec => <<"string()">>, response_spec => <<"boolean() | integer()">>, query_fee => QF, ttl => TTL, fee => 4 + ttl_fee(TTL)}), Tx. mk_oracle_query_tx(#account{ pubkey = PK, nonce = N }, #query{ fee = QF, query_ttl = TTL, response_ttl = RTTL, oracle = O, query = Q }) -> {ok, Tx} = dsdo_query_tx:new(#{sender => PK, nonce => N + 1, oracle => O, query => list_to_binary(Q), query_fee => QF, query_ttl => TTL, response_ttl => RTTL, fee => 2 + ttl_fee(TTL)}), Tx. mk_oracle_response_tx(#account{ pubkey = PK, nonce = N }, #query{ response_ttl = TTL, id = Id }, R) -> {ok, Tx} = dsdo_response_tx:new(#{oracle => PK, nonce => N + 1, query_id => Id, response => R, fee => 2 + ttl_fee(TTL)}), Tx. ttl_fee(_) -> 1. update_oracle(O = #oracle{ address = PK }, S = #state{ oracles = Os }) -> S#state{ oracles = lists:keystore(PK, #oracle.address, Os, O) }. update_query(Q = #query{ id = Id }, S = #state{ queries = Qs }) -> S#state{ queries = lists:keystore(Id, #query.id, Qs, Q) }. add_response(Response, S) -> S#state{ responses = S#state.responses ++ [Response] }. update_account(A, S = #state{ accounts = As }) -> S#state{ accounts = lists:keystore(A#account.pubkey, #account.pubkey, As, A) }. non_oracle_accounts(#state{ accounts = As, oracles = Os, height = H }) -> lists:filter(fun(#account{ pubkey = PK }) -> case lists:keyfind(PK, #oracle.address, Os) of false -> true; O -> oracle_expired(O, H) end end, As). balance(PK, #state{ accounts = As }) -> #account{ balance = B } = lists:keyfind(PK, #account.pubkey, As), B. -define(SERVER, epoch_eqc). state_start(Chain) -> (catch erlang:exit(whereis(?SERVER), kill)), timer:sleep(1), register(?SERVER, spawn(fun() -> loop(Chain) end)). state_get() -> state_rpc(get). state_put(Chain) -> state_rpc({put, Chain}). state_rpc(Cmd) -> Ref = make_ref(), ?SERVER ! {epoch, self(), Ref, Cmd}, receive {epoch, Ref, Res} -> Res after 200 -> error({rpc_timeout, Cmd}) end. loop(Chain) -> receive {epoch, From, Ref, get} -> From ! {epoch, Ref, Chain}, loop(Chain); {epoch, From, Ref, {put, NewChain}} -> From ! {epoch, Ref, ok}, loop(NewChain) end. top_block_with_state(Chain) -> Block = dsdc_chain_state:top_block(Chain), {ok, BlockHash} = dsdc_blocks:hash_internal_representation(Block), {ok, Trees} = dsdc_chain_state:get_block_state(BlockHash, Chain), {Block, Trees}.
c7c22cded93edd5acc6ae9391315eb13c27027a0517ff8d424618ed00f77c903
fossas/fossa-cli
FpmTomlSpec.hs
module Fortran.FpmTomlSpec ( spec, ) where import Data.Map (fromList) import Data.Set qualified as Set import Data.Text (Text) import Data.Text.IO qualified as TIO import DepTypes ( DepEnvironment (EnvDevelopment, EnvProduction), DepType (GitType), Dependency (Dependency), VerConstraint (CEq), ) import GraphUtil (expectDeps, expectEdges) import Strategy.Fortran.FpmToml ( FpmDependency (..), FpmGitDependency (..), FpmPathDependency (..), FpmToml (..), buildGraph, fpmTomlCodec, ) import Test.Hspec ( Spec, describe, it, runIO, shouldBe, ) import Toml qualified mkPathFpmDep :: Text -> FpmDependency mkPathFpmDep name = FpmPathDep $ FpmPathDependency name mkGitDep :: Text -> Maybe Text -> Set.Set DepEnvironment -> Dependency mkGitDep name version envs = Dependency GitType name (CEq <$> version) [] envs mempty mkGitFpmDep :: FpmGitDependency mkGitFpmDep = FpmGitDependency "git-url" Nothing Nothing Nothing expectedFpmToml :: FpmToml expectedFpmToml = FpmToml ( fromList [ ("my-utils", mkPathFpmDep "utils") , ("dep-head", FpmGitDep mkGitFpmDep) , ("dep-branch", FpmGitDep $ mkGitFpmDep{branch = Just "main"}) , ("dep-tag", FpmGitDep $ mkGitFpmDep{tag = Just "v0.2.1"}) , ("dep-rev", FpmGitDep $ mkGitFpmDep{rev = Just "2f5eaba"}) ] ) (fromList [("dep-dev", FpmGitDep mkGitFpmDep{url = "git-url-dev-dep", rev = Just "2f5eaba"})]) [fromList [("dep-exec", FpmGitDep mkGitFpmDep{url = "git-url-exec"})]] spec :: Spec spec = do content <- runIO (TIO.readFile "test/Fortran/testdata/fpm.toml") describe "fpmTomlCodec" $ it "should parse fpm.toml file" $ Toml.decode fpmTomlCodec content `shouldBe` Right expectedFpmToml describe "buildGraph" $ do let graph = buildGraph expectedFpmToml let graphDeps = [ mkGitDep "git-url" Nothing $ Set.singleton EnvProduction , mkGitDep "git-url" (Just "main") $ Set.singleton EnvProduction , mkGitDep "git-url" (Just "v0.2.1") $ Set.singleton EnvProduction , mkGitDep "git-url" (Just "2f5eaba") $ Set.singleton EnvProduction , mkGitDep "git-url-dev-dep" (Just "2f5eaba") $ Set.singleton EnvDevelopment , mkGitDep "git-url-exec" (Nothing) $ Set.singleton EnvProduction ] it "should not have any edges" $ expectEdges [] graph it "should have deps" $ do expectDeps graphDeps graph
null
https://raw.githubusercontent.com/fossas/fossa-cli/efc29b4f9c874e338f0b5a7d1c5b13cb9543156f/test/Fortran/FpmTomlSpec.hs
haskell
module Fortran.FpmTomlSpec ( spec, ) where import Data.Map (fromList) import Data.Set qualified as Set import Data.Text (Text) import Data.Text.IO qualified as TIO import DepTypes ( DepEnvironment (EnvDevelopment, EnvProduction), DepType (GitType), Dependency (Dependency), VerConstraint (CEq), ) import GraphUtil (expectDeps, expectEdges) import Strategy.Fortran.FpmToml ( FpmDependency (..), FpmGitDependency (..), FpmPathDependency (..), FpmToml (..), buildGraph, fpmTomlCodec, ) import Test.Hspec ( Spec, describe, it, runIO, shouldBe, ) import Toml qualified mkPathFpmDep :: Text -> FpmDependency mkPathFpmDep name = FpmPathDep $ FpmPathDependency name mkGitDep :: Text -> Maybe Text -> Set.Set DepEnvironment -> Dependency mkGitDep name version envs = Dependency GitType name (CEq <$> version) [] envs mempty mkGitFpmDep :: FpmGitDependency mkGitFpmDep = FpmGitDependency "git-url" Nothing Nothing Nothing expectedFpmToml :: FpmToml expectedFpmToml = FpmToml ( fromList [ ("my-utils", mkPathFpmDep "utils") , ("dep-head", FpmGitDep mkGitFpmDep) , ("dep-branch", FpmGitDep $ mkGitFpmDep{branch = Just "main"}) , ("dep-tag", FpmGitDep $ mkGitFpmDep{tag = Just "v0.2.1"}) , ("dep-rev", FpmGitDep $ mkGitFpmDep{rev = Just "2f5eaba"}) ] ) (fromList [("dep-dev", FpmGitDep mkGitFpmDep{url = "git-url-dev-dep", rev = Just "2f5eaba"})]) [fromList [("dep-exec", FpmGitDep mkGitFpmDep{url = "git-url-exec"})]] spec :: Spec spec = do content <- runIO (TIO.readFile "test/Fortran/testdata/fpm.toml") describe "fpmTomlCodec" $ it "should parse fpm.toml file" $ Toml.decode fpmTomlCodec content `shouldBe` Right expectedFpmToml describe "buildGraph" $ do let graph = buildGraph expectedFpmToml let graphDeps = [ mkGitDep "git-url" Nothing $ Set.singleton EnvProduction , mkGitDep "git-url" (Just "main") $ Set.singleton EnvProduction , mkGitDep "git-url" (Just "v0.2.1") $ Set.singleton EnvProduction , mkGitDep "git-url" (Just "2f5eaba") $ Set.singleton EnvProduction , mkGitDep "git-url-dev-dep" (Just "2f5eaba") $ Set.singleton EnvDevelopment , mkGitDep "git-url-exec" (Nothing) $ Set.singleton EnvProduction ] it "should not have any edges" $ expectEdges [] graph it "should have deps" $ do expectDeps graphDeps graph
87e77460a5989111b8545e2cec6e7ab65715d118f2bd3bc548af880483ba8299
plum-umd/fundamentals
point-fun.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname point-fun) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ;; A Point is a (make-point Real Real) (define-struct point (x y)) ;; dist0 : Point -> Real ;; Compute the distance to origin from given point (check-expect (dist0 (make-point 3 4)) 5) (define (dist0 p) (sqrt (+ (sqr (point-x p)) (sqr (point-y p))))) dist : Point Point - > Real ;; Compute the distance between given points (check-expect (dist (make-point 4 5) (make-point 1 1)) 5) (define (dist p1 p2) (sqrt (+ (sqr (- (point-x p1) (point-x p2))) (sqr (- (point-y p1) (point-x p2)))))) move : Point Real Real - > Point ;; Move the point by the given amount (check-expect (move (make-point 2 3) -1 2) (make-point 1 5)) (define (move p Ξ”x Ξ”y) (make-point (+ (point-x p) Ξ”x) (+ (point-y p) Ξ”y))) point= ? : Point Point - > Boolean Are the two points the same ? (check-expect (point=? (make-point 3 4) (make-point 3 4)) #true) (check-expect (point=? (make-point 3 4) (make-point 0 0)) #false) (define (point=? p1 p2) (and (= (point-x p1) (point-x p2)) (= (point-y p1) (point-y p2))))
null
https://raw.githubusercontent.com/plum-umd/fundamentals/eb01ac528d42855be53649991a17d19c025a97ad/1/www/code/point-fun.rkt
racket
about the language level of this file in a form that our tools can easily process. A Point is a (make-point Real Real) dist0 : Point -> Real Compute the distance to origin from given point Compute the distance between given points Move the point by the given amount
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname point-fun) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (define-struct point (x y)) (check-expect (dist0 (make-point 3 4)) 5) (define (dist0 p) (sqrt (+ (sqr (point-x p)) (sqr (point-y p))))) dist : Point Point - > Real (check-expect (dist (make-point 4 5) (make-point 1 1)) 5) (define (dist p1 p2) (sqrt (+ (sqr (- (point-x p1) (point-x p2))) (sqr (- (point-y p1) (point-x p2)))))) move : Point Real Real - > Point (check-expect (move (make-point 2 3) -1 2) (make-point 1 5)) (define (move p Ξ”x Ξ”y) (make-point (+ (point-x p) Ξ”x) (+ (point-y p) Ξ”y))) point= ? : Point Point - > Boolean Are the two points the same ? (check-expect (point=? (make-point 3 4) (make-point 3 4)) #true) (check-expect (point=? (make-point 3 4) (make-point 0 0)) #false) (define (point=? p1 p2) (and (= (point-x p1) (point-x p2)) (= (point-y p1) (point-y p2))))
7c90deaee45792d33a901a516920f5df377cf1787d460e9dda6d3fbaa34e9fcb
Haskell-OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator
Lib.hs
{-# LANGUAGE OverloadedStrings #-} module Lib where import Data.ByteString.Char8 import Network.HTTP.Client import OpenAPI import OpenAPI.Common runAddPet :: MonadHTTP m => m (Response AddPetResponse) runAddPet = runWithConfiguration defaultConfiguration (addPet myPet) where myPet = Pet { petCategory = Nothing, petId = Nothing, petName = "Harro", petPhotoUrls = [], petStatus = Nothing, petTags = Nothing } runGetInventory :: MonadHTTP m => m (Response GetInventoryResponse) runGetInventory = runWithConfiguration defaultConfiguration getInventory runFindPetsByStatus :: MonadHTTP m => m (Response FindPetsByStatusResponse) runFindPetsByStatus = runWithConfiguration defaultConfiguration (findPetsByStatus [FindPetsByStatusParametersStatusEnumPending])
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator/2779306860af040f47a6e57ede65027e2862133e/example/src/Lib.hs
haskell
# LANGUAGE OverloadedStrings #
module Lib where import Data.ByteString.Char8 import Network.HTTP.Client import OpenAPI import OpenAPI.Common runAddPet :: MonadHTTP m => m (Response AddPetResponse) runAddPet = runWithConfiguration defaultConfiguration (addPet myPet) where myPet = Pet { petCategory = Nothing, petId = Nothing, petName = "Harro", petPhotoUrls = [], petStatus = Nothing, petTags = Nothing } runGetInventory :: MonadHTTP m => m (Response GetInventoryResponse) runGetInventory = runWithConfiguration defaultConfiguration getInventory runFindPetsByStatus :: MonadHTTP m => m (Response FindPetsByStatusResponse) runFindPetsByStatus = runWithConfiguration defaultConfiguration (findPetsByStatus [FindPetsByStatusParametersStatusEnumPending])
f4d84b25d733e1ca79814b5ba7ce0c2953239ba34c881340519fc2c42946de49
amnh/PCG
Type.hs
------------------------------------------------------------------------------ -- | -- Module : Data.Graph.Type Copyright : ( c ) 2015 - 2021 Ward Wheeler -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : portable -- ----------------------------------------------------------------------------- # LANGUAGE DerivingStrategies # {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RecordWildCards # {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TypeApplications # module Data.Graph.Type ( Graph(..) , GraphBuilder(..) , HasTreeReferences(..) , HasNetworkReferences(..) , HasRootReferences(..) , HasLeafReferences(..) , HasCachedData(..) , RootFocusGraph , Focus , makeRootFocusGraphs , buildGraph , index , getRootInds , unfoldGraph , unsafeLeafInd , unsafeRootInd , unsafeTreeInd , unsafeNetworkInd ) where import Control . Arrow ( first ) import Control.Lens.Combinators (Bifunctor(..), Identity, ix, lens, singular, view) import Control.Lens.Operators ((^.)) import Control.Lens.Type (Lens, Lens') import Control . Monad . State . Strict import Data.Graph.Indices import Data.Graph.NodeContext import Data.Kind (Type) import Data . Maybe ( ) import Data.Pair.Strict import Data . Set ( Set ) --import qualified Data.Set as S import Data.Vector (Vector, generate) import Data.Vector.Instances () import Test.QuickCheck.Arbitrary import TextShow hiding (Builder) import VectorBuilder.Builder import VectorBuilder.Vector β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ -- β”‚ Types β”‚ -- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ data GraphShape i n r t = GraphShape { leafData : : Vector t , treeData : : Vector i , networkData : : Vector n , rootData : : Vector r } data GraphShape i n r t = GraphShape { leafData :: Vector t , treeData :: Vector i , networkData :: Vector n , rootData :: Vector r } -} -- | A specialized representation of a Directed , Acyclic Graph ( DAG ) which has -- the following constraints on the construction of nodes: -- - In - degree ≀ 2 - Out - degree ≀ 2 - Degree ≀ 3 - Out - degree = 0 β‡’ in - degree = 1 -- - In-degree = 0 β‡’ Out-degree ∈ {1,2} - In - degree = 2 β‡’ Out - degree 1 -- data Graph (f :: Type -> Type) (c :: Type) (e :: Type) (n :: Type) (t :: Type) = Graph { leafReferences :: Vector (LeafIndexData t ) , treeReferences :: Vector (TreeIndexData (f n) e) , networkReferences :: Vector (NetworkIndexData (f n) e) , rootReferences :: Vector (RootIndexData (f n) e) , cachedData :: c } deriving stock Show -- | -- Builder type designed to improve the asymptotics of incrementally building a -- complete graph object. data GraphBuilder (f :: Type -> Type) (e :: Type) (n :: Type) (t :: Type) = GraphBuilder { leafReferencesBuilder :: Builder (LeafIndexData t ) , treeReferencesBuilder :: Builder (TreeIndexData (f n) e) , networkReferencesBuilder :: Builder (NetworkIndexData (f n) e) , rootReferencesBuilder :: Builder (RootIndexData (f n) e) } -- | -- A reference to a node index which is considered the traversal focus (root), -- in a re-rooting traversal. type Focus = Pair IndexType UntaggedIndex -- | -- The result of a re-rooting traversal, noting the node index which was -- considered the traversal focus (root), and the resulting rerooted 'Graph'. type RootFocusGraph f c e n t = Pair Focus (Graph f c e n t) -- | -- A 'Lens' for the 'cachedData' field. class HasCachedData s t a b | s -> a, t -> b, s b -> t, t a -> b where _cachedData :: Lens s t a b -- | -- A 'Lens' for the 'leafReferences' field. class HasLeafReferences s t a b | s -> a, t -> b, s b -> t, t a -> s where _leafReferences :: Lens s t a b -- | -- A 'Lens' for the 'networkReferences' field. class HasNetworkReferences s a | s -> a where _networkReferences :: Lens' s a -- | -- A 'Lens' for the 'rootReferences' field. class HasRootReferences s a | s -> a where _rootReferences :: Lens' s a -- | -- A 'Lens' for the 'treeReferences' field. class HasTreeReferences s a | s -> a where _treeReferences :: Lens' s a β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ -- β”‚ Instances β”‚ -- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ instance Arbitrary (Graph f c e n t) where arbitrary = pure undefined instance Functor f => Bifunctor (Graph f c e) where bimap f g graph@Graph{..} = graph { leafReferences = (fmap . fmap $ g) leafReferences , treeReferences = (fmap . fmap . fmap $ f) treeReferences , networkReferences = (fmap . fmap . fmap $ f) networkReferences , rootReferences = (fmap . fmap . fmap $ f) rootReferences } instance HasCachedData (Graph f c1 e n t) (Graph f c2 e n t) c1 c2 where _cachedData = lens cachedData (\g c2 -> g {cachedData = c2}) instance HasLeafReferences (Graph f c e n t) (Graph f c e n t') (Vector (IndexData LeafContext t)) (Vector (IndexData LeafContext t')) where _leafReferences = lens leafReferences (\g l -> g { leafReferences = l}) instance HasNetworkReferences (Graph f c e n t) (Vector (IndexData (NetworkContext e) (f n))) where _networkReferences = lens networkReferences (\g fn -> g {networkReferences = fn}) instance HasRootReferences (Graph f c e n t) (Vector (IndexData (RootContext e) (f n))) where _rootReferences = lens rootReferences (\g fn -> g {rootReferences = fn}) instance HasTreeReferences (Graph f c e n t) (Vector (IndexData (TreeContext e) (f n))) where _treeReferences = lens treeReferences (\g fn -> g {treeReferences = fn}) --instance Show (Graph f c e n t) where show = toString . instance TextShow (Graph f c e n t) where showb = undefined -- | Finalize a ' GraphBuilder ' into a ' Graph ' . -- -- The 'GraphBuilder' has better asymptotics for combining graphs, but poor -- performance for 'Graph' manipulation and queries. The 'Graph' type supports -- efficient queries and graph manipulation, but is not efficient at combining. buildGraph :: GraphBuilder f e n t -> c -> Graph f c e n t buildGraph GraphBuilder{..} cachedData = let leafReferences = build leafReferencesBuilder treeReferences = build treeReferencesBuilder networkReferences = build networkReferencesBuilder rootReferences = build rootReferencesBuilder in Graph{..} -- | -- This makes a list of graphs along with the roots to focus upon. makeRootFocusGraphs :: Graph f c e n t -> [RootFocusGraph f c e n t] makeRootFocusGraphs graph = let rootLength = length (view _rootReferences graph) rootNames :: [Focus] rootNames = let rootInds = case rootLength of 0 -> [] 1 -> [0] n -> [0..(n - 1)] in Pair RootTag <$> rootInds in (:!: graph) <$> rootNames β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ -- β”‚ Utility β”‚ -- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -- | -- Index the graph, retrieving the node data at the specified index. index :: Tagged taggedInd => Graph f c e n t -> taggedInd -> NodeIndexData (f n) e t index graph taggedIndex = let ind = getIndex taggedIndex in case getTag taggedIndex of LeafTag -> LeafNodeIndexData $ graph ^. _leafReferences . singular (ix ind) TreeTag -> TreeNodeIndexData $ graph ^. _treeReferences . singular (ix ind) NetworkTag -> NetworkNodeIndexData $ graph ^. _networkReferences . singular (ix ind) RootTag -> RootNodeIndexData $ graph ^. _rootReferences . singular (ix ind) -- | -- Get the indices of all root nodes within the graph. getRootInds :: Graph f c e n t -> Vector TaggedIndex getRootInds graph = let numberOfRoots = length (view _rootReferences graph) roots = generate numberOfRoots (`TaggedIndex` RootTag) in roots size : : Builder a - > Int size = length . build @Vector size :: Builder a -> Int size = length . build @Vector -} data RoseTree e t = { root : : t , : : ( [ ( RoseTree e t , e ) ] , [ ( t , e ) ] ) } data RoseTree e t = RoseTree { root :: t , subForest :: ([(RoseTree e t, e)], [(t, e)]) } -} type RoseForest e t = [ RoseTree e t ] unfoldToRoseForest : : forall a e t. Ord t = > ( a - > ( [ ( a , e ) ] , t , [ ( a , e ) ] ) ) - > a - > RoseForest e t unfoldToRoseForest unfoldFn seed = unfoldFromRoots roots where roots : : [ a ] roots = findRootsFrom seed ` evalState ` mempty isRoot : : a - > [ b ] - > Maybe a isRoot start pars = if null pars then Just start else Nothing -- To do : use hashmaps instead of set addRoot : : a - > State ( Set t ) ( Maybe a ) addRoot start = do let ( pars , , children ) = unfoldFn start seenNodes < - get put ( val ` S.insert ` seenNodes ) pure $ if val ` S.member ` seenNodes then Nothing else isRoot start pars : : a - > State ( Set t ) [ a ] findRootsFrom start = do let ( pars , , children ) = unfoldFn start let otherNodes = fst < $ > pars < > children startRoot < - addRoot start let otherRootNodes : : State ( Set t ) [ a ] otherRootNodes = < $ > traverse addRoot otherNodes case startRoot of Nothing - > otherRootNodes Just r - > ( r :) < $ > otherRootNodes unfoldFromRoots : : [ a ] - > RoseForest e t unfoldFromRoots = : : a - > RoseTree e t unfoldFromRoot root = let ( pars , , children ) = unfoldFn root subtrees = first unfoldFromRoot < $ > children parVals = first ( view _ 2 . unfoldFn ) < $ > pars in RoseTree { root = val , = ( subtrees , parVals ) } -- | -- This function will convert a rose tree into a binary tree which we then convert to our internal format . normaliseRoseTree : : RoseTree e t normaliseRoseTree = undefined fromRoseTree : : Graph Identity ( ) e t t fromRoseTree = undefined unfoldToRoseForest :: forall a e t. Ord t => (a -> ([(a,e)], t, [(a,e)])) -> a -> RoseForest e t unfoldToRoseForest unfoldFn seed = unfoldFromRoots roots where roots :: [a] roots = findRootsFrom seed `evalState` mempty isRoot :: a -> [b] -> Maybe a isRoot start pars = if null pars then Just start else Nothing -- To do: use hashmaps instead of set addRoot :: a -> State (Set t) (Maybe a) addRoot start = do let (pars, val, children) = unfoldFn start seenNodes <- get put (val `S.insert` seenNodes) pure $ if val `S.member` seenNodes then Nothing else isRoot start pars findRootsFrom :: a -> State (Set t) [a] findRootsFrom start = do let (pars, val, children) = unfoldFn start let otherNodes = fst <$> pars <> children startRoot <- addRoot start let otherRootNodes :: State (Set t) [a] otherRootNodes = catMaybes <$> traverse addRoot otherNodes case startRoot of Nothing -> otherRootNodes Just r -> (r :) <$> otherRootNodes unfoldFromRoots :: [a] -> RoseForest e t unfoldFromRoots = fmap unfoldFromRoot unfoldFromRoot :: a -> RoseTree e t unfoldFromRoot root = let (pars, val, children) = unfoldFn root subtrees = first unfoldFromRoot <$> children parVals = first (view _2 . unfoldFn) <$> pars in RoseTree { root = val , subForest = (subtrees, parVals) } -- | -- This function will convert a rose tree into a binary tree which we then convert to our internal format. normaliseRoseTree :: RoseTree e t -> RoseTree e t normaliseRoseTree = undefined fromRoseTree :: RoseTree e t -> Graph Identity () e t t fromRoseTree = undefined -} -- | -- This function is intended as a way to convert from unstructured -- external tree formats to our *internal* phylogenetic binary networks. -- It is not intended to be used for internal logic. unfoldGraph ( Eq a , Show a , Monoid e ) = > (a -> ([(a,e)], t, [(a,e)])) -> a -> Graph Identity () e t t unfoldGraph _unfoldFn _seed = undefined where go : : a - > GraphBuilder Identity e t t - > GraphBuilder Identity e t t go a ( GraphBuilder currTreeRefs currLeafRefs currNetRefs currRootRefs ) = case unfoldFn a of ( [ ] , t , [ ( par , e ) ] ) - > let newInd = undefined in undefined where go :: a -> GraphBuilder Identity e t t -> GraphBuilder Identity e t t go a (GraphBuilder currTreeRefs currLeafRefs currNetRefs currRootRefs) = case unfoldFn a of ([], t, [(par, e)]) -> let newInd = undefined in undefined -} β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ -- β”‚ Unsafe Indexing β”‚ -- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -- | Perform an unsafe indexing into the /leaf/ node vector . # INLINE unsafeLeafInd # unsafeLeafInd :: Graph f c e n t -> LeafInd -> LeafIndexData t unsafeLeafInd graph (LeafInd i) = graph ^. _leafReferences . singular (ix i) -- | Perform an unsafe indexing into the /root/ node vector . # INLINE unsafeRootInd # unsafeRootInd :: Graph f c e n t -> RootInd -> RootIndexData (f n) e unsafeRootInd graph (RootInd i) = graph ^. _rootReferences . singular (ix i) -- | -- Perform an unsafe indexing into the /network/ node vector. # INLINE unsafeNetworkInd # unsafeNetworkInd :: Graph f c e n t -> NetworkInd -> NetworkIndexData (f n) e unsafeNetworkInd graph (NetworkInd i) = graph ^. _networkReferences . singular (ix i) -- | -- Perform an unsafe indexing into the /tree/ node vector. # INLINE unsafeTreeInd # unsafeTreeInd :: Graph f c e n t -> TreeInd -> TreeIndexData (f n) e unsafeTreeInd graph (TreeInd i) = graph ^. _treeReferences . singular (ix i) β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ -- β”‚ Rendering β”‚ -- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ topologyRendering : : Graph f e c n t - > Text topologyRendering = undefined horizontalRendering : : _ horizontalRendering = undefined : : Graph f e c n t - > Text referenceRendering = undefined toBinaryRenderingTree : : ( n - > String ) - > Graph f e c n t - > NonEmpty = undefined topologyRendering :: Graph f e c n t -> Text topologyRendering = undefined horizontalRendering :: _ horizontalRendering = undefined referenceRendering :: Graph f e c n t -> Text referenceRendering = undefined toBinaryRenderingTree :: (n -> String) -> Graph f e c n t -> NonEmpty BinaryRenderingTree toBinaryRenderingTree = undefined -}
null
https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/graph/src/Data/Graph/Type.hs
haskell
---------------------------------------------------------------------------- | Module : Data.Graph.Type License : BSD-style Maintainer : Stability : provisional Portability : portable --------------------------------------------------------------------------- # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # import qualified Data.Set as S β”‚ Types β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ | the following constraints on the construction of nodes: - In-degree = 0 β‡’ Out-degree ∈ {1,2} | Builder type designed to improve the asymptotics of incrementally building a complete graph object. | A reference to a node index which is considered the traversal focus (root), in a re-rooting traversal. | The result of a re-rooting traversal, noting the node index which was considered the traversal focus (root), and the resulting rerooted 'Graph'. | A 'Lens' for the 'cachedData' field. | A 'Lens' for the 'leafReferences' field. | A 'Lens' for the 'networkReferences' field. | A 'Lens' for the 'rootReferences' field. | A 'Lens' for the 'treeReferences' field. β”‚ Instances β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ instance Show (Graph f c e n t) where | The 'GraphBuilder' has better asymptotics for combining graphs, but poor performance for 'Graph' manipulation and queries. The 'Graph' type supports efficient queries and graph manipulation, but is not efficient at combining. | This makes a list of graphs along with the roots to focus upon. β”‚ Utility β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ | Index the graph, retrieving the node data at the specified index. | Get the indices of all root nodes within the graph. To do : use hashmaps instead of set | This function will convert a rose tree into a binary tree which we then convert to our internal format . To do: use hashmaps instead of set | This function will convert a rose tree into a binary tree which we then convert to our internal format. | This function is intended as a way to convert from unstructured external tree formats to our *internal* phylogenetic binary networks. It is not intended to be used for internal logic. β”‚ Unsafe Indexing β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ | | | Perform an unsafe indexing into the /network/ node vector. | Perform an unsafe indexing into the /tree/ node vector. β”‚ Rendering β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Copyright : ( c ) 2015 - 2021 Ward Wheeler # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # module Data.Graph.Type ( Graph(..) , GraphBuilder(..) , HasTreeReferences(..) , HasNetworkReferences(..) , HasRootReferences(..) , HasLeafReferences(..) , HasCachedData(..) , RootFocusGraph , Focus , makeRootFocusGraphs , buildGraph , index , getRootInds , unfoldGraph , unsafeLeafInd , unsafeRootInd , unsafeTreeInd , unsafeNetworkInd ) where import Control . Arrow ( first ) import Control.Lens.Combinators (Bifunctor(..), Identity, ix, lens, singular, view) import Control.Lens.Operators ((^.)) import Control.Lens.Type (Lens, Lens') import Control . Monad . State . Strict import Data.Graph.Indices import Data.Graph.NodeContext import Data.Kind (Type) import Data . Maybe ( ) import Data.Pair.Strict import Data . Set ( Set ) import Data.Vector (Vector, generate) import Data.Vector.Instances () import Test.QuickCheck.Arbitrary import TextShow hiding (Builder) import VectorBuilder.Builder import VectorBuilder.Vector β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ data GraphShape i n r t = GraphShape { leafData : : Vector t , treeData : : Vector i , networkData : : Vector n , rootData : : Vector r } data GraphShape i n r t = GraphShape { leafData :: Vector t , treeData :: Vector i , networkData :: Vector n , rootData :: Vector r } -} A specialized representation of a Directed , Acyclic Graph ( DAG ) which has - In - degree ≀ 2 - Out - degree ≀ 2 - Degree ≀ 3 - Out - degree = 0 β‡’ in - degree = 1 - In - degree = 2 β‡’ Out - degree 1 data Graph (f :: Type -> Type) (c :: Type) (e :: Type) (n :: Type) (t :: Type) = Graph { leafReferences :: Vector (LeafIndexData t ) , treeReferences :: Vector (TreeIndexData (f n) e) , networkReferences :: Vector (NetworkIndexData (f n) e) , rootReferences :: Vector (RootIndexData (f n) e) , cachedData :: c } deriving stock Show data GraphBuilder (f :: Type -> Type) (e :: Type) (n :: Type) (t :: Type) = GraphBuilder { leafReferencesBuilder :: Builder (LeafIndexData t ) , treeReferencesBuilder :: Builder (TreeIndexData (f n) e) , networkReferencesBuilder :: Builder (NetworkIndexData (f n) e) , rootReferencesBuilder :: Builder (RootIndexData (f n) e) } type Focus = Pair IndexType UntaggedIndex type RootFocusGraph f c e n t = Pair Focus (Graph f c e n t) class HasCachedData s t a b | s -> a, t -> b, s b -> t, t a -> b where _cachedData :: Lens s t a b class HasLeafReferences s t a b | s -> a, t -> b, s b -> t, t a -> s where _leafReferences :: Lens s t a b class HasNetworkReferences s a | s -> a where _networkReferences :: Lens' s a class HasRootReferences s a | s -> a where _rootReferences :: Lens' s a class HasTreeReferences s a | s -> a where _treeReferences :: Lens' s a β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ instance Arbitrary (Graph f c e n t) where arbitrary = pure undefined instance Functor f => Bifunctor (Graph f c e) where bimap f g graph@Graph{..} = graph { leafReferences = (fmap . fmap $ g) leafReferences , treeReferences = (fmap . fmap . fmap $ f) treeReferences , networkReferences = (fmap . fmap . fmap $ f) networkReferences , rootReferences = (fmap . fmap . fmap $ f) rootReferences } instance HasCachedData (Graph f c1 e n t) (Graph f c2 e n t) c1 c2 where _cachedData = lens cachedData (\g c2 -> g {cachedData = c2}) instance HasLeafReferences (Graph f c e n t) (Graph f c e n t') (Vector (IndexData LeafContext t)) (Vector (IndexData LeafContext t')) where _leafReferences = lens leafReferences (\g l -> g { leafReferences = l}) instance HasNetworkReferences (Graph f c e n t) (Vector (IndexData (NetworkContext e) (f n))) where _networkReferences = lens networkReferences (\g fn -> g {networkReferences = fn}) instance HasRootReferences (Graph f c e n t) (Vector (IndexData (RootContext e) (f n))) where _rootReferences = lens rootReferences (\g fn -> g {rootReferences = fn}) instance HasTreeReferences (Graph f c e n t) (Vector (IndexData (TreeContext e) (f n))) where _treeReferences = lens treeReferences (\g fn -> g {treeReferences = fn}) show = toString . instance TextShow (Graph f c e n t) where showb = undefined Finalize a ' GraphBuilder ' into a ' Graph ' . buildGraph :: GraphBuilder f e n t -> c -> Graph f c e n t buildGraph GraphBuilder{..} cachedData = let leafReferences = build leafReferencesBuilder treeReferences = build treeReferencesBuilder networkReferences = build networkReferencesBuilder rootReferences = build rootReferencesBuilder in Graph{..} makeRootFocusGraphs :: Graph f c e n t -> [RootFocusGraph f c e n t] makeRootFocusGraphs graph = let rootLength = length (view _rootReferences graph) rootNames :: [Focus] rootNames = let rootInds = case rootLength of 0 -> [] 1 -> [0] n -> [0..(n - 1)] in Pair RootTag <$> rootInds in (:!: graph) <$> rootNames β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ index :: Tagged taggedInd => Graph f c e n t -> taggedInd -> NodeIndexData (f n) e t index graph taggedIndex = let ind = getIndex taggedIndex in case getTag taggedIndex of LeafTag -> LeafNodeIndexData $ graph ^. _leafReferences . singular (ix ind) TreeTag -> TreeNodeIndexData $ graph ^. _treeReferences . singular (ix ind) NetworkTag -> NetworkNodeIndexData $ graph ^. _networkReferences . singular (ix ind) RootTag -> RootNodeIndexData $ graph ^. _rootReferences . singular (ix ind) getRootInds :: Graph f c e n t -> Vector TaggedIndex getRootInds graph = let numberOfRoots = length (view _rootReferences graph) roots = generate numberOfRoots (`TaggedIndex` RootTag) in roots size : : Builder a - > Int size = length . build @Vector size :: Builder a -> Int size = length . build @Vector -} data RoseTree e t = { root : : t , : : ( [ ( RoseTree e t , e ) ] , [ ( t , e ) ] ) } data RoseTree e t = RoseTree { root :: t , subForest :: ([(RoseTree e t, e)], [(t, e)]) } -} type RoseForest e t = [ RoseTree e t ] unfoldToRoseForest : : forall a e t. Ord t = > ( a - > ( [ ( a , e ) ] , t , [ ( a , e ) ] ) ) - > a - > RoseForest e t unfoldToRoseForest unfoldFn seed = unfoldFromRoots roots where roots : : [ a ] roots = findRootsFrom seed ` evalState ` mempty isRoot : : a - > [ b ] - > Maybe a isRoot start pars = if null pars then Just start else Nothing addRoot : : a - > State ( Set t ) ( Maybe a ) addRoot start = do let ( pars , , children ) = unfoldFn start seenNodes < - get put ( val ` S.insert ` seenNodes ) pure $ if val ` S.member ` seenNodes then Nothing else isRoot start pars : : a - > State ( Set t ) [ a ] findRootsFrom start = do let ( pars , , children ) = unfoldFn start let otherNodes = fst < $ > pars < > children startRoot < - addRoot start let otherRootNodes : : State ( Set t ) [ a ] otherRootNodes = < $ > traverse addRoot otherNodes case startRoot of Nothing - > otherRootNodes Just r - > ( r :) < $ > otherRootNodes unfoldFromRoots : : [ a ] - > RoseForest e t unfoldFromRoots = : : a - > RoseTree e t unfoldFromRoot root = let ( pars , , children ) = unfoldFn root subtrees = first unfoldFromRoot < $ > children parVals = first ( view _ 2 . unfoldFn ) < $ > pars in RoseTree { root = val , = ( subtrees , parVals ) } normaliseRoseTree : : RoseTree e t normaliseRoseTree = undefined fromRoseTree : : Graph Identity ( ) e t t fromRoseTree = undefined unfoldToRoseForest :: forall a e t. Ord t => (a -> ([(a,e)], t, [(a,e)])) -> a -> RoseForest e t unfoldToRoseForest unfoldFn seed = unfoldFromRoots roots where roots :: [a] roots = findRootsFrom seed `evalState` mempty isRoot :: a -> [b] -> Maybe a isRoot start pars = if null pars then Just start else Nothing addRoot :: a -> State (Set t) (Maybe a) addRoot start = do let (pars, val, children) = unfoldFn start seenNodes <- get put (val `S.insert` seenNodes) pure $ if val `S.member` seenNodes then Nothing else isRoot start pars findRootsFrom :: a -> State (Set t) [a] findRootsFrom start = do let (pars, val, children) = unfoldFn start let otherNodes = fst <$> pars <> children startRoot <- addRoot start let otherRootNodes :: State (Set t) [a] otherRootNodes = catMaybes <$> traverse addRoot otherNodes case startRoot of Nothing -> otherRootNodes Just r -> (r :) <$> otherRootNodes unfoldFromRoots :: [a] -> RoseForest e t unfoldFromRoots = fmap unfoldFromRoot unfoldFromRoot :: a -> RoseTree e t unfoldFromRoot root = let (pars, val, children) = unfoldFn root subtrees = first unfoldFromRoot <$> children parVals = first (view _2 . unfoldFn) <$> pars in RoseTree { root = val , subForest = (subtrees, parVals) } normaliseRoseTree :: RoseTree e t -> RoseTree e t normaliseRoseTree = undefined fromRoseTree :: RoseTree e t -> Graph Identity () e t t fromRoseTree = undefined -} unfoldGraph ( Eq a , Show a , Monoid e ) = > (a -> ([(a,e)], t, [(a,e)])) -> a -> Graph Identity () e t t unfoldGraph _unfoldFn _seed = undefined where go : : a - > GraphBuilder Identity e t t - > GraphBuilder Identity e t t go a ( GraphBuilder currTreeRefs currLeafRefs currNetRefs currRootRefs ) = case unfoldFn a of ( [ ] , t , [ ( par , e ) ] ) - > let newInd = undefined in undefined where go :: a -> GraphBuilder Identity e t t -> GraphBuilder Identity e t t go a (GraphBuilder currTreeRefs currLeafRefs currNetRefs currRootRefs) = case unfoldFn a of ([], t, [(par, e)]) -> let newInd = undefined in undefined -} β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ Perform an unsafe indexing into the /leaf/ node vector . # INLINE unsafeLeafInd # unsafeLeafInd :: Graph f c e n t -> LeafInd -> LeafIndexData t unsafeLeafInd graph (LeafInd i) = graph ^. _leafReferences . singular (ix i) Perform an unsafe indexing into the /root/ node vector . # INLINE unsafeRootInd # unsafeRootInd :: Graph f c e n t -> RootInd -> RootIndexData (f n) e unsafeRootInd graph (RootInd i) = graph ^. _rootReferences . singular (ix i) # INLINE unsafeNetworkInd # unsafeNetworkInd :: Graph f c e n t -> NetworkInd -> NetworkIndexData (f n) e unsafeNetworkInd graph (NetworkInd i) = graph ^. _networkReferences . singular (ix i) # INLINE unsafeTreeInd # unsafeTreeInd :: Graph f c e n t -> TreeInd -> TreeIndexData (f n) e unsafeTreeInd graph (TreeInd i) = graph ^. _treeReferences . singular (ix i) β”Œ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ topologyRendering : : Graph f e c n t - > Text topologyRendering = undefined horizontalRendering : : _ horizontalRendering = undefined : : Graph f e c n t - > Text referenceRendering = undefined toBinaryRenderingTree : : ( n - > String ) - > Graph f e c n t - > NonEmpty = undefined topologyRendering :: Graph f e c n t -> Text topologyRendering = undefined horizontalRendering :: _ horizontalRendering = undefined referenceRendering :: Graph f e c n t -> Text referenceRendering = undefined toBinaryRenderingTree :: (n -> String) -> Graph f e c n t -> NonEmpty BinaryRenderingTree toBinaryRenderingTree = undefined -}
e154e278a33a6b7e00e309beca75b2a64a6beb26e93277b70458a0b8837987e4
thattommyhall/offline-4clojure
p10.clj
;; Intro to Maps - Elementary ;; Maps store key-value pairs. Both maps and keywords can be used as lookup functions. Commas can be used to make maps more readable, but they are not required. ;; tags - ;; restricted - (ns offline-4clojure.p10 (:use clojure.test)) (def __ ;; your solution here ) (defn -main [] (are [soln] soln (= __ ((hash-map :a 10, :b 20, :c 30) :b)) (= __ (:b {:a 10, :b 20, :c 30})) ))
null
https://raw.githubusercontent.com/thattommyhall/offline-4clojure/73e32fc6687816aea3c514767cef3916176589ab/src/offline_4clojure/p10.clj
clojure
Intro to Maps - Elementary Maps store key-value pairs. Both maps and keywords can be used as lookup functions. Commas can be used to make maps more readable, but they are not required. tags - restricted - your solution here
(ns offline-4clojure.p10 (:use clojure.test)) (def __ ) (defn -main [] (are [soln] soln (= __ ((hash-map :a 10, :b 20, :c 30) :b)) (= __ (:b {:a 10, :b 20, :c 30})) ))
1daff26c92fed8fe2e1758946c016f8657de33bcb6324aa30e24b0fef133df55
kronkltd/jiksnu
helpers_test.clj
(ns jiksnu.modules.web.helpers-test (:require [jiksnu.modules.web.helpers :as helpers] [jiksnu.test-helper :as th] [midje.sweet :refer :all]) (:import org.apache.http.HttpStatus)) (facts "#'jiksnu.modules.web.helpers/serve-template" (fact "when the template exists" (let [template-name "index-activities" request {:params {:* template-name}}] (helpers/serve-template request) => (contains {:status HttpStatus/SC_OK}))) (fact "when the template does not exist" (let [template-name "zzyzx" request {:params {:* template-name}}] (helpers/serve-template request) => (contains {:status HttpStatus/SC_NOT_FOUND}))))
null
https://raw.githubusercontent.com/kronkltd/jiksnu/8c91e9b1fddcc0224b028e573f7c3ca2f227e516/test/jiksnu/modules/web/helpers_test.clj
clojure
(ns jiksnu.modules.web.helpers-test (:require [jiksnu.modules.web.helpers :as helpers] [jiksnu.test-helper :as th] [midje.sweet :refer :all]) (:import org.apache.http.HttpStatus)) (facts "#'jiksnu.modules.web.helpers/serve-template" (fact "when the template exists" (let [template-name "index-activities" request {:params {:* template-name}}] (helpers/serve-template request) => (contains {:status HttpStatus/SC_OK}))) (fact "when the template does not exist" (let [template-name "zzyzx" request {:params {:* template-name}}] (helpers/serve-template request) => (contains {:status HttpStatus/SC_NOT_FOUND}))))
417b21dc4cab6f5b48b37926781e7a0a59f281a18141ab1656357b8961d901d9
synsem/texhs
Catcode.hs
---------------------------------------------------------------------- -- | Module : Text . . Catcode Copyright : 2015 - 2017 , 2015 - 2016 Language Science Press . -- License : GPL-3 -- -- Maintainer : -- Stability : experimental Portability : GHC -- Types and utility functions for TeX catcodes and catcode tables . ---------------------------------------------------------------------- module Text.TeX.Lexer.Catcode ( -- * Catcodes Catcode(..) , showCatcodePP * Catcode groups , catcodesAllowed , catcodesNonescaped , catcodesPassive * Catcode tables , CatcodeTable , defaultCatcodeTable * * Catcode table lookup ( read ) , catcodeOf , defaultCatcodeOf , quoteCatcodeOf , hasCatcode * * Catcode table modifications ( write ) , updateCatcodeTable ) where import Data.Char (isAlpha, isSpace) import Data.Maybe (fromMaybe) -- | TeX catcodes. The @Enum@ instance respects the canonical mapping -- of catcodes to the integers 0-15. data Catcode = Escape | Bgroup | Egroup | Mathshift | AlignTab | Eol | ParamPrefix | Supscript | Subscript | Ignored | Space | Letter | Other | Active | Comment | Invalid deriving (Eq, Ord, Enum) instance Show Catcode where show = show . fromEnum -- | Show the name of a category code, mostly as reported by 's @\\meaning@. See TeX82 , Β§ 298 . showCatcodePP :: Catcode -> String showCatcodePP Escape = "escape character" showCatcodePP Bgroup = "begin-group character" showCatcodePP Egroup = "end-group character" showCatcodePP Mathshift = "math shift character" showCatcodePP AlignTab = "alignment tab character" showCatcodePP Eol = "end of line character" showCatcodePP ParamPrefix = "macro parameter character" showCatcodePP Supscript = "superscript character" showCatcodePP Subscript = "subscript character" showCatcodePP Ignored = "ignored character" showCatcodePP Space = "space character" showCatcodePP Letter = "the letter" showCatcodePP Other = "the character" showCatcodePP Active = "active character" showCatcodePP Comment = "comment character" showCatcodePP Invalid = "invalid character" -- | A catcode table is a (typically partial) assignment of catcodes to characters . If a character has no entry in this table , its catcode is determined as follows : If it is a Unicode letter , it has catcode ' Letter ' ; otherwise it has catcode ' Other ' . See ' catcodeOf ' . type CatcodeTable = [(Char, Catcode)] | The default catcode table setup by plain and LaTeX. defaultCatcodeTable :: CatcodeTable defaultCatcodeTable = [ ('\\', Escape) , ('{', Bgroup) , ('}', Egroup) , ('$', Mathshift) , ('&', AlignTab) , ('\n', Eol) , ('#', ParamPrefix) , ('^', Supscript) , ('_', Subscript) , ('\0', Ignored) , (' ', Space) , ('\t', Space) , ('~', Active) , ('%', Comment) , ('\DEL', Invalid) ] -------- Catcode groups | /Allowed/ catcodes are all catcodes except those ignored by , namely ' Ignored ' and ' Invalid ' . catcodesAllowed :: [Catcode] catcodesAllowed = Escape : catcodesNonescaped -- | /Non-escaped/ catcodes are all /allowed/ catcodes except 'Escape'. catcodesNonescaped :: [Catcode] catcodesNonescaped = catcodesPassive ++ [Bgroup, Egroup, Eol, ParamPrefix, Space, Active, Comment] -- | /Passive/ catcodes are catcodes that are treated as literal characters -- by the lexer. These are all catcodes except: -- ( 1 ) those that have dedicated parsers in " Text . TeX.Lexer " ( ' Escape ' , ' Bgroup ' , ' ' , ' Eol ' , ' ' , -- 'Space', 'Active', 'Comment'), and -- ( 2 ) those that are ignored by TeX ( ' Ignored ' , ' Invalid ' ) . catcodesPassive :: [Catcode] catcodesPassive = [Letter, Other, Mathshift, AlignTab, Supscript, Subscript] -------- Catcode table lookup ( read ) | Lookup the catcode for the character relative to catcode table If @ch@ is not listed in @t@ , Unicode letters default to catcode ' Letter ' , all other characters default to catcode ' Other ' . catcodeOf :: Char -> CatcodeTable -> Catcode catcodeOf ch t = fromMaybe (if isAlpha ch then Letter else Other) (lookup ch t) -- | Lookup the default catcode for a character, -- using 'defaultCatcodeTable'. defaultCatcodeOf :: Char -> Catcode defaultCatcodeOf = flip catcodeOf defaultCatcodeTable -- | Lookup the default quoting catcode for a character: -- letters are treated are 'Letter' tokens, -- whitespace characters as 'Space' tokens (no 'Eol') and -- all other characters as 'Other' tokens. quoteCatcodeOf :: Char -> Catcode quoteCatcodeOf ch | isAlpha ch = Letter | isSpace ch = Space | otherwise = Other | Test whether character has catcode @cc@ relative to catcode table hasCatcode :: Catcode -> CatcodeTable -> Char -> Bool hasCatcode cc t ch = catcodeOf ch t == cc -------- Catcode table modifications ( write ) | Add a @(Char , Catcode)@ mapping to a ' CatcodeTable ' . updateCatcodeTable :: (Char, Catcode) -> CatcodeTable -> CatcodeTable updateCatcodeTable = (:)
null
https://raw.githubusercontent.com/synsem/texhs/9e2dce4ec8ae0b2c024e1883d9a93bab15f9a86f/src/Text/TeX/Lexer/Catcode.hs
haskell
-------------------------------------------------------------------- | License : GPL-3 Maintainer : Stability : experimental -------------------------------------------------------------------- * Catcodes | TeX catcodes. The @Enum@ instance respects the canonical mapping of catcodes to the integers 0-15. | Show the name of a category code, | A catcode table is a (typically partial) assignment of catcodes to ------ Catcode groups | /Non-escaped/ catcodes are all /allowed/ catcodes except 'Escape'. | /Passive/ catcodes are catcodes that are treated as literal characters by the lexer. These are all catcodes except: 'Space', 'Active', 'Comment'), and ------ Catcode table lookup ( read ) | Lookup the default catcode for a character, using 'defaultCatcodeTable'. | Lookup the default quoting catcode for a character: letters are treated are 'Letter' tokens, whitespace characters as 'Space' tokens (no 'Eol') and all other characters as 'Other' tokens. ------ Catcode table modifications ( write )
Module : Text . . Catcode Copyright : 2015 - 2017 , 2015 - 2016 Language Science Press . Portability : GHC Types and utility functions for TeX catcodes and catcode tables . module Text.TeX.Lexer.Catcode Catcode(..) , showCatcodePP * Catcode groups , catcodesAllowed , catcodesNonescaped , catcodesPassive * Catcode tables , CatcodeTable , defaultCatcodeTable * * Catcode table lookup ( read ) , catcodeOf , defaultCatcodeOf , quoteCatcodeOf , hasCatcode * * Catcode table modifications ( write ) , updateCatcodeTable ) where import Data.Char (isAlpha, isSpace) import Data.Maybe (fromMaybe) data Catcode = Escape | Bgroup | Egroup | Mathshift | AlignTab | Eol | ParamPrefix | Supscript | Subscript | Ignored | Space | Letter | Other | Active | Comment | Invalid deriving (Eq, Ord, Enum) instance Show Catcode where show = show . fromEnum mostly as reported by 's @\\meaning@. See TeX82 , Β§ 298 . showCatcodePP :: Catcode -> String showCatcodePP Escape = "escape character" showCatcodePP Bgroup = "begin-group character" showCatcodePP Egroup = "end-group character" showCatcodePP Mathshift = "math shift character" showCatcodePP AlignTab = "alignment tab character" showCatcodePP Eol = "end of line character" showCatcodePP ParamPrefix = "macro parameter character" showCatcodePP Supscript = "superscript character" showCatcodePP Subscript = "subscript character" showCatcodePP Ignored = "ignored character" showCatcodePP Space = "space character" showCatcodePP Letter = "the letter" showCatcodePP Other = "the character" showCatcodePP Active = "active character" showCatcodePP Comment = "comment character" showCatcodePP Invalid = "invalid character" characters . If a character has no entry in this table , its catcode is determined as follows : If it is a Unicode letter , it has catcode ' Letter ' ; otherwise it has catcode ' Other ' . See ' catcodeOf ' . type CatcodeTable = [(Char, Catcode)] | The default catcode table setup by plain and LaTeX. defaultCatcodeTable :: CatcodeTable defaultCatcodeTable = [ ('\\', Escape) , ('{', Bgroup) , ('}', Egroup) , ('$', Mathshift) , ('&', AlignTab) , ('\n', Eol) , ('#', ParamPrefix) , ('^', Supscript) , ('_', Subscript) , ('\0', Ignored) , (' ', Space) , ('\t', Space) , ('~', Active) , ('%', Comment) , ('\DEL', Invalid) ] | /Allowed/ catcodes are all catcodes except those ignored by , namely ' Ignored ' and ' Invalid ' . catcodesAllowed :: [Catcode] catcodesAllowed = Escape : catcodesNonescaped catcodesNonescaped :: [Catcode] catcodesNonescaped = catcodesPassive ++ [Bgroup, Egroup, Eol, ParamPrefix, Space, Active, Comment] ( 1 ) those that have dedicated parsers in " Text . TeX.Lexer " ( ' Escape ' , ' Bgroup ' , ' ' , ' Eol ' , ' ' , ( 2 ) those that are ignored by TeX ( ' Ignored ' , ' Invalid ' ) . catcodesPassive :: [Catcode] catcodesPassive = [Letter, Other, Mathshift, AlignTab, Supscript, Subscript] | Lookup the catcode for the character relative to catcode table If @ch@ is not listed in @t@ , Unicode letters default to catcode ' Letter ' , all other characters default to catcode ' Other ' . catcodeOf :: Char -> CatcodeTable -> Catcode catcodeOf ch t = fromMaybe (if isAlpha ch then Letter else Other) (lookup ch t) defaultCatcodeOf :: Char -> Catcode defaultCatcodeOf = flip catcodeOf defaultCatcodeTable quoteCatcodeOf :: Char -> Catcode quoteCatcodeOf ch | isAlpha ch = Letter | isSpace ch = Space | otherwise = Other | Test whether character has catcode @cc@ relative to catcode table hasCatcode :: Catcode -> CatcodeTable -> Char -> Bool hasCatcode cc t ch = catcodeOf ch t == cc | Add a @(Char , Catcode)@ mapping to a ' CatcodeTable ' . updateCatcodeTable :: (Char, Catcode) -> CatcodeTable -> CatcodeTable updateCatcodeTable = (:)
d3b22d93737b0bb9f1ef243ede58ad49141095ed0c2cdd73a1bb8bcbe84f74be
BillHallahan/G2
PolyTypes.hs
module PolyTypes where polyFst :: a -> b -> a polyFst a b = a typedFst :: Int -> Double -> Int typedFst a b = polyFst a b
null
https://raw.githubusercontent.com/BillHallahan/G2/dfd377793dcccdc7126a9f4a65b58249673e8a70/tests/TestFiles/PolyTypes.hs
haskell
module PolyTypes where polyFst :: a -> b -> a polyFst a b = a typedFst :: Int -> Double -> Int typedFst a b = polyFst a b
eda60559f50f842eee286d47525ba89ac5d02c0037aaeec3f9faf2d4abe94dfe
rainyt/ocaml-haxe
return_demo.ml
exception BOOL of bool;; exception STRING of string;; exception INT of int;; exception FLOAT of float;; let getString () = try let i = ref 0 in let break = ref true in while (!break && true) do i := !i + 1; (* EIf *) if (!i = 10) then ignore (raise (STRING ("123123(" ^ (string_of_int !i) ^ ")"))) ; (* EIf *) if (!i = 8) then ignore (raise (STRING ("123123(" ^ (string_of_int !i) ^ ")"))) ; break := false; done; "123" with STRING ret -> ret;; let getParam () = try while true do ignore(raise (BOOL false)); done; true; with BOOL r -> r ;; let getParam_return () = try getParam() with BOOL r -> r;; let () = let i = ref 0 in while !i < 10 do i := !i + 1; Printf.printf "%i %b" !i (getParam ()); done; ;;
null
https://raw.githubusercontent.com/rainyt/ocaml-haxe/2861a572b9171d45c3f0f40b19c538cbf9f7bfec/ocaml_ml_demo/return_demo.ml
ocaml
EIf EIf
exception BOOL of bool;; exception STRING of string;; exception INT of int;; exception FLOAT of float;; let getString () = try let i = ref 0 in let break = ref true in while (!break && true) do i := !i + 1; if (!i = 10) then ignore (raise (STRING ("123123(" ^ (string_of_int !i) ^ ")"))) ; if (!i = 8) then ignore (raise (STRING ("123123(" ^ (string_of_int !i) ^ ")"))) ; break := false; done; "123" with STRING ret -> ret;; let getParam () = try while true do ignore(raise (BOOL false)); done; true; with BOOL r -> r ;; let getParam_return () = try getParam() with BOOL r -> r;; let () = let i = ref 0 in while !i < 10 do i := !i + 1; Printf.printf "%i %b" !i (getParam ()); done; ;;
80c1bafd8061c588b21452935993ea4fba873c1233ff2a75e17212097b0fe4ff
spwhitton/anaphora
early.lisp
-*- Mode : Lisp ; Base : 10 ; Syntax : ANSI - Common - Lisp ; Package : ANAPHORA -*- Anaphora : The Anaphoric Macro Package from Hell ;;;; ;;;; This been placed in Public Domain by the author, Nikodemus Siivola < > (in-package :anaphora) (defmacro with-unique-names ((&rest bindings) &body body) `(let ,(mapcar #'(lambda (binding) (destructuring-bind (var prefix) (if (consp binding) binding (list binding binding)) `(,var (gensym ,(string prefix))))) bindings) ,@body)) (defmacro ignore-first (first expr) (declare (ignore first)) expr)
null
https://raw.githubusercontent.com/spwhitton/anaphora/71964047c83cdd734bae9b318b597177f1c00665/early.lisp
lisp
Base : 10 ; Syntax : ANSI - Common - Lisp ; Package : ANAPHORA -*- This been placed in Public Domain by the author,
Anaphora : The Anaphoric Macro Package from Hell Nikodemus Siivola < > (in-package :anaphora) (defmacro with-unique-names ((&rest bindings) &body body) `(let ,(mapcar #'(lambda (binding) (destructuring-bind (var prefix) (if (consp binding) binding (list binding binding)) `(,var (gensym ,(string prefix))))) bindings) ,@body)) (defmacro ignore-first (first expr) (declare (ignore first)) expr)
173899a318afdb3f44c06f9c6c4e4b0761a61d2345e5bb68c502c422931439a3
korya/efuns
env.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : env.mli , v 1.1 2000/08/30 13:02:44 lefessan Exp $ (* Environment handling *) open Types type t val empty: t val initial: t (* Lookup by paths *) val find_value: Path.t -> t -> value_description val find_type: Path.t -> t -> type_declaration val find_module: Path.t -> t -> module_type val find_modtype: Path.t -> t -> modtype_declaration val find_class: Path.t -> t -> class_declaration val find_cltype: Path.t -> t -> cltype_declaration val find_type_expansion: Path.t -> t -> type_expr list * type_expr val find_modtype_expansion: Path.t -> t -> Types.module_type (* Lookup by long identifiers *) val lookup_value: Longident.t -> t -> Path.t * value_description val lookup_constructor: Longident.t -> t -> constructor_description val lookup_label: Longident.t -> t -> label_description val lookup_type: Longident.t -> t -> Path.t * type_declaration val lookup_module: Longident.t -> t -> Path.t * module_type val lookup_modtype: Longident.t -> t -> Path.t * modtype_declaration val lookup_class: Longident.t -> t -> Path.t * class_declaration val lookup_cltype: Longident.t -> t -> Path.t * cltype_declaration (* Insertion by identifier *) val add_value: Ident.t -> value_description -> t -> t val add_type: Ident.t -> type_declaration -> t -> t val add_exception: Ident.t -> exception_declaration -> t -> t val add_module: Ident.t -> module_type -> t -> t val add_modtype: Ident.t -> modtype_declaration -> t -> t val add_class: Ident.t -> class_declaration -> t -> t val add_cltype: Ident.t -> cltype_declaration -> t -> t (* Insertion of all fields of a signature. *) val add_item: signature_item -> t -> t val add_signature: signature -> t -> t (* Insertion of all fields of a signature, relative to the given path. Used to implement open. *) val open_signature: Path.t -> signature -> t -> t val open_pers_signature: string -> t -> t (* Insertion by name *) val enter_value: string -> value_description -> t -> Ident.t * t val enter_type: string -> type_declaration -> t -> Ident.t * t val enter_exception: string -> exception_declaration -> t -> Ident.t * t val enter_module: string -> module_type -> t -> Ident.t * t val enter_modtype: string -> modtype_declaration -> t -> Ident.t * t val enter_class: string -> class_declaration -> t -> Ident.t * t val enter_cltype: string -> cltype_declaration -> t -> Ident.t * t (* Reset the cache of in-core module interfaces. To be called in particular when load_path changes. *) val reset_cache: unit -> unit (* Read, save a signature to/from a file *) val read_signature: string -> string -> signature (* Arguments: module name, file name. Results: signature. *) val save_signature: signature -> string -> string -> unit (* Arguments: signature, module name, file name. *) Return the CRC of the interface of the given compilation unit val crc_of_unit: string -> Digest.t Return the set of compilation units imported , with their CRC val imported_units: unit -> (string * Digest.t) list (* Summaries -- compact representation of an environment, to be exported in debugging information. *) type summary = Env_empty | Env_value of summary * Ident.t * value_description | Env_type of summary * Ident.t * type_declaration | Env_exception of summary * Ident.t * exception_declaration | Env_module of summary * Ident.t * module_type | Env_modtype of summary * Ident.t * modtype_declaration | Env_class of summary * Ident.t * class_declaration | Env_cltype of summary * Ident.t * cltype_declaration | Env_open of summary * Path.t val summary: t -> summary (* Error report *) type error = Not_an_interface of string | Corrupted_interface of string | Illegal_renaming of string * string | Inconsistent_import of string * string * string exception Error of error open Format val report_error: formatter -> error -> unit Forward declaration to break mutual recursion with . val check_modtype_inclusion: (t -> module_type -> module_type -> unit) ref
null
https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/ocamlsrc/compat/beta/include/env.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* Environment handling Lookup by paths Lookup by long identifiers Insertion by identifier Insertion of all fields of a signature. Insertion of all fields of a signature, relative to the given path. Used to implement open. Insertion by name Reset the cache of in-core module interfaces. To be called in particular when load_path changes. Read, save a signature to/from a file Arguments: module name, file name. Results: signature. Arguments: signature, module name, file name. Summaries -- compact representation of an environment, to be exported in debugging information. Error report
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : env.mli , v 1.1 2000/08/30 13:02:44 lefessan Exp $ open Types type t val empty: t val initial: t val find_value: Path.t -> t -> value_description val find_type: Path.t -> t -> type_declaration val find_module: Path.t -> t -> module_type val find_modtype: Path.t -> t -> modtype_declaration val find_class: Path.t -> t -> class_declaration val find_cltype: Path.t -> t -> cltype_declaration val find_type_expansion: Path.t -> t -> type_expr list * type_expr val find_modtype_expansion: Path.t -> t -> Types.module_type val lookup_value: Longident.t -> t -> Path.t * value_description val lookup_constructor: Longident.t -> t -> constructor_description val lookup_label: Longident.t -> t -> label_description val lookup_type: Longident.t -> t -> Path.t * type_declaration val lookup_module: Longident.t -> t -> Path.t * module_type val lookup_modtype: Longident.t -> t -> Path.t * modtype_declaration val lookup_class: Longident.t -> t -> Path.t * class_declaration val lookup_cltype: Longident.t -> t -> Path.t * cltype_declaration val add_value: Ident.t -> value_description -> t -> t val add_type: Ident.t -> type_declaration -> t -> t val add_exception: Ident.t -> exception_declaration -> t -> t val add_module: Ident.t -> module_type -> t -> t val add_modtype: Ident.t -> modtype_declaration -> t -> t val add_class: Ident.t -> class_declaration -> t -> t val add_cltype: Ident.t -> cltype_declaration -> t -> t val add_item: signature_item -> t -> t val add_signature: signature -> t -> t val open_signature: Path.t -> signature -> t -> t val open_pers_signature: string -> t -> t val enter_value: string -> value_description -> t -> Ident.t * t val enter_type: string -> type_declaration -> t -> Ident.t * t val enter_exception: string -> exception_declaration -> t -> Ident.t * t val enter_module: string -> module_type -> t -> Ident.t * t val enter_modtype: string -> modtype_declaration -> t -> Ident.t * t val enter_class: string -> class_declaration -> t -> Ident.t * t val enter_cltype: string -> cltype_declaration -> t -> Ident.t * t val reset_cache: unit -> unit val read_signature: string -> string -> signature val save_signature: signature -> string -> string -> unit Return the CRC of the interface of the given compilation unit val crc_of_unit: string -> Digest.t Return the set of compilation units imported , with their CRC val imported_units: unit -> (string * Digest.t) list type summary = Env_empty | Env_value of summary * Ident.t * value_description | Env_type of summary * Ident.t * type_declaration | Env_exception of summary * Ident.t * exception_declaration | Env_module of summary * Ident.t * module_type | Env_modtype of summary * Ident.t * modtype_declaration | Env_class of summary * Ident.t * class_declaration | Env_cltype of summary * Ident.t * cltype_declaration | Env_open of summary * Path.t val summary: t -> summary type error = Not_an_interface of string | Corrupted_interface of string | Illegal_renaming of string * string | Inconsistent_import of string * string * string exception Error of error open Format val report_error: formatter -> error -> unit Forward declaration to break mutual recursion with . val check_modtype_inclusion: (t -> module_type -> module_type -> unit) ref
230c8ee6f1f516748f673219460fd87f1f61fa695319d49e0885048ffe238cd8
pbrisbin/renters-reality
Completion.hs
module Handler.Completion ( getCompLandlordsR , getCompSearchesR ) where import Import import Helpers.Completion getCompLandlordsR :: Handler RepJson getCompLandlordsR = generalCompletion $ \t -> do landlords <- uniqueLandlords return $ filter (looseMatch t) landlords getCompSearchesR :: Handler RepJson getCompSearchesR = generalCompletion $ \t -> do landlords <- uniqueLandlords addrs <- uniqueAddresses return $ filter (looseMatch t) (landlords ++ addrs)
null
https://raw.githubusercontent.com/pbrisbin/renters-reality/2e20e4ab3f47a62d0bad75f49d5e6beee1d81648/Handler/Completion.hs
haskell
module Handler.Completion ( getCompLandlordsR , getCompSearchesR ) where import Import import Helpers.Completion getCompLandlordsR :: Handler RepJson getCompLandlordsR = generalCompletion $ \t -> do landlords <- uniqueLandlords return $ filter (looseMatch t) landlords getCompSearchesR :: Handler RepJson getCompSearchesR = generalCompletion $ \t -> do landlords <- uniqueLandlords addrs <- uniqueAddresses return $ filter (looseMatch t) (landlords ++ addrs)
263687dd72752abec4c4ac37d0de9119a34c6e990c1d501e5fc053efc5c9587e
liamoc/agda-snippets
Snippets.hs
# LANGUAGE ViewPatterns # module Agda.Contrib.Snippets ( renderAgdaSnippets , CSSClass , CommandLineOptions (..) , defaultOptions ) where import Control.Monad.Except import Control.Monad.State (get) import Data.Char import Data.Function import Data.List import Data.Maybe import qualified Data.Map as Map import qualified Data.IntMap as IMap import Network.URI import System.Exit (exitFailure) import Text.XHtml.Strict import Agda.Interaction.Highlighting.Precise import qualified Agda.Interaction.Imports as Imp import Agda.Interaction.Options import Agda.Syntax.Abstract.Name (toTopLevelModuleName) import Agda.Syntax.Common import Agda.Syntax.Concrete.Name (TopLevelModuleName, moduleNameParts) import Agda.TypeChecking.Errors import Agda.TypeChecking.Monad (TCM) import qualified Agda.TypeChecking.Monad as TCM import Agda.Utils.FileName import qualified Agda.Utils.IO.UTF8 as UTF8 import Agda.Utils.Lens checkFile :: AbsolutePath -> TCM TopLevelModuleName checkFile file = do TCM.resetState toTopLevelModuleName . TCM.iModuleName . fst <$> Imp.typeCheckMain file getModule :: TopLevelModuleName -> TCM (HighlightingInfo, String) getModule m = do Just mi <- TCM.getVisitedModule m Just f <- Map.lookup m . (^. TCM.stModuleToSource) <$> get s <- liftIO . UTF8.readTextFile . filePath $ f return (TCM.iHighlighting (TCM.miInterface mi), s) pairPositions :: HighlightingInfo -> String -> [(Int, String, Aspects)] pairPositions info contents = map (\cs@((mi, (pos, _)) : _) -> (pos, map (snd . snd) cs, fromMaybe mempty mi)) . groupBy ((==) `on` fst) . map (\(pos, c) -> (IMap.lookup pos infoMap, (pos, c))) . zip [1..] $ contents where infoMap = toMap (decompress info) TODO make these more accurate beginCode :: String -> Bool beginCode s = "\\begin{code}" `isInfixOf` s endCode :: String -> Bool endCode s = "\\end{code}" `isInfixOf` s infixEnd :: Eq a => [a] -> [a] -> [a] infixEnd i s = head [drop (length i) s' | s' <- tails s, i `isPrefixOf` s'] stripBegin :: (Int, String, Aspects) -> (Int, String, Aspects) stripBegin (i, s, mi) = (i, cut (dropWhile (== ' ') (infixEnd "\\begin{code}" s)), mi) where cut ('\n' : s') = s' cut s' = s' groupLiterate :: [(Int, String, Aspects)] -> [Either String [(Int, String, Aspects)]] groupLiterate contents = let (com, rest) = span (notCode beginCode) contents in Left ("\n\n" ++ concat [s | (_, s, _) <- com] ++ "\n\n") : go rest where go [] = [] go (be : mis) = let be'@(_, s, _) = stripBegin be (code, rest) = span (notCode endCode) mis in if "\\end{code}" `isInfixOf` s || "%" `isInfixOf` s then -- We simply ignore empty code blocks groupLiterate mis else Right (be' : code) : If there 's nothing between \end{code } and \begin{code } , we -- start consuming code again. case rest of [] -> error "malformed file" ((_, beginCode -> True, _) : code') -> go code' (_ : com ) -> groupLiterate com notCode f (_, s, _) = not (f s) annotate :: URI -> TopLevelModuleName -> Int -> Aspects -> Html -> Html annotate libs m pos mi = anchor ! attributes where attributes = [name (show pos)] ++ fromMaybe [] (definitionSite mi >>= link) ++ (case classes of [] -> []; cs -> [theclass (unwords cs)]) classes = maybe [] noteClasses (note mi) ++ otherAspectClasses (otherAspects mi) ++ maybe [] aspectClasses (aspect mi) aspectClasses (Name mKind op) = let kindClass = maybe [] ((: []) . showKind) mKind showKind (Constructor Inductive) = "InductiveConstructor" showKind (Constructor CoInductive) = "CoinductiveConstructor" showKind k = show k opClass = ["Operator" | op] in kindClass ++ opClass aspectClasses a = [show a] otherAspectClasses = map show Notes are not included . noteClasses _ = [] link (m', pos') = if m == m' then Just [href ("#" ++ show pos')] else Just [href (show (tostdliblink m') ++ "#" ++ show pos')] tostdliblink mn = fromMaybe nullURI (parseURIReference (intercalate "." (moduleNameParts mn ++ ["html"]))) `nonStrictRelativeTo` libs renderFragments :: URI -> String -> TopLevelModuleName -> [Either String [(Int, String, Aspects)]] -> String renderFragments libs classpr m contents = concat [ case c of Left s -> s Right cs -> let h = pre . tag "code" . mconcat $ [ annotate libs m pos mi (stringToHtml s) | (pos, s, mi) <- cs ] in renderHtmlFragment (h ! [theclass classpr]) | c <- contents ] convert :: URI -> String -> TopLevelModuleName -> TCM String convert libs classpr m = do (info, contents) <- getModule m return . renderFragments libs classpr m . groupLiterate . pairPositions info $ contents | The CSS Class to use for Agda code blocks type CSSClass = String | Render a literate Agda module 's code snippets to HTML . renderAgdaSnippets ^ Agda Command line options -> CSSClass -- ^ CSS Class name ^ URI where other Agda HTML listings are found ( for library links etc ) ^ File name of literate agda file -> IO String -- ^ Returns the file contents as a string, where each code block has been rendered to HTML. renderAgdaSnippets opts classpr libs fp = do afp <- absolute fp r <- TCM.runTCMTop $ catchError (TCM.setCommandLineOptions opts >> checkFile afp >>= convert libs classpr) $ \err -> do s <- prettyError err liftIO (putStrLn s) throwError err case r of Right s -> return (dropWhile isSpace s) Left _ -> exitFailure
null
https://raw.githubusercontent.com/liamoc/agda-snippets/433f16261b0787c87fc145d67a440fecb11c94f7/agda-snippets/src/Agda/Contrib/Snippets.hs
haskell
We simply ignore empty code blocks start consuming code again. ^ CSS Class name ^ Returns the file contents as a string, where each code block has been rendered to HTML.
# LANGUAGE ViewPatterns # module Agda.Contrib.Snippets ( renderAgdaSnippets , CSSClass , CommandLineOptions (..) , defaultOptions ) where import Control.Monad.Except import Control.Monad.State (get) import Data.Char import Data.Function import Data.List import Data.Maybe import qualified Data.Map as Map import qualified Data.IntMap as IMap import Network.URI import System.Exit (exitFailure) import Text.XHtml.Strict import Agda.Interaction.Highlighting.Precise import qualified Agda.Interaction.Imports as Imp import Agda.Interaction.Options import Agda.Syntax.Abstract.Name (toTopLevelModuleName) import Agda.Syntax.Common import Agda.Syntax.Concrete.Name (TopLevelModuleName, moduleNameParts) import Agda.TypeChecking.Errors import Agda.TypeChecking.Monad (TCM) import qualified Agda.TypeChecking.Monad as TCM import Agda.Utils.FileName import qualified Agda.Utils.IO.UTF8 as UTF8 import Agda.Utils.Lens checkFile :: AbsolutePath -> TCM TopLevelModuleName checkFile file = do TCM.resetState toTopLevelModuleName . TCM.iModuleName . fst <$> Imp.typeCheckMain file getModule :: TopLevelModuleName -> TCM (HighlightingInfo, String) getModule m = do Just mi <- TCM.getVisitedModule m Just f <- Map.lookup m . (^. TCM.stModuleToSource) <$> get s <- liftIO . UTF8.readTextFile . filePath $ f return (TCM.iHighlighting (TCM.miInterface mi), s) pairPositions :: HighlightingInfo -> String -> [(Int, String, Aspects)] pairPositions info contents = map (\cs@((mi, (pos, _)) : _) -> (pos, map (snd . snd) cs, fromMaybe mempty mi)) . groupBy ((==) `on` fst) . map (\(pos, c) -> (IMap.lookup pos infoMap, (pos, c))) . zip [1..] $ contents where infoMap = toMap (decompress info) TODO make these more accurate beginCode :: String -> Bool beginCode s = "\\begin{code}" `isInfixOf` s endCode :: String -> Bool endCode s = "\\end{code}" `isInfixOf` s infixEnd :: Eq a => [a] -> [a] -> [a] infixEnd i s = head [drop (length i) s' | s' <- tails s, i `isPrefixOf` s'] stripBegin :: (Int, String, Aspects) -> (Int, String, Aspects) stripBegin (i, s, mi) = (i, cut (dropWhile (== ' ') (infixEnd "\\begin{code}" s)), mi) where cut ('\n' : s') = s' cut s' = s' groupLiterate :: [(Int, String, Aspects)] -> [Either String [(Int, String, Aspects)]] groupLiterate contents = let (com, rest) = span (notCode beginCode) contents in Left ("\n\n" ++ concat [s | (_, s, _) <- com] ++ "\n\n") : go rest where go [] = [] go (be : mis) = let be'@(_, s, _) = stripBegin be (code, rest) = span (notCode endCode) mis in if "\\end{code}" `isInfixOf` s || "%" `isInfixOf` s groupLiterate mis else Right (be' : code) : If there 's nothing between \end{code } and \begin{code } , we case rest of [] -> error "malformed file" ((_, beginCode -> True, _) : code') -> go code' (_ : com ) -> groupLiterate com notCode f (_, s, _) = not (f s) annotate :: URI -> TopLevelModuleName -> Int -> Aspects -> Html -> Html annotate libs m pos mi = anchor ! attributes where attributes = [name (show pos)] ++ fromMaybe [] (definitionSite mi >>= link) ++ (case classes of [] -> []; cs -> [theclass (unwords cs)]) classes = maybe [] noteClasses (note mi) ++ otherAspectClasses (otherAspects mi) ++ maybe [] aspectClasses (aspect mi) aspectClasses (Name mKind op) = let kindClass = maybe [] ((: []) . showKind) mKind showKind (Constructor Inductive) = "InductiveConstructor" showKind (Constructor CoInductive) = "CoinductiveConstructor" showKind k = show k opClass = ["Operator" | op] in kindClass ++ opClass aspectClasses a = [show a] otherAspectClasses = map show Notes are not included . noteClasses _ = [] link (m', pos') = if m == m' then Just [href ("#" ++ show pos')] else Just [href (show (tostdliblink m') ++ "#" ++ show pos')] tostdliblink mn = fromMaybe nullURI (parseURIReference (intercalate "." (moduleNameParts mn ++ ["html"]))) `nonStrictRelativeTo` libs renderFragments :: URI -> String -> TopLevelModuleName -> [Either String [(Int, String, Aspects)]] -> String renderFragments libs classpr m contents = concat [ case c of Left s -> s Right cs -> let h = pre . tag "code" . mconcat $ [ annotate libs m pos mi (stringToHtml s) | (pos, s, mi) <- cs ] in renderHtmlFragment (h ! [theclass classpr]) | c <- contents ] convert :: URI -> String -> TopLevelModuleName -> TCM String convert libs classpr m = do (info, contents) <- getModule m return . renderFragments libs classpr m . groupLiterate . pairPositions info $ contents | The CSS Class to use for Agda code blocks type CSSClass = String | Render a literate Agda module 's code snippets to HTML . renderAgdaSnippets ^ Agda Command line options ^ URI where other Agda HTML listings are found ( for library links etc ) ^ File name of literate agda file renderAgdaSnippets opts classpr libs fp = do afp <- absolute fp r <- TCM.runTCMTop $ catchError (TCM.setCommandLineOptions opts >> checkFile afp >>= convert libs classpr) $ \err -> do s <- prettyError err liftIO (putStrLn s) throwError err case r of Right s -> return (dropWhile isSpace s) Left _ -> exitFailure
3fa4925c2ca7d9c7e2cc1766c6a066c34a3809255c5d27cb750b123cc981954d
threatgrid/ctia
asset_mapping_test.clj
(ns ctia.http.routes.graphql.asset-mapping-test (:require [clj-momo.test-helpers.core :as mth] [clojure.test :refer [deftest is are join-fixtures testing use-fixtures]] [ctia.entity.asset-mapping :as asset-mapping] [ctia.test-helpers.auth :refer [all-capabilities]] [ctia.test-helpers.core :as helpers] [ctia.test-helpers.fake-whoami-service :as whoami-helpers] [ctia.test-helpers.fixtures :as fixt] [ctia.test-helpers.graphql :as gh] [ctia.test-helpers.store :refer [test-for-each-store-with-app]] [ctim.examples.asset-mappings :refer [asset-mapping-maximal]])) (use-fixtures :once (join-fixtures [mth/fixture-schema-validation whoami-helpers/fixture-server])) (def ownership-data-fixture {:owner "foouser" :groups ["foogroup"]}) (def asset-mapping-1 (fixt/randomize asset-mapping-maximal)) (def asset-mapping-2 (assoc (fixt/randomize asset-mapping-maximal) :source "ngfw")) (defn prepare-result [asset-mapping] (dissoc asset-mapping :search-txt)) (deftest asset-mapping-graphql-test (test-for-each-store-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (let [asset-mapping1 (prepare-result (gh/create-object app "asset-mapping" asset-mapping-1)) asset-mapping2 (prepare-result (gh/create-object app "asset-mapping" asset-mapping-2)) graphql-queries (slurp "test/data/asset.graphql")] (testing "asset mapping query" (let [{:keys [data errors status]} (gh/query app graphql-queries {:id (:id asset-mapping1)} "AssetMappingQueryTest")] (is (= 200 status)) (is (empty? errors) "No errors") (testing "the asset-mapping" (is (= asset-mapping1 (:asset_mapping data)))))) (testing "asset-mappings query" (testing "asset-mappings connection" (gh/connection-test app "AssetMappingsQueryTest" graphql-queries {"query" "*"} [:asset_mappings] (map #(merge % ownership-data-fixture) [asset-mapping1 asset-mapping2])) (testing "sorting" (gh/connection-sort-test app "AssetMappingsQueryTest" graphql-queries {:query "*"} [:asset_mappings] asset-mapping/asset-mapping-fields))) (testing "query argument" (are [query data-vec expected] (let [{:keys [data errors status]} (gh/query app graphql-queries {:query query} "AssetMappingsQueryTest")] (is (= 200 status)) (is (empty? errors) "No errors") (is (= expected (get-in data data-vec)) (format "make sure data at '%s' matches the expected" data-vec)) true) "source:\"ngfw\"" [:asset_mappings :totalCount] 1 "source:\"ngfw\"" [:asset_mappings :nodes] [asset-mapping2] (format "observable.type:\"%s\"" (-> asset-mapping2 :observable :type)) [:asset_mappings :nodes 0 :observable :value] (-> asset-mapping2 :observable :value))))))))
null
https://raw.githubusercontent.com/threatgrid/ctia/32857663cdd7ac385161103dbafa8dc4f98febf0/test/ctia/http/routes/graphql/asset_mapping_test.clj
clojure
(ns ctia.http.routes.graphql.asset-mapping-test (:require [clj-momo.test-helpers.core :as mth] [clojure.test :refer [deftest is are join-fixtures testing use-fixtures]] [ctia.entity.asset-mapping :as asset-mapping] [ctia.test-helpers.auth :refer [all-capabilities]] [ctia.test-helpers.core :as helpers] [ctia.test-helpers.fake-whoami-service :as whoami-helpers] [ctia.test-helpers.fixtures :as fixt] [ctia.test-helpers.graphql :as gh] [ctia.test-helpers.store :refer [test-for-each-store-with-app]] [ctim.examples.asset-mappings :refer [asset-mapping-maximal]])) (use-fixtures :once (join-fixtures [mth/fixture-schema-validation whoami-helpers/fixture-server])) (def ownership-data-fixture {:owner "foouser" :groups ["foogroup"]}) (def asset-mapping-1 (fixt/randomize asset-mapping-maximal)) (def asset-mapping-2 (assoc (fixt/randomize asset-mapping-maximal) :source "ngfw")) (defn prepare-result [asset-mapping] (dissoc asset-mapping :search-txt)) (deftest asset-mapping-graphql-test (test-for-each-store-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (let [asset-mapping1 (prepare-result (gh/create-object app "asset-mapping" asset-mapping-1)) asset-mapping2 (prepare-result (gh/create-object app "asset-mapping" asset-mapping-2)) graphql-queries (slurp "test/data/asset.graphql")] (testing "asset mapping query" (let [{:keys [data errors status]} (gh/query app graphql-queries {:id (:id asset-mapping1)} "AssetMappingQueryTest")] (is (= 200 status)) (is (empty? errors) "No errors") (testing "the asset-mapping" (is (= asset-mapping1 (:asset_mapping data)))))) (testing "asset-mappings query" (testing "asset-mappings connection" (gh/connection-test app "AssetMappingsQueryTest" graphql-queries {"query" "*"} [:asset_mappings] (map #(merge % ownership-data-fixture) [asset-mapping1 asset-mapping2])) (testing "sorting" (gh/connection-sort-test app "AssetMappingsQueryTest" graphql-queries {:query "*"} [:asset_mappings] asset-mapping/asset-mapping-fields))) (testing "query argument" (are [query data-vec expected] (let [{:keys [data errors status]} (gh/query app graphql-queries {:query query} "AssetMappingsQueryTest")] (is (= 200 status)) (is (empty? errors) "No errors") (is (= expected (get-in data data-vec)) (format "make sure data at '%s' matches the expected" data-vec)) true) "source:\"ngfw\"" [:asset_mappings :totalCount] 1 "source:\"ngfw\"" [:asset_mappings :nodes] [asset-mapping2] (format "observable.type:\"%s\"" (-> asset-mapping2 :observable :type)) [:asset_mappings :nodes 0 :observable :value] (-> asset-mapping2 :observable :value))))))))
c2fe31dda80c4dff83ca498e24fe3bfc99daaee755e126659b66b9bb50841143
xapi-project/xen-api-libs
xen_cmdline.mli
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2006-2009 Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) * Helper module to view , modify and delete Xen command - line options (** Gives a list of CPU feature masks currently set. *) val list_cpuid_masks : unit -> (string * string) list (** Sets CPU feature masks. *) val set_cpuid_masks : (string * string) list -> string (** Removes CPU feature masks. *) val delete_cpuid_masks : string list -> string list
null
https://raw.githubusercontent.com/xapi-project/xen-api-libs/d603ee2b8456bc2aac99b0a4955f083e22f4f314/xen-utils/xen_cmdline.mli
ocaml
* Gives a list of CPU feature masks currently set. * Sets CPU feature masks. * Removes CPU feature masks.
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2006-2009 Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) * Helper module to view , modify and delete Xen command - line options val list_cpuid_masks : unit -> (string * string) list val set_cpuid_masks : (string * string) list -> string val delete_cpuid_masks : string list -> string list
6be533c62422b897a42113a87b86eef4a34ae16a4ce32807dd2335b4232b2323
mooreryan/ocaml_python_bindgen
test_specs_file.ml
open! Base open! Lib let with_data_as_file ~data ~f = let open Stdio in let fname, oc = Caml.Filename.open_temp_file "pyml_bindeng_test" "" in Exn.protectx ~f:(fun oc -> Out_channel.output_string oc data; Out_channel.flush oc; f ~file_name:fname) ~finally:Out_channel.close oc let test_data = {|val add : x:int -> y:int -> unit -> int # .......... # ................ # @py_fun_name=add val add_int : x:int -> y:int -> unit -> int [@@py_fun_name add] # I like cheese. # #And#Apples #Pie # # @py_fun_name=add val add_float : x:float -> y:float -> unit -> float [@@py_fun_name add] val sub : x:int -> y:int -> unit -> int [@@py_fun_name silly] [@@yummy cake_stuff] [@@thing what] # Comment at the end # HEHE |} let%expect_test _ = let specs = with_data_as_file ~data:test_data ~f:(fun ~file_name -> Specs_file.read file_name) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list] specs; [%expect {| (((attrs ()) (val_spec "val add : x:int -> y:int -> unit -> int")) ((attrs ("[@@py_fun_name add]")) (val_spec "val add_int : x:int -> y:int -> unit -> int")) ((attrs ("[@@py_fun_name add]")) (val_spec "val add_float : x:float -> y:float -> unit -> float")) ((attrs ("[@@py_fun_name silly] [@@yummy cake_stuff] [@@thing what]")) (val_spec "val sub : x:int -> y:int -> unit -> int"))) |}] let%expect_test "attributes must start a line" = let data = {| val f : int [@@apple pie] -> int |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Error (Failure "attributes must start a line")) |}] let%expect_test _ = let data = {| int -> int [@@apple pie] [@@is good] |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Error (Failure "In the middle of a val spec, but have none to work on.")) |}] let%expect_test _ = let data = {| [@@apple pie] [@@is good] |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Error (Failure "We have attributes but no val spec for them to go with.")) |}] let%expect_test _ = let data = {| val f : int [@@apple pie] int -> float |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Error (Failure "Found unused attrs but in the middle of a val spec.")) |}] let%expect_test _ = let data = {| val f : int -> float |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Ok (((attrs ()) (val_spec "val f : int -> float")))) |}] let%expect_test _ = let data = {| val f : int -> float [@@hello world]|} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Ok (((attrs ("[@@hello world]")) (val_spec "val f : int -> float")))) |}] let%expect_test _ = let data = {| val f : int -> float [@@hello world] |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Ok (((attrs ("[@@hello world]")) (val_spec "val f : int -> float")))) |}] let%expect_test _ = let data = {| val f : int -> float |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Ok (((attrs ()) (val_spec "val f : int -> float")))) |}]
null
https://raw.githubusercontent.com/mooreryan/ocaml_python_bindgen/70e6e0fba31d4634a776df7f7e89b6b3ea528a12/test/test_specs_file.ml
ocaml
open! Base open! Lib let with_data_as_file ~data ~f = let open Stdio in let fname, oc = Caml.Filename.open_temp_file "pyml_bindeng_test" "" in Exn.protectx ~f:(fun oc -> Out_channel.output_string oc data; Out_channel.flush oc; f ~file_name:fname) ~finally:Out_channel.close oc let test_data = {|val add : x:int -> y:int -> unit -> int # .......... # ................ # @py_fun_name=add val add_int : x:int -> y:int -> unit -> int [@@py_fun_name add] # I like cheese. # #And#Apples #Pie # # @py_fun_name=add val add_float : x:float -> y:float -> unit -> float [@@py_fun_name add] val sub : x:int -> y:int -> unit -> int [@@py_fun_name silly] [@@yummy cake_stuff] [@@thing what] # Comment at the end # HEHE |} let%expect_test _ = let specs = with_data_as_file ~data:test_data ~f:(fun ~file_name -> Specs_file.read file_name) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list] specs; [%expect {| (((attrs ()) (val_spec "val add : x:int -> y:int -> unit -> int")) ((attrs ("[@@py_fun_name add]")) (val_spec "val add_int : x:int -> y:int -> unit -> int")) ((attrs ("[@@py_fun_name add]")) (val_spec "val add_float : x:float -> y:float -> unit -> float")) ((attrs ("[@@py_fun_name silly] [@@yummy cake_stuff] [@@thing what]")) (val_spec "val sub : x:int -> y:int -> unit -> int"))) |}] let%expect_test "attributes must start a line" = let data = {| val f : int [@@apple pie] -> int |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Error (Failure "attributes must start a line")) |}] let%expect_test _ = let data = {| int -> int [@@apple pie] [@@is good] |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Error (Failure "In the middle of a val spec, but have none to work on.")) |}] let%expect_test _ = let data = {| [@@apple pie] [@@is good] |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Error (Failure "We have attributes but no val spec for them to go with.")) |}] let%expect_test _ = let data = {| val f : int [@@apple pie] int -> float |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Error (Failure "Found unused attrs but in the middle of a val spec.")) |}] let%expect_test _ = let data = {| val f : int -> float |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Ok (((attrs ()) (val_spec "val f : int -> float")))) |}] let%expect_test _ = let data = {| val f : int -> float [@@hello world]|} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Ok (((attrs ("[@@hello world]")) (val_spec "val f : int -> float")))) |}] let%expect_test _ = let data = {| val f : int -> float [@@hello world] |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Ok (((attrs ("[@@hello world]")) (val_spec "val f : int -> float")))) |}] let%expect_test _ = let data = {| val f : int -> float |} in let specs = with_data_as_file ~data ~f:(fun ~file_name -> Or_error.try_with (fun () -> Specs_file.read file_name)) in Stdio.print_s @@ [%sexp_of: Specs_file.spec list Or_error.t] specs; [%expect {| (Ok (((attrs ()) (val_spec "val f : int -> float")))) |}]
7e5a2b4cf7de140c6ce60ae9280cd6349a361940e379914082c379608689fbe1
abarbu/haskell-torch
Common.hs
# LANGUAGE AllowAmbiguousTypes , ConstraintKinds , DataKinds , FlexibleContexts , FlexibleInstances , FunctionalDependencies , GADTs # # LANGUAGE KindSignatures , MultiParamTypeClasses , OverloadedLabels , OverloadedStrings , PartialTypeSignatures , PolyKinds , QuasiQuotes # # LANGUAGE RankNTypes , ScopedTypeVariables , TemplateHaskell , TypeApplications , TypeFamilies , TypeFamilyDependencies , TypeInType # # LANGUAGE TypeOperators , UndecidableInstances # # OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver # -- | You'll notice that this module calls performMinorGC in various -- places. There's no way to tell the Haskell GC about external memory so huge -- amounts of memory can build up before any finalizers get run :( module Torch.Datasets.Common where import Control.Monad.Except import Control.Monad.Loops import Data.Foldable import Data.IORef import Data.Sequence (Seq) import qualified Data.Sequence as S import Data.Singletons import Data.Text (Text) import qualified Data.Text as T import qualified Data.Vector as V' import Foreign.ForeignPtr import qualified Foreign.Matio as M import Foreign.Matio.Types (CMat) import Foreign.Storable import Pipes import qualified Pipes as P import qualified Pipes.Prelude as P import qualified Shelly as S import qualified System.Directory as P import System.Mem import Torch.Misc import Torch.Tensor import Torch.Types type CanFail = ExceptT Text IO canFail :: ExceptT e m a -> m (Either e a) canFail = runExceptT type Path = Text | A datasets is a wrapper around one stream of data . This means that -- conceptually a training set and test set are disjoint datasets! Certain -- operations behave differently at training and test time, like data -- augmentation and batch normalization. The extra type safety here makes sure -- that there's no confusion and no room for mistakes. data Dataset metadata (dataPurpose :: DataPurpose) index object label = Dataset { checkDataset :: IO (Either Text ()) , fetchDataset :: IO (Either Text (DataStream dataPurpose index object label)) , forceFetchDataset :: IO (Either Text (DataStream dataPurpose index object label)) , accessDataset :: IO (Either Text (DataStream dataPurpose index object label)) , metadataDataset :: IO (Either Text metadata) } -- | One of the most standard ways to view a dataset is as a pair of fixed -- training and test sets. type TrainTestDataset metadata index object label = (Dataset metadata Train index object label, Dataset metadata Test index object label) -- | A data sample from a dataset. It is tagged with its purpose, either training or -- test. This is so that some APIs can prevent you from misusing data, like say -- training on the test data. It has properties which are accessible for any data point and an associated object / label which requires IO to access . -- Listing data and its properties is cheap but reading the data point or the label -- might be expensive so we keep these behind IO ops that you run when you need the -- data itself. -- -- Functions take optional arguments which provide storage for the output. When -- the argument is given the results must be written to it! TODO How can I enforce this? data DataSample (dataPurpose :: DataPurpose) properties object label = DataSample { dataProperties :: properties , dataObject :: IO object , dataLabel :: IO label } dataPurpose :: forall (datap :: DataPurpose) p o l. SingI datap => DataSample datap p o l -> DataPurpose dataPurpose _ = demote @datap -- | This is an inefficient way of satisfying the requirement that datasets must -- write to their input if provided. setTensorIfGiven_ :: IO (Tensor ty ki sz) -> Maybe (Tensor ty ki sz) -> IO (Tensor ty ki sz) setTensorIfGiven_ f x = do t <- f case x of Nothing -> pure t Just x' -> set_ x' t >> pure x' -- | This is a more efficient way of streaming data, write to the given tensor, -- we'll take care of dealing with providing a fresh one or using the input. useTensorIfGiven_ f x = case x of Nothing -> empty >>= f Just t -> f t -- | A stream of data. This is like an entire training or test set. Datasets -- with unbounded size can be conveniently represented because lists are lazy. -- A dataset contains a single stream of data. type DataStream dp index object label = Producer (DataSample dp index object label) IO () -- | Create a stream of data samples from an action mapObjects :: (o -> IO o') -> Pipe (DataSample dp p o l) (DataSample dp p o' l) IO () mapObjects f = forever $ do (DataSample p o l) <- await yield $ DataSample p (o >>= f) l -- | Create a stream of data labels from an action mapLabels :: (l -> IO l') -> Pipe (DataSample dp p o l) (DataSample dp p o l') IO () mapLabels f = forever $ do (DataSample p o l) <- await yield $ DataSample p o (l >>= f) -- * Manipulate datasets applyTrain :: (DataStream Train index object label -> DataStream Train index' object' label') -> Dataset metadata Train index object label -> Dataset metadata Train index' object' label' applyTrain f d = Dataset { checkDataset = checkDataset d , fetchDataset = (f <$>) <$> fetchDataset d , forceFetchDataset = (f <$>) <$> forceFetchDataset d , accessDataset = (f <$>) <$> accessDataset d , metadataDataset = metadataDataset d } applyTest :: (DataStream Test index object label -> DataStream Test index' object' label') -> Dataset metadata Test index object label -> Dataset metadata Test index' object' label' applyTest f d = Dataset { checkDataset = checkDataset d , fetchDataset = (f <$>) <$> fetchDataset d , forceFetchDataset = (f <$>) <$> forceFetchDataset d , accessDataset = (f <$>) <$> accessDataset d , metadataDataset = metadataDataset d } augmentTrainData :: (object -> IO object') -> Dataset metadata Train index object label -> Dataset metadata Train index object' label augmentTrainData f = applyTrain (\d -> P.for d (\s -> yield $ DataSample { dataProperties = dataProperties s , dataObject = f =<< dataObject s , dataLabel = dataLabel s })) augmentTestData :: (object -> IO object') -> Dataset metadata Test index object label -> Dataset metadata Test index object' label augmentTestData f = applyTest (\d -> P.for d (\s -> yield $ DataSample { dataProperties = dataProperties s , dataObject = f =<< dataObject s , dataLabel = dataLabel s })) augmentTrain :: (index -> index') -> (object -> IO object') -> (label -> IO label') -> Dataset metadata Train index object label -> Dataset metadata Train index' object' label' augmentTrain fi fo fl = applyTrain (\d -> P.for d (\s -> yield $ DataSample { dataProperties = fi $ dataProperties s , dataObject = fo =<< dataObject s , dataLabel = fl =<< dataLabel s })) augmentTest :: (index -> index') -> (object -> IO object') -> (label -> IO label') -> Dataset metadata Test index object label -> Dataset metadata Test index' object' label' augmentTest fi fo fl = applyTest (\d -> P.for d (\s -> yield $ DataSample { dataProperties = fi $ dataProperties s , dataObject = fo =<< dataObject s , dataLabel = fl =<< dataLabel s })) -- * Standard operations on datasets forEachData :: MonadIO m => (a -> IO b) -> Producer a m r -> m r forEachData f stream = runEffect $ for stream (\x -> liftIO (f x >> performMinorGC >> pure ())) forEachDataN :: MonadIO m => (a -> Int -> IO b) -> Producer a m r -> m r forEachDataN f stream = do n <- liftIO $ newIORef (0 :: Int) runEffect $ for stream (\x -> liftIO $ do f x =<< readIORef n modifyIORef' n (+1) performMinorGC pure ()) | Each of the arguments are called with the step number & epoch . forEachDataUntil :: MonadIO m => (Int -> Int -> IO Bool) -- ^ are we done? -> (Int -> Int -> Producer a m r -> IO (Producer a m r)) -- ^ what to do when starting a new epoch -> (Int -> Int -> a -> IO b) -- ^ per sample op -> Producer a m r -- ^ data stream -> m (Int, Int) forEachDataUntil isDone newEpoch perSample initialStream = do step <- liftIO $ newIORef (0 :: Int) epoch <- liftIO $ newIORef (0 :: Int) stream' <- liftIO $ newEpoch 0 0 initialStream let go stream = do n <- next stream s <- liftIO $ readIORef step e <- liftIO $ readIORef epoch b <- liftIO $ isDone s e if not b then case n of Left r -> do stream' <- liftIO $ newEpoch s e initialStream liftIO $ modifyIORef epoch (+ 1) go stream' Right (value, stream') -> do liftIO $ perSample s e value liftIO $ modifyIORef step (+ 1) go stream' else pure () go stream' s <- liftIO $ readIORef step e <- liftIO $ readIORef epoch pure (s,e) foldData :: MonadIO m => (b -> a -> m b) -> b -> Producer a m () -> m b foldData f i stream = P.foldM (\a b -> liftIO performMinorGC >> f a b) (pure i) pure stream lossForEachData :: (TensorConstraints ty ki sz) => (t -> IO (Tensor ty ki sz)) -> Producer t IO () -> IO (Tensor ty ki sz) lossForEachData loss stream = P.foldM (\l d -> do performMinorGC l' <- liftIO $ loss d l `add` l') zeros pure stream lossSum :: (SingI ty, SingI ki , Num (TensorTyToHs ty), Storable (TensorTyToHs ty) , Num (TensorTyToHsC ty), Storable (TensorTyToHsC ty)) => V'.Vector (Scalar ty ki) -> IO (Scalar ty ki) lossSum v = do z <- zeros foldM add z v -- | This works like the dataset shuffler in tensorflow. You have a horizon out -- to which you shuffle data. This is because data streams might be infinite in -- length and a shuffle of the entire data isn't possible there. -- -- If you're gathering data from an intermittent source and your horizon is long -- this will block until enough data is available! shuffle :: Int -> Producer a IO r -> Producer a IO r shuffle horizon p = go p S.empty where go p s = do n <- liftIO $ next p case n of Left r -> iterateUntilM S.null randomSeqYield s >> pure r Right (a, p') -> do let s' = a S.<| s if S.length s' < horizon then go p' s' else randomSeqYield s' >>= go p' randomSeqYield :: Seq a -> Pipes.Proxy x' x () a IO (Seq a) randomSeqYield s = do r <- liftIO $ randomElement s case r of (Just (e, s')) -> do yield e pure s' Nothing -> lift mzero batch :: Int -> Bool -> Producer a IO r -> Producer (V'.Vector a) IO r batch batchSize returnPartial p = go p S.empty where go p s = do n <- liftIO $ next p case n of Left r -> do when returnPartial $ yield (V'.fromList $ toList s) pure r Right (a, p') -> do let s' = s S.|> a if S.length s' >= batchSize then yield (V'.fromList $ toList s') >> go p' S.empty else go p' s' batchFn :: Int -> Bool -> Producer a IO r -> (V'.Vector a -> IO b) -> Producer b IO r batchFn batchSize returnPartial p fn = go p S.empty where go p s = do n <- liftIO $ next p case n of Left r -> do when returnPartial $ do y <- liftIO $ fn $ V'.fromList $ toList s yield y pure r Right (a, p') -> do let s' = s S.|> a if S.length s' >= batchSize then do y <- liftIO $ fn $ V'.fromList $ toList s' yield y go p' S.empty else go p' s' batchTensors :: forall batchSize ty ki sz ty' ki' sz' dp p r. (SingI batchSize ,Num (TensorTyToHs ty), Storable (TensorTyToHs ty) ,Num (TensorTyToHs ty'), Storable (TensorTyToHs ty') ,Num (TensorTyToHsC ty), Storable (TensorTyToHsC ty) ,Num (TensorTyToHsC ty'), Storable (TensorTyToHsC ty') ,SingI (InsertIndex sz 0 batchSize) ,SingI ty, SingI ki, SingI sz, SingI sz' ,SingI (InsertIndex sz' 0 batchSize) ,SingI ty', SingI ki') => BatchSize batchSize -> Producer (DataSample dp p (Tensor ty ki sz) (Tensor ty' ki' sz')) IO r -> Producer (DataSample dp (V'.Vector p) (Tensor ty ki (InsertIndex sz 0 batchSize)) (Tensor ty' ki' (InsertIndex sz' 0 batchSize))) IO r batchTensors BatchSize p = batchFn (demoteN @batchSize) False p (\v -> pure $ DataSample (V'.map dataProperties v) (do v <- (V'.mapM dataObject v) s <- stack (groups_ @batchSize) (dimension_ @0) v case s of Nothing -> error "Oddly-sized batch -- this is a bug" Just x -> pure x) (do v <- (V'.mapM dataLabel v) s <- stack (groups_ @batchSize) (dimension_ @0) v case s of Nothing -> error "Oddly-sized batch -- this is a bug" Just x -> pure x)) TODO preload preload : : Int - > Producer ( DataSample dp p o l ) IO r - > Producer ( DataSample dp p o l ) IO r -- preload n = undefined TODO preloadBatch preloadBatches : : Int - > Producer ( Vector ( DataSample dp p o l ) ) IO r - > Producer ( Vector ( DataSample dp p o l ) ) IO r -- preloadBatches n = undefined {- TODO filter (pick subset that matches predicate) sample with replacement balanace with respect to some label most of this works with pipes aside from sampling! lets just do a list for now -} onError :: MonadError e m => m a -> m a -> m a onError f g = f `catchError` const g retryAfter :: MonadError e m => m a -> m a -> m a retryAfter f g = f `catchError` const (g >> f) checkMD5 :: Path -> Text -> CanFail () checkMD5 path md5 = do e <- liftIO $ doesFileExist path if e then do out <- S.shelly $ S.run "md5sum" [path] case T.splitOn " " out of (s:_) -> if s == md5 then pure () else throwError $ "MD5 check failed, got " <#> path <#> s <#> "but expected" <#> md5 _ -> throwError $ "Bad result from md5" <#> out else throwError $ "Missing file" <#> path downloadUrl :: Text -> Path -> CanFail () downloadUrl url dest = do c <- S.shelly $ S.verbosely $ do S.run_ "curl" ["--progress-bar", "-L", url, "--output", dest] S.lastExitCode unless (c == 0) $ throwError $ "Download with curl failed" <#> url <#> dest extractTar :: Path -> Path -> CanFail () extractTar path dest = do e <- liftIO $ doesFileExist path unless e $ throwError $ "Can't extract, tar file doesn't exist" <#> path c <- S.shelly $ S.verbosely $ do S.run_ "tar" ["xvf", path, "-C", dest] S.lastExitCode unless (c == 0) $ throwError $ "Extracting tar file failed" <#> path extractGzip :: Path -> CanFail () extractGzip path = do e <- liftIO $ doesFileExist path unless e $ throwError $ "Can't extract, gzip file doesn't exist" <#> path c <- S.shelly $ S.verbosely $ do S.run_ "gunzip" [path] S.lastExitCode unless (c == 0) $ throwError $ "gunzip failed" <#> path -- | This is a high-level wrapper to get a file, or fail gently downloadAndVerifyFile :: Text -> Text -> Text -> Text -> IO (Either Text ()) downloadAndVerifyFile url filename dir md5 = canFail $ do liftIO $ createDirectoryIfMissing' dir checkMD5 (dir </> filename) md5 `retryAfter` downloadUrl url (dir </> filename) -- | This is the end point for downloading a model or other data that must be -- cached. The data is stored in the user's XDG cache directory so it will -- persist after reboots. getCachedFileOrDownload :: Text -> Text -> Text -> Text -> IO Text getCachedFileOrDownload url md5 filename subtype = do location <- T.pack <$> P.getXdgDirectory P.XdgCache ("haskell-torch/" <> T.unpack subtype) let path = location </> filename e <- doesFileExist path if e then pure $ location </> filename else do r <- downloadAndVerifyFile url filename location md5 case r of Left err -> do f <- canFail (checkMD5 path md5) case f of -- Remove the file if the md5sum was bad Left e -> do P.removeFile $ T.unpack path _ -> pure () error $ T.unpack err Right _ -> pure $ location </> filename -- * Utility functions on pipes pipeMatfilesReadOnly :: [Text] -> Producer (ForeignPtr CMat) IO () pipeMatfilesReadOnly fs = mapM_ (\f -> do liftIO $ print $ "Reading " ++ show f mf <- liftIO $ M.openReadOnly f yield mf) fs pipeListDirectory :: Text -> Producer Text IO () pipeListDirectory path = do l <- liftIO $ listDirectory path mapM_ (yield . (path </>)) l
null
https://raw.githubusercontent.com/abarbu/haskell-torch/03b2c10bf8ca3d4508d52c2123e753d93b3c4236/haskell-torch/src/Torch/Datasets/Common.hs
haskell
| You'll notice that this module calls performMinorGC in various places. There's no way to tell the Haskell GC about external memory so huge amounts of memory can build up before any finalizers get run :( conceptually a training set and test set are disjoint datasets! Certain operations behave differently at training and test time, like data augmentation and batch normalization. The extra type safety here makes sure that there's no confusion and no room for mistakes. | One of the most standard ways to view a dataset is as a pair of fixed training and test sets. | A data sample from a dataset. It is tagged with its purpose, either training or test. This is so that some APIs can prevent you from misusing data, like say training on the test data. It has properties which are accessible for any data Listing data and its properties is cheap but reading the data point or the label might be expensive so we keep these behind IO ops that you run when you need the data itself. Functions take optional arguments which provide storage for the output. When the argument is given the results must be written to it! TODO How can I enforce this? | This is an inefficient way of satisfying the requirement that datasets must write to their input if provided. | This is a more efficient way of streaming data, write to the given tensor, we'll take care of dealing with providing a fresh one or using the input. | A stream of data. This is like an entire training or test set. Datasets with unbounded size can be conveniently represented because lists are lazy. A dataset contains a single stream of data. | Create a stream of data samples from an action | Create a stream of data labels from an action * Manipulate datasets * Standard operations on datasets ^ are we done? ^ what to do when starting a new epoch ^ per sample op ^ data stream | This works like the dataset shuffler in tensorflow. You have a horizon out to which you shuffle data. This is because data streams might be infinite in length and a shuffle of the entire data isn't possible there. If you're gathering data from an intermittent source and your horizon is long this will block until enough data is available! preload n = undefined preloadBatches n = undefined TODO filter (pick subset that matches predicate) sample with replacement balanace with respect to some label most of this works with pipes aside from sampling! lets just do a list for now | This is a high-level wrapper to get a file, or fail gently | This is the end point for downloading a model or other data that must be cached. The data is stored in the user's XDG cache directory so it will persist after reboots. Remove the file if the md5sum was bad * Utility functions on pipes
# LANGUAGE AllowAmbiguousTypes , ConstraintKinds , DataKinds , FlexibleContexts , FlexibleInstances , FunctionalDependencies , GADTs # # LANGUAGE KindSignatures , MultiParamTypeClasses , OverloadedLabels , OverloadedStrings , PartialTypeSignatures , PolyKinds , QuasiQuotes # # LANGUAGE RankNTypes , ScopedTypeVariables , TemplateHaskell , TypeApplications , TypeFamilies , TypeFamilyDependencies , TypeInType # # LANGUAGE TypeOperators , UndecidableInstances # # OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver # module Torch.Datasets.Common where import Control.Monad.Except import Control.Monad.Loops import Data.Foldable import Data.IORef import Data.Sequence (Seq) import qualified Data.Sequence as S import Data.Singletons import Data.Text (Text) import qualified Data.Text as T import qualified Data.Vector as V' import Foreign.ForeignPtr import qualified Foreign.Matio as M import Foreign.Matio.Types (CMat) import Foreign.Storable import Pipes import qualified Pipes as P import qualified Pipes.Prelude as P import qualified Shelly as S import qualified System.Directory as P import System.Mem import Torch.Misc import Torch.Tensor import Torch.Types type CanFail = ExceptT Text IO canFail :: ExceptT e m a -> m (Either e a) canFail = runExceptT type Path = Text | A datasets is a wrapper around one stream of data . This means that data Dataset metadata (dataPurpose :: DataPurpose) index object label = Dataset { checkDataset :: IO (Either Text ()) , fetchDataset :: IO (Either Text (DataStream dataPurpose index object label)) , forceFetchDataset :: IO (Either Text (DataStream dataPurpose index object label)) , accessDataset :: IO (Either Text (DataStream dataPurpose index object label)) , metadataDataset :: IO (Either Text metadata) } type TrainTestDataset metadata index object label = (Dataset metadata Train index object label, Dataset metadata Test index object label) point and an associated object / label which requires IO to access . data DataSample (dataPurpose :: DataPurpose) properties object label = DataSample { dataProperties :: properties , dataObject :: IO object , dataLabel :: IO label } dataPurpose :: forall (datap :: DataPurpose) p o l. SingI datap => DataSample datap p o l -> DataPurpose dataPurpose _ = demote @datap setTensorIfGiven_ :: IO (Tensor ty ki sz) -> Maybe (Tensor ty ki sz) -> IO (Tensor ty ki sz) setTensorIfGiven_ f x = do t <- f case x of Nothing -> pure t Just x' -> set_ x' t >> pure x' useTensorIfGiven_ f x = case x of Nothing -> empty >>= f Just t -> f t type DataStream dp index object label = Producer (DataSample dp index object label) IO () mapObjects :: (o -> IO o') -> Pipe (DataSample dp p o l) (DataSample dp p o' l) IO () mapObjects f = forever $ do (DataSample p o l) <- await yield $ DataSample p (o >>= f) l mapLabels :: (l -> IO l') -> Pipe (DataSample dp p o l) (DataSample dp p o l') IO () mapLabels f = forever $ do (DataSample p o l) <- await yield $ DataSample p o (l >>= f) applyTrain :: (DataStream Train index object label -> DataStream Train index' object' label') -> Dataset metadata Train index object label -> Dataset metadata Train index' object' label' applyTrain f d = Dataset { checkDataset = checkDataset d , fetchDataset = (f <$>) <$> fetchDataset d , forceFetchDataset = (f <$>) <$> forceFetchDataset d , accessDataset = (f <$>) <$> accessDataset d , metadataDataset = metadataDataset d } applyTest :: (DataStream Test index object label -> DataStream Test index' object' label') -> Dataset metadata Test index object label -> Dataset metadata Test index' object' label' applyTest f d = Dataset { checkDataset = checkDataset d , fetchDataset = (f <$>) <$> fetchDataset d , forceFetchDataset = (f <$>) <$> forceFetchDataset d , accessDataset = (f <$>) <$> accessDataset d , metadataDataset = metadataDataset d } augmentTrainData :: (object -> IO object') -> Dataset metadata Train index object label -> Dataset metadata Train index object' label augmentTrainData f = applyTrain (\d -> P.for d (\s -> yield $ DataSample { dataProperties = dataProperties s , dataObject = f =<< dataObject s , dataLabel = dataLabel s })) augmentTestData :: (object -> IO object') -> Dataset metadata Test index object label -> Dataset metadata Test index object' label augmentTestData f = applyTest (\d -> P.for d (\s -> yield $ DataSample { dataProperties = dataProperties s , dataObject = f =<< dataObject s , dataLabel = dataLabel s })) augmentTrain :: (index -> index') -> (object -> IO object') -> (label -> IO label') -> Dataset metadata Train index object label -> Dataset metadata Train index' object' label' augmentTrain fi fo fl = applyTrain (\d -> P.for d (\s -> yield $ DataSample { dataProperties = fi $ dataProperties s , dataObject = fo =<< dataObject s , dataLabel = fl =<< dataLabel s })) augmentTest :: (index -> index') -> (object -> IO object') -> (label -> IO label') -> Dataset metadata Test index object label -> Dataset metadata Test index' object' label' augmentTest fi fo fl = applyTest (\d -> P.for d (\s -> yield $ DataSample { dataProperties = fi $ dataProperties s , dataObject = fo =<< dataObject s , dataLabel = fl =<< dataLabel s })) forEachData :: MonadIO m => (a -> IO b) -> Producer a m r -> m r forEachData f stream = runEffect $ for stream (\x -> liftIO (f x >> performMinorGC >> pure ())) forEachDataN :: MonadIO m => (a -> Int -> IO b) -> Producer a m r -> m r forEachDataN f stream = do n <- liftIO $ newIORef (0 :: Int) runEffect $ for stream (\x -> liftIO $ do f x =<< readIORef n modifyIORef' n (+1) performMinorGC pure ()) | Each of the arguments are called with the step number & epoch . forEachDataUntil :: MonadIO m -> m (Int, Int) forEachDataUntil isDone newEpoch perSample initialStream = do step <- liftIO $ newIORef (0 :: Int) epoch <- liftIO $ newIORef (0 :: Int) stream' <- liftIO $ newEpoch 0 0 initialStream let go stream = do n <- next stream s <- liftIO $ readIORef step e <- liftIO $ readIORef epoch b <- liftIO $ isDone s e if not b then case n of Left r -> do stream' <- liftIO $ newEpoch s e initialStream liftIO $ modifyIORef epoch (+ 1) go stream' Right (value, stream') -> do liftIO $ perSample s e value liftIO $ modifyIORef step (+ 1) go stream' else pure () go stream' s <- liftIO $ readIORef step e <- liftIO $ readIORef epoch pure (s,e) foldData :: MonadIO m => (b -> a -> m b) -> b -> Producer a m () -> m b foldData f i stream = P.foldM (\a b -> liftIO performMinorGC >> f a b) (pure i) pure stream lossForEachData :: (TensorConstraints ty ki sz) => (t -> IO (Tensor ty ki sz)) -> Producer t IO () -> IO (Tensor ty ki sz) lossForEachData loss stream = P.foldM (\l d -> do performMinorGC l' <- liftIO $ loss d l `add` l') zeros pure stream lossSum :: (SingI ty, SingI ki , Num (TensorTyToHs ty), Storable (TensorTyToHs ty) , Num (TensorTyToHsC ty), Storable (TensorTyToHsC ty)) => V'.Vector (Scalar ty ki) -> IO (Scalar ty ki) lossSum v = do z <- zeros foldM add z v shuffle :: Int -> Producer a IO r -> Producer a IO r shuffle horizon p = go p S.empty where go p s = do n <- liftIO $ next p case n of Left r -> iterateUntilM S.null randomSeqYield s >> pure r Right (a, p') -> do let s' = a S.<| s if S.length s' < horizon then go p' s' else randomSeqYield s' >>= go p' randomSeqYield :: Seq a -> Pipes.Proxy x' x () a IO (Seq a) randomSeqYield s = do r <- liftIO $ randomElement s case r of (Just (e, s')) -> do yield e pure s' Nothing -> lift mzero batch :: Int -> Bool -> Producer a IO r -> Producer (V'.Vector a) IO r batch batchSize returnPartial p = go p S.empty where go p s = do n <- liftIO $ next p case n of Left r -> do when returnPartial $ yield (V'.fromList $ toList s) pure r Right (a, p') -> do let s' = s S.|> a if S.length s' >= batchSize then yield (V'.fromList $ toList s') >> go p' S.empty else go p' s' batchFn :: Int -> Bool -> Producer a IO r -> (V'.Vector a -> IO b) -> Producer b IO r batchFn batchSize returnPartial p fn = go p S.empty where go p s = do n <- liftIO $ next p case n of Left r -> do when returnPartial $ do y <- liftIO $ fn $ V'.fromList $ toList s yield y pure r Right (a, p') -> do let s' = s S.|> a if S.length s' >= batchSize then do y <- liftIO $ fn $ V'.fromList $ toList s' yield y go p' S.empty else go p' s' batchTensors :: forall batchSize ty ki sz ty' ki' sz' dp p r. (SingI batchSize ,Num (TensorTyToHs ty), Storable (TensorTyToHs ty) ,Num (TensorTyToHs ty'), Storable (TensorTyToHs ty') ,Num (TensorTyToHsC ty), Storable (TensorTyToHsC ty) ,Num (TensorTyToHsC ty'), Storable (TensorTyToHsC ty') ,SingI (InsertIndex sz 0 batchSize) ,SingI ty, SingI ki, SingI sz, SingI sz' ,SingI (InsertIndex sz' 0 batchSize) ,SingI ty', SingI ki') => BatchSize batchSize -> Producer (DataSample dp p (Tensor ty ki sz) (Tensor ty' ki' sz')) IO r -> Producer (DataSample dp (V'.Vector p) (Tensor ty ki (InsertIndex sz 0 batchSize)) (Tensor ty' ki' (InsertIndex sz' 0 batchSize))) IO r batchTensors BatchSize p = batchFn (demoteN @batchSize) False p (\v -> pure $ DataSample (V'.map dataProperties v) (do v <- (V'.mapM dataObject v) s <- stack (groups_ @batchSize) (dimension_ @0) v case s of Nothing -> error "Oddly-sized batch -- this is a bug" Just x -> pure x) (do v <- (V'.mapM dataLabel v) s <- stack (groups_ @batchSize) (dimension_ @0) v case s of Nothing -> error "Oddly-sized batch -- this is a bug" Just x -> pure x)) TODO preload preload : : Int - > Producer ( DataSample dp p o l ) IO r - > Producer ( DataSample dp p o l ) IO r TODO preloadBatch preloadBatches : : Int - > Producer ( Vector ( DataSample dp p o l ) ) IO r - > Producer ( Vector ( DataSample dp p o l ) ) IO r onError :: MonadError e m => m a -> m a -> m a onError f g = f `catchError` const g retryAfter :: MonadError e m => m a -> m a -> m a retryAfter f g = f `catchError` const (g >> f) checkMD5 :: Path -> Text -> CanFail () checkMD5 path md5 = do e <- liftIO $ doesFileExist path if e then do out <- S.shelly $ S.run "md5sum" [path] case T.splitOn " " out of (s:_) -> if s == md5 then pure () else throwError $ "MD5 check failed, got " <#> path <#> s <#> "but expected" <#> md5 _ -> throwError $ "Bad result from md5" <#> out else throwError $ "Missing file" <#> path downloadUrl :: Text -> Path -> CanFail () downloadUrl url dest = do c <- S.shelly $ S.verbosely $ do S.run_ "curl" ["--progress-bar", "-L", url, "--output", dest] S.lastExitCode unless (c == 0) $ throwError $ "Download with curl failed" <#> url <#> dest extractTar :: Path -> Path -> CanFail () extractTar path dest = do e <- liftIO $ doesFileExist path unless e $ throwError $ "Can't extract, tar file doesn't exist" <#> path c <- S.shelly $ S.verbosely $ do S.run_ "tar" ["xvf", path, "-C", dest] S.lastExitCode unless (c == 0) $ throwError $ "Extracting tar file failed" <#> path extractGzip :: Path -> CanFail () extractGzip path = do e <- liftIO $ doesFileExist path unless e $ throwError $ "Can't extract, gzip file doesn't exist" <#> path c <- S.shelly $ S.verbosely $ do S.run_ "gunzip" [path] S.lastExitCode unless (c == 0) $ throwError $ "gunzip failed" <#> path downloadAndVerifyFile :: Text -> Text -> Text -> Text -> IO (Either Text ()) downloadAndVerifyFile url filename dir md5 = canFail $ do liftIO $ createDirectoryIfMissing' dir checkMD5 (dir </> filename) md5 `retryAfter` downloadUrl url (dir </> filename) getCachedFileOrDownload :: Text -> Text -> Text -> Text -> IO Text getCachedFileOrDownload url md5 filename subtype = do location <- T.pack <$> P.getXdgDirectory P.XdgCache ("haskell-torch/" <> T.unpack subtype) let path = location </> filename e <- doesFileExist path if e then pure $ location </> filename else do r <- downloadAndVerifyFile url filename location md5 case r of Left err -> do f <- canFail (checkMD5 path md5) case f of Left e -> do P.removeFile $ T.unpack path _ -> pure () error $ T.unpack err Right _ -> pure $ location </> filename pipeMatfilesReadOnly :: [Text] -> Producer (ForeignPtr CMat) IO () pipeMatfilesReadOnly fs = mapM_ (\f -> do liftIO $ print $ "Reading " ++ show f mf <- liftIO $ M.openReadOnly f yield mf) fs pipeListDirectory :: Text -> Producer Text IO () pipeListDirectory path = do l <- liftIO $ listDirectory path mapM_ (yield . (path </>)) l
68df333a74605003d1612d73959d03b5575eb1af2c28c4ef743fb52dfa70accc
ofmooseandmen/jord
LengthSpec.hs
module Data.Geo.Jord.LengthSpec ( spec ) where import Test.Hspec import qualified Data.Geo.Jord.Length as Length spec :: Spec spec = do describe "Reading valid lengths" $ do it "reads -15.2m" $ Length.read "-15.2m" `shouldBe` Just (Length.metres (-15.2)) it "reads 154km" $ Length.read "154km" `shouldBe` Just (Length.kilometres 154) it "reads 1000nm" $ Length.read "1000nm" `shouldBe` Just (Length.nauticalMiles 1000) it "reads 25000ft" $ Length.read "25000ft" `shouldBe` Just (Length.feet 25000) describe "Reading invalid lengths" $ do it "fails to read 5" $ Length.read "5" `shouldBe` Nothing it "fails to read 5nmi" $ Length.read "5nmi" `shouldBe` Nothing describe "Showing lengths" $ do it "shows length in Length.metres when <= 10000 m" $ show (Length.metres 5) `shouldBe` "5.0m" it "shows length in Length.kilometres when > 10000 m" $ show (Length.kilometres 1000) `shouldBe` "1000.0km" describe "Converting lengths" $ do it "converts Length.metres to Length.kilometres" $ Length.toKilometres (Length.metres 1000) `shouldBe` 1.0 it "converts Length.metres to nautical miles" $ Length.toNauticalMiles (Length.metres 1000) `shouldBe` 0.5399568034557235 it "converts Length.kilometres to nautical miles" $ Length.toNauticalMiles (Length.kilometres 1000) `shouldBe` 539.9568034557235 it "converts nautical miles to Length.metres" $ Length.toMetres (Length.nauticalMiles 10.5) `shouldBe` 19446 it "converts nautical miles to Length.kilometres" $ Length.toKilometres (Length.nauticalMiles 10.5) `shouldBe` 19.446 it "converts Length.feet to Length.metres" $ Length.toMetres (Length.feet 25000) `shouldBe` 7620 it "converts Length.metres to Length.feet" $ Length.toFeet (Length.metres 7620) `shouldBe` 25000 describe "Resolution" $ do it "handles 1 kilometre" $ Length.toKilometres (Length.kilometres 1) `shouldBe` 1 it "handles 1 metre" $ Length.toMetres (Length.metres 1) `shouldBe` 1 it "handles 1 nautical mile" $ Length.toNauticalMiles (Length.nauticalMiles 1) `shouldBe` 1 it "handles 1 foot" $ Length.toFeet (Length.feet 1) `shouldBe` 1 describe "Adding/Subtracting lengths" $ do it "adds lengths" $ Length.add (Length.kilometres 1000) (Length.metres 1000) `shouldBe` Length.metres 1001000 it "subtracts lengths" $ Length.subtract (Length.metres 1000) (Length.nauticalMiles 10.5) `shouldBe` Length.metres (-18446)
null
https://raw.githubusercontent.com/ofmooseandmen/jord/9acd8d9aec817ce05de6ed1d78e025437e1193bf/test/Data/Geo/Jord/LengthSpec.hs
haskell
module Data.Geo.Jord.LengthSpec ( spec ) where import Test.Hspec import qualified Data.Geo.Jord.Length as Length spec :: Spec spec = do describe "Reading valid lengths" $ do it "reads -15.2m" $ Length.read "-15.2m" `shouldBe` Just (Length.metres (-15.2)) it "reads 154km" $ Length.read "154km" `shouldBe` Just (Length.kilometres 154) it "reads 1000nm" $ Length.read "1000nm" `shouldBe` Just (Length.nauticalMiles 1000) it "reads 25000ft" $ Length.read "25000ft" `shouldBe` Just (Length.feet 25000) describe "Reading invalid lengths" $ do it "fails to read 5" $ Length.read "5" `shouldBe` Nothing it "fails to read 5nmi" $ Length.read "5nmi" `shouldBe` Nothing describe "Showing lengths" $ do it "shows length in Length.metres when <= 10000 m" $ show (Length.metres 5) `shouldBe` "5.0m" it "shows length in Length.kilometres when > 10000 m" $ show (Length.kilometres 1000) `shouldBe` "1000.0km" describe "Converting lengths" $ do it "converts Length.metres to Length.kilometres" $ Length.toKilometres (Length.metres 1000) `shouldBe` 1.0 it "converts Length.metres to nautical miles" $ Length.toNauticalMiles (Length.metres 1000) `shouldBe` 0.5399568034557235 it "converts Length.kilometres to nautical miles" $ Length.toNauticalMiles (Length.kilometres 1000) `shouldBe` 539.9568034557235 it "converts nautical miles to Length.metres" $ Length.toMetres (Length.nauticalMiles 10.5) `shouldBe` 19446 it "converts nautical miles to Length.kilometres" $ Length.toKilometres (Length.nauticalMiles 10.5) `shouldBe` 19.446 it "converts Length.feet to Length.metres" $ Length.toMetres (Length.feet 25000) `shouldBe` 7620 it "converts Length.metres to Length.feet" $ Length.toFeet (Length.metres 7620) `shouldBe` 25000 describe "Resolution" $ do it "handles 1 kilometre" $ Length.toKilometres (Length.kilometres 1) `shouldBe` 1 it "handles 1 metre" $ Length.toMetres (Length.metres 1) `shouldBe` 1 it "handles 1 nautical mile" $ Length.toNauticalMiles (Length.nauticalMiles 1) `shouldBe` 1 it "handles 1 foot" $ Length.toFeet (Length.feet 1) `shouldBe` 1 describe "Adding/Subtracting lengths" $ do it "adds lengths" $ Length.add (Length.kilometres 1000) (Length.metres 1000) `shouldBe` Length.metres 1001000 it "subtracts lengths" $ Length.subtract (Length.metres 1000) (Length.nauticalMiles 10.5) `shouldBe` Length.metres (-18446)
6e0e0d716f1e8f07893a2a403fb77e363d1acc875a370d5a446c522e9da38603
ekmett/gl
Registry.hs
# OPTIONS_GHC -Wall # ----------------------------------------------------------------------------- -- | Copyright : ( C ) 2014 and -- License : BSD-style (see the file LICENSE) Maintainer : < > -- Stability : experimental -- Portability : portable -- ---------------------------------------------------------------------------- module Registry ( Registry(..) , Command(..) , Parameter(..) , Enumeratee(..) , Extension(..) , Feature(..) , Group(..) , Remove(..) , Require(..) , Type(..) , lookupCommand , lookupEnum , deshenaniganize ) where import Data.Functor import Prelude data Registry = Registry { registryCommands :: [Command] , registryEnums :: [Enumeratee] , registryExtensions :: [Extension] , registryFeatures :: [Feature] , registryGroups :: [Group] } deriving (Eq, Show) data Parameter = Parameter { parameterName :: String , parameterType :: Type , parameterGroup :: Maybe String , parameterLen :: Maybe String } deriving (Eq, Show) data Command = Command { commandName :: String , commandType :: Type , commandParameters :: [Parameter] , commandVectorEquivalent :: Maybe String , commandAlias :: Maybe String } deriving (Eq, Show) data Enumeratee = Enumeratee { enumName :: String , enumValue :: String } deriving (Eq, Show) data Extension = Extension { extensionName :: String , extensionPlatform :: String , extensionRequires :: [Require] } deriving (Eq, Show) data Feature = Feature { featureName :: String , featureRequires :: [Require] , featureRemoves :: [Remove] } deriving (Eq, Show) data Group = Group { groupName :: String , groupEnum :: [String] } deriving (Eq, Show) data Remove = Remove { removeProfile :: String , removeComment :: String , removeEnums :: [String] , removeCommands :: [String] } deriving (Eq, Show) data Require = Require { requireEnums :: [String] , requireCommands :: [String] , requireComment :: String , requireProfile :: String } deriving (Eq, Show) data Type = Type { typeName :: Maybe String , typePointer :: Int } deriving (Eq, Show) lookupCommand :: Registry -> String -> Command lookupCommand registry command = head . filter ((== command) . commandName) $ registryCommands registry lookupEnum :: Registry -> String -> Enumeratee lookupEnum registry enum = head . filter ((== enum) . enumName) $ registryEnums registry -- | Resolve shenanigans in the OpenGL Registry deshenaniganize :: Registry -> Registry deshenaniganize registry = registry { registryFeatures = cleanFeature "GL_VERSION_3_1" clean31require . cleanFeature "GL_VERSION_4_4" clean44require . cleanFeature "GL_VERSION_4_5" clean45require . cleanFeature "GL_ES_VERSION_3_2" cleanES32require <$> registryFeatures registry , registryCommands = cleanCommand <$> registryCommands registry , registryExtensions = cleanExtensions <$> registryExtensions registry } cleanCommand :: Command -> Command cleanCommand cmd = cmd { commandParameters = cleanParameter <$> commandParameters cmd } cleanExtensions :: Extension -> Extension cleanExtensions ext | extensionName ext == "GL_EXT_multisampled_compatibility" = ext { extensionName = "GL_EXT_multisample_compatibility" } | otherwise = ext cleanParameter :: Parameter -> Parameter cleanParameter param | parameterName param == "baseAndCount" = param { parameterType = (parameterType param) { typePointer = 1 }} | otherwise = param { parameterGroup = cleanParameterGroup <$> parameterGroup param } cleanParameterGroup :: String -> String cleanParameterGroup "PixelInternalFormat" = "InternalFormat" cleanParameterGroup "SGIXFfdMask" = "FfdMaskSGIX" cleanParameterGroup xs = xs cleanFeature :: String -> (Require -> Require) -> Feature -> Feature cleanFeature name f feature | featureName feature == name = feature { featureRequires = f <$> featureRequires feature } | otherwise = feature clean31require :: Require -> Require clean31require require = require { requireCommands = filter (`notElem` removed) $ requireCommands require , requireEnums = "GL_BLEND_COLOR" : requireEnums require } where removed = [ "glBindBufferBase" , "glBindBufferRange" , "glGetIntegeri_v" ] clean44require :: Require -> Require clean44require require = require { requireEnums = filter (`notElem` removed) $ requireEnums require } where removed = [ "GL_MAP_READ_BIT" , "GL_MAP_WRITE_BIT" , "GL_STENCIL_INDEX" , "GL_STENCIL_INDEX8" , "GL_TRANSFORM_FEEDBACK_BUFFER" , "GL_UNSIGNED_INT_10F_11F_11F_REV" ] clean45require :: Require -> Require clean45require require = require { requireEnums = filter (`notElem` removed) $ requireEnums require } where removed = [ "GL_BACK" , "GL_LOWER_LEFT" , "GL_NONE" , "GL_NO_ERROR" , "GL_TEXTURE_BINDING_1D" , "GL_TEXTURE_BINDING_1D_ARRAY" , "GL_TEXTURE_BINDING_2D" , "GL_TEXTURE_BINDING_2D_ARRAY" , "GL_TEXTURE_BINDING_2D_MULTISAMPLE" , "GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY" , "GL_TEXTURE_BINDING_3D" , "GL_TEXTURE_BINDING_BUFFER" , "GL_TEXTURE_BINDING_CUBE_MAP" , "GL_TEXTURE_BINDING_CUBE_MAP_ARRAY" , "GL_TEXTURE_BINDING_RECTANGLE" , "GL_UPPER_LEFT" ] cleanES32require :: Require -> Require cleanES32require require = require { requireEnums = filter (`notElem` removed) $ requireEnums require } where removed = [ "GL_CCW" , "GL_CW" , "GL_EQUAL" , "GL_NO_ERROR" , "GL_STENCIL_INDEX" , "GL_STENCIL_INDEX8" , "GL_TRIANGLES" ]
null
https://raw.githubusercontent.com/ekmett/gl/1488e8dce368279d39b269b5ae5dda86ba10eb2d/src/Registry.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style (see the file LICENSE) Stability : experimental Portability : portable -------------------------------------------------------------------------- | Resolve shenanigans in the OpenGL Registry
# OPTIONS_GHC -Wall # Copyright : ( C ) 2014 and Maintainer : < > module Registry ( Registry(..) , Command(..) , Parameter(..) , Enumeratee(..) , Extension(..) , Feature(..) , Group(..) , Remove(..) , Require(..) , Type(..) , lookupCommand , lookupEnum , deshenaniganize ) where import Data.Functor import Prelude data Registry = Registry { registryCommands :: [Command] , registryEnums :: [Enumeratee] , registryExtensions :: [Extension] , registryFeatures :: [Feature] , registryGroups :: [Group] } deriving (Eq, Show) data Parameter = Parameter { parameterName :: String , parameterType :: Type , parameterGroup :: Maybe String , parameterLen :: Maybe String } deriving (Eq, Show) data Command = Command { commandName :: String , commandType :: Type , commandParameters :: [Parameter] , commandVectorEquivalent :: Maybe String , commandAlias :: Maybe String } deriving (Eq, Show) data Enumeratee = Enumeratee { enumName :: String , enumValue :: String } deriving (Eq, Show) data Extension = Extension { extensionName :: String , extensionPlatform :: String , extensionRequires :: [Require] } deriving (Eq, Show) data Feature = Feature { featureName :: String , featureRequires :: [Require] , featureRemoves :: [Remove] } deriving (Eq, Show) data Group = Group { groupName :: String , groupEnum :: [String] } deriving (Eq, Show) data Remove = Remove { removeProfile :: String , removeComment :: String , removeEnums :: [String] , removeCommands :: [String] } deriving (Eq, Show) data Require = Require { requireEnums :: [String] , requireCommands :: [String] , requireComment :: String , requireProfile :: String } deriving (Eq, Show) data Type = Type { typeName :: Maybe String , typePointer :: Int } deriving (Eq, Show) lookupCommand :: Registry -> String -> Command lookupCommand registry command = head . filter ((== command) . commandName) $ registryCommands registry lookupEnum :: Registry -> String -> Enumeratee lookupEnum registry enum = head . filter ((== enum) . enumName) $ registryEnums registry deshenaniganize :: Registry -> Registry deshenaniganize registry = registry { registryFeatures = cleanFeature "GL_VERSION_3_1" clean31require . cleanFeature "GL_VERSION_4_4" clean44require . cleanFeature "GL_VERSION_4_5" clean45require . cleanFeature "GL_ES_VERSION_3_2" cleanES32require <$> registryFeatures registry , registryCommands = cleanCommand <$> registryCommands registry , registryExtensions = cleanExtensions <$> registryExtensions registry } cleanCommand :: Command -> Command cleanCommand cmd = cmd { commandParameters = cleanParameter <$> commandParameters cmd } cleanExtensions :: Extension -> Extension cleanExtensions ext | extensionName ext == "GL_EXT_multisampled_compatibility" = ext { extensionName = "GL_EXT_multisample_compatibility" } | otherwise = ext cleanParameter :: Parameter -> Parameter cleanParameter param | parameterName param == "baseAndCount" = param { parameterType = (parameterType param) { typePointer = 1 }} | otherwise = param { parameterGroup = cleanParameterGroup <$> parameterGroup param } cleanParameterGroup :: String -> String cleanParameterGroup "PixelInternalFormat" = "InternalFormat" cleanParameterGroup "SGIXFfdMask" = "FfdMaskSGIX" cleanParameterGroup xs = xs cleanFeature :: String -> (Require -> Require) -> Feature -> Feature cleanFeature name f feature | featureName feature == name = feature { featureRequires = f <$> featureRequires feature } | otherwise = feature clean31require :: Require -> Require clean31require require = require { requireCommands = filter (`notElem` removed) $ requireCommands require , requireEnums = "GL_BLEND_COLOR" : requireEnums require } where removed = [ "glBindBufferBase" , "glBindBufferRange" , "glGetIntegeri_v" ] clean44require :: Require -> Require clean44require require = require { requireEnums = filter (`notElem` removed) $ requireEnums require } where removed = [ "GL_MAP_READ_BIT" , "GL_MAP_WRITE_BIT" , "GL_STENCIL_INDEX" , "GL_STENCIL_INDEX8" , "GL_TRANSFORM_FEEDBACK_BUFFER" , "GL_UNSIGNED_INT_10F_11F_11F_REV" ] clean45require :: Require -> Require clean45require require = require { requireEnums = filter (`notElem` removed) $ requireEnums require } where removed = [ "GL_BACK" , "GL_LOWER_LEFT" , "GL_NONE" , "GL_NO_ERROR" , "GL_TEXTURE_BINDING_1D" , "GL_TEXTURE_BINDING_1D_ARRAY" , "GL_TEXTURE_BINDING_2D" , "GL_TEXTURE_BINDING_2D_ARRAY" , "GL_TEXTURE_BINDING_2D_MULTISAMPLE" , "GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY" , "GL_TEXTURE_BINDING_3D" , "GL_TEXTURE_BINDING_BUFFER" , "GL_TEXTURE_BINDING_CUBE_MAP" , "GL_TEXTURE_BINDING_CUBE_MAP_ARRAY" , "GL_TEXTURE_BINDING_RECTANGLE" , "GL_UPPER_LEFT" ] cleanES32require :: Require -> Require cleanES32require require = require { requireEnums = filter (`notElem` removed) $ requireEnums require } where removed = [ "GL_CCW" , "GL_CW" , "GL_EQUAL" , "GL_NO_ERROR" , "GL_STENCIL_INDEX" , "GL_STENCIL_INDEX8" , "GL_TRIANGLES" ]
6dc2fc173552a2cb94c5968206fe6c43aa8a1bb17d329b019b6b9913ae0eb653
ThoughtWorksInc/stonecutter
middleware.clj
(ns stonecutter.middleware (:require [clojure.tools.logging :as log] [ring.util.response :as r] [ring.middleware.file :as ring-mf] [stonecutter.translation :as translation] [stonecutter.routes :as routes] [stonecutter.controller.user :as user] [stonecutter.helper :as helper] [stonecutter.config :as config] [stonecutter.controller.common :as common])) (defn wrap-error-handling [handler err-handler dev-mode?] (if-not dev-mode? (fn [request] (try (handler request) (catch Exception e (log/error e e) (err-handler request)))) handler)) (defn wrap-handle-403 [handler error-403-handler] (fn [request] (let [response (handler request)] (if (= (:status response) 403) (error-403-handler request) response)))) (defn wrap-config [handler config-m] (fn [request] (-> request (assoc-in [:context :config-m] config-m) handler))) (defn wrap-handlers-except [handlers wrap-function exclusions] (into {} (for [[k v] handlers] [k (if (k exclusions) v (wrap-function v))]))) (defn wrap-disable-caching [handler] (fn [request] (-> request handler helper/disable-caching))) (defn wrap-signed-in [handler] (fn [request] (if (common/signed-in? request) (handler request) (r/redirect (routes/path :index))))) (defn wrap-custom-static-resources [handler config-m] (if-let [static-resources-dir-path (config/static-resources-dir-path config-m)] (do (log/info (str "All resources in " static-resources-dir-path " are now being served as static resources")) (ring-mf/wrap-file handler static-resources-dir-path)) handler)) (defn wrap-just-these-handlers [handlers-m wrap-function inclusions] (into {} (for [[k v] handlers-m] [k (if (k inclusions) (wrap-function v) v)]))) (defn wrap-authorised [handler authorisation-checker] (fn [request] (when (authorisation-checker request) (handler request))))
null
https://raw.githubusercontent.com/ThoughtWorksInc/stonecutter/37ed22dd276ac652176c4d880e0f1b0c1e27abfe/src/stonecutter/middleware.clj
clojure
(ns stonecutter.middleware (:require [clojure.tools.logging :as log] [ring.util.response :as r] [ring.middleware.file :as ring-mf] [stonecutter.translation :as translation] [stonecutter.routes :as routes] [stonecutter.controller.user :as user] [stonecutter.helper :as helper] [stonecutter.config :as config] [stonecutter.controller.common :as common])) (defn wrap-error-handling [handler err-handler dev-mode?] (if-not dev-mode? (fn [request] (try (handler request) (catch Exception e (log/error e e) (err-handler request)))) handler)) (defn wrap-handle-403 [handler error-403-handler] (fn [request] (let [response (handler request)] (if (= (:status response) 403) (error-403-handler request) response)))) (defn wrap-config [handler config-m] (fn [request] (-> request (assoc-in [:context :config-m] config-m) handler))) (defn wrap-handlers-except [handlers wrap-function exclusions] (into {} (for [[k v] handlers] [k (if (k exclusions) v (wrap-function v))]))) (defn wrap-disable-caching [handler] (fn [request] (-> request handler helper/disable-caching))) (defn wrap-signed-in [handler] (fn [request] (if (common/signed-in? request) (handler request) (r/redirect (routes/path :index))))) (defn wrap-custom-static-resources [handler config-m] (if-let [static-resources-dir-path (config/static-resources-dir-path config-m)] (do (log/info (str "All resources in " static-resources-dir-path " are now being served as static resources")) (ring-mf/wrap-file handler static-resources-dir-path)) handler)) (defn wrap-just-these-handlers [handlers-m wrap-function inclusions] (into {} (for [[k v] handlers-m] [k (if (k inclusions) (wrap-function v) v)]))) (defn wrap-authorised [handler authorisation-checker] (fn [request] (when (authorisation-checker request) (handler request))))
0683abafb41b3d3db2fba98829570b90d30b46f77586140addb5c0bd928d0d46
lem-project/lem
input.lisp
(in-package :lem-capi) (defun shift-bit-p (modifiers) (/= 0 (logand modifiers sys:gesture-spec-shift-bit))) (defun control-bit-p (modifiers) (/= 0 (logand modifiers sys:gesture-spec-control-bit))) (defun meta-bit-p (modifiers) (/= 0 (logand modifiers sys:gesture-spec-meta-bit))) (defparameter *data-sym-table* (alexandria:alist-hash-table `((,(char-code #\Return) . "Return") (,(char-code #\Tab) . "Tab") (,(char-code #\Escape) . "Escape") (,(char-code #\Backspace) . "Backspace") (,(char-code #\Space) . "Space") (:next . "PageDown") (:prior . "PageUp")))) (defparameter *keyboard-table* (alexandria:plist-hash-table (list #\1 #\! #\2 #\" #\3 #\# #\4 #\$ #\5 #\% #\6 #\& #\7 #\' #\8 #\( #\9 #\) #\- #\= #\^ #\~ #\\ #\_ #\@ #\` #\[ #\{ #\; #\+ #\: #\* #\] #\} #\, #\< #\. #\> #\/ #\? #\\ #\_))) (defun convert-gesture-spec-data (data shiftp) (cond ((not shiftp) (values data nil)) ((alpha-char-p (code-char data)) (values (char-upcase (code-char data)) nil)) (t (multiple-value-bind (value success) (gethash (code-char data) *keyboard-table*) (if success (values value nil) (values data shiftp)))))) (defun gesture-spec-to-key-for-windows (gesture-spec) (when (sys:gesture-spec-p gesture-spec) (let* ((data (sys:gesture-spec-data gesture-spec)) (modifiers (sys:gesture-spec-modifiers gesture-spec)) (shiftp (shift-bit-p modifiers)) (ctrlp (control-bit-p modifiers)) (metap (meta-bit-p modifiers))) (multiple-value-bind (data shiftp) (convert-gesture-spec-data data shiftp) (let ((sym (or (gethash data *data-sym-table*) (typecase data (string data) (keyword (string-capitalize data)) (integer (string (code-char data))) (character (string data)))))) (when sym (cond ((and (not metap) ctrlp (not shiftp) (string= sym "i")) (lem:make-key :sym "Tab")) (t (lem:make-key :meta metap :ctrl ctrlp :shift shiftp :sym sym))))))))) (defun gesture-spec-to-key-for-linux (gesture-spec) (when (sys:gesture-spec-p gesture-spec) (let* ((data (sys:gesture-spec-data gesture-spec)) (modifiers (sys:gesture-spec-modifiers gesture-spec)) (shiftp (shift-bit-p modifiers)) (ctrlp (control-bit-p modifiers)) (metap (meta-bit-p modifiers)) (sym (or (gethash data *data-sym-table*) (typecase data (string data) (keyword (string-capitalize data)) (integer (string (code-char data))))))) (when sym (cond ((and (not metap) ctrlp (not shiftp) (string= sym "i")) (lem:make-key :sym "Tab")) (t (lem:make-key :meta metap :ctrl ctrlp :shift shiftp :sym sym))))))) (defun gesture-spec-to-key (gesture-spec) #+windows (gesture-spec-to-key-for-windows gesture-spec) #-windows (gesture-spec-to-key-for-linux gesture-spec))
null
https://raw.githubusercontent.com/lem-project/lem/4f620f94a1fd3bdfb8b2364185e7db16efab57a1/frontends/capi/input.lisp
lisp
#\+
(in-package :lem-capi) (defun shift-bit-p (modifiers) (/= 0 (logand modifiers sys:gesture-spec-shift-bit))) (defun control-bit-p (modifiers) (/= 0 (logand modifiers sys:gesture-spec-control-bit))) (defun meta-bit-p (modifiers) (/= 0 (logand modifiers sys:gesture-spec-meta-bit))) (defparameter *data-sym-table* (alexandria:alist-hash-table `((,(char-code #\Return) . "Return") (,(char-code #\Tab) . "Tab") (,(char-code #\Escape) . "Escape") (,(char-code #\Backspace) . "Backspace") (,(char-code #\Space) . "Space") (:next . "PageDown") (:prior . "PageUp")))) (defparameter *keyboard-table* (alexandria:plist-hash-table (list #\1 #\! #\2 #\" #\3 #\# #\4 #\$ #\5 #\% #\6 #\& #\7 #\' #\8 #\( #\9 #\) #\- #\= #\^ #\~ #\\ #\_ #\@ #\` #\[ #\{ #\: #\* #\] #\} #\, #\< #\. #\> #\/ #\? #\\ #\_))) (defun convert-gesture-spec-data (data shiftp) (cond ((not shiftp) (values data nil)) ((alpha-char-p (code-char data)) (values (char-upcase (code-char data)) nil)) (t (multiple-value-bind (value success) (gethash (code-char data) *keyboard-table*) (if success (values value nil) (values data shiftp)))))) (defun gesture-spec-to-key-for-windows (gesture-spec) (when (sys:gesture-spec-p gesture-spec) (let* ((data (sys:gesture-spec-data gesture-spec)) (modifiers (sys:gesture-spec-modifiers gesture-spec)) (shiftp (shift-bit-p modifiers)) (ctrlp (control-bit-p modifiers)) (metap (meta-bit-p modifiers))) (multiple-value-bind (data shiftp) (convert-gesture-spec-data data shiftp) (let ((sym (or (gethash data *data-sym-table*) (typecase data (string data) (keyword (string-capitalize data)) (integer (string (code-char data))) (character (string data)))))) (when sym (cond ((and (not metap) ctrlp (not shiftp) (string= sym "i")) (lem:make-key :sym "Tab")) (t (lem:make-key :meta metap :ctrl ctrlp :shift shiftp :sym sym))))))))) (defun gesture-spec-to-key-for-linux (gesture-spec) (when (sys:gesture-spec-p gesture-spec) (let* ((data (sys:gesture-spec-data gesture-spec)) (modifiers (sys:gesture-spec-modifiers gesture-spec)) (shiftp (shift-bit-p modifiers)) (ctrlp (control-bit-p modifiers)) (metap (meta-bit-p modifiers)) (sym (or (gethash data *data-sym-table*) (typecase data (string data) (keyword (string-capitalize data)) (integer (string (code-char data))))))) (when sym (cond ((and (not metap) ctrlp (not shiftp) (string= sym "i")) (lem:make-key :sym "Tab")) (t (lem:make-key :meta metap :ctrl ctrlp :shift shiftp :sym sym))))))) (defun gesture-spec-to-key (gesture-spec) #+windows (gesture-spec-to-key-for-windows gesture-spec) #-windows (gesture-spec-to-key-for-linux gesture-spec))
d66e5b7a720e9ff3c4bb95a4f4bcfc553a9b2437b0fd1142352ffec93b427793
ocaml-gospel/gospel
HashTable.mli
(**************************************************************************) (* *) VOCaL -- A Verified OCaml Library (* *) Copyright ( c ) 2020 The VOCaL Project (* *) This software is free software , distributed under the MIT license (* (as described in file LICENSE enclosed). *) (**************************************************************************) module type HashedType = sig type t (*@ predicate equiv (x: t) (y: t) *) (*@ axiom refl : forall x: t. equiv x x *) @ axiom sym : forall x y : y - > equiv y x @ axiom trans : forall x y z : y - > equiv y z - > equiv x z val equal : t -> t -> bool (*@ b = equal x y ensures b <-> equiv x y *) (*@ function hash_f (x: t) : integer *) @ axiom compatibility : forall x y : y - > hash_f x = hash_f y val hash : t -> int (*@ h = hash x ensures h = hash_f x *) end module Make (K : HashedType) : sig type key = K.t type 'a table (*@ ephemeral mutable model dom : key set mutable model view: key -> 'a list with self invariant forall x y: key. Set.mem x self.dom -> Set.mem y self.dom -> K.equiv x y -> x = y invariant forall k: key. not (Set.mem k self.dom) -> self.view k = [] *) type 'a t = 'a table val create : int -> 'a t @ h = create n requires n > = 0 ensures forall k : key . h.view k = [ ] requires n >= 0 ensures forall k: key. h.view k = [] *) val clear : 'a t -> unit @ clear h modifies h ensures forall k : key . h.view k = [ ] modifies h ensures forall k: key. h.view k = [] *) val reset : 'a t -> unit @ reset h modifies h ensures forall k : key . h.view k = [ ] modifies h ensures forall k: key. h.view k = [] *) val copy : 'a t -> 'a t (*@ h2 = copy h1 ensures forall k: key. h2.view k = h1.view k *) (*@ function pop (h: 'a t) : integer = Set.fold (fun k c -> List.length (h.view k) + c) h.dom 0 *) val population : 'a t -> int @ n = population h ensures n = pop h ensures n = pop h *) val length : 'a t -> int (*@ n = length h ensures n = pop h *) val iter : (key -> 'a -> unit) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b type statistics = { num_bindings : int; num_buckets : int; max_bucket_length : int; bucket_histogram : int array; } val stats : 'a t -> statistics val add : 'a t -> key -> 'a -> unit @ add h k v modifies h ensures forall k ' : key . h.view k = if K.equiv k ' k then v : : old ( h.view k ' ) else old ( h.view k ' ) modifies h ensures forall k': key. h.view k = if K.equiv k' k then v :: old (h.view k') else old (h.view k') *) (*@ function tail (l: 'a list) : 'a list = match l with [] -> [] | _ :: s -> s*) val remove : 'a t -> key -> unit @ remove h k modifies h ensures forall k ' : key . h.view k = if K.equiv k ' k then tail ( old ( h.view k ' ) ) else old ( h.view k ' ) modifies h ensures forall k': key. h.view k = if K.equiv k' k then tail (old (h.view k')) else old (h.view k') *) val find : 'a t -> key -> 'a option @ r = find h k ensures r = match h.view k with [ ] - > None | x : : _ - > Some x ensures r = match h.view k with [] -> None | x :: _ -> Some x*) val find_all : 'a t -> key -> 'a list (*@ l = find_all h k ensures l = h.view k *) val replace : 'a t -> key -> 'a -> unit @ replace h k v modifies h ensures forall k ' : key . h.view k = if K.equiv k ' k then v : : tail ( old ( h.view k ) ) else old ( h.view k ' ) modifies h ensures forall k': key. h.view k = if K.equiv k' k then v :: tail (old (h.view k)) else old (h.view k') *) val mem : 'a t -> key -> bool @ b = mem h k ensures b < - > h.view k < > [ ] ensures b <-> h.view k <> [] *) end (* {gospel_expected| [0] OK |gospel_expected} *)
null
https://raw.githubusercontent.com/ocaml-gospel/gospel/bd213d7fdfaf224666acb413efc49f872251bca7/test/vocal/HashTable.mli
ocaml
************************************************************************ (as described in file LICENSE enclosed). ************************************************************************ @ predicate equiv (x: t) (y: t) @ axiom refl : forall x: t. equiv x x @ b = equal x y ensures b <-> equiv x y @ function hash_f (x: t) : integer @ h = hash x ensures h = hash_f x @ ephemeral mutable model dom : key set mutable model view: key -> 'a list with self invariant forall x y: key. Set.mem x self.dom -> Set.mem y self.dom -> K.equiv x y -> x = y invariant forall k: key. not (Set.mem k self.dom) -> self.view k = [] @ h2 = copy h1 ensures forall k: key. h2.view k = h1.view k @ function pop (h: 'a t) : integer = Set.fold (fun k c -> List.length (h.view k) + c) h.dom 0 @ n = length h ensures n = pop h @ function tail (l: 'a list) : 'a list = match l with [] -> [] | _ :: s -> s @ l = find_all h k ensures l = h.view k {gospel_expected| [0] OK |gospel_expected}
VOCaL -- A Verified OCaml Library Copyright ( c ) 2020 The VOCaL Project This software is free software , distributed under the MIT license module type HashedType = sig type t @ axiom sym : forall x y : y - > equiv y x @ axiom trans : forall x y z : y - > equiv y z - > equiv x z val equal : t -> t -> bool @ axiom compatibility : forall x y : y - > hash_f x = hash_f y val hash : t -> int end module Make (K : HashedType) : sig type key = K.t type 'a table type 'a t = 'a table val create : int -> 'a t @ h = create n requires n > = 0 ensures forall k : key . h.view k = [ ] requires n >= 0 ensures forall k: key. h.view k = [] *) val clear : 'a t -> unit @ clear h modifies h ensures forall k : key . h.view k = [ ] modifies h ensures forall k: key. h.view k = [] *) val reset : 'a t -> unit @ reset h modifies h ensures forall k : key . h.view k = [ ] modifies h ensures forall k: key. h.view k = [] *) val copy : 'a t -> 'a t val population : 'a t -> int @ n = population h ensures n = pop h ensures n = pop h *) val length : 'a t -> int val iter : (key -> 'a -> unit) -> 'a t -> unit val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b type statistics = { num_bindings : int; num_buckets : int; max_bucket_length : int; bucket_histogram : int array; } val stats : 'a t -> statistics val add : 'a t -> key -> 'a -> unit @ add h k v modifies h ensures forall k ' : key . h.view k = if K.equiv k ' k then v : : old ( h.view k ' ) else old ( h.view k ' ) modifies h ensures forall k': key. h.view k = if K.equiv k' k then v :: old (h.view k') else old (h.view k') *) val remove : 'a t -> key -> unit @ remove h k modifies h ensures forall k ' : key . h.view k = if K.equiv k ' k then tail ( old ( h.view k ' ) ) else old ( h.view k ' ) modifies h ensures forall k': key. h.view k = if K.equiv k' k then tail (old (h.view k')) else old (h.view k') *) val find : 'a t -> key -> 'a option @ r = find h k ensures r = match h.view k with [ ] - > None | x : : _ - > Some x ensures r = match h.view k with [] -> None | x :: _ -> Some x*) val find_all : 'a t -> key -> 'a list val replace : 'a t -> key -> 'a -> unit @ replace h k v modifies h ensures forall k ' : key . h.view k = if K.equiv k ' k then v : : tail ( old ( h.view k ) ) else old ( h.view k ' ) modifies h ensures forall k': key. h.view k = if K.equiv k' k then v :: tail (old (h.view k)) else old (h.view k') *) val mem : 'a t -> key -> bool @ b = mem h k ensures b < - > h.view k < > [ ] ensures b <-> h.view k <> [] *) end
06b68736d95c1c3d28a64e01a1d9efbc7e222fc0f59db931877ab3a97cafd65b
oklm-wsh/MrMime
input.ml
include RingBuffer.Committed type st = Internal_buffer.st = St type bs = Internal_buffer.bs = Bs
null
https://raw.githubusercontent.com/oklm-wsh/MrMime/4d2a9dc75905927a092c0424cff7462e2b26bb96/lib/input.ml
ocaml
include RingBuffer.Committed type st = Internal_buffer.st = St type bs = Internal_buffer.bs = Bs
44041586c8dd9f6416c7d62ec612e192a634c4f92d868fda10bf26cf8cb83490
justinwoo/md2sht
MD2SHT.hs
{-# LANGUAGE OverloadedStrings #-} module MD2SHT where import Data.Text (pack, unpack, isInfixOf) import MD2SHT.Types import Text.HTML.TagSoup extractStyles :: [Rule] -> [String] -> String extractStyles rules classNames = concat $ applyRule =<< classNames where extractLine (Line (Property prop) (Value val)) = unpack prop ++ ":" ++ unpack val ++ ";" applyOnMatch match (Rule (Selector sel) ls) = if pack match `isInfixOf` sel then return $ concat $ extractLine <$> ls else mempty applyRule cn = applyOnMatch ("." ++ cn) =<< rules replaceClassnames :: [Rule] -> String -> String replaceClassnames rules html = renderTags $ replaceClass <$> parseTags html where extractClassNames = words . fromAttrib "class" replaceClass tag@(TagOpen name attrs) = do let style = extractStyles rules $ extractClassNames tag -- throw away class let attrs' = filter ((/= "class") . fst) attrs TagOpen name $ [("style", style) | style /= ""] ++ attrs' replaceClass tag = tag
null
https://raw.githubusercontent.com/justinwoo/md2sht/c4971c65ef92af1425126dd7e28ae925128a2f0f/src/MD2SHT.hs
haskell
# LANGUAGE OverloadedStrings # throw away class
module MD2SHT where import Data.Text (pack, unpack, isInfixOf) import MD2SHT.Types import Text.HTML.TagSoup extractStyles :: [Rule] -> [String] -> String extractStyles rules classNames = concat $ applyRule =<< classNames where extractLine (Line (Property prop) (Value val)) = unpack prop ++ ":" ++ unpack val ++ ";" applyOnMatch match (Rule (Selector sel) ls) = if pack match `isInfixOf` sel then return $ concat $ extractLine <$> ls else mempty applyRule cn = applyOnMatch ("." ++ cn) =<< rules replaceClassnames :: [Rule] -> String -> String replaceClassnames rules html = renderTags $ replaceClass <$> parseTags html where extractClassNames = words . fromAttrib "class" replaceClass tag@(TagOpen name attrs) = do let style = extractStyles rules $ extractClassNames tag let attrs' = filter ((/= "class") . fst) attrs TagOpen name $ [("style", style) | style /= ""] ++ attrs' replaceClass tag = tag
2d62a383505fe8217e8ea74ae582ad186faeee9bdc71d9433411c475d7d51ce5
suprematic/otplike
project.clj
(def project-version "0.6.1-alpha-SNAPSHOT") (defproject otplike/otplike project-version :description "Erlang/OTP like processes and behaviours on top of core.async" :url "" :license {:name "Eclipse Public License - v1.0" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/core.async "0.4.474"] [org.clojure/core.match "0.3.0-alpha5"] [org.clojure/data.int-map "0.2.4"] [clojure-future-spec "1.9.0-beta4"]] :plugins [[lein-codox "0.10.3"] [lein-eftest "0.5.8"]] :source-paths ["src"] : main ;;:source-paths ["src" "examples"] :profiles {:test {:dependencies [[org.clojure/math.combinatorics "0.1.4"]]} :uberjar {:aot :all} :test-parallel {:eftest {:multithread? :vars : ? : namespaces : ? false : ? true } :java-opts ["-Dclojure.core.async.pool-size=32"]} :test-sequentially {:eftest {:multithread? false} :java-opts ["-Dclojure.core.async.pool-size=1"]} :test-1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :test-1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :test-1.10 {:dependencies [[org.clojure/clojure "1.10.1"]]} :repl {:dependencies [[org.clojure/math.combinatorics "0.1.4"] [eftest "0.5.2"]] :source-paths ["src" "examples"]}} :codox {:source-paths ["src"] :source-uri "/{version}/{filepath}#L{line}" :output-path ~(str "docs/" project-version) :namespaces [#"^(?!otplike.spec-util)"] :metadata {:doc/format :markdown}} :test-selectors {:parallel :parallel :serial :serial :all (constantly true) :default (complement :exhaustive)} :monkeypatch-clojure-test false)
null
https://raw.githubusercontent.com/suprematic/otplike/bc9d4e82c14053fac8a0ec141eaca897dd2cfe9b/project.clj
clojure
:source-paths ["src" "examples"]
(def project-version "0.6.1-alpha-SNAPSHOT") (defproject otplike/otplike project-version :description "Erlang/OTP like processes and behaviours on top of core.async" :url "" :license {:name "Eclipse Public License - v1.0" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/core.async "0.4.474"] [org.clojure/core.match "0.3.0-alpha5"] [org.clojure/data.int-map "0.2.4"] [clojure-future-spec "1.9.0-beta4"]] :plugins [[lein-codox "0.10.3"] [lein-eftest "0.5.8"]] :source-paths ["src"] : main :profiles {:test {:dependencies [[org.clojure/math.combinatorics "0.1.4"]]} :uberjar {:aot :all} :test-parallel {:eftest {:multithread? :vars : ? : namespaces : ? false : ? true } :java-opts ["-Dclojure.core.async.pool-size=32"]} :test-sequentially {:eftest {:multithread? false} :java-opts ["-Dclojure.core.async.pool-size=1"]} :test-1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :test-1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :test-1.10 {:dependencies [[org.clojure/clojure "1.10.1"]]} :repl {:dependencies [[org.clojure/math.combinatorics "0.1.4"] [eftest "0.5.2"]] :source-paths ["src" "examples"]}} :codox {:source-paths ["src"] :source-uri "/{version}/{filepath}#L{line}" :output-path ~(str "docs/" project-version) :namespaces [#"^(?!otplike.spec-util)"] :metadata {:doc/format :markdown}} :test-selectors {:parallel :parallel :serial :serial :all (constantly true) :default (complement :exhaustive)} :monkeypatch-clojure-test false)
4defedf0d3d5c90f1b5d5f4f2040d84badb795e424583d5505e51d34b62af5b3
parenthesin/microservice-boilerplate
adapters_test.clj
(ns unit.microservice-boilerplate.adapters-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.properties :as properties] [matcher-combinators.matchers :as matchers] [matcher-combinators.test :refer [match?]] [microservice-boilerplate.adapters :as adapters] [microservice-boilerplate.schemas.db :as schemas.db] [microservice-boilerplate.schemas.types :as schemas.types] [microservice-boilerplate.schemas.wire-in :as schemas.wire-in] [schema-generators.generators :as g] [schema.core :as s] [schema.test :as schema.test])) (use-fixtures :once schema.test/validate-schemas) (deftest inst->formated-string (testing "should adapt clojure/instant to formated string" (is (= "1987-02-10 09:38:43" (adapters/inst->utc-formated-string #inst "1987-02-10T09:38:43.000Z" "yyyy-MM-dd hh:mm:ss"))))) (def coindesk-response-fixture {:time {:updated "Jun 26, 2021 20:06:00 UTC" :updatedISO "2021-06-26T20:06:00+00:00" :updateduk "Jun 26, 2021 at 21:06 BST"} :bpi {:USD {:code "USD" :symbol "&#36;" :rate "31,343.9261" :description "United States Dollar" :rate_float 31343.9261} :GBP {:code "GBP" :symbol "&pound;" :rate "22,573.9582" :description "British Pound Sterling" :rate_float 22573.9582}}}) (deftest wire->usd-price-test (testing "should adapt coindesk response into a number" (is (match? 31343.9261M (adapters/wire->usd-price coindesk-response-fixture))))) (defspec wire-in-db-test 50 (properties/for-all [id (g/generator s/Uuid) pos-num (g/generator schemas.types/PositiveNumber schemas.types/TypesLeafGenerators) neg-num (g/generator schemas.types/NegativeNumber schemas.types/TypesLeafGenerators)] (s/validate schemas.db/WalletTransaction (adapters/withdrawal->db id neg-num pos-num)) (s/validate schemas.db/WalletTransaction (adapters/deposit->db id pos-num pos-num)))) (defspec db-wire-in-test 50 (properties/for-all [wallet-db (g/generator schemas.db/WalletEntry schemas.types/TypesLeafGenerators)] (s/validate schemas.wire-in/WalletEntry (adapters/db->wire-in wallet-db)))) (def wallet-entry-1 #:wallet{:id #uuid "ecdcf860-0c2a-3abf-9af1-a70e770cea9a" :btc_amount 3 :usd_amount_at 34000M :created_at #inst "2020-10-23T00:00:00"}) (def wallet-entry-2 #:wallet{:id #uuid "67272ecc-b839-37e3-9656-2895d1f0fda2" :btc_amount -1 :usd_amount_at 33000M :created_at #inst "2020-10-24T00:00:00"}) (def wallet-entry-3 #:wallet{:id #uuid "f4259476-efe4-3a26-ad30-1dd0ffd49fc3" :btc_amount -1 :usd_amount_at 32000M :created_at #inst "2020-10-25T00:00:00"}) (def wallet-entry-4 #:wallet{:id #uuid "0d93f041-eae4-3af9-b5e1-f9ee844e82d9" :btc_amount 1 :usd_amount_at 36000M :created_at #inst "2020-10-26T00:00:00"}) (def wallet-entries [wallet-entry-1 wallet-entry-2 wallet-entry-3 wallet-entry-4]) (deftest ->wallet-history-test (testing "should reduce and get totals for wallet entries and current usd" (is (match? {:entries (matchers/embeds [{:id uuid? :btc-amount number? :usd-amount-at number? :created-at inst?}]) :total-btc 2M :total-current-usd 60000M} (adapters/->wallet-history 30000M wallet-entries)))))
null
https://raw.githubusercontent.com/parenthesin/microservice-boilerplate/285f26a6788e9c5b0e87f1042255d8a9841129b5/test/unit/microservice_boilerplate/adapters_test.clj
clojure
(ns unit.microservice-boilerplate.adapters-test (:require [clojure.test :refer [deftest is testing use-fixtures]] [clojure.test.check.clojure-test :refer [defspec]] [clojure.test.check.properties :as properties] [matcher-combinators.matchers :as matchers] [matcher-combinators.test :refer [match?]] [microservice-boilerplate.adapters :as adapters] [microservice-boilerplate.schemas.db :as schemas.db] [microservice-boilerplate.schemas.types :as schemas.types] [microservice-boilerplate.schemas.wire-in :as schemas.wire-in] [schema-generators.generators :as g] [schema.core :as s] [schema.test :as schema.test])) (use-fixtures :once schema.test/validate-schemas) (deftest inst->formated-string (testing "should adapt clojure/instant to formated string" (is (= "1987-02-10 09:38:43" (adapters/inst->utc-formated-string #inst "1987-02-10T09:38:43.000Z" "yyyy-MM-dd hh:mm:ss"))))) (def coindesk-response-fixture {:time {:updated "Jun 26, 2021 20:06:00 UTC" :updatedISO "2021-06-26T20:06:00+00:00" :updateduk "Jun 26, 2021 at 21:06 BST"} :bpi {:USD {:code "USD" :symbol "&#36;" :rate "31,343.9261" :description "United States Dollar" :rate_float 31343.9261} :GBP {:code "GBP" :symbol "&pound;" :rate "22,573.9582" :description "British Pound Sterling" :rate_float 22573.9582}}}) (deftest wire->usd-price-test (testing "should adapt coindesk response into a number" (is (match? 31343.9261M (adapters/wire->usd-price coindesk-response-fixture))))) (defspec wire-in-db-test 50 (properties/for-all [id (g/generator s/Uuid) pos-num (g/generator schemas.types/PositiveNumber schemas.types/TypesLeafGenerators) neg-num (g/generator schemas.types/NegativeNumber schemas.types/TypesLeafGenerators)] (s/validate schemas.db/WalletTransaction (adapters/withdrawal->db id neg-num pos-num)) (s/validate schemas.db/WalletTransaction (adapters/deposit->db id pos-num pos-num)))) (defspec db-wire-in-test 50 (properties/for-all [wallet-db (g/generator schemas.db/WalletEntry schemas.types/TypesLeafGenerators)] (s/validate schemas.wire-in/WalletEntry (adapters/db->wire-in wallet-db)))) (def wallet-entry-1 #:wallet{:id #uuid "ecdcf860-0c2a-3abf-9af1-a70e770cea9a" :btc_amount 3 :usd_amount_at 34000M :created_at #inst "2020-10-23T00:00:00"}) (def wallet-entry-2 #:wallet{:id #uuid "67272ecc-b839-37e3-9656-2895d1f0fda2" :btc_amount -1 :usd_amount_at 33000M :created_at #inst "2020-10-24T00:00:00"}) (def wallet-entry-3 #:wallet{:id #uuid "f4259476-efe4-3a26-ad30-1dd0ffd49fc3" :btc_amount -1 :usd_amount_at 32000M :created_at #inst "2020-10-25T00:00:00"}) (def wallet-entry-4 #:wallet{:id #uuid "0d93f041-eae4-3af9-b5e1-f9ee844e82d9" :btc_amount 1 :usd_amount_at 36000M :created_at #inst "2020-10-26T00:00:00"}) (def wallet-entries [wallet-entry-1 wallet-entry-2 wallet-entry-3 wallet-entry-4]) (deftest ->wallet-history-test (testing "should reduce and get totals for wallet entries and current usd" (is (match? {:entries (matchers/embeds [{:id uuid? :btc-amount number? :usd-amount-at number? :created-at inst?}]) :total-btc 2M :total-current-usd 60000M} (adapters/->wallet-history 30000M wallet-entries)))))
f9d5967ae5856bdb9e730a7e9a5e92861e050a80b2f092d302876a42ad780c40
ku-fpg/haskino
Morse.hs
------------------------------------------------------------------------------- -- | Module : System . Hardware . Haskino . SamplePrograms . Strong . -- Based on System.Hardware.Arduino Copyright : ( c ) University of Kansas System . Hardware . Arduino ( c ) -- License : BSD3 -- Stability : experimental -- code blinker . Original by , modified to simplify -- and fit into the existing examples structure. ------------------------------------------------------------------------------- module System.Hardware.Haskino.SamplePrograms.Strong.Morse where import Control.Monad (forever) import Control.Monad.Trans (liftIO) import Data.Char (toUpper) import Data.List (intercalate) import Data.Maybe (fromMaybe) import System.Hardware.Haskino | A dit or a dah is all we need for : A @dit@ is a dot ; and a @dah@ is a dash in the world . We use ' LBreak ' and ' ' to indicate a letter and a word break -- so we can insert some delay between letters and words as we -- transmit. data Morse = Dit | Dah | LBreak | WBreak deriving Show -- | Morse code dictionary dict :: [(Char, [Morse])] dict = map encode m where encode (k, s) = (k, map (\c -> if c == '.' then Dit else Dah) s) m = [ ('A', ".-" ), ('B', "-..." ), ('C', "-.-." ), ('D', "-.." ), ('E', "." ) , ('F', "..-." ), ('G', "--." ), ('H', "...." ), ('I', ".." ), ('J', ".---" ) , ('K', "-.-" ), ('L', ".-.." ), ('M', "--" ), ('N', "-." ), ('O', "---" ) , ('P', ".--." ), ('Q', "--.-" ), ('R', ".-." ), ('S', "..." ), ('T', "-" ) , ('U', "..-" ), ('V', "...-" ), ('W', ".--" ), ('X', "-..-" ), ('Y', "-.--" ) , ('Z', "--.." ), ('0', "-----"), ('1', ".----"), ('2', "..---"), ('3', "...--") , ('4', "....-"), ('5', "....."), ('6', "-...."), ('7', "--..."), ('8', "---..") , ('9', "----."), ('+', ".-.-."), ('/', "-..-."), ('=', "-...-") ] -- | Given a sentence, decode it. We simply drop any letters that we -- do not have a mapping for. decode :: String -> [Morse] decode = intercalate [WBreak] . map (intercalate [LBreak] . map cvt) . words where cvt c = fromMaybe [] $ toUpper c `lookup` dict -- | Given a morsified sentence, compute the delay times. A 'Left' value means -- turn the led on that long, a 'Right' value means turn it off that long. morsify :: [Morse] -> [Either Int Int] morsify = map t where unit = 300 t Dit = Left $ 1 * unit t Dah = Left $ 3 * unit t LBreak = Right $ 3 * unit t WBreak = Right $ 7 * unit -- | Finally, turn a full sentence into a sequence of blink on/off codes transmit :: Pin -> String -> Arduino () transmit p = sequence_ . concatMap code . morsify . decode where code (Left i) = [digitalWrite p True, delayMillis $ fromIntegral i, digitalWrite p False, delayMillis $ fromIntegral i] code (Right i) = [digitalWrite p False, delayMillis $ fromIntegral i] -- | A simple demo driver. To run this example, you only need the Arduino connected to your computer , no other hardware is needed . We use the internal led on pin 13 . Of course , you can attach a led to pin 13 as well , for artistic effect . -- -- <<-fpg/arduino-lab/raw/master/System/Hardware/Haskino/SamplePrograms/Schematics/Blink.png>> morseDemo :: IO () morseDemo = withArduino False "/dev/cu.usbmodem1421" $ do setPinMode led OUTPUT forever send where led = 13 send = do liftIO $ putStr "Message? " m <- liftIO getLine transmit led m
null
https://raw.githubusercontent.com/ku-fpg/haskino/9a0709c92c2da9b9371e292b00fd076e5539eb18/legacy/Shallow/Morse.hs
haskell
----------------------------------------------------------------------------- | Based on System.Hardware.Arduino License : BSD3 Stability : experimental and fit into the existing examples structure. ----------------------------------------------------------------------------- so we can insert some delay between letters and words as we transmit. | Morse code dictionary | Given a sentence, decode it. We simply drop any letters that we do not have a mapping for. | Given a morsified sentence, compute the delay times. A 'Left' value means turn the led on that long, a 'Right' value means turn it off that long. | Finally, turn a full sentence into a sequence of blink on/off codes | A simple demo driver. To run this example, you only need the Arduino connected to your <<-fpg/arduino-lab/raw/master/System/Hardware/Haskino/SamplePrograms/Schematics/Blink.png>>
Module : System . Hardware . Haskino . SamplePrograms . Strong . Copyright : ( c ) University of Kansas System . Hardware . Arduino ( c ) code blinker . Original by , modified to simplify module System.Hardware.Haskino.SamplePrograms.Strong.Morse where import Control.Monad (forever) import Control.Monad.Trans (liftIO) import Data.Char (toUpper) import Data.List (intercalate) import Data.Maybe (fromMaybe) import System.Hardware.Haskino | A dit or a dah is all we need for : A @dit@ is a dot ; and a @dah@ is a dash in the world . We use ' LBreak ' and ' ' to indicate a letter and a word break data Morse = Dit | Dah | LBreak | WBreak deriving Show dict :: [(Char, [Morse])] dict = map encode m where encode (k, s) = (k, map (\c -> if c == '.' then Dit else Dah) s) m = [ ('A', ".-" ), ('B', "-..." ), ('C', "-.-." ), ('D', "-.." ), ('E', "." ) , ('F', "..-." ), ('G', "--." ), ('H', "...." ), ('I', ".." ), ('J', ".---" ) , ('K', "-.-" ), ('L', ".-.." ), ('M', "--" ), ('N', "-." ), ('O', "---" ) , ('P', ".--." ), ('Q', "--.-" ), ('R', ".-." ), ('S', "..." ), ('T', "-" ) , ('U', "..-" ), ('V', "...-" ), ('W', ".--" ), ('X', "-..-" ), ('Y', "-.--" ) , ('Z', "--.." ), ('0', "-----"), ('1', ".----"), ('2', "..---"), ('3', "...--") , ('4', "....-"), ('5', "....."), ('6', "-...."), ('7', "--..."), ('8', "---..") , ('9', "----."), ('+', ".-.-."), ('/', "-..-."), ('=', "-...-") ] decode :: String -> [Morse] decode = intercalate [WBreak] . map (intercalate [LBreak] . map cvt) . words where cvt c = fromMaybe [] $ toUpper c `lookup` dict morsify :: [Morse] -> [Either Int Int] morsify = map t where unit = 300 t Dit = Left $ 1 * unit t Dah = Left $ 3 * unit t LBreak = Right $ 3 * unit t WBreak = Right $ 7 * unit transmit :: Pin -> String -> Arduino () transmit p = sequence_ . concatMap code . morsify . decode where code (Left i) = [digitalWrite p True, delayMillis $ fromIntegral i, digitalWrite p False, delayMillis $ fromIntegral i] code (Right i) = [digitalWrite p False, delayMillis $ fromIntegral i] computer , no other hardware is needed . We use the internal led on pin 13 . Of course , you can attach a led to pin 13 as well , for artistic effect . morseDemo :: IO () morseDemo = withArduino False "/dev/cu.usbmodem1421" $ do setPinMode led OUTPUT forever send where led = 13 send = do liftIO $ putStr "Message? " m <- liftIO getLine transmit led m
688d018e15718241da5cec73eeea272d9afd18f8a9001ce27bf411f0c3a840e8
mzp/coq-for-ipad
eval.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt Objective Caml port by and (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : eval.ml 9547 2010 - 01 - 22 12:48:24Z doligez $ open Misc open Path open Instruct open Types open Parser_aux type error = Unbound_identifier of Ident.t | Not_initialized_yet of Path.t | Unbound_long_identifier of Longident.t | Unknown_name of int | Tuple_index of type_expr * int * int | Array_index of int * int | List_index of int * int | String_index of string * int * int | Wrong_item_type of type_expr * int | Wrong_label of type_expr * string | Not_a_record of type_expr | No_result exception Error of error let abstract_type = Btype.newgenty (Tconstr (Pident (Ident.create "<abstr>"), [], ref Mnil)) let rec path event = function Pident id -> if Ident.global id then try Debugcom.Remote_value.global (Symtable.get_global_position id) with Symtable.Error _ -> raise(Error(Unbound_identifier id)) else begin match event with Some ev -> begin try let pos = Ident.find_same id ev.ev_compenv.ce_stack in Debugcom.Remote_value.local (ev.ev_stacksize - pos) with Not_found -> try let pos = Ident.find_same id ev.ev_compenv.ce_heap in Debugcom.Remote_value.from_environment pos with Not_found -> raise(Error(Unbound_identifier id)) end | None -> raise(Error(Unbound_identifier id)) end | Pdot(root, fieldname, pos) -> let v = path event root in if not (Debugcom.Remote_value.is_block v) then raise(Error(Not_initialized_yet root)); Debugcom.Remote_value.field v pos | Papply(p1, p2) -> fatal_error "Eval.path: Papply" let rec expression event env = function E_ident lid -> begin try let (p, valdesc) = Env.lookup_value lid env in (begin match valdesc.val_kind with Val_ivar (_, cl_num) -> let (p0, _) = Env.lookup_value (Longident.Lident ("self-" ^ cl_num)) env in let v = path event p0 in let i = path event p in Debugcom.Remote_value.field v (Debugcom.Remote_value.obj i) | _ -> path event p end, Ctype.correct_levels valdesc.val_type) with Not_found -> raise(Error(Unbound_long_identifier lid)) end | E_result -> begin match event with Some {ev_kind = Event_after ty; ev_typsubst = subst} when !Frames.current_frame = 0 -> (Debugcom.Remote_value.accu(), Subst.type_expr subst ty) | _ -> raise(Error(No_result)) end | E_name n -> begin try Printval.find_named_value n with Not_found -> raise(Error(Unknown_name n)) end | E_item(arg, n) -> let (v, ty) = expression event env arg in begin match (Ctype.repr(Ctype.expand_head_opt env ty)).desc with Ttuple ty_list -> if n < 1 || n > List.length ty_list then raise(Error(Tuple_index(ty, List.length ty_list, n))) else (Debugcom.Remote_value.field v (n-1), List.nth ty_list (n-1)) | Tconstr(path, [ty_arg], _) when Path.same path Predef.path_array -> let size = Debugcom.Remote_value.size v in if n >= size then raise(Error(Array_index(size, n))) else (Debugcom.Remote_value.field v n, ty_arg) | Tconstr(path, [ty_arg], _) when Path.same path Predef.path_list -> let rec nth pos v = if not (Debugcom.Remote_value.is_block v) then raise(Error(List_index(pos, n))) else if pos = n then (Debugcom.Remote_value.field v 0, ty_arg) else nth (pos + 1) (Debugcom.Remote_value.field v 1) in nth 0 v | Tconstr(path, [], _) when Path.same path Predef.path_string -> let s = (Debugcom.Remote_value.obj v : string) in if n >= String.length s then raise(Error(String_index(s, String.length s, n))) else (Debugcom.Remote_value.of_int(Char.code s.[n]), Predef.type_char) | _ -> raise(Error(Wrong_item_type(ty, n))) end | E_field(arg, lbl) -> let (v, ty) = expression event env arg in begin match (Ctype.repr(Ctype.expand_head_opt env ty)).desc with Tconstr(path, args, _) -> let tydesc = Env.find_type path env in begin match tydesc.type_kind with Type_record(lbl_list, repr) -> let (pos, ty_res) = find_label lbl env ty path tydesc 0 lbl_list in (Debugcom.Remote_value.field v pos, ty_res) | _ -> raise(Error(Not_a_record ty)) end | _ -> raise(Error(Not_a_record ty)) end and find_label lbl env ty path tydesc pos = function [] -> raise(Error(Wrong_label(ty, lbl))) | (name, mut, ty_arg) :: rem -> if name = lbl then begin let ty_res = Btype.newgenty(Tconstr(path, tydesc.type_params, ref Mnil)) in (pos, try Ctype.apply env [ty_res] ty_arg [ty] with Ctype.Cannot_apply -> abstract_type) end else find_label lbl env ty path tydesc (pos + 1) rem (* Error report *) open Format let report_error ppf = function | Unbound_identifier id -> fprintf ppf "@[Unbound identifier %s@]@." (Ident.name id) | Not_initialized_yet path -> fprintf ppf "@[The module path %a is not yet initialized.@ \ Please run program forward@ \ until its initialization code is executed.@]@." Printtyp.path path | Unbound_long_identifier lid -> fprintf ppf "@[Unbound identifier %a@]@." Printtyp.longident lid | Unknown_name n -> fprintf ppf "@[Unknown value name $%i@]@." n | Tuple_index(ty, len, pos) -> Printtyp.reset_and_mark_loops ty; fprintf ppf "@[Cannot extract field number %i from a %i-tuple of type@ %a@]@." pos len Printtyp.type_expr ty | Array_index(len, pos) -> fprintf ppf "@[Cannot extract element number %i from an array of length %i@]@." pos len | List_index(len, pos) -> fprintf ppf "@[Cannot extract element number %i from a list of length %i@]@." pos len | String_index(s, len, pos) -> fprintf ppf "@[Cannot extract character number %i@ \ from the following string of length %i:@ %S@]@." pos len s | Wrong_item_type(ty, pos) -> fprintf ppf "@[Cannot extract item number %i from a value of type@ %a@]@." pos Printtyp.type_expr ty | Wrong_label(ty, lbl) -> fprintf ppf "@[The record type@ %a@ has no label named %s@]@." Printtyp.type_expr ty lbl | Not_a_record ty -> fprintf ppf "@[The type@ %a@ is not a record type@]@." Printtyp.type_expr ty | No_result -> fprintf ppf "@[No result available at current program event@]@."
null
https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/debugger/eval.ml
ocaml
********************************************************************* Objective Caml ********************************************************************* Error report
, projet Cristal , INRIA Rocquencourt Objective Caml port by and Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : eval.ml 9547 2010 - 01 - 22 12:48:24Z doligez $ open Misc open Path open Instruct open Types open Parser_aux type error = Unbound_identifier of Ident.t | Not_initialized_yet of Path.t | Unbound_long_identifier of Longident.t | Unknown_name of int | Tuple_index of type_expr * int * int | Array_index of int * int | List_index of int * int | String_index of string * int * int | Wrong_item_type of type_expr * int | Wrong_label of type_expr * string | Not_a_record of type_expr | No_result exception Error of error let abstract_type = Btype.newgenty (Tconstr (Pident (Ident.create "<abstr>"), [], ref Mnil)) let rec path event = function Pident id -> if Ident.global id then try Debugcom.Remote_value.global (Symtable.get_global_position id) with Symtable.Error _ -> raise(Error(Unbound_identifier id)) else begin match event with Some ev -> begin try let pos = Ident.find_same id ev.ev_compenv.ce_stack in Debugcom.Remote_value.local (ev.ev_stacksize - pos) with Not_found -> try let pos = Ident.find_same id ev.ev_compenv.ce_heap in Debugcom.Remote_value.from_environment pos with Not_found -> raise(Error(Unbound_identifier id)) end | None -> raise(Error(Unbound_identifier id)) end | Pdot(root, fieldname, pos) -> let v = path event root in if not (Debugcom.Remote_value.is_block v) then raise(Error(Not_initialized_yet root)); Debugcom.Remote_value.field v pos | Papply(p1, p2) -> fatal_error "Eval.path: Papply" let rec expression event env = function E_ident lid -> begin try let (p, valdesc) = Env.lookup_value lid env in (begin match valdesc.val_kind with Val_ivar (_, cl_num) -> let (p0, _) = Env.lookup_value (Longident.Lident ("self-" ^ cl_num)) env in let v = path event p0 in let i = path event p in Debugcom.Remote_value.field v (Debugcom.Remote_value.obj i) | _ -> path event p end, Ctype.correct_levels valdesc.val_type) with Not_found -> raise(Error(Unbound_long_identifier lid)) end | E_result -> begin match event with Some {ev_kind = Event_after ty; ev_typsubst = subst} when !Frames.current_frame = 0 -> (Debugcom.Remote_value.accu(), Subst.type_expr subst ty) | _ -> raise(Error(No_result)) end | E_name n -> begin try Printval.find_named_value n with Not_found -> raise(Error(Unknown_name n)) end | E_item(arg, n) -> let (v, ty) = expression event env arg in begin match (Ctype.repr(Ctype.expand_head_opt env ty)).desc with Ttuple ty_list -> if n < 1 || n > List.length ty_list then raise(Error(Tuple_index(ty, List.length ty_list, n))) else (Debugcom.Remote_value.field v (n-1), List.nth ty_list (n-1)) | Tconstr(path, [ty_arg], _) when Path.same path Predef.path_array -> let size = Debugcom.Remote_value.size v in if n >= size then raise(Error(Array_index(size, n))) else (Debugcom.Remote_value.field v n, ty_arg) | Tconstr(path, [ty_arg], _) when Path.same path Predef.path_list -> let rec nth pos v = if not (Debugcom.Remote_value.is_block v) then raise(Error(List_index(pos, n))) else if pos = n then (Debugcom.Remote_value.field v 0, ty_arg) else nth (pos + 1) (Debugcom.Remote_value.field v 1) in nth 0 v | Tconstr(path, [], _) when Path.same path Predef.path_string -> let s = (Debugcom.Remote_value.obj v : string) in if n >= String.length s then raise(Error(String_index(s, String.length s, n))) else (Debugcom.Remote_value.of_int(Char.code s.[n]), Predef.type_char) | _ -> raise(Error(Wrong_item_type(ty, n))) end | E_field(arg, lbl) -> let (v, ty) = expression event env arg in begin match (Ctype.repr(Ctype.expand_head_opt env ty)).desc with Tconstr(path, args, _) -> let tydesc = Env.find_type path env in begin match tydesc.type_kind with Type_record(lbl_list, repr) -> let (pos, ty_res) = find_label lbl env ty path tydesc 0 lbl_list in (Debugcom.Remote_value.field v pos, ty_res) | _ -> raise(Error(Not_a_record ty)) end | _ -> raise(Error(Not_a_record ty)) end and find_label lbl env ty path tydesc pos = function [] -> raise(Error(Wrong_label(ty, lbl))) | (name, mut, ty_arg) :: rem -> if name = lbl then begin let ty_res = Btype.newgenty(Tconstr(path, tydesc.type_params, ref Mnil)) in (pos, try Ctype.apply env [ty_res] ty_arg [ty] with Ctype.Cannot_apply -> abstract_type) end else find_label lbl env ty path tydesc (pos + 1) rem open Format let report_error ppf = function | Unbound_identifier id -> fprintf ppf "@[Unbound identifier %s@]@." (Ident.name id) | Not_initialized_yet path -> fprintf ppf "@[The module path %a is not yet initialized.@ \ Please run program forward@ \ until its initialization code is executed.@]@." Printtyp.path path | Unbound_long_identifier lid -> fprintf ppf "@[Unbound identifier %a@]@." Printtyp.longident lid | Unknown_name n -> fprintf ppf "@[Unknown value name $%i@]@." n | Tuple_index(ty, len, pos) -> Printtyp.reset_and_mark_loops ty; fprintf ppf "@[Cannot extract field number %i from a %i-tuple of type@ %a@]@." pos len Printtyp.type_expr ty | Array_index(len, pos) -> fprintf ppf "@[Cannot extract element number %i from an array of length %i@]@." pos len | List_index(len, pos) -> fprintf ppf "@[Cannot extract element number %i from a list of length %i@]@." pos len | String_index(s, len, pos) -> fprintf ppf "@[Cannot extract character number %i@ \ from the following string of length %i:@ %S@]@." pos len s | Wrong_item_type(ty, pos) -> fprintf ppf "@[Cannot extract item number %i from a value of type@ %a@]@." pos Printtyp.type_expr ty | Wrong_label(ty, lbl) -> fprintf ppf "@[The record type@ %a@ has no label named %s@]@." Printtyp.type_expr ty lbl | Not_a_record ty -> fprintf ppf "@[The type@ %a@ is not a record type@]@." Printtyp.type_expr ty | No_result -> fprintf ppf "@[No result available at current program event@]@."
697560d0c7b7415f7c18fd9917d42b45128e5835ddd218a63089a3011a049295
clojure/clojurescript
core.cljs
Copyright ( c ) . All rights reserved . ;; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns foreign-libs-cljs-2249.core (:require [thirdparty.calculator])) (defn main [] (println (js/Calculator.add 1 2)))
null
https://raw.githubusercontent.com/clojure/clojurescript/a4673b880756531ac5690f7b4721ad76c0810327/src/test/cljs_build/foreign_libs_cljs_2249/core.cljs
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) . All rights reserved . Eclipse Public License 1.0 ( -1.0.php ) (ns foreign-libs-cljs-2249.core (:require [thirdparty.calculator])) (defn main [] (println (js/Calculator.add 1 2)))
e4e36377a67c08fe11e3775c4f4ca555c1af880c5a97a8328ae5eb71207f6217
TrustInSoft/tis-interpreter
idxmap.ml
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) module type S = sig type key type 'a t val is_empty : 'a t -> bool val empty : 'a t val add : key -> 'a -> 'a t -> 'a t val mem : key -> 'a t -> bool val find : key -> 'a t -> 'a val remove : key -> 'a t -> 'a t val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val map : (key -> 'a -> 'b) -> 'a t -> 'b t val mapf : (key -> 'a -> 'b option) -> 'a t -> 'b t val mapq : (key -> 'a -> 'a option) -> 'a t -> 'a t val filter : (key -> 'a -> bool) -> 'a t -> 'a t val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val union : (key -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t val inter : (key -> 'a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t val interf : (key -> 'a -> 'b -> 'c option) -> 'a t -> 'b t -> 'c t val interq : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val diffq : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val merge : (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t (** [insert (fun key v old -> ...) key v map] *) val insert : (key -> 'a -> 'a -> 'a) -> key -> 'a -> 'a t -> 'a t val change : (key -> 'b -> 'a option -> 'a option) -> key -> 'b -> 'a t -> 'a t end module type IndexedKey = sig type t val id : t -> int (** unique per t *) end module Make( K : IndexedKey ) = struct type key = K.t type 'a t = (key * 'a) Intmap.t let is_empty = Intmap.is_empty let empty = Intmap.empty (* good sharing *) let add k x m = Intmap.add (K.id k) (k,x) m let _pack k = function None -> None | Some v -> Some (k,v) let _packold ((k,old) as o) w = if w==old then o else k,w let _oldpack o = function None -> None | Some w -> Some (_packold o w) (* good sharing *) let insert f k v m = Intmap.insert (fun _k (k,v) ((_,old) as o) -> _packold o (f k v old)) (K.id k) (k,v) m (* good sharing *) let change f k v m = Intmap.change (fun _k (k,v) -> function | None -> _pack k (f k v None) | Some ((_,old) as o) -> _oldpack o (f k v (Some old))) (K.id k) (k,v) m let mem k m = Intmap.mem (K.id k) m let find k m = snd (Intmap.find (K.id k) m) let compare f m1 m2 = Intmap.compare (fun (_,a) (_,b) -> f a b) m1 m2 let equal f m1 m2 = Intmap.equal (fun (_,a) (_,b) -> f a b) m1 m2 let iter f m = Intmap.iter (fun (k,v) -> f k v) m let fold f m w = Intmap.fold (fun (k,v) w -> f k v w) m w let map f m = Intmap.map (fun (k,v) -> k,f k v) m let mapf f m = Intmap.mapf (fun _ (k,v) -> _pack k (f k v)) m (* good sharing *) let mapq f = Intmap.mapq (fun _ ((k,old) as o) -> _oldpack o (f k old)) (* good sharing *) let partition f = Intmap.partition (fun _ (k,v) -> f k v) (* good sharing *) let remove k = Intmap.remove (K.id k) (* good sharing *) let filter f = Intmap.filter (fun _ (k,v) -> f k v) (* good sharing *) let union f = Intmap.union (fun _ ((k,v) as x) ((_,v') as y) -> let w = f k v v' in if w==v then x else if w==v then y else k,w ) let inter f = Intmap.inter (fun _ (k,v) (_,v') -> k,f k v v') let interf f = Intmap.interf (fun _ (k,v) (_,v') -> _pack k (f k v v')) (* good sharing *) let interq f = Intmap.interq (fun _ ((k,v) as x) ((_,v') as y) -> match f k v v' with None -> None | Some w -> Some (if w==v then x else if w==v then y else k,w)) (* good sharing *) let diffq f = Intmap.diffq (fun _ ((k,v) as x) ((_,v') as y) -> match f k v v' with None -> None | Some w -> Some (if w==v then x else if w==v then y else k,w)) let merge f a b = Intmap.merge (fun _ u v -> match u , v with | None , None -> None | Some(k,v) , None -> _pack k (f k (Some v) None) | None , Some(k,v) -> _pack k (f k None (Some v)) | Some(k,v) , Some(_,v') -> _pack k (f k (Some v) (Some v')) ) a b end
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/wp/qed/src/idxmap.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * [insert (fun key v old -> ...) key v map] * unique per t good sharing good sharing good sharing good sharing good sharing good sharing good sharing good sharing good sharing good sharing
Modified by TrustInSoft This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . module type S = sig type key type 'a t val is_empty : 'a t -> bool val empty : 'a t val add : key -> 'a -> 'a t -> 'a t val mem : key -> 'a t -> bool val find : key -> 'a t -> 'a val remove : key -> 'a t -> 'a t val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val map : (key -> 'a -> 'b) -> 'a t -> 'b t val mapf : (key -> 'a -> 'b option) -> 'a t -> 'b t val mapq : (key -> 'a -> 'a option) -> 'a t -> 'a t val filter : (key -> 'a -> bool) -> 'a t -> 'a t val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val union : (key -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t val inter : (key -> 'a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t val interf : (key -> 'a -> 'b -> 'c option) -> 'a t -> 'b t -> 'c t val interq : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val diffq : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t val merge : (key -> 'a option -> 'b option -> 'c option) -> 'a t -> 'b t -> 'c t val insert : (key -> 'a -> 'a -> 'a) -> key -> 'a -> 'a t -> 'a t val change : (key -> 'b -> 'a option -> 'a option) -> key -> 'b -> 'a t -> 'a t end module type IndexedKey = sig type t end module Make( K : IndexedKey ) = struct type key = K.t type 'a t = (key * 'a) Intmap.t let is_empty = Intmap.is_empty let empty = Intmap.empty let add k x m = Intmap.add (K.id k) (k,x) m let _pack k = function None -> None | Some v -> Some (k,v) let _packold ((k,old) as o) w = if w==old then o else k,w let _oldpack o = function None -> None | Some w -> Some (_packold o w) let insert f k v m = Intmap.insert (fun _k (k,v) ((_,old) as o) -> _packold o (f k v old)) (K.id k) (k,v) m let change f k v m = Intmap.change (fun _k (k,v) -> function | None -> _pack k (f k v None) | Some ((_,old) as o) -> _oldpack o (f k v (Some old))) (K.id k) (k,v) m let mem k m = Intmap.mem (K.id k) m let find k m = snd (Intmap.find (K.id k) m) let compare f m1 m2 = Intmap.compare (fun (_,a) (_,b) -> f a b) m1 m2 let equal f m1 m2 = Intmap.equal (fun (_,a) (_,b) -> f a b) m1 m2 let iter f m = Intmap.iter (fun (k,v) -> f k v) m let fold f m w = Intmap.fold (fun (k,v) w -> f k v w) m w let map f m = Intmap.map (fun (k,v) -> k,f k v) m let mapf f m = Intmap.mapf (fun _ (k,v) -> _pack k (f k v)) m let mapq f = Intmap.mapq (fun _ ((k,old) as o) -> _oldpack o (f k old)) let partition f = Intmap.partition (fun _ (k,v) -> f k v) let remove k = Intmap.remove (K.id k) let filter f = Intmap.filter (fun _ (k,v) -> f k v) let union f = Intmap.union (fun _ ((k,v) as x) ((_,v') as y) -> let w = f k v v' in if w==v then x else if w==v then y else k,w ) let inter f = Intmap.inter (fun _ (k,v) (_,v') -> k,f k v v') let interf f = Intmap.interf (fun _ (k,v) (_,v') -> _pack k (f k v v')) let interq f = Intmap.interq (fun _ ((k,v) as x) ((_,v') as y) -> match f k v v' with None -> None | Some w -> Some (if w==v then x else if w==v then y else k,w)) let diffq f = Intmap.diffq (fun _ ((k,v) as x) ((_,v') as y) -> match f k v v' with None -> None | Some w -> Some (if w==v then x else if w==v then y else k,w)) let merge f a b = Intmap.merge (fun _ u v -> match u , v with | None , None -> None | Some(k,v) , None -> _pack k (f k (Some v) None) | None , Some(k,v) -> _pack k (f k None (Some v)) | Some(k,v) , Some(_,v') -> _pack k (f k (Some v) (Some v')) ) a b end
724a7e368216f74eea8ce7157122a732b1ca96f44528c21611b3d6e34674f18b
metaocaml/ber-metaocaml
caml_tex.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Gallium , INRIA Paris , Nagoya University (* *) Copyright 2018 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. *) (* *) (**************************************************************************) [@@@warning "a-40-6"] open StdLabels open Str let camlprefix = "caml" let latex_escape s = String.concat "" ["$"; s; "$"] let camlin = latex_escape {|\\?|} ^ {|\1|} let camlout = latex_escape {|\\:|} ^ {|\1|} let camlbunderline = "<<" let camleunderline = ">>" (** Restrict the number of latex environment *) type env = Env of string let main = Env "example" let input_env = Env "input" let ok_output = Env "output" let error = Env "error" let warning = Env "warn" let phrase_env = Env "" let start out (Env s) args = Format.fprintf out "\\begin{%s%s}" camlprefix s; List.iter (Format.fprintf out "{%s}") args; Format.fprintf out "\n" let stop out (Env s) = Format.fprintf out "\\end{%s%s}" camlprefix s; Format.fprintf out "\n" let code_env env out s = let sep = if s.[String.length s - 1] = '\n' then "" else "\n" in Format.fprintf out "%a%s%s%a" (fun ppf env -> start ppf env []) env s sep stop env type example_mode = Toplevel | Verbatim | Signature let string_of_mode = function | Toplevel -> "toplevel" | Verbatim -> "verbatim" | Signature -> "signature" let verbose = ref true let linelen = ref 72 let outfile = ref "" let cut_at_blanks = ref false let files = ref [] let repo_root = ref "" let (~!) = let memo = ref [] in fun key -> try List.assq key !memo with Not_found -> let data = Str.regexp key in memo := (key, data) :: !memo; data exception Phrase_parsing of string module Toplevel = struct (** Initialize the toplevel loop, redirect stdout and stderr, capture warnings and error messages *) type output = { error : string; (** error message text *) warnings : string list; (** warning messages text *) values : string; (** toplevel output *) stdout : string; (** output printed on the toplevel stdout *) underlined : (int * int) list (** locations to underline in input phrases *) } let buffer_fmt () = let b = Buffer.create 30 in b, Format.formatter_of_buffer b let error_fmt = buffer_fmt () let warning_fmt = buffer_fmt () let out_fmt = buffer_fmt () let flush_fmt (b,fmt) = Format.pp_print_flush fmt (); let r = Buffer.contents b in Buffer.reset b; r (** Redirect the stdout *) let stdout_out, stdout_in = Unix.pipe ~cloexec:true () let () = Unix.dup2 stdout_in Unix.stdout let self_error_fmt = Format.formatter_of_out_channel stderr let eprintf = Format.eprintf let read_stdout = let size = 50 in let b = Bytes.create size in let buffer = Buffer.create 100 in let rec read_toplevel_stdout () = match Unix.select[stdout_out][][] 0. with | [a], _, _ -> let n = Unix.read stdout_out b 0 size in Buffer.add_subbytes buffer b 0 n; if n = size then read_toplevel_stdout () | _ -> () in fun () -> let () = flush stdout; read_toplevel_stdout () in let r = Buffer.contents buffer in Buffer.reset buffer; r (** Store character intervals directly *) let locs = ref [] let register_loc (loc : Location.t) = let startchar = loc.loc_start.pos_cnum in let endchar = loc.loc_end.pos_cnum in if startchar >= 0 then locs := (startchar, endchar) :: !locs (** Record locations in the main error and suberrors without printing them *) let printer_register_locs = let base = Location.batch_mode_printer in { Location.pp_main_loc = (fun _ _ _ loc -> register_loc loc); pp_submsg_loc = (fun _ _ _ loc -> register_loc loc); (* The following fields are kept identical to [base], listed explicitly so that future field additions result in an error -- using (Location.batch_mode_printer with ...) would be the symmetric problem to a fragile pattern-matching. *) pp = base.pp; pp_report_kind = base.pp_report_kind; pp_main_txt = base.pp_main_txt; pp_submsgs = base.pp_submsgs; pp_submsg = base.pp_submsg; pp_submsg_txt = base.pp_submsg_txt; } (** Capture warnings and keep them in a list *) let warnings = ref [] let report_printer = (* Extend [printer_register_locs] *) let pp self ppf report = match report.Location.kind with | Location.Report_warning _ | Location.Report_warning_as_error _ -> printer_register_locs.pp self (snd warning_fmt) report; let w = flush_fmt warning_fmt in warnings := w :: !warnings | _ -> printer_register_locs.pp self ppf report in { printer_register_locs with pp } let fatal ic oc fmt = Format.kfprintf (fun ppf -> Format.fprintf ppf "@]@."; close_in ic; close_out oc; exit 1) self_error_fmt ("@[<hov 2> Error " ^^ fmt) let init () = Location.report_printer := (fun () -> report_printer); Clflags.color := Some Misc.Color.Never; Clflags.no_std_include := true; Compenv.last_include_dirs := [Filename.concat !repo_root "stdlib"]; Compmisc.init_path (); try Toploop.initialize_toplevel_env (); Sys.interactive := false with _ -> (eprintf "Invalid repo root: %s?%!" !repo_root; exit 2) let exec (_,ppf) p = try ignore @@ Toploop.execute_phrase true ppf p with exn -> let bt = Printexc.get_raw_backtrace () in begin try Location.report_exception (snd error_fmt) exn with _ -> eprintf "Uncaught exception: %s\n%s\n" (Printexc.to_string exn) (Printexc.raw_backtrace_to_string bt) end let parse fname mode s = let lex = Lexing.from_string s in Location.init lex fname; Location.input_name := fname; Location.input_lexbuf := Some lex; try match mode with | Toplevel -> Parse.toplevel_phrase lex | Verbatim -> Ptop_def (Parse.implementation lex) | Signature -> let sign = Parse.interface lex in let name = Location.mknoloc "wrap" in let str = Ast_helper.[Str.modtype @@ Mtd.mk ~typ:(Mty.signature sign) name] in Ptop_def str with | Lexer.Error _ | Syntaxerr.Error _ -> raise (Phrase_parsing s) let take x = let r = !x in x := []; r let read_output () = let warnings = take warnings in let error = flush_fmt error_fmt in let values = replace_first ~!{|^#\( *\*\)* *|} "" @@ flush_fmt out_fmt in (* the inner ( *\* )* group is here to clean the starting "*" introduced for multiline comments *) let underlined = take locs in let stdout = read_stdout () in { values; warnings; error; stdout; underlined } (** exec and ignore all output from the toplevel *) let eval b = let s = Buffer.contents b in let ast = Parse.toplevel_phrase (Lexing.from_string s) in exec out_fmt ast; ignore (read_output()); Buffer.reset b end let () = Arg.parse ["-n", Arg.Int (fun n -> linelen := n), "line length"; "-o", Arg.String (fun s -> outfile := s), "output"; "-repo-root", Arg.String ((:=) repo_root ), "repo root"; "-w", Arg.Set cut_at_blanks, "cut at blanks"; "-v", Arg.Bool (fun b -> verbose := b ), "output result on stderr" ] (fun s -> files := s :: !files) "caml-tex: "; Toplevel.init () (** The Output module deals with the analysis and classification of the interpreter output and the parsing of status-related options or annotations for the caml_example environment *) module Output = struct (** Interpreter output status *) type status = | Ok | Warning of int | Error type kind = | Annotation (** Local annotation: [ [@@expect (*annotation*) ] ]*) | Option (** Global environment option: [\begin{caml_example}[option[=value]] ... \end{caml_example}] *) (** Pretty printer for status *) let pp_status ppf = function | Error -> Format.fprintf ppf "error" | Ok -> Format.fprintf ppf "ok" | Warning n -> Format.fprintf ppf "warning %d" n (** Pretty printer for status preceded with an undefined determinant *) let pp_a_status ppf = function | Error -> Format.fprintf ppf "an error" | Ok -> Format.fprintf ppf "an ok" | Warning n -> Format.fprintf ppf "a warning %d" n * { 1 Related latex environment } let env = function | Error -> error | Warning _ -> warning | Ok -> ok_output * { 1 Exceptions } exception Parsing_error of kind * string type source = { file : string; lines : int * int; phrase : string; output : string } type unexpected_report = {source : source; expected : status; got : status} exception Unexpected_status of unexpected_report let print_source ppf {file; lines = (start, stop); phrase; output} = Format.fprintf ppf "%s, lines %d to %d:\n\"\n%s\n\"\n\"\n%s\n\"." file start stop phrase output let print_unexpected {source; expected; got} = if expected = Ok then Toplevel.eprintf "Error when evaluating a caml_example environment in %a\n\ Unexpected %a status.\n\ If %a status was expected, add an [@@expect %a] annotation.\n" print_source source pp_status got pp_a_status got pp_status got else Toplevel.eprintf "Error when evaluating a guarded caml_example environment in %a\n\ Unexpected %a status, %a status was expected.\n\ If %a status was in fact expected, change the status annotation to \ [@@expect %a].\n" print_source source pp_status got pp_a_status expected pp_a_status got pp_status got; flush stderr let print_parsing_error k s = match k with | Option -> Toplevel.eprintf "Unknown caml_example option: [%s].\n\ Supported options are \"ok\",\"error\", or \"warning=n\" (with n \ a warning number).\n" s | Annotation -> Toplevel.eprintf "Unknown caml_example phrase annotation: [@@expect %s].\n\ Supported annotations are [@@expect ok], [@@expect error],\n\ and [@@expect warning n] (with n a warning number).\n" s (** {1 Output analysis} *) let catch_error = function | "" -> None | _ -> Some Error let catch_warning = function | [] -> None | s :: _ when string_match ~!{|Warning \([0-9]+\):|} s 0 -> Some (Warning (int_of_string @@ matched_group 1 s)) | _ -> None let status ws es = match catch_warning ws, catch_error es with | Some w, _ -> w | None, Some e -> e | None, None -> Ok * { 1 Parsing caml_example options } * [ warning = n ] options for caml_example options let parse_warning s = if string_match ~!{|warning=\([0-9]+\)|} s 0 then Some (Warning (int_of_string @@ matched_group 1 s)) else None * [ warning n ] annotations let parse_local_warning s = if string_match ~!{|warning \([0-9]+\)|} s 0 then Some (Warning (int_of_string @@ matched_group 1 s)) else None let parse_error s = if s="error" then Some Error else None let parse_ok s = if s = "ok" then Some Ok else None * the environment - wide expected status output let expected s = match parse_warning s, parse_error s with | Some w, _ -> w | None, Some e -> e | None, None -> raise (Parsing_error (Option,s)) * the local ( i.e. phrase - wide ) expected status output let local_expected s = match parse_local_warning s, parse_error s, parse_ok s with | Some w, _, _ -> w | None, Some e, _ -> e | None, None, Some ok -> ok | None, None, None -> raise (Parsing_error (Annotation,s)) end module Text_transform = struct type kind = | Underline | Ellipsis type t = { kind : kind; start : int; stop : int} exception Intersection of { line : int; file : string; left : t; right : t; } let pp ppf = function | Underline -> Format.fprintf ppf "underline" | Ellipsis -> Format.fprintf ppf "ellipsis" let underline start stop = { kind = Underline; start; stop} let ellipsis start stop = { kind = Ellipsis; start; stop } let escape_specials s = s |> global_replace ~!{|\$|} {|$\textdollar$|} let rec apply_transform input (pos,underline_stop,out) t = if pos >= String.length input then pos, underline_stop, out else match underline_stop with | Some stop when stop <= t.start -> let f = escape_specials (String.sub input ~pos ~len:(stop - pos)) in let out = camleunderline :: f :: out in apply_transform input (stop,None,out) t | _ -> let out = escape_specials (String.sub input ~pos ~len:(t.start - pos))::out in match t.kind with | Ellipsis -> t.stop, underline_stop, latex_escape {|\ldots|} :: out | Underline -> t.start, Some t.stop, camlbunderline :: out (** Check that all ellipsis are strictly nested inside underline transform and that otherwise no transform starts before the end of the previous transform in a list of transforms *) type partition = U of t * t list | E of t let check_partition line file l = let init = ellipsis 0 0 in let rec partition = function | [] -> [] | {kind=Underline; _ } as t :: q -> underline t [] q | {kind=Ellipsis; _ } as t :: q -> E t :: partition q and underline u n = function | [] -> end_underline u n [] | {kind=Underline; _ } :: _ as q -> end_underline u n q | {kind=Ellipsis; _ } as t :: q -> if t.stop < u.stop then underline u (t::n) q else end_underline u n (t::q) and end_underline u n l = U(u,List.rev n) :: partition l in let check_elt last t = if t.start < last.stop then raise (Intersection {line;file; left = last; right = t}) else t in let check acc = function | E t -> check_elt acc t | U(u,n) -> let _ = check_elt acc u in let _ = List.fold_left ~f:check_elt ~init n in u in List.fold_left ~f:check ~init (partition l) |> ignore let apply ts file line s = remove duplicated transforms that can appear due to duplicated parse tree elements . For instance , [ let f : ( _ [ @ellipsis ] = ( ) ] is transformed to [ let f : ( _ [ @ellipsis ] ) = ( ( ): ( _ [ @ellipsis ] ) ] with the same location for the two ellipses . duplicated parse tree elements. For instance, [let f : (_ [@ellipsis] = ()] is transformed to [let f: (_ [@ellipsis]) = (():(_ [@ellipsis])] with the same location for the two ellipses. *) let ts = List.sort_uniq compare ts in let ts = List.sort (fun x y -> compare x.start y.start) ts in check_partition line file ts; let last, underline, ls = List.fold_left ~f:(apply_transform s) ~init:(0,None,[]) ts in let last, ls = match underline with | None -> last, ls | Some stop -> let f = escape_specials (String.sub s ~pos:last ~len:(stop - last)) in stop, camleunderline :: f :: ls in let ls = let n = String.length s in if last = n then ls else escape_specials (String.sub s last (n-last)) :: ls in String.concat "" (List.rev ls) end exception Missing_double_semicolon of string * int exception Missing_mode of string * int type incompatibility = | Signature_with_visible_answer of string * int exception Incompatible_options of incompatibility module Ellipsis = struct (** This module implements the extraction of ellipsis locations from phrases. An ellipsis is either an [[@ellipsis]] attribute, or a pair of [[@@@ellipsis.start]...[@@@ellipsis.stop]] attributes. *) exception Unmatched_ellipsis of {kind : string; start : int; stop : int} (** raised when an [[@@@ellipsis.start]] or [[@@@ellipsis.stop]] is not paired with another ellipsis attribute *) exception Nested_ellipses of {first : int ; second : int} (** raised by [[@@@ellipsis.start][@@@ellipsis.start]] *) let extract f x = let transforms = ref [] in let last_loc = ref Location.none in let left_mark = ref None (* stored position of [@@@ellipsis.start]*) in let location _this loc = we rely on the fact that the default iterator calls first the location subiterator , then the attribute subiterator the location subiterator, then the attribute subiterator *) last_loc := loc in let attribute _this attr = let module L = Location in let module P = Parsetree in let name = attr.P.attr_name.L.txt in let loc = !last_loc in let start = loc.L.loc_start.Lexing.pos_cnum in let attr_start = attr.P.attr_loc.L.loc_start.Lexing.pos_cnum in let attr_stop = attr.P.attr_loc.L.loc_end.Lexing.pos_cnum in let stop = max loc.L.loc_end.Lexing.pos_cnum attr_stop in let check_nested () = match !left_mark with | Some (first,_) -> raise (Nested_ellipses {first; second=attr_start}) | None -> () in match name with | "ellipsis" -> check_nested (); transforms := {Text_transform.kind=Ellipsis; start; stop } :: !transforms | "ellipsis.start" -> check_nested (); left_mark := Some (start, stop) | "ellipsis.stop" -> begin match !left_mark with | None -> raise (Unmatched_ellipsis {kind="right"; start; stop}) | Some (start', stop' ) -> let start, stop = min start start', max stop stop' in transforms := {kind=Ellipsis; start ; stop } :: !transforms; left_mark := None end | _ -> () in f {Ast_iterator.default_iterator with location; attribute} x; (match !left_mark with | None -> () | Some (start,stop) -> raise (Unmatched_ellipsis {kind="left"; start; stop }) ); !transforms let find = function | Parsetree.Ptop_def ast -> extract (fun it -> it.structure it) ast | Ptop_dir _ -> [] end let process_file file = let ic = try open_in file with _ -> failwith "Cannot read input file" in let phrase_start = ref 1 and phrase_stop = ref 1 in let incr_phrase_start () = incr phrase_start; phrase_stop := !phrase_start in let oc = try if !outfile = "-" then stdout else if !outfile = "" then open_out (replace_first ~!"\\.tex$" "" file ^ ".ml.tex") else open_out_gen [Open_wronly; Open_creat; Open_append; Open_text] 0x666 !outfile with _ -> failwith "Cannot open output file" in let tex_fmt = Format.formatter_of_out_channel oc in let fatal x = Toplevel.fatal ic oc x in let re_spaces = "[ \t]*" in let re_start = ~!( {|\\begin{caml_example\(\*?\)}|} ^ re_spaces ^ {|\({toplevel}\|{verbatim}\|{signature}\)?|} ^ re_spaces ^ {|\(\[\(.*\)\]\)?|} ^ re_spaces ^ "$" ) in try while true do let input = ref (input_line ic) in incr_phrase_start(); if string_match re_start !input 0 then begin let omit_answer = matched_group 1 !input = "*" in let mode = match matched_group 2 !input with | exception Not_found -> raise (Missing_mode(file, !phrase_stop)) | "{toplevel}" -> Toplevel | "{verbatim}" -> Verbatim | "{signature}" -> Signature | _ -> assert false in if mode = Signature && not omit_answer then raise (Incompatible_options( Signature_with_visible_answer(file,!phrase_stop)) ); let explicit_stop = match mode with | Verbatim | Signature -> false | Toplevel -> true in let global_expected = try Output.expected @@ matched_group 4 !input with Not_found -> Output.Ok in start tex_fmt main [string_of_mode mode]; let first = ref true in let read_phrase () = let phrase = Buffer.create 256 in let rec read () = let input = incr phrase_stop; input_line ic in let implicit_stop = if string_match ~!"\\\\end{caml_example\\*?}[ \t]*$" input 0 then begin if !phrase_stop = 1 + !phrase_start then raise End_of_file else if explicit_stop then raise @@ Missing_double_semicolon (file,!phrase_stop) else true end else false in if Buffer.length phrase > 0 then Buffer.add_char phrase '\n'; let stop = implicit_stop || ( not (mode = Signature) && string_match ~!"\\(.*\\)[ \t]*;;[ \t]*$" input 0 ) in if not stop then ( Buffer.add_string phrase input; read () ) else begin decr phrase_stop; let last_input = if implicit_stop then "" else matched_group 1 input in let expected = if string_match ~!{|\(.*\)\[@@expect \(.*\)\]|} last_input 0 then ( Buffer.add_string phrase (matched_group 1 last_input); Output.local_expected @@ matched_group 2 last_input ) else (Buffer.add_string phrase last_input; global_expected) in if not implicit_stop then Buffer.add_string phrase ";;"; implicit_stop, Buffer.contents phrase, expected end in read () in try while true do let implicit_stop, phrase, expected = read_phrase () in let ast = Toplevel.parse file mode phrase in let ellipses = Ellipsis.find ast in let () = Toplevel.(exec out_fmt) ast in let out = Toplevel.read_output () in let error_msgs = String.concat "" (out.warnings @ [out.error]) in let output = String.concat "" [error_msgs; out.stdout; out.values] in let status = Output.status out.warnings out.error in if status <> expected then ( let source = Output.{ file; lines = (!phrase_start, !phrase_stop); phrase; output } in raise (Output.Unexpected_status {Output.got=status; expected; source} ) ) else ( incr phrase_stop; phrase_start := !phrase_stop ); let phrase = let underline = List.map (fun (x,y) -> Text_transform.underline x y) out.underlined in Text_transform.apply (underline @ ellipses) file !phrase_stop phrase in (* Special characters may also appear in output strings -Didier *) let output = Text_transform.escape_specials output in let phrase = global_replace ~!{|^\(.\)|} camlin phrase and output = global_replace ~!{|^\(.\)|} camlout output in let final_output = if omit_answer && String.length error_msgs > 0 then global_replace ~!{|^\(.\)|} camlout error_msgs else if omit_answer then "" else output in start tex_fmt phrase_env []; code_env input_env tex_fmt phrase; if String.length final_output > 0 then code_env (Output.env status) tex_fmt final_output; stop tex_fmt phrase_env; flush oc; first := false; if implicit_stop then raise End_of_file done with End_of_file -> phrase_start:= !phrase_stop; stop tex_fmt main end else if string_match ~!"\\\\begin{caml_eval}[ \t]*$" !input 0 then begin let eval_buffer = Buffer.create 256 in while input := input_line ic; not (string_match ~!"\\\\end{caml_eval}[ \t]*$" !input 0) do Buffer.add_string eval_buffer !input; Buffer.add_char eval_buffer '\n'; if string_match ~!".*;;[ \t]*$" !input 0 then begin Toplevel.eval eval_buffer end done; if Buffer.length eval_buffer > 0 then ( Buffer.add_string eval_buffer ";;\n"; Toplevel.eval eval_buffer ) end else begin Format.fprintf tex_fmt "%s\n" !input; Format.pp_print_flush tex_fmt () end done with | End_of_file -> close_in ic; close_out oc | Output.Unexpected_status r -> ( Output.print_unexpected r; close_in ic; close_out oc; exit 1 ) | Output.Parsing_error (k,s) -> ( Output.print_parsing_error k s; close_in ic; close_out oc; exit 1 ) | Phrase_parsing s -> fatal "when parsing the following phrase:@ %s" s | Missing_double_semicolon (file, line_number) -> fatal "when evaluating a caml_example environment in %s:@;\ missing \";;\" at line %d" file (line_number-2) | Missing_mode (file, line_number) -> fatal "when parsing a caml_example environment in %s:@;\ missing mode argument at line %d,@ \ available modes {toplevel,verbatim}" file (line_number-2) | Incompatible_options Signature_with_visible_answer (file, line_number) -> fatal "when parsing a caml_example environment in@ \ %s, line %d:@,\ the signature mode is only compatible with \"caml_example*\"@ \ Hint: did you forget to add \"*\"?" file (line_number-2); | Text_transform.Intersection {line;file;left;right} -> fatal "when evaluating a caml_example environment in %s, line %d:@ \ Textual transforms must be well-separated.@ The \"%a\" transform \ spanned the interval %d-%d,@ \ intersecting with another \"%a\" transform @ \ on the %d-%d interval.@ \ Hind: did you try to elide a code fragment which raised a warning?" file (line-2) Text_transform.pp left.kind left.start left.stop Text_transform.pp right.kind right.start right.stop | Ellipsis.Unmatched_ellipsis {kind;start;stop} -> fatal "when evaluating a caml_example environment,@ \ the %s mark at position %d-%d was unmatched" kind start stop | Ellipsis.Nested_ellipses {first;second} -> fatal "when evaluating a caml_example environment,@ \ there were two nested ellipsis attribute.@ The first one \ started at position %d,@ the second one at %d" first second let _ = if !outfile <> "-" && !outfile <> "" then begin try close_out (open_out !outfile) with _ -> failwith "Cannot open output file" end; List.iter process_file (List.rev !files);
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/tools/caml_tex.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. ************************************************************************ * Restrict the number of latex environment * Initialize the toplevel loop, redirect stdout and stderr, capture warnings and error messages * error message text * warning messages text * toplevel output * output printed on the toplevel stdout * locations to underline in input phrases * Redirect the stdout * Store character intervals directly * Record locations in the main error and suberrors without printing them The following fields are kept identical to [base], listed explicitly so that future field additions result in an error -- using (Location.batch_mode_printer with ...) would be the symmetric problem to a fragile pattern-matching. * Capture warnings and keep them in a list Extend [printer_register_locs] the inner ( *\* )* group is here to clean the starting "*" introduced for multiline comments * exec and ignore all output from the toplevel * The Output module deals with the analysis and classification of the interpreter output and the parsing of status-related options or annotations for the caml_example environment * Interpreter output status * Local annotation: [ [@@expect (*annotation * Global environment option: [\begin{caml_example}[option[=value]] ... \end{caml_example}] * Pretty printer for status * Pretty printer for status preceded with an undefined determinant * {1 Output analysis} * Check that all ellipsis are strictly nested inside underline transform and that otherwise no transform starts before the end of the previous transform in a list of transforms * This module implements the extraction of ellipsis locations from phrases. An ellipsis is either an [[@ellipsis]] attribute, or a pair of [[@@@ellipsis.start]...[@@@ellipsis.stop]] attributes. * raised when an [[@@@ellipsis.start]] or [[@@@ellipsis.stop]] is not paired with another ellipsis attribute * raised by [[@@@ellipsis.start][@@@ellipsis.start]] stored position of [@@@ellipsis.start] Special characters may also appear in output strings -Didier
, projet Gallium , INRIA Paris , Nagoya University Copyright 2018 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the [@@@warning "a-40-6"] open StdLabels open Str let camlprefix = "caml" let latex_escape s = String.concat "" ["$"; s; "$"] let camlin = latex_escape {|\\?|} ^ {|\1|} let camlout = latex_escape {|\\:|} ^ {|\1|} let camlbunderline = "<<" let camleunderline = ">>" type env = Env of string let main = Env "example" let input_env = Env "input" let ok_output = Env "output" let error = Env "error" let warning = Env "warn" let phrase_env = Env "" let start out (Env s) args = Format.fprintf out "\\begin{%s%s}" camlprefix s; List.iter (Format.fprintf out "{%s}") args; Format.fprintf out "\n" let stop out (Env s) = Format.fprintf out "\\end{%s%s}" camlprefix s; Format.fprintf out "\n" let code_env env out s = let sep = if s.[String.length s - 1] = '\n' then "" else "\n" in Format.fprintf out "%a%s%s%a" (fun ppf env -> start ppf env []) env s sep stop env type example_mode = Toplevel | Verbatim | Signature let string_of_mode = function | Toplevel -> "toplevel" | Verbatim -> "verbatim" | Signature -> "signature" let verbose = ref true let linelen = ref 72 let outfile = ref "" let cut_at_blanks = ref false let files = ref [] let repo_root = ref "" let (~!) = let memo = ref [] in fun key -> try List.assq key !memo with Not_found -> let data = Str.regexp key in memo := (key, data) :: !memo; data exception Phrase_parsing of string module Toplevel = struct type output = { underlined : (int * int) list } let buffer_fmt () = let b = Buffer.create 30 in b, Format.formatter_of_buffer b let error_fmt = buffer_fmt () let warning_fmt = buffer_fmt () let out_fmt = buffer_fmt () let flush_fmt (b,fmt) = Format.pp_print_flush fmt (); let r = Buffer.contents b in Buffer.reset b; r let stdout_out, stdout_in = Unix.pipe ~cloexec:true () let () = Unix.dup2 stdout_in Unix.stdout let self_error_fmt = Format.formatter_of_out_channel stderr let eprintf = Format.eprintf let read_stdout = let size = 50 in let b = Bytes.create size in let buffer = Buffer.create 100 in let rec read_toplevel_stdout () = match Unix.select[stdout_out][][] 0. with | [a], _, _ -> let n = Unix.read stdout_out b 0 size in Buffer.add_subbytes buffer b 0 n; if n = size then read_toplevel_stdout () | _ -> () in fun () -> let () = flush stdout; read_toplevel_stdout () in let r = Buffer.contents buffer in Buffer.reset buffer; r let locs = ref [] let register_loc (loc : Location.t) = let startchar = loc.loc_start.pos_cnum in let endchar = loc.loc_end.pos_cnum in if startchar >= 0 then locs := (startchar, endchar) :: !locs let printer_register_locs = let base = Location.batch_mode_printer in { Location.pp_main_loc = (fun _ _ _ loc -> register_loc loc); pp_submsg_loc = (fun _ _ _ loc -> register_loc loc); pp = base.pp; pp_report_kind = base.pp_report_kind; pp_main_txt = base.pp_main_txt; pp_submsgs = base.pp_submsgs; pp_submsg = base.pp_submsg; pp_submsg_txt = base.pp_submsg_txt; } let warnings = ref [] let report_printer = let pp self ppf report = match report.Location.kind with | Location.Report_warning _ | Location.Report_warning_as_error _ -> printer_register_locs.pp self (snd warning_fmt) report; let w = flush_fmt warning_fmt in warnings := w :: !warnings | _ -> printer_register_locs.pp self ppf report in { printer_register_locs with pp } let fatal ic oc fmt = Format.kfprintf (fun ppf -> Format.fprintf ppf "@]@."; close_in ic; close_out oc; exit 1) self_error_fmt ("@[<hov 2> Error " ^^ fmt) let init () = Location.report_printer := (fun () -> report_printer); Clflags.color := Some Misc.Color.Never; Clflags.no_std_include := true; Compenv.last_include_dirs := [Filename.concat !repo_root "stdlib"]; Compmisc.init_path (); try Toploop.initialize_toplevel_env (); Sys.interactive := false with _ -> (eprintf "Invalid repo root: %s?%!" !repo_root; exit 2) let exec (_,ppf) p = try ignore @@ Toploop.execute_phrase true ppf p with exn -> let bt = Printexc.get_raw_backtrace () in begin try Location.report_exception (snd error_fmt) exn with _ -> eprintf "Uncaught exception: %s\n%s\n" (Printexc.to_string exn) (Printexc.raw_backtrace_to_string bt) end let parse fname mode s = let lex = Lexing.from_string s in Location.init lex fname; Location.input_name := fname; Location.input_lexbuf := Some lex; try match mode with | Toplevel -> Parse.toplevel_phrase lex | Verbatim -> Ptop_def (Parse.implementation lex) | Signature -> let sign = Parse.interface lex in let name = Location.mknoloc "wrap" in let str = Ast_helper.[Str.modtype @@ Mtd.mk ~typ:(Mty.signature sign) name] in Ptop_def str with | Lexer.Error _ | Syntaxerr.Error _ -> raise (Phrase_parsing s) let take x = let r = !x in x := []; r let read_output () = let warnings = take warnings in let error = flush_fmt error_fmt in let values = replace_first ~!{|^#\( *\*\)* *|} "" @@ flush_fmt out_fmt in let underlined = take locs in let stdout = read_stdout () in { values; warnings; error; stdout; underlined } let eval b = let s = Buffer.contents b in let ast = Parse.toplevel_phrase (Lexing.from_string s) in exec out_fmt ast; ignore (read_output()); Buffer.reset b end let () = Arg.parse ["-n", Arg.Int (fun n -> linelen := n), "line length"; "-o", Arg.String (fun s -> outfile := s), "output"; "-repo-root", Arg.String ((:=) repo_root ), "repo root"; "-w", Arg.Set cut_at_blanks, "cut at blanks"; "-v", Arg.Bool (fun b -> verbose := b ), "output result on stderr" ] (fun s -> files := s :: !files) "caml-tex: "; Toplevel.init () module Output = struct type status = | Ok | Warning of int | Error type kind = let pp_status ppf = function | Error -> Format.fprintf ppf "error" | Ok -> Format.fprintf ppf "ok" | Warning n -> Format.fprintf ppf "warning %d" n let pp_a_status ppf = function | Error -> Format.fprintf ppf "an error" | Ok -> Format.fprintf ppf "an ok" | Warning n -> Format.fprintf ppf "a warning %d" n * { 1 Related latex environment } let env = function | Error -> error | Warning _ -> warning | Ok -> ok_output * { 1 Exceptions } exception Parsing_error of kind * string type source = { file : string; lines : int * int; phrase : string; output : string } type unexpected_report = {source : source; expected : status; got : status} exception Unexpected_status of unexpected_report let print_source ppf {file; lines = (start, stop); phrase; output} = Format.fprintf ppf "%s, lines %d to %d:\n\"\n%s\n\"\n\"\n%s\n\"." file start stop phrase output let print_unexpected {source; expected; got} = if expected = Ok then Toplevel.eprintf "Error when evaluating a caml_example environment in %a\n\ Unexpected %a status.\n\ If %a status was expected, add an [@@expect %a] annotation.\n" print_source source pp_status got pp_a_status got pp_status got else Toplevel.eprintf "Error when evaluating a guarded caml_example environment in %a\n\ Unexpected %a status, %a status was expected.\n\ If %a status was in fact expected, change the status annotation to \ [@@expect %a].\n" print_source source pp_status got pp_a_status expected pp_a_status got pp_status got; flush stderr let print_parsing_error k s = match k with | Option -> Toplevel.eprintf "Unknown caml_example option: [%s].\n\ Supported options are \"ok\",\"error\", or \"warning=n\" (with n \ a warning number).\n" s | Annotation -> Toplevel.eprintf "Unknown caml_example phrase annotation: [@@expect %s].\n\ Supported annotations are [@@expect ok], [@@expect error],\n\ and [@@expect warning n] (with n a warning number).\n" s let catch_error = function | "" -> None | _ -> Some Error let catch_warning = function | [] -> None | s :: _ when string_match ~!{|Warning \([0-9]+\):|} s 0 -> Some (Warning (int_of_string @@ matched_group 1 s)) | _ -> None let status ws es = match catch_warning ws, catch_error es with | Some w, _ -> w | None, Some e -> e | None, None -> Ok * { 1 Parsing caml_example options } * [ warning = n ] options for caml_example options let parse_warning s = if string_match ~!{|warning=\([0-9]+\)|} s 0 then Some (Warning (int_of_string @@ matched_group 1 s)) else None * [ warning n ] annotations let parse_local_warning s = if string_match ~!{|warning \([0-9]+\)|} s 0 then Some (Warning (int_of_string @@ matched_group 1 s)) else None let parse_error s = if s="error" then Some Error else None let parse_ok s = if s = "ok" then Some Ok else None * the environment - wide expected status output let expected s = match parse_warning s, parse_error s with | Some w, _ -> w | None, Some e -> e | None, None -> raise (Parsing_error (Option,s)) * the local ( i.e. phrase - wide ) expected status output let local_expected s = match parse_local_warning s, parse_error s, parse_ok s with | Some w, _, _ -> w | None, Some e, _ -> e | None, None, Some ok -> ok | None, None, None -> raise (Parsing_error (Annotation,s)) end module Text_transform = struct type kind = | Underline | Ellipsis type t = { kind : kind; start : int; stop : int} exception Intersection of { line : int; file : string; left : t; right : t; } let pp ppf = function | Underline -> Format.fprintf ppf "underline" | Ellipsis -> Format.fprintf ppf "ellipsis" let underline start stop = { kind = Underline; start; stop} let ellipsis start stop = { kind = Ellipsis; start; stop } let escape_specials s = s |> global_replace ~!{|\$|} {|$\textdollar$|} let rec apply_transform input (pos,underline_stop,out) t = if pos >= String.length input then pos, underline_stop, out else match underline_stop with | Some stop when stop <= t.start -> let f = escape_specials (String.sub input ~pos ~len:(stop - pos)) in let out = camleunderline :: f :: out in apply_transform input (stop,None,out) t | _ -> let out = escape_specials (String.sub input ~pos ~len:(t.start - pos))::out in match t.kind with | Ellipsis -> t.stop, underline_stop, latex_escape {|\ldots|} :: out | Underline -> t.start, Some t.stop, camlbunderline :: out type partition = U of t * t list | E of t let check_partition line file l = let init = ellipsis 0 0 in let rec partition = function | [] -> [] | {kind=Underline; _ } as t :: q -> underline t [] q | {kind=Ellipsis; _ } as t :: q -> E t :: partition q and underline u n = function | [] -> end_underline u n [] | {kind=Underline; _ } :: _ as q -> end_underline u n q | {kind=Ellipsis; _ } as t :: q -> if t.stop < u.stop then underline u (t::n) q else end_underline u n (t::q) and end_underline u n l = U(u,List.rev n) :: partition l in let check_elt last t = if t.start < last.stop then raise (Intersection {line;file; left = last; right = t}) else t in let check acc = function | E t -> check_elt acc t | U(u,n) -> let _ = check_elt acc u in let _ = List.fold_left ~f:check_elt ~init n in u in List.fold_left ~f:check ~init (partition l) |> ignore let apply ts file line s = remove duplicated transforms that can appear due to duplicated parse tree elements . For instance , [ let f : ( _ [ @ellipsis ] = ( ) ] is transformed to [ let f : ( _ [ @ellipsis ] ) = ( ( ): ( _ [ @ellipsis ] ) ] with the same location for the two ellipses . duplicated parse tree elements. For instance, [let f : (_ [@ellipsis] = ()] is transformed to [let f: (_ [@ellipsis]) = (():(_ [@ellipsis])] with the same location for the two ellipses. *) let ts = List.sort_uniq compare ts in let ts = List.sort (fun x y -> compare x.start y.start) ts in check_partition line file ts; let last, underline, ls = List.fold_left ~f:(apply_transform s) ~init:(0,None,[]) ts in let last, ls = match underline with | None -> last, ls | Some stop -> let f = escape_specials (String.sub s ~pos:last ~len:(stop - last)) in stop, camleunderline :: f :: ls in let ls = let n = String.length s in if last = n then ls else escape_specials (String.sub s last (n-last)) :: ls in String.concat "" (List.rev ls) end exception Missing_double_semicolon of string * int exception Missing_mode of string * int type incompatibility = | Signature_with_visible_answer of string * int exception Incompatible_options of incompatibility module Ellipsis = struct exception Unmatched_ellipsis of {kind : string; start : int; stop : int} exception Nested_ellipses of {first : int ; second : int} let extract f x = let transforms = ref [] in let last_loc = ref Location.none in let location _this loc = we rely on the fact that the default iterator calls first the location subiterator , then the attribute subiterator the location subiterator, then the attribute subiterator *) last_loc := loc in let attribute _this attr = let module L = Location in let module P = Parsetree in let name = attr.P.attr_name.L.txt in let loc = !last_loc in let start = loc.L.loc_start.Lexing.pos_cnum in let attr_start = attr.P.attr_loc.L.loc_start.Lexing.pos_cnum in let attr_stop = attr.P.attr_loc.L.loc_end.Lexing.pos_cnum in let stop = max loc.L.loc_end.Lexing.pos_cnum attr_stop in let check_nested () = match !left_mark with | Some (first,_) -> raise (Nested_ellipses {first; second=attr_start}) | None -> () in match name with | "ellipsis" -> check_nested (); transforms := {Text_transform.kind=Ellipsis; start; stop } :: !transforms | "ellipsis.start" -> check_nested (); left_mark := Some (start, stop) | "ellipsis.stop" -> begin match !left_mark with | None -> raise (Unmatched_ellipsis {kind="right"; start; stop}) | Some (start', stop' ) -> let start, stop = min start start', max stop stop' in transforms := {kind=Ellipsis; start ; stop } :: !transforms; left_mark := None end | _ -> () in f {Ast_iterator.default_iterator with location; attribute} x; (match !left_mark with | None -> () | Some (start,stop) -> raise (Unmatched_ellipsis {kind="left"; start; stop }) ); !transforms let find = function | Parsetree.Ptop_def ast -> extract (fun it -> it.structure it) ast | Ptop_dir _ -> [] end let process_file file = let ic = try open_in file with _ -> failwith "Cannot read input file" in let phrase_start = ref 1 and phrase_stop = ref 1 in let incr_phrase_start () = incr phrase_start; phrase_stop := !phrase_start in let oc = try if !outfile = "-" then stdout else if !outfile = "" then open_out (replace_first ~!"\\.tex$" "" file ^ ".ml.tex") else open_out_gen [Open_wronly; Open_creat; Open_append; Open_text] 0x666 !outfile with _ -> failwith "Cannot open output file" in let tex_fmt = Format.formatter_of_out_channel oc in let fatal x = Toplevel.fatal ic oc x in let re_spaces = "[ \t]*" in let re_start = ~!( {|\\begin{caml_example\(\*?\)}|} ^ re_spaces ^ {|\({toplevel}\|{verbatim}\|{signature}\)?|} ^ re_spaces ^ {|\(\[\(.*\)\]\)?|} ^ re_spaces ^ "$" ) in try while true do let input = ref (input_line ic) in incr_phrase_start(); if string_match re_start !input 0 then begin let omit_answer = matched_group 1 !input = "*" in let mode = match matched_group 2 !input with | exception Not_found -> raise (Missing_mode(file, !phrase_stop)) | "{toplevel}" -> Toplevel | "{verbatim}" -> Verbatim | "{signature}" -> Signature | _ -> assert false in if mode = Signature && not omit_answer then raise (Incompatible_options( Signature_with_visible_answer(file,!phrase_stop)) ); let explicit_stop = match mode with | Verbatim | Signature -> false | Toplevel -> true in let global_expected = try Output.expected @@ matched_group 4 !input with Not_found -> Output.Ok in start tex_fmt main [string_of_mode mode]; let first = ref true in let read_phrase () = let phrase = Buffer.create 256 in let rec read () = let input = incr phrase_stop; input_line ic in let implicit_stop = if string_match ~!"\\\\end{caml_example\\*?}[ \t]*$" input 0 then begin if !phrase_stop = 1 + !phrase_start then raise End_of_file else if explicit_stop then raise @@ Missing_double_semicolon (file,!phrase_stop) else true end else false in if Buffer.length phrase > 0 then Buffer.add_char phrase '\n'; let stop = implicit_stop || ( not (mode = Signature) && string_match ~!"\\(.*\\)[ \t]*;;[ \t]*$" input 0 ) in if not stop then ( Buffer.add_string phrase input; read () ) else begin decr phrase_stop; let last_input = if implicit_stop then "" else matched_group 1 input in let expected = if string_match ~!{|\(.*\)\[@@expect \(.*\)\]|} last_input 0 then ( Buffer.add_string phrase (matched_group 1 last_input); Output.local_expected @@ matched_group 2 last_input ) else (Buffer.add_string phrase last_input; global_expected) in if not implicit_stop then Buffer.add_string phrase ";;"; implicit_stop, Buffer.contents phrase, expected end in read () in try while true do let implicit_stop, phrase, expected = read_phrase () in let ast = Toplevel.parse file mode phrase in let ellipses = Ellipsis.find ast in let () = Toplevel.(exec out_fmt) ast in let out = Toplevel.read_output () in let error_msgs = String.concat "" (out.warnings @ [out.error]) in let output = String.concat "" [error_msgs; out.stdout; out.values] in let status = Output.status out.warnings out.error in if status <> expected then ( let source = Output.{ file; lines = (!phrase_start, !phrase_stop); phrase; output } in raise (Output.Unexpected_status {Output.got=status; expected; source} ) ) else ( incr phrase_stop; phrase_start := !phrase_stop ); let phrase = let underline = List.map (fun (x,y) -> Text_transform.underline x y) out.underlined in Text_transform.apply (underline @ ellipses) file !phrase_stop phrase in let output = Text_transform.escape_specials output in let phrase = global_replace ~!{|^\(.\)|} camlin phrase and output = global_replace ~!{|^\(.\)|} camlout output in let final_output = if omit_answer && String.length error_msgs > 0 then global_replace ~!{|^\(.\)|} camlout error_msgs else if omit_answer then "" else output in start tex_fmt phrase_env []; code_env input_env tex_fmt phrase; if String.length final_output > 0 then code_env (Output.env status) tex_fmt final_output; stop tex_fmt phrase_env; flush oc; first := false; if implicit_stop then raise End_of_file done with End_of_file -> phrase_start:= !phrase_stop; stop tex_fmt main end else if string_match ~!"\\\\begin{caml_eval}[ \t]*$" !input 0 then begin let eval_buffer = Buffer.create 256 in while input := input_line ic; not (string_match ~!"\\\\end{caml_eval}[ \t]*$" !input 0) do Buffer.add_string eval_buffer !input; Buffer.add_char eval_buffer '\n'; if string_match ~!".*;;[ \t]*$" !input 0 then begin Toplevel.eval eval_buffer end done; if Buffer.length eval_buffer > 0 then ( Buffer.add_string eval_buffer ";;\n"; Toplevel.eval eval_buffer ) end else begin Format.fprintf tex_fmt "%s\n" !input; Format.pp_print_flush tex_fmt () end done with | End_of_file -> close_in ic; close_out oc | Output.Unexpected_status r -> ( Output.print_unexpected r; close_in ic; close_out oc; exit 1 ) | Output.Parsing_error (k,s) -> ( Output.print_parsing_error k s; close_in ic; close_out oc; exit 1 ) | Phrase_parsing s -> fatal "when parsing the following phrase:@ %s" s | Missing_double_semicolon (file, line_number) -> fatal "when evaluating a caml_example environment in %s:@;\ missing \";;\" at line %d" file (line_number-2) | Missing_mode (file, line_number) -> fatal "when parsing a caml_example environment in %s:@;\ missing mode argument at line %d,@ \ available modes {toplevel,verbatim}" file (line_number-2) | Incompatible_options Signature_with_visible_answer (file, line_number) -> fatal "when parsing a caml_example environment in@ \ %s, line %d:@,\ the signature mode is only compatible with \"caml_example*\"@ \ Hint: did you forget to add \"*\"?" file (line_number-2); | Text_transform.Intersection {line;file;left;right} -> fatal "when evaluating a caml_example environment in %s, line %d:@ \ Textual transforms must be well-separated.@ The \"%a\" transform \ spanned the interval %d-%d,@ \ intersecting with another \"%a\" transform @ \ on the %d-%d interval.@ \ Hind: did you try to elide a code fragment which raised a warning?" file (line-2) Text_transform.pp left.kind left.start left.stop Text_transform.pp right.kind right.start right.stop | Ellipsis.Unmatched_ellipsis {kind;start;stop} -> fatal "when evaluating a caml_example environment,@ \ the %s mark at position %d-%d was unmatched" kind start stop | Ellipsis.Nested_ellipses {first;second} -> fatal "when evaluating a caml_example environment,@ \ there were two nested ellipsis attribute.@ The first one \ started at position %d,@ the second one at %d" first second let _ = if !outfile <> "-" && !outfile <> "" then begin try close_out (open_out !outfile) with _ -> failwith "Cannot open output file" end; List.iter process_file (List.rev !files);
c0580eaa6bd51760b2aa27f3d1abcc82caa49d1d5863deda5ad18727bdcc303c
ygrek/ocaml-extlib
test_UTF8.ml
let substring_inputs = [ [| ""; "⟿"; "βŸΏα‰„"; "βŸΏα‰„ΕŸ"; "βŸΏα‰„ΕŸιΎŸ"; "βŸΏα‰„ΕŸιΎŸΒ―"; |]; [| ""; "Γ§"; "Γ§e"; "Γ§ek"; "Γ§eko"; "Γ§ekos"; "Γ§ekosl"; "Γ§ekoslo"; "Γ§ekoslov"; "Γ§ekoslova"; "Γ§ekoslovak"; "Γ§ekoslovaky"; "Γ§ekoslovakya"; "Γ§ekoslovakyal"; "Γ§ekoslovakyala"; "Γ§ekoslovakyalaş"; "Γ§ekoslovakyalaşt"; "Γ§ekoslovakyalaştΔ±"; "Γ§ekoslovakyalaştΔ±r"; "Γ§ekoslovakyalaştΔ±ra"; "Γ§ekoslovakyalaştΔ±ram"; "Γ§ekoslovakyalaştΔ±rama"; "Γ§ekoslovakyalaştΔ±ramad"; "Γ§ekoslovakyalaştΔ±ramadΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±k"; "Γ§ekoslovakyalaştΔ±ramadΔ±kl"; "Γ§ekoslovakyalaştΔ±ramadΔ±kla"; "Γ§ekoslovakyalaştΔ±ramadΔ±klar"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±m"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±z"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zd"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zda"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdan"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanm"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±s"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±sΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±sΔ±n"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±sΔ±nΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±sΔ±nΔ±z"; |] ] let test_substring () = let test a = let m = Array.length a - 1 in let v = a.(m) in assert(UTF8.length v = m); for i = 0 to m do assert(a.(i) = UTF8.substring v 0 i); done; for i = 0 to m - 1 do for j = i to m - 1 do let u = UTF8.substring v i (j - i + 1) in UTF8.validate u done done in List.iter test substring_inputs let () = Util.register1 "UTF" "substring" test_substring
null
https://raw.githubusercontent.com/ygrek/ocaml-extlib/69b77f0f0500c98371aea9a6f2abb56c946cdab0/test/test_UTF8.ml
ocaml
let substring_inputs = [ [| ""; "⟿"; "βŸΏα‰„"; "βŸΏα‰„ΕŸ"; "βŸΏα‰„ΕŸιΎŸ"; "βŸΏα‰„ΕŸιΎŸΒ―"; |]; [| ""; "Γ§"; "Γ§e"; "Γ§ek"; "Γ§eko"; "Γ§ekos"; "Γ§ekosl"; "Γ§ekoslo"; "Γ§ekoslov"; "Γ§ekoslova"; "Γ§ekoslovak"; "Γ§ekoslovaky"; "Γ§ekoslovakya"; "Γ§ekoslovakyal"; "Γ§ekoslovakyala"; "Γ§ekoslovakyalaş"; "Γ§ekoslovakyalaşt"; "Γ§ekoslovakyalaştΔ±"; "Γ§ekoslovakyalaştΔ±r"; "Γ§ekoslovakyalaştΔ±ra"; "Γ§ekoslovakyalaştΔ±ram"; "Γ§ekoslovakyalaştΔ±rama"; "Γ§ekoslovakyalaştΔ±ramad"; "Γ§ekoslovakyalaştΔ±ramadΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±k"; "Γ§ekoslovakyalaştΔ±ramadΔ±kl"; "Γ§ekoslovakyalaştΔ±ramadΔ±kla"; "Γ§ekoslovakyalaştΔ±ramadΔ±klar"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±m"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±z"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zd"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zda"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdan"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanm"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±s"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±sΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±sΔ±n"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±sΔ±nΔ±"; "Γ§ekoslovakyalaştΔ±ramadΔ±klarΔ±mΔ±zdanmΔ±sΔ±nΔ±z"; |] ] let test_substring () = let test a = let m = Array.length a - 1 in let v = a.(m) in assert(UTF8.length v = m); for i = 0 to m do assert(a.(i) = UTF8.substring v 0 i); done; for i = 0 to m - 1 do for j = i to m - 1 do let u = UTF8.substring v i (j - i + 1) in UTF8.validate u done done in List.iter test substring_inputs let () = Util.register1 "UTF" "substring" test_substring
30271d08e009dd65102cd8e167e62c93a82290cae1a6866037543f81af09c86c
billstclair/trubanc-lisp
swank-indentation.lisp
(in-package :swank) (defvar *application-hints-tables* '() "A list of hash tables mapping symbols to indentation hints (lists of symbols and numbers as per cl-indent.el). Applications can add hash tables to the list to change the auto indentation slime sends to emacs.") (defun has-application-indentation-hint-p (symbol) (let ((default (load-time-value (gensym)))) (dolist (table *application-hints-tables*) (let ((indentation (gethash symbol table default))) (unless (eq default indentation) (return-from has-application-indentation-hint-p (values indentation t)))))) (values nil nil)) (defun application-indentation-hint (symbol) (let ((indentation (has-application-indentation-hint-p symbol))) (labels ((walk (indentation-spec) (etypecase indentation-spec (null nil) (number indentation-spec) (symbol (symbol-name indentation-spec)) (cons (cons (walk (car indentation-spec)) (walk (cdr indentation-spec))))))) (walk indentation)))) ;;; override swank version of this function (defun symbol-indentation (symbol) "Return a form describing the indentation of SYMBOL. The form is to be used as the `common-lisp-indent-function' property in Emacs." (cond ((has-application-indentation-hint-p symbol) (application-indentation-hint symbol)) ((and (macro-function symbol) (not (known-to-emacs-p symbol))) (let ((arglist (arglist symbol))) (etypecase arglist ((member :not-available) nil) (list (macro-indentation arglist))))) (t nil)))
null
https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/slime/contrib/swank-indentation.lisp
lisp
override swank version of this function
(in-package :swank) (defvar *application-hints-tables* '() "A list of hash tables mapping symbols to indentation hints (lists of symbols and numbers as per cl-indent.el). Applications can add hash tables to the list to change the auto indentation slime sends to emacs.") (defun has-application-indentation-hint-p (symbol) (let ((default (load-time-value (gensym)))) (dolist (table *application-hints-tables*) (let ((indentation (gethash symbol table default))) (unless (eq default indentation) (return-from has-application-indentation-hint-p (values indentation t)))))) (values nil nil)) (defun application-indentation-hint (symbol) (let ((indentation (has-application-indentation-hint-p symbol))) (labels ((walk (indentation-spec) (etypecase indentation-spec (null nil) (number indentation-spec) (symbol (symbol-name indentation-spec)) (cons (cons (walk (car indentation-spec)) (walk (cdr indentation-spec))))))) (walk indentation)))) (defun symbol-indentation (symbol) "Return a form describing the indentation of SYMBOL. The form is to be used as the `common-lisp-indent-function' property in Emacs." (cond ((has-application-indentation-hint-p symbol) (application-indentation-hint symbol)) ((and (macro-function symbol) (not (known-to-emacs-p symbol))) (let ((arglist (arglist symbol))) (etypecase arglist ((member :not-available) nil) (list (macro-indentation arglist))))) (t nil)))
6176ad26481cc556a7339517e29e868bb78b4c1c9b4e38223a879d8b10ec1c73
kumarshantanu/lein-servlet
engine.clj
(ns leiningen.servlet.engine "Access servlet engines" (:use leiningen.servlet.util) (:require [clojure.string :as str] [bultitude.core :as bult])) (def engine-ns-prefix "leiningen.servlet.engine") (defn engine-namespaces "Return a seq of [eng-ns eng-name] symbol pairs of corresponding available servlet engines." [] (let [ens (->> (bult/namespaces-on-classpath :prefix engine-ns-prefix) (filter #(re-find #"^leiningen\.servlet\.engine\.[^\.]+$" (name %))) distinct sort)] (map #(vector % (-> % name (str/split #"\.") last symbol)) ens))) (defn engine-entrypoint "Resolve engine entrypoint and return the value, else return nil." [eng-ns-symbol eng-name-symbol] {:pre [(symbol? eng-ns-symbol) (symbol? eng-name-symbol)] :post [(or (nil? %) (fn? %))]} (echo "Going to resolve engine entry-point" [eng-ns-symbol eng-name-symbol]) (when-let [v (-> eng-ns-symbol (doto require) (ns-resolve eng-name-symbol))] @v)) (defn choose-engine "Return a [eng-ns eng-name] symbol pair based on config" [wanted-eng eng-namespaces] {:pre [(coll? eng-namespaces) (every? vector? eng-namespaces) (every? #(= 2 (count %)) eng-namespaces) (every? #(every? symbol? %) eng-namespaces)]} (let [wanted-eng (and wanted-eng (as-str wanted-eng)) eng-varmap (reduce merge {} (map #(do {(-> % second name) %}) eng-namespaces))] (cond (empty? eng-varmap) (err-println "No servlet engine on CLASSPATH") (nil? wanted-eng) (-> eng-varmap vals first) :otherwise (if-let [e (get eng-varmap wanted-eng)] e (err-println (format "No such engine '%s', found: %s" wanted-eng (comma-sep eng-varmap))))))) ( defn apply - config ;; [f project args] ;; (let [config (:servlet project)] ;; (if (map? config) ;; (f config args) ;; (err-println "No :servlet map found in project.clj - see help"))))
null
https://raw.githubusercontent.com/kumarshantanu/lein-servlet/2be06155a677eba1c5a812d28499cd5b23535414/plugin/src/leiningen/servlet/engine.clj
clojure
[f project args] (let [config (:servlet project)] (if (map? config) (f config args) (err-println "No :servlet map found in project.clj - see help"))))
(ns leiningen.servlet.engine "Access servlet engines" (:use leiningen.servlet.util) (:require [clojure.string :as str] [bultitude.core :as bult])) (def engine-ns-prefix "leiningen.servlet.engine") (defn engine-namespaces "Return a seq of [eng-ns eng-name] symbol pairs of corresponding available servlet engines." [] (let [ens (->> (bult/namespaces-on-classpath :prefix engine-ns-prefix) (filter #(re-find #"^leiningen\.servlet\.engine\.[^\.]+$" (name %))) distinct sort)] (map #(vector % (-> % name (str/split #"\.") last symbol)) ens))) (defn engine-entrypoint "Resolve engine entrypoint and return the value, else return nil." [eng-ns-symbol eng-name-symbol] {:pre [(symbol? eng-ns-symbol) (symbol? eng-name-symbol)] :post [(or (nil? %) (fn? %))]} (echo "Going to resolve engine entry-point" [eng-ns-symbol eng-name-symbol]) (when-let [v (-> eng-ns-symbol (doto require) (ns-resolve eng-name-symbol))] @v)) (defn choose-engine "Return a [eng-ns eng-name] symbol pair based on config" [wanted-eng eng-namespaces] {:pre [(coll? eng-namespaces) (every? vector? eng-namespaces) (every? #(= 2 (count %)) eng-namespaces) (every? #(every? symbol? %) eng-namespaces)]} (let [wanted-eng (and wanted-eng (as-str wanted-eng)) eng-varmap (reduce merge {} (map #(do {(-> % second name) %}) eng-namespaces))] (cond (empty? eng-varmap) (err-println "No servlet engine on CLASSPATH") (nil? wanted-eng) (-> eng-varmap vals first) :otherwise (if-let [e (get eng-varmap wanted-eng)] e (err-println (format "No such engine '%s', found: %s" wanted-eng (comma-sep eng-varmap))))))) ( defn apply - config
570aac006ada7f6d4db403c659500856b61f27a6544d4877747c02429f4802d3
ocaml/opam
opamPackage.mli
(**************************************************************************) (* *) Copyright 2012 - 2019 OCamlPro Copyright 2012 INRIA (* *) (* 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. *) (* *) (**************************************************************************) (** The package type, and package name type (name+version, values often called "nv" in the code) *) * { 2 Package name and versions } (** Versions *) module Version: sig include OpamStd.ABSTRACT * Compare two versions using the Debian version scheme val compare: t -> t -> int * Are two package versions equal ? val equal: t -> t -> bool (** Default version used when no version is given *) val default : t end (** Names *) module Name: sig include OpamStd.ABSTRACT * Compare two package names val compare: t -> t -> int * Are two package names equal ? val equal: t -> t -> bool end type t = private { name: Name.t; version: Version.t; } (** Package (name x version) pairs *) include OpamStd.ABSTRACT with type t := t (** Return the package name *) val name: t -> Name.t (** Return None if [nv] is not a valid package name *) val of_string_opt: string -> t option (** Return the version name *) val version: t -> Version.t (** Create a new pair (name x version) *) val create: Name.t -> Version.t -> t * To fit in the GenericPackage type , for generic display functions val name_to_string: t -> string val version_to_string: t -> string (** Guess the package name from a filename. This function extracts [name] and [version] from {i /path/to/$name.$version/opam}, or {i /path/to/$name.$version.opam} *) val of_filename: OpamFilename.t -> t option * Guess the package name from a directory name . This function extracts { i $ name } and { i $ version } from { i /path / to/$name.$version/ } $name} and {i $version} from {i /path/to/$name.$version/} *) val of_dirname: OpamFilename.Dir.t -> t option * Guess the package name from an archive file . This function extract { i $ name } and { i $ version } from { i /path / to/$name.$version+opam.tar.gz } {i $name} and {i $version} from {i /path/to/$name.$version+opam.tar.gz} *) val of_archive: OpamFilename.t -> t option (** Convert a set of pairs to a map [name -> versions] *) val to_map: Set.t -> Version.Set.t Name.Map.t (** The converse of [to_map] *) val of_map: Version.Set.t Name.Map.t -> Set.t (** Returns the keys in a package map as a package set *) val keys: 'a Map.t -> Set.t (** Extract the versions from a collection of packages *) val versions_of_packages: Set.t -> Version.Set.t (** Return the list of versions for a given package *) val versions_of_name: Set.t -> Name.t -> Version.Set.t * Extract the naes from a collection of packages val names_of_packages: Set.t -> Name.Set.t (** Returns true if the set contains a package with the given name *) val has_name: Set.t -> Name.t -> bool (** Return all the packages with the given name *) val packages_of_name: Set.t -> Name.t -> Set.t val packages_of_name_map: 'a Map.t -> Name.t -> 'a Map.t (** Return a package with the given name *) val package_of_name: Set.t -> Name.t -> t (** Return a package with the given name, if any *) val package_of_name_opt: Set.t -> Name.t -> t option * Return all the packages with one of the given names val packages_of_names: Set.t -> Name.Set.t -> Set.t (** Removes all packages with the given name from a set of packages *) val filter_name_out: Set.t -> Name.t -> Set.t (** Return the maximal available version of a package name from a set. Raises [Not_found] if no such package available. *) val max_version: Set.t -> Name.t -> t * Compare two packages val compare: t -> t -> int * Are two packages equal ? val equal: t -> t -> bool (** Hash a package *) val hash: t -> int (** Return all the package descriptions in a given directory *) val list: OpamFilename.Dir.t -> Set.t (** Return all the package descriptions in the current directory (and their eventual prefixes). *) val prefixes: OpamFilename.Dir.t -> string option Map.t (** {2 Errors} *) (** Parallel executions. *) module Graph: OpamParallel.GRAPH with type V.t = t
null
https://raw.githubusercontent.com/ocaml/opam/5305e159d34ccc0b9fecbaa59727ac36e75f9223/src/format/opamPackage.mli
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ * The package type, and package name type (name+version, values often called "nv" in the code) * Versions * Default version used when no version is given * Names * Package (name x version) pairs * Return the package name * Return None if [nv] is not a valid package name * Return the version name * Create a new pair (name x version) * Guess the package name from a filename. This function extracts [name] and [version] from {i /path/to/$name.$version/opam}, or {i /path/to/$name.$version.opam} * Convert a set of pairs to a map [name -> versions] * The converse of [to_map] * Returns the keys in a package map as a package set * Extract the versions from a collection of packages * Return the list of versions for a given package * Returns true if the set contains a package with the given name * Return all the packages with the given name * Return a package with the given name * Return a package with the given name, if any * Removes all packages with the given name from a set of packages * Return the maximal available version of a package name from a set. Raises [Not_found] if no such package available. * Hash a package * Return all the package descriptions in a given directory * Return all the package descriptions in the current directory (and their eventual prefixes). * {2 Errors} * Parallel executions.
Copyright 2012 - 2019 OCamlPro Copyright 2012 INRIA GNU Lesser General Public License version 2.1 , with the special * { 2 Package name and versions } module Version: sig include OpamStd.ABSTRACT * Compare two versions using the Debian version scheme val compare: t -> t -> int * Are two package versions equal ? val equal: t -> t -> bool val default : t end module Name: sig include OpamStd.ABSTRACT * Compare two package names val compare: t -> t -> int * Are two package names equal ? val equal: t -> t -> bool end type t = private { name: Name.t; version: Version.t; } include OpamStd.ABSTRACT with type t := t val name: t -> Name.t val of_string_opt: string -> t option val version: t -> Version.t val create: Name.t -> Version.t -> t * To fit in the GenericPackage type , for generic display functions val name_to_string: t -> string val version_to_string: t -> string val of_filename: OpamFilename.t -> t option * Guess the package name from a directory name . This function extracts { i $ name } and { i $ version } from { i /path / to/$name.$version/ } $name} and {i $version} from {i /path/to/$name.$version/} *) val of_dirname: OpamFilename.Dir.t -> t option * Guess the package name from an archive file . This function extract { i $ name } and { i $ version } from { i /path / to/$name.$version+opam.tar.gz } {i $name} and {i $version} from {i /path/to/$name.$version+opam.tar.gz} *) val of_archive: OpamFilename.t -> t option val to_map: Set.t -> Version.Set.t Name.Map.t val of_map: Version.Set.t Name.Map.t -> Set.t val keys: 'a Map.t -> Set.t val versions_of_packages: Set.t -> Version.Set.t val versions_of_name: Set.t -> Name.t -> Version.Set.t * Extract the naes from a collection of packages val names_of_packages: Set.t -> Name.Set.t val has_name: Set.t -> Name.t -> bool val packages_of_name: Set.t -> Name.t -> Set.t val packages_of_name_map: 'a Map.t -> Name.t -> 'a Map.t val package_of_name: Set.t -> Name.t -> t val package_of_name_opt: Set.t -> Name.t -> t option * Return all the packages with one of the given names val packages_of_names: Set.t -> Name.Set.t -> Set.t val filter_name_out: Set.t -> Name.t -> Set.t val max_version: Set.t -> Name.t -> t * Compare two packages val compare: t -> t -> int * Are two packages equal ? val equal: t -> t -> bool val hash: t -> int val list: OpamFilename.Dir.t -> Set.t val prefixes: OpamFilename.Dir.t -> string option Map.t module Graph: OpamParallel.GRAPH with type V.t = t
69d61b0eeea71314f09c3376e99dd01e399258bafe01777ff5fbc9e65d1c6e17
CryptoKami/cryptokami-core
Signing.hs
-- | Signing done with public/private keys. module Pos.Crypto.Signing.Types.Signing ( -- * Keys PublicKey (..) , SecretKey (..) , toPublic , formatFullPublicKey , fullPublicKeyF , fullPublicKeyHexF , shortPublicKeyHexF , parseFullPublicKey -- * Signing and verification , Signature (..) , Signed (..) -- * Proxy signature scheme , ProxyCert (..) , ProxySecretKey (..) , ProxySignature (..) , isSelfSignedPsk ) where import qualified Cryptokami.Crypto.Wallet as CC import Data.Hashable (Hashable) import qualified Data.Hashable as Hashable import qualified Data.Text.Buildable as B import Data.Text.Lazy.Builder (Builder) import Formatting (Format, bprint, build, fitLeft, later, (%), (%.)) import Prelude (show) import qualified Serokell.Util.Base16 as B16 import qualified Serokell.Util.Base64 as Base64 (decode, formatBase64) import Serokell.Util.Text (pairF) import Universum hiding (show) import Pos.Binary.Class (Bi) import Pos.Crypto.Hashing (hash) ---------------------------------------------------------------------------- -- Orphan instances ---------------------------------------------------------------------------- instance Eq CC.XPub where a == b = CC.unXPub a == CC.unXPub b instance Ord CC.XPub where compare = comparing CC.unXPub instance Show CC.XPub where show = show . CC.unXPub instance Hashable CC.XPub where hashWithSalt n = Hashable.hashWithSalt n . CC.unXPub ---------------------------------------------------------------------------- -- Keys, key generation & printing & decoding ---------------------------------------------------------------------------- | Wrapper around ' CC.XPub ' . newtype PublicKey = PublicKey CC.XPub deriving (Eq, Ord, Show, Generic, NFData, Hashable, Typeable) | Wrapper around ' CC.XPrv ' . newtype SecretKey = SecretKey CC.XPrv deriving (NFData) -- | Generate a public key from a secret key. Fast (it just drops some bytes -- off the secret key). toPublic :: SecretKey -> PublicKey toPublic (SecretKey k) = PublicKey (CC.toXPub k) | Direct comparison of secret keys is a security issue ( ) instance Bi SecretKey => Eq SecretKey where a == b = hash a == hash b instance Show SecretKey where show sk = "<secret of " ++ show (toPublic sk) ++ ">" instance Bi PublicKey => B.Buildable PublicKey where build = bprint ("pub:"%shortPublicKeyHexF) instance Bi PublicKey => B.Buildable SecretKey where build = bprint ("sec:"%shortPublicKeyHexF) . toPublic | ' Builder ' for ' PublicKey ' to show it in base64 encoded form . formatFullPublicKey :: PublicKey -> Builder formatFullPublicKey (PublicKey pk) = Base64.formatBase64 . CC.unXPub $ pk | Formatter for ' PublicKey ' to show it in base64 . fullPublicKeyF :: Format r (PublicKey -> r) fullPublicKeyF = later formatFullPublicKey | Formatter for ' PublicKey ' to show it in hex . fullPublicKeyHexF :: Format r (PublicKey -> r) fullPublicKeyHexF = later $ \(PublicKey x) -> B16.formatBase16 . CC.unXPub $ x | Formatter for ' PublicKey ' to show it in hex , but only first 8 chars . shortPublicKeyHexF :: Format r (PublicKey -> r) shortPublicKeyHexF = fitLeft 8 %. fullPublicKeyHexF | Parse ' PublicKey ' from base64 encoded string . parseFullPublicKey :: Text -> Either Text PublicKey parseFullPublicKey s = do b <- Base64.decode s PublicKey <$> first fromString (CC.xpub b) ---------------------------------------------------------------------------- -- Signatures ---------------------------------------------------------------------------- -- | Wrapper around 'CC.XSignature'. newtype Signature a = Signature CC.XSignature deriving (Eq, Ord, Show, Generic, NFData, Hashable, Typeable) instance B.Buildable (Signature a) where build _ = "<signature>" -- | Value and signature for this value. data Signed a = Signed { signedValue :: !a -- ^ Value to be signed , signedSig :: !(Signature a) -- ^ 'Signature' of 'signedValue' } deriving (Show, Eq, Ord, Generic) ---------------------------------------------------------------------------- -- Proxy signing ---------------------------------------------------------------------------- -- | Proxy certificate, made of Ο‰ + public key of delegate. newtype ProxyCert w = ProxyCert { unProxyCert :: CC.XSignature } deriving (Eq, Ord, Show, Generic, NFData, Hashable) instance B.Buildable (ProxyCert w) where build _ = "<proxy_cert>" -- | Convenient wrapper for secret key, that's basically Ο‰ plus -- certificate. -- -- The invariant is that the certificate is valid (as checked by -- 'validateProxySecretKey'). data ProxySecretKey w = UnsafeProxySecretKey { pskOmega :: w , pskIssuerPk :: PublicKey , pskDelegatePk :: PublicKey , pskCert :: ProxyCert w } deriving (Eq, Ord, Show, Generic) instance NFData w => NFData (ProxySecretKey w) instance Hashable w => Hashable (ProxySecretKey w) instance {-# OVERLAPPABLE #-} (B.Buildable w, Bi PublicKey) => B.Buildable (ProxySecretKey w) where build (UnsafeProxySecretKey w iPk dPk _) = bprint ("ProxySk { w = "%build%", iPk = "%build%", dPk = "%build%" }") w iPk dPk instance (B.Buildable w, Bi PublicKey) => B.Buildable (ProxySecretKey (w,w)) where build (UnsafeProxySecretKey w iPk dPk _) = bprint ("ProxySk { w = "%pairF%", iPk = "%build%", dPk = "%build%" }") w iPk dPk -- | Delegate signature made with certificate-based permission. @w@ stays for message type used in proxy ( Ο‰ in the implementation -- notes), @a@ for type of message signed. -- -- We add whole psk as a field because otherwise we can't verify sig in heavyweight transitive delegation : i β†’ x β†’ d , we have psk from x to d , slot leader is i. data ProxySignature w a = ProxySignature { psigPsk :: ProxySecretKey w , psigSig :: CC.XSignature } deriving (Eq, Ord, Show, Generic) instance NFData w => NFData (ProxySignature w a) instance Hashable w => Hashable (ProxySignature w a) instance {-# OVERLAPPABLE #-} (B.Buildable w, Bi PublicKey) => B.Buildable (ProxySignature w a) where build ProxySignature{..} = bprint ("Proxy signature { psk = "%build%" }") psigPsk instance (B.Buildable w, Bi PublicKey) => B.Buildable (ProxySignature (w,w) a) where build ProxySignature{..} = bprint ("Proxy signature { psk = "%build%" }") psigPsk -- | Checks if delegate and issuer fields of proxy secret key are -- equal. isSelfSignedPsk :: ProxySecretKey w -> Bool isSelfSignedPsk psk = pskIssuerPk psk == pskDelegatePk psk
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/crypto/Pos/Crypto/Signing/Types/Signing.hs
haskell
| Signing done with public/private keys. * Keys * Signing and verification * Proxy signature scheme -------------------------------------------------------------------------- Orphan instances -------------------------------------------------------------------------- -------------------------------------------------------------------------- Keys, key generation & printing & decoding -------------------------------------------------------------------------- | Generate a public key from a secret key. Fast (it just drops some bytes off the secret key). -------------------------------------------------------------------------- Signatures -------------------------------------------------------------------------- | Wrapper around 'CC.XSignature'. | Value and signature for this value. ^ Value to be signed ^ 'Signature' of 'signedValue' -------------------------------------------------------------------------- Proxy signing -------------------------------------------------------------------------- | Proxy certificate, made of Ο‰ + public key of delegate. | Convenient wrapper for secret key, that's basically Ο‰ plus certificate. The invariant is that the certificate is valid (as checked by 'validateProxySecretKey'). # OVERLAPPABLE # | Delegate signature made with certificate-based permission. @w@ notes), @a@ for type of message signed. We add whole psk as a field because otherwise we can't verify sig # OVERLAPPABLE # | Checks if delegate and issuer fields of proxy secret key are equal.
module Pos.Crypto.Signing.Types.Signing ( PublicKey (..) , SecretKey (..) , toPublic , formatFullPublicKey , fullPublicKeyF , fullPublicKeyHexF , shortPublicKeyHexF , parseFullPublicKey , Signature (..) , Signed (..) , ProxyCert (..) , ProxySecretKey (..) , ProxySignature (..) , isSelfSignedPsk ) where import qualified Cryptokami.Crypto.Wallet as CC import Data.Hashable (Hashable) import qualified Data.Hashable as Hashable import qualified Data.Text.Buildable as B import Data.Text.Lazy.Builder (Builder) import Formatting (Format, bprint, build, fitLeft, later, (%), (%.)) import Prelude (show) import qualified Serokell.Util.Base16 as B16 import qualified Serokell.Util.Base64 as Base64 (decode, formatBase64) import Serokell.Util.Text (pairF) import Universum hiding (show) import Pos.Binary.Class (Bi) import Pos.Crypto.Hashing (hash) instance Eq CC.XPub where a == b = CC.unXPub a == CC.unXPub b instance Ord CC.XPub where compare = comparing CC.unXPub instance Show CC.XPub where show = show . CC.unXPub instance Hashable CC.XPub where hashWithSalt n = Hashable.hashWithSalt n . CC.unXPub | Wrapper around ' CC.XPub ' . newtype PublicKey = PublicKey CC.XPub deriving (Eq, Ord, Show, Generic, NFData, Hashable, Typeable) | Wrapper around ' CC.XPrv ' . newtype SecretKey = SecretKey CC.XPrv deriving (NFData) toPublic :: SecretKey -> PublicKey toPublic (SecretKey k) = PublicKey (CC.toXPub k) | Direct comparison of secret keys is a security issue ( ) instance Bi SecretKey => Eq SecretKey where a == b = hash a == hash b instance Show SecretKey where show sk = "<secret of " ++ show (toPublic sk) ++ ">" instance Bi PublicKey => B.Buildable PublicKey where build = bprint ("pub:"%shortPublicKeyHexF) instance Bi PublicKey => B.Buildable SecretKey where build = bprint ("sec:"%shortPublicKeyHexF) . toPublic | ' Builder ' for ' PublicKey ' to show it in base64 encoded form . formatFullPublicKey :: PublicKey -> Builder formatFullPublicKey (PublicKey pk) = Base64.formatBase64 . CC.unXPub $ pk | Formatter for ' PublicKey ' to show it in base64 . fullPublicKeyF :: Format r (PublicKey -> r) fullPublicKeyF = later formatFullPublicKey | Formatter for ' PublicKey ' to show it in hex . fullPublicKeyHexF :: Format r (PublicKey -> r) fullPublicKeyHexF = later $ \(PublicKey x) -> B16.formatBase16 . CC.unXPub $ x | Formatter for ' PublicKey ' to show it in hex , but only first 8 chars . shortPublicKeyHexF :: Format r (PublicKey -> r) shortPublicKeyHexF = fitLeft 8 %. fullPublicKeyHexF | Parse ' PublicKey ' from base64 encoded string . parseFullPublicKey :: Text -> Either Text PublicKey parseFullPublicKey s = do b <- Base64.decode s PublicKey <$> first fromString (CC.xpub b) newtype Signature a = Signature CC.XSignature deriving (Eq, Ord, Show, Generic, NFData, Hashable, Typeable) instance B.Buildable (Signature a) where build _ = "<signature>" data Signed a = Signed } deriving (Show, Eq, Ord, Generic) newtype ProxyCert w = ProxyCert { unProxyCert :: CC.XSignature } deriving (Eq, Ord, Show, Generic, NFData, Hashable) instance B.Buildable (ProxyCert w) where build _ = "<proxy_cert>" data ProxySecretKey w = UnsafeProxySecretKey { pskOmega :: w , pskIssuerPk :: PublicKey , pskDelegatePk :: PublicKey , pskCert :: ProxyCert w } deriving (Eq, Ord, Show, Generic) instance NFData w => NFData (ProxySecretKey w) instance Hashable w => Hashable (ProxySecretKey w) (B.Buildable w, Bi PublicKey) => B.Buildable (ProxySecretKey w) where build (UnsafeProxySecretKey w iPk dPk _) = bprint ("ProxySk { w = "%build%", iPk = "%build%", dPk = "%build%" }") w iPk dPk instance (B.Buildable w, Bi PublicKey) => B.Buildable (ProxySecretKey (w,w)) where build (UnsafeProxySecretKey w iPk dPk _) = bprint ("ProxySk { w = "%pairF%", iPk = "%build%", dPk = "%build%" }") w iPk dPk stays for message type used in proxy ( Ο‰ in the implementation in heavyweight transitive delegation : i β†’ x β†’ d , we have psk from x to d , slot leader is i. data ProxySignature w a = ProxySignature { psigPsk :: ProxySecretKey w , psigSig :: CC.XSignature } deriving (Eq, Ord, Show, Generic) instance NFData w => NFData (ProxySignature w a) instance Hashable w => Hashable (ProxySignature w a) (B.Buildable w, Bi PublicKey) => B.Buildable (ProxySignature w a) where build ProxySignature{..} = bprint ("Proxy signature { psk = "%build%" }") psigPsk instance (B.Buildable w, Bi PublicKey) => B.Buildable (ProxySignature (w,w) a) where build ProxySignature{..} = bprint ("Proxy signature { psk = "%build%" }") psigPsk isSelfSignedPsk :: ProxySecretKey w -> Bool isSelfSignedPsk psk = pskIssuerPk psk == pskDelegatePk psk
9594e6df80738fcae27dcfc22056269206971d56a53356ff5b7fe86be18504d1
richhickey/clojure-contrib
java_utils.clj
Copyright ( c ) Stuart Halloway & Contributors , April 2009 . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Design goals: ; ( 1 ) Ease - of - use . These APIs should be convenient . Performance is secondary . ; ( 2 ) Duck typing . I hate having to think about the difference between a string that names a file , and a File . Ditto for a ton of other wrapper classes in the Java world ( URL , ) . With these ; APIs you should be able to think about domain equivalence, not type ; equivalence. ; ( 3 ) No bossiness . I am not marking any of these functions as private ; ; the docstrings will tell you the intended usage but do what works for you. ; ; Feedback welcome! ; ; If something in this module violates the principle of least surprise, please let me ( ) and the Clojure community know via the mailing list . ; ; Contributors: ; Stuart Sierra (ns #^{:author "Stuart Halloway, Stephen C. Gilardi, Shawn Hoover, Perry Trolard, Stuart Sierra", :doc "A set of utilties for dealing with Java stuff like files and properties. Design goals: (1) Ease-of-use. These APIs should be convenient. Performance is secondary. (2) Duck typing. I hate having to think about the difference between a string that names a file, and a File. Ditto for a ton of other wrapper classes in the Java world (URL, InternetAddress). With these APIs you should be able to think about domain equivalence, not type equivalence. (3) No bossiness. I am not marking any of these functions as private the docstrings will tell you the intended usage but do what works for you. Feedback welcome! If something in this module violates the principle of least surprise, please let me (Stu) and the Clojure community know via the mailing list. "} clojure.contrib.java-utils (:import [java.io File FileOutputStream] [java.util Properties] [java.net URI URL])) (defmulti relative-path-string "Interpret a String or java.io.File as a relative path string. Building block for clojure.contrib.java-utils/file." class) (defmethod relative-path-string String [#^String s] (relative-path-string (File. s))) (defmethod relative-path-string File [#^File f] (if (.isAbsolute f) (throw (IllegalArgumentException. (str f " is not a relative path"))) (.getPath f))) (defmulti #^File as-file "Interpret a String or a java.io.File as a File. Building block for clojure.contrib.java-utils/file, which you should prefer in most cases." class) (defmethod as-file String [#^String s] (File. s)) (defmethod as-file File [f] f) (defn #^File file "Returns a java.io.File from string or file args." ([arg] (as-file arg)) ([parent child] (File. #^File (as-file parent) #^String (relative-path-string child))) ([parent child & more] (reduce file (file parent child) more))) (defn as-str "Like clojure.core/str, but if an argument is a keyword or symbol, its name will be used instead of its literal representation. Example: = > \":foo : bar\ " = > " Note that this does not apply to keywords or symbols nested within data structures; they will be rendered as with str. Example: = > \"{:foo : bar}\ " = > \"{:foo : " " ([] "") ([x] (if (instance? clojure.lang.Named x) (name x) (str x))) ([x & ys] ((fn [#^StringBuilder sb more] (if more (recur (. sb (append (as-str (first more)))) (next more)) (str sb))) (new StringBuilder #^String (as-str x)) ys))) (defn get-system-property "Get a system property." ([stringable] (System/getProperty (as-str stringable))) ([stringable default] (System/getProperty (as-str stringable) default))) (defn set-system-properties "Set some system properties. Nil clears a property." [settings] (doseq [[name val] settings] (if val (System/setProperty (as-str name) (as-str val)) (System/clearProperty (as-str name))))) (defmacro with-system-properties "setting => property-name value Sets the system properties to the supplied values, executes the body, and sets the properties back to their original values. Values of nil are translated to a clearing of the property." [settings & body] `(let [settings# ~settings current# (reduce (fn [coll# k#] (assoc coll# k# (get-system-property k#))) {} (keys settings#))] (set-system-properties settings#) (try ~@body (finally (set-system-properties current#))))) ; Not there is no corresponding props->map. Just destructure! (defn #^Properties as-properties "Convert any seq of pairs to a java.utils.Properties instance. Uses as-str to convert both keys and values into strings." {:tag Properties} [m] (let [p (Properties.)] (doseq [[k v] m] (.setProperty p (as-str k) (as-str v))) p)) (defn read-properties "Read properties from file-able." [file-able] (with-open [f (java.io.FileInputStream. (file file-able))] (doto (Properties.) (.load f)))) (defn write-properties "Write properties to file-able." {:tag Properties} ([m file-able] (write-properties m file-able nil)) ([m file-able comments] (with-open [#^FileOutputStream f (FileOutputStream. (file file-able))] (doto (as-properties m) (.store f #^String comments))))) (defn delete-file "Delete file f. Raise an exception if it fails unless silently is true." [f & [silently]] (or (.delete (file f)) silently (throw (java.io.IOException. (str "Couldn't delete " f))))) (defn delete-file-recursively "Delete file f. If it's a directory, recursively delete all its contents. Raise an exception if any deletion fails unless silently is true." [f & [silently]] (let [f (file f)] (if (.isDirectory f) (doseq [child (.listFiles f)] (delete-file-recursively child silently))) (delete-file f silently))) (defmulti #^{:doc "Coerces argument (URL, URI, or String) to a java.net.URL." :arglists '([arg])} as-url type) (defmethod as-url URL [x] x) (defmethod as-url URI [#^URI x] (.toURL x)) (defmethod as-url String [#^String x] (URL. x)) (defmethod as-url File [#^File x] (.toURL x)) (defn wall-hack-method "Calls a private or protected method. params is a vector of class which correspond to the arguments to the method obj is nil for static methods, the instance object otherwise the method name is given as a symbol or a keyword (something Named)" [class-name method-name params obj & args] (-> class-name (.getDeclaredMethod (name method-name) (into-array Class params)) (doto (.setAccessible true)) (.invoke obj (into-array Object args)))) (defn wall-hack-field "Access to private or protected field." [class-name field-name obj] (-> class-name (.getDeclaredField (name field-name)) (doto (.setAccessible true)) (.get obj)))
null
https://raw.githubusercontent.com/richhickey/clojure-contrib/40b960bba41ba02811ef0e2c632d721eb199649f/src/main/clojure/clojure/contrib/java_utils.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. Design goals: APIs you should be able to think about domain equivalence, not type equivalence. the docstrings will tell you the intended usage but do what works for you. Feedback welcome! If something in this module violates the principle of least surprise, please Contributors: they will be rendered as with str. Not there is no corresponding props->map. Just destructure!
Copyright ( c ) Stuart Halloway & Contributors , April 2009 . All rights reserved . ( 1 ) Ease - of - use . These APIs should be convenient . Performance is secondary . ( 2 ) Duck typing . I hate having to think about the difference between a string that names a file , and a File . Ditto for a ton of other wrapper classes in the Java world ( URL , ) . With these let me ( ) and the Clojure community know via the mailing list . Stuart Sierra (ns #^{:author "Stuart Halloway, Stephen C. Gilardi, Shawn Hoover, Perry Trolard, Stuart Sierra", :doc "A set of utilties for dealing with Java stuff like files and properties. Design goals: (1) Ease-of-use. These APIs should be convenient. Performance is secondary. (2) Duck typing. I hate having to think about the difference between a string that names a file, and a File. Ditto for a ton of other wrapper classes in the Java world (URL, InternetAddress). With these APIs you should be able to think about domain equivalence, not type equivalence. (3) No bossiness. I am not marking any of these functions as private the docstrings will tell you the intended usage but do what works for you. Feedback welcome! If something in this module violates the principle of least surprise, please let me (Stu) and the Clojure community know via the mailing list. "} clojure.contrib.java-utils (:import [java.io File FileOutputStream] [java.util Properties] [java.net URI URL])) (defmulti relative-path-string "Interpret a String or java.io.File as a relative path string. Building block for clojure.contrib.java-utils/file." class) (defmethod relative-path-string String [#^String s] (relative-path-string (File. s))) (defmethod relative-path-string File [#^File f] (if (.isAbsolute f) (throw (IllegalArgumentException. (str f " is not a relative path"))) (.getPath f))) (defmulti #^File as-file "Interpret a String or a java.io.File as a File. Building block for clojure.contrib.java-utils/file, which you should prefer in most cases." class) (defmethod as-file String [#^String s] (File. s)) (defmethod as-file File [f] f) (defn #^File file "Returns a java.io.File from string or file args." ([arg] (as-file arg)) ([parent child] (File. #^File (as-file parent) #^String (relative-path-string child))) ([parent child & more] (reduce file (file parent child) more))) (defn as-str "Like clojure.core/str, but if an argument is a keyword or symbol, its name will be used instead of its literal representation. Example: = > \":foo : bar\ " = > " Note that this does not apply to keywords or symbols nested within Example: = > \"{:foo : bar}\ " = > \"{:foo : " " ([] "") ([x] (if (instance? clojure.lang.Named x) (name x) (str x))) ([x & ys] ((fn [#^StringBuilder sb more] (if more (recur (. sb (append (as-str (first more)))) (next more)) (str sb))) (new StringBuilder #^String (as-str x)) ys))) (defn get-system-property "Get a system property." ([stringable] (System/getProperty (as-str stringable))) ([stringable default] (System/getProperty (as-str stringable) default))) (defn set-system-properties "Set some system properties. Nil clears a property." [settings] (doseq [[name val] settings] (if val (System/setProperty (as-str name) (as-str val)) (System/clearProperty (as-str name))))) (defmacro with-system-properties "setting => property-name value Sets the system properties to the supplied values, executes the body, and sets the properties back to their original values. Values of nil are translated to a clearing of the property." [settings & body] `(let [settings# ~settings current# (reduce (fn [coll# k#] (assoc coll# k# (get-system-property k#))) {} (keys settings#))] (set-system-properties settings#) (try ~@body (finally (set-system-properties current#))))) (defn #^Properties as-properties "Convert any seq of pairs to a java.utils.Properties instance. Uses as-str to convert both keys and values into strings." {:tag Properties} [m] (let [p (Properties.)] (doseq [[k v] m] (.setProperty p (as-str k) (as-str v))) p)) (defn read-properties "Read properties from file-able." [file-able] (with-open [f (java.io.FileInputStream. (file file-able))] (doto (Properties.) (.load f)))) (defn write-properties "Write properties to file-able." {:tag Properties} ([m file-able] (write-properties m file-able nil)) ([m file-able comments] (with-open [#^FileOutputStream f (FileOutputStream. (file file-able))] (doto (as-properties m) (.store f #^String comments))))) (defn delete-file "Delete file f. Raise an exception if it fails unless silently is true." [f & [silently]] (or (.delete (file f)) silently (throw (java.io.IOException. (str "Couldn't delete " f))))) (defn delete-file-recursively "Delete file f. If it's a directory, recursively delete all its contents. Raise an exception if any deletion fails unless silently is true." [f & [silently]] (let [f (file f)] (if (.isDirectory f) (doseq [child (.listFiles f)] (delete-file-recursively child silently))) (delete-file f silently))) (defmulti #^{:doc "Coerces argument (URL, URI, or String) to a java.net.URL." :arglists '([arg])} as-url type) (defmethod as-url URL [x] x) (defmethod as-url URI [#^URI x] (.toURL x)) (defmethod as-url String [#^String x] (URL. x)) (defmethod as-url File [#^File x] (.toURL x)) (defn wall-hack-method "Calls a private or protected method. params is a vector of class which correspond to the arguments to the method obj is nil for static methods, the instance object otherwise the method name is given as a symbol or a keyword (something Named)" [class-name method-name params obj & args] (-> class-name (.getDeclaredMethod (name method-name) (into-array Class params)) (doto (.setAccessible true)) (.invoke obj (into-array Object args)))) (defn wall-hack-field "Access to private or protected field." [class-name field-name obj] (-> class-name (.getDeclaredField (name field-name)) (doto (.setAccessible true)) (.get obj)))
373f4365dd7a947f128745f329395415ae75d27f4228b8d1fce5f903a66dc16e
fukamachi/clozure-cl
darwinx8664-syscalls.lisp
-*-Mode : LISP ; Package : CCL -*- ;;; Copyright ( C ) 2001 - 2009 Clozure Associates This file is part of Clozure CL . ;;; Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the ;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL, which is distributed with Clozure CL as the file " LGPL " . Where these ;;; conflict, the preamble takes precedence. ;;; ;;; Clozure CL is referenced in the preamble as the "LIBRARY." ;;; ;;; The LLGPL is also available online at ;;; (in-package "CCL") (eval-when (:compile-toplevel :load-toplevel :execute) (require "SYSCALL") (defconstant darwinx8664-unix-syscall-mask #x2000000)) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::exit (logior darwinx8664-unix-syscall-mask 1) (:int) :void ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fork (logior darwinx8664-unix-syscall-mask 2) () :void) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::read (logior darwinx8664-unix-syscall-mask 3) (:unsigned-fullword :address :unsigned-long) :signed-long ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::write (logior darwinx8664-unix-syscall-mask 4) (:unsigned-fullword :address :unsigned-long) :signed-long ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::open (logior darwinx8664-unix-syscall-mask 5) (:address :unsigned-fullword :unsigned-fullword) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::close (logior darwinx8664-unix-syscall-mask 6) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::wait4 (logior darwinx8664-unix-syscall-mask 7) (:unsigned-fullword :address :signed-fullword :address) :unsigned-fullword ) 8 is old creat (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::link (logior darwinx8664-unix-syscall-mask 9) (:address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::unlink (logior darwinx8664-unix-syscall-mask 10) (:address) :signed-fullword ) 11 is obsolete execv (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::chdir (logior darwinx8664-unix-syscall-mask 12) (:address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fchdir (logior darwinx8664-unix-syscall-mask 13) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mknod (logior darwinx8664-unix-syscall-mask 14) (:address :unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::chmod (logior darwinx8664-unix-syscall-mask 15) (:address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lchown (logior darwinx8664-unix-syscall-mask 16) (:address :unsigned-fullword :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getpid (logior darwinx8664-unix-syscall-mask 20) () :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setuid (logior darwinx8664-unix-syscall-mask 23) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getuid (logior darwinx8664-unix-syscall-mask 24) () :unsigned-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::geteuid (logior darwinx8664-unix-syscall-mask 25) () :unsigned-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::recvmsg (logior darwinx8664-unix-syscall-mask 27) (:unsigned-fullword :address :unsigned-fullword):signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sendmsg (logior darwinx8664-unix-syscall-mask 28) (:unsigned-fullword :address :unsigned-fullword):signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::recvfrom (logior darwinx8664-unix-syscall-mask 29) (:unsigned-fullword :address :unsigned-long :unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::accept (logior darwinx8664-unix-syscall-mask 30) (:unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getpeername (logior darwinx8664-unix-syscall-mask 31) (:unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getsockname (logior darwinx8664-unix-syscall-mask 32) (:unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::kill (logior darwinx8664-unix-syscall-mask 37) (:signed-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sync (logior darwinx8664-unix-syscall-mask 36) () :unsigned-fullword ) 38 is old stat (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getppid (logior darwinx8664-unix-syscall-mask 39) () :unsigned-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::dup (logior darwinx8664-unix-syscall-mask 41) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::pipe (logior darwinx8664-unix-syscall-mask 42) () :signed-doubleword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getgid (logior darwinx8664-unix-syscall-mask 47) () :unsigned-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ioctl (logior darwinx8664-unix-syscall-mask 54) (:unsigned-fullword :signed-fullword :address) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::dup2 (logior darwinx8664-unix-syscall-mask 90) (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fcntl (logior darwinx8664-unix-syscall-mask 92) (:unsigned-fullword :signed-fullword :signed-fullword) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::select (logior darwinx8664-unix-syscall-mask 93) (:unsigned-fullword :address :address :address :address) :signed-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fsync (logior darwinx8664-unix-syscall-mask 95) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::socket (logior darwinx8664-unix-syscall-mask 97) (:unsigned-fullword :unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::connect (logior darwinx8664-unix-syscall-mask 98) (:unsigned-fullword :address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::bind (logior darwinx8664-unix-syscall-mask 104) (:unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setsockopt (logior darwinx8664-unix-syscall-mask 105) (:unsigned-fullword :signed-fullword :signed-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::listen (logior darwinx8664-unix-syscall-mask 106) (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::gettimeofday (logior darwinx8664-unix-syscall-mask 116) (:address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getrusage (logior darwinx8664-unix-syscall-mask 117) (:signed-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getsockopt (logior darwinx8664-unix-syscall-mask 118) (:unsigned-fullword :signed-fullword :unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fchmod (logior darwinx8664-unix-syscall-mask 124) (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::rename (logior darwinx8664-unix-syscall-mask 128) (:address :address) :signed-fullword) 129 is old truncate 130 is old ftruncate (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sendto (logior darwinx8664-unix-syscall-mask 133) (:unsigned-fullword :address :unsigned-fullword :unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shutdown (logior darwinx8664-unix-syscall-mask 134) (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::socketpair (logior darwinx8664-unix-syscall-mask 135) (:unsigned-fullword :unsigned-fullword :unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mkdir (logior darwinx8664-unix-syscall-mask 136) (:address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::rmdir (logior darwinx8664-unix-syscall-mask 137) (:address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mount (logior darwinx8664-unix-syscall-mask 167) (:address :address :unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setgid (logior darwinx8664-unix-syscall-mask 181) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::stat (logior darwinx8664-unix-syscall-mask 188) (:address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fstat (logior darwinx8664-unix-syscall-mask 189) (:unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lstat (logior darwinx8664-unix-syscall-mask 190) (:address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lseek (logior darwinx8664-unix-syscall-mask 199) (:unsigned-fullword :signed-doubleword :unsigned-fullword) :signed-doubleword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::truncate (logior darwinx8664-unix-syscall-mask 200) (:address :unsigned-doubleword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ftruncate (logior darwinx8664-unix-syscall-mask 201) (:unsigned-fullword :unsigned-doubleword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::poll (logior darwinx8664-unix-syscall-mask 230) ((:* (:struct :pollfd)) :int :int) :int) #+notdefinedyet (progn ; 17 is obsolete sbreak 18 is old getfsstat 19 is old lseek 21 is obsolete mount 22 is obsolete umount (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ptrace (logior darwinx8664-unix-syscall-mask 26) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::access (logior darwinx8664-unix-syscall-mask 33) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::chflags (logior darwinx8664-unix-syscall-mask 34) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fchflags (logior darwinx8664-unix-syscall-mask 35) () ) 40 is old lstat (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getegid (logior darwinx8664-unix-syscall-mask 43) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::profil (logior darwinx8664-unix-syscall-mask 44) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ktrace (logior darwinx8664-unix-syscall-mask 45) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigaction (logior darwinx8664-unix-syscall-mask 46) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigprocmask (logior darwinx8664-unix-syscall-mask 48) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getlogin (logior darwinx8664-unix-syscall-mask 49) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setlogin (logior darwinx8664-unix-syscall-mask 50) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::acct (logior darwinx8664-unix-syscall-mask 51) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigpending (logior darwinx8664-unix-syscall-mask 52) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigaltstack (logior darwinx8664-unix-syscall-mask 53) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::reboot (logior darwinx8664-unix-syscall-mask 55) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::revoke (logior darwinx8664-unix-syscall-mask 56) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::symlink (logior darwinx8664-unix-syscall-mask 57) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::readlink (logior darwinx8664-unix-syscall-mask 58) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::execve (logior darwinx8664-unix-syscall-mask 59) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::umask (logior darwinx8664-unix-syscall-mask 60) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::chroot (logior darwinx8664-unix-syscall-mask 61) () ) 62 is old fstat 63 is unused 64 is old getpagesize (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msync (logior darwinx8664-unix-syscall-mask 65) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::vfork (logior darwinx8664-unix-syscall-mask 66) () ) ; 67 is obsolete vread 68 is obsolete vwrite (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sbrk (logior darwinx8664-unix-syscall-mask 69) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sstk (logior darwinx8664-unix-syscall-mask 70) () ) 71 is old mmap 72 is obsolete vadvise (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::munmap (logior darwinx8664-unix-syscall-mask 73) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mprotect (logior darwinx8664-unix-syscall-mask 74) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::madvise (logior darwinx8664-unix-syscall-mask 75) () ) 76 is obsolete 77 is obsolete vlimit (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mincore (logior darwinx8664-unix-syscall-mask 78) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getgroups (logior darwinx8664-unix-syscall-mask 79) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setgroups (logior darwinx8664-unix-syscall-mask 80) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getpgrp (logior darwinx8664-unix-syscall-mask 81) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setpgid (logior darwinx8664-unix-syscall-mask 82) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setitimer (logior darwinx8664-unix-syscall-mask 83) () ) 84 is old wait (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::swapon (logior darwinx8664-unix-syscall-mask 85) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getitimer (logior darwinx8664-unix-syscall-mask 86) () ) 87 is old gethostname ; 88 is old sethostname (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getdtablesize (logior darwinx8664-unix-syscall-mask 89) () ) ; 94 is obsolete setdopt (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setpriority (logior darwinx8664-unix-syscall-mask 96) () ) 99 is old accept (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getpriority (logior darwinx8664-unix-syscall-mask 100) () ) 101 is old send 102 is old recv (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigreturn (logior darwinx8664-unix-syscall-mask 103) () ) 107 is obsolete vtimes 108 is old sigvec 109 is old sigblock 110 is old sigsetmask (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigsuspend (logior darwinx8664-unix-syscall-mask 111) () ) 112 is old sigstack 113 is old recvmsg 114 is old sendmsg 115 is obsolete vtrace 119 is obsolete resuba (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::readv (logior darwinx8664-unix-syscall-mask 120) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::writev (logior darwinx8664-unix-syscall-mask 121) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::settimeofday (logior darwinx8664-unix-syscall-mask 122) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fchown (logior darwinx8664-unix-syscall-mask 123) () ) 125 is old 126 is old 127 is old setregid (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::flock (logior darwinx8664-unix-syscall-mask 131) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mkfifo (logior darwinx8664-unix-syscall-mask 132) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::utimes (logior darwinx8664-unix-syscall-mask 138) () ) 139 is unused (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::adjtime (logior darwinx8664-unix-syscall-mask 140) () ) 141 is old getpeername 142 is old gethostid 143 is old 144 is old getrlimit 145 is old setrlimit 146 is old killpg (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setsid (logior darwinx8664-unix-syscall-mask 147) () ) 148 is obsolete setquota 149 is obsolete quota 150 is old ; 151 is reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setprivexec (logior darwinx8664-unix-syscall-mask 152) () ) 153 is reserved 154 is reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::nfssvc (logior darwinx8664-unix-syscall-mask 155) () ) 156 is old getdirentries (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::statfs (logior darwinx8664-unix-syscall-mask 157) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fstatfs (logior darwinx8664-unix-syscall-mask 158) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::unmount (logior darwinx8664-unix-syscall-mask 159) () ) 160 is obsolete async_daemon (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getfh (logior darwinx8664-unix-syscall-mask 161) () ) 162 is old getdomainname 163 is old setdomainname 164 is obsolete pcfs_mount (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::quotactl (logior darwinx8664-unix-syscall-mask 165) () ) 166 is obsolete exportfs 168 is obsolete ustat 169 is unused (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::table (logior darwinx8664-unix-syscall-mask 170) () ) 171 is old wait_3 172 is obsolete rpause 173 is unused 174 is obsolete getdents (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::gc_control (logior darwinx8664-unix-syscall-mask 175) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::add_profil (logior darwinx8664-unix-syscall-mask 176) () ) 177 is unused 178 is unused 179 is unused (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::kdebug_trace (logior darwinx8664-unix-syscall-mask 180) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setegid (logior darwinx8664-unix-syscall-mask 182) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::seteuid (logior darwinx8664-unix-syscall-mask 183) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lfs_bmapv (logior darwinx8664-unix-syscall-mask 184) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lfs_markv (logior darwinx8664-unix-syscall-mask 185) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lfs_segclean (logior darwinx8664-unix-syscall-mask 186) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lfs_segwait (logior darwinx8664-unix-syscall-mask 187) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::pathconf (logior darwinx8664-unix-syscall-mask 191) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fpathconf (logior darwinx8664-unix-syscall-mask 192) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getrlimit (logior darwinx8664-unix-syscall-mask 194) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setrlimit (logior darwinx8664-unix-syscall-mask 195) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getdirentries (logior darwinx8664-unix-syscall-mask 196) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mmap (logior darwinx8664-unix-syscall-mask 197) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::__syscall (logior darwinx8664-unix-syscall-mask 198) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::__sysctl (logior darwinx8664-unix-syscall-mask 202) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mlock (logior darwinx8664-unix-syscall-mask 203) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::munlock (logior darwinx8664-unix-syscall-mask 204) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::undelete (logior darwinx8664-unix-syscall-mask 205) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATsocket (logior darwinx8664-unix-syscall-mask 206) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATgetmsg (logior darwinx8664-unix-syscall-mask 207) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATputmsg (logior darwinx8664-unix-syscall-mask 208) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATPsndreq (logior darwinx8664-unix-syscall-mask 209) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATPsndrsp (logior darwinx8664-unix-syscall-mask 210) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATPgetreq (logior darwinx8664-unix-syscall-mask 211) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATPgetrsp (logior darwinx8664-unix-syscall-mask 212) () ) 213 - 215 are reserved for AppleTalk (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mkcomplex (logior darwinx8664-unix-syscall-mask 216) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::statv (logior darwinx8664-unix-syscall-mask 217) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lstatv (logior darwinx8664-unix-syscall-mask 218) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fstatv (logior darwinx8664-unix-syscall-mask 219) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getattrlist (logior darwinx8664-unix-syscall-mask 220) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setattrlist (logior darwinx8664-unix-syscall-mask 221) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getdirentriesattr (logior darwinx8664-unix-syscall-mask 222) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::exchangedata (logior darwinx8664-unix-syscall-mask 223) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::checkuseraccess (logior darwinx8664-unix-syscall-mask 224) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::searchfs (logior darwinx8664-unix-syscall-mask 225) () ) 226 - 230 are reserved for HFS expansion 231 - 249 are reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::minherit (logior darwinx8664-unix-syscall-mask 250) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semsys (logior darwinx8664-unix-syscall-mask 251) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgsys (logior darwinx8664-unix-syscall-mask 252) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmsys (logior darwinx8664-unix-syscall-mask 253) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semctl (logior darwinx8664-unix-syscall-mask 254) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semget (logior darwinx8664-unix-syscall-mask 255) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semop (logior darwinx8664-unix-syscall-mask 256) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semconfig (logior darwinx8664-unix-syscall-mask 257) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgctl (logior darwinx8664-unix-syscall-mask 258) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgget (logior darwinx8664-unix-syscall-mask 259) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgsnd (logior darwinx8664-unix-syscall-mask 260) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgrcv (logior darwinx8664-unix-syscall-mask 261) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmat (logior darwinx8664-unix-syscall-mask 262) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmctl (logior darwinx8664-unix-syscall-mask 263) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmdt (logior darwinx8664-unix-syscall-mask 264) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmget (logior darwinx8664-unix-syscall-mask 265) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shm_open (logior darwinx8664-unix-syscall-mask 266) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shm_unlink (logior darwinx8664-unix-syscall-mask 267) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_open (logior darwinx8664-unix-syscall-mask 268) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_close (logior darwinx8664-unix-syscall-mask 269) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_unlink (logior darwinx8664-unix-syscall-mask 270) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_wait (logior darwinx8664-unix-syscall-mask 271) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_trywait (logior darwinx8664-unix-syscall-mask 272) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_post (logior darwinx8664-unix-syscall-mask 273) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_getvalue (logior darwinx8664-unix-syscall-mask 274) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_init (logior darwinx8664-unix-syscall-mask 275) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_destroy (logior darwinx8664-unix-syscall-mask 276) () ) 277 - 295 are reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::load_shared_file (logior darwinx8664-unix-syscall-mask 296) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::reset_shared_file (logior darwinx8664-unix-syscall-mask 297) () ) 298 - 323 are reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mlockall (logior darwinx8664-unix-syscall-mask 324) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::munlockall (logior darwinx8664-unix-syscall-mask 325) () ) 326 is reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::issetugid (logior darwinx8664-unix-syscall-mask 327) () ) )
null
https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/library/darwinx8664-syscalls.lisp
lisp
Package : CCL -*- file "LICENSE". The LLGPL consists of a preamble and the LGPL, conflict, the preamble takes precedence. Clozure CL is referenced in the preamble as the "LIBRARY." The LLGPL is also available online at 17 is obsolete sbreak 67 is obsolete vread 88 is old sethostname 94 is obsolete setdopt 151 is reserved
Copyright ( C ) 2001 - 2009 Clozure Associates This file is part of Clozure CL . Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the which is distributed with Clozure CL as the file " LGPL " . Where these (in-package "CCL") (eval-when (:compile-toplevel :load-toplevel :execute) (require "SYSCALL") (defconstant darwinx8664-unix-syscall-mask #x2000000)) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::exit (logior darwinx8664-unix-syscall-mask 1) (:int) :void ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fork (logior darwinx8664-unix-syscall-mask 2) () :void) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::read (logior darwinx8664-unix-syscall-mask 3) (:unsigned-fullword :address :unsigned-long) :signed-long ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::write (logior darwinx8664-unix-syscall-mask 4) (:unsigned-fullword :address :unsigned-long) :signed-long ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::open (logior darwinx8664-unix-syscall-mask 5) (:address :unsigned-fullword :unsigned-fullword) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::close (logior darwinx8664-unix-syscall-mask 6) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::wait4 (logior darwinx8664-unix-syscall-mask 7) (:unsigned-fullword :address :signed-fullword :address) :unsigned-fullword ) 8 is old creat (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::link (logior darwinx8664-unix-syscall-mask 9) (:address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::unlink (logior darwinx8664-unix-syscall-mask 10) (:address) :signed-fullword ) 11 is obsolete execv (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::chdir (logior darwinx8664-unix-syscall-mask 12) (:address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fchdir (logior darwinx8664-unix-syscall-mask 13) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mknod (logior darwinx8664-unix-syscall-mask 14) (:address :unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::chmod (logior darwinx8664-unix-syscall-mask 15) (:address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lchown (logior darwinx8664-unix-syscall-mask 16) (:address :unsigned-fullword :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getpid (logior darwinx8664-unix-syscall-mask 20) () :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setuid (logior darwinx8664-unix-syscall-mask 23) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getuid (logior darwinx8664-unix-syscall-mask 24) () :unsigned-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::geteuid (logior darwinx8664-unix-syscall-mask 25) () :unsigned-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::recvmsg (logior darwinx8664-unix-syscall-mask 27) (:unsigned-fullword :address :unsigned-fullword):signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sendmsg (logior darwinx8664-unix-syscall-mask 28) (:unsigned-fullword :address :unsigned-fullword):signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::recvfrom (logior darwinx8664-unix-syscall-mask 29) (:unsigned-fullword :address :unsigned-long :unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::accept (logior darwinx8664-unix-syscall-mask 30) (:unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getpeername (logior darwinx8664-unix-syscall-mask 31) (:unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getsockname (logior darwinx8664-unix-syscall-mask 32) (:unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::kill (logior darwinx8664-unix-syscall-mask 37) (:signed-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sync (logior darwinx8664-unix-syscall-mask 36) () :unsigned-fullword ) 38 is old stat (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getppid (logior darwinx8664-unix-syscall-mask 39) () :unsigned-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::dup (logior darwinx8664-unix-syscall-mask 41) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::pipe (logior darwinx8664-unix-syscall-mask 42) () :signed-doubleword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getgid (logior darwinx8664-unix-syscall-mask 47) () :unsigned-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ioctl (logior darwinx8664-unix-syscall-mask 54) (:unsigned-fullword :signed-fullword :address) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::dup2 (logior darwinx8664-unix-syscall-mask 90) (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fcntl (logior darwinx8664-unix-syscall-mask 92) (:unsigned-fullword :signed-fullword :signed-fullword) :signed-fullword :min-args 2 ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::select (logior darwinx8664-unix-syscall-mask 93) (:unsigned-fullword :address :address :address :address) :signed-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fsync (logior darwinx8664-unix-syscall-mask 95) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::socket (logior darwinx8664-unix-syscall-mask 97) (:unsigned-fullword :unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::connect (logior darwinx8664-unix-syscall-mask 98) (:unsigned-fullword :address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::bind (logior darwinx8664-unix-syscall-mask 104) (:unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setsockopt (logior darwinx8664-unix-syscall-mask 105) (:unsigned-fullword :signed-fullword :signed-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::listen (logior darwinx8664-unix-syscall-mask 106) (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::gettimeofday (logior darwinx8664-unix-syscall-mask 116) (:address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getrusage (logior darwinx8664-unix-syscall-mask 117) (:signed-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getsockopt (logior darwinx8664-unix-syscall-mask 118) (:unsigned-fullword :signed-fullword :unsigned-fullword :address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fchmod (logior darwinx8664-unix-syscall-mask 124) (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::rename (logior darwinx8664-unix-syscall-mask 128) (:address :address) :signed-fullword) 129 is old truncate 130 is old ftruncate (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sendto (logior darwinx8664-unix-syscall-mask 133) (:unsigned-fullword :address :unsigned-fullword :unsigned-fullword :address :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shutdown (logior darwinx8664-unix-syscall-mask 134) (:unsigned-fullword :unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::socketpair (logior darwinx8664-unix-syscall-mask 135) (:unsigned-fullword :unsigned-fullword :unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mkdir (logior darwinx8664-unix-syscall-mask 136) (:address :unsigned-fullword) :signed-fullword) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::rmdir (logior darwinx8664-unix-syscall-mask 137) (:address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mount (logior darwinx8664-unix-syscall-mask 167) (:address :address :unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setgid (logior darwinx8664-unix-syscall-mask 181) (:unsigned-fullword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::stat (logior darwinx8664-unix-syscall-mask 188) (:address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fstat (logior darwinx8664-unix-syscall-mask 189) (:unsigned-fullword :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lstat (logior darwinx8664-unix-syscall-mask 190) (:address :address) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lseek (logior darwinx8664-unix-syscall-mask 199) (:unsigned-fullword :signed-doubleword :unsigned-fullword) :signed-doubleword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::truncate (logior darwinx8664-unix-syscall-mask 200) (:address :unsigned-doubleword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ftruncate (logior darwinx8664-unix-syscall-mask 201) (:unsigned-fullword :unsigned-doubleword) :signed-fullword ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::poll (logior darwinx8664-unix-syscall-mask 230) ((:* (:struct :pollfd)) :int :int) :int) #+notdefinedyet (progn 18 is old getfsstat 19 is old lseek 21 is obsolete mount 22 is obsolete umount (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ptrace (logior darwinx8664-unix-syscall-mask 26) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::access (logior darwinx8664-unix-syscall-mask 33) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::chflags (logior darwinx8664-unix-syscall-mask 34) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fchflags (logior darwinx8664-unix-syscall-mask 35) () ) 40 is old lstat (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getegid (logior darwinx8664-unix-syscall-mask 43) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::profil (logior darwinx8664-unix-syscall-mask 44) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ktrace (logior darwinx8664-unix-syscall-mask 45) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigaction (logior darwinx8664-unix-syscall-mask 46) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigprocmask (logior darwinx8664-unix-syscall-mask 48) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getlogin (logior darwinx8664-unix-syscall-mask 49) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setlogin (logior darwinx8664-unix-syscall-mask 50) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::acct (logior darwinx8664-unix-syscall-mask 51) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigpending (logior darwinx8664-unix-syscall-mask 52) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigaltstack (logior darwinx8664-unix-syscall-mask 53) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::reboot (logior darwinx8664-unix-syscall-mask 55) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::revoke (logior darwinx8664-unix-syscall-mask 56) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::symlink (logior darwinx8664-unix-syscall-mask 57) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::readlink (logior darwinx8664-unix-syscall-mask 58) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::execve (logior darwinx8664-unix-syscall-mask 59) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::umask (logior darwinx8664-unix-syscall-mask 60) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::chroot (logior darwinx8664-unix-syscall-mask 61) () ) 62 is old fstat 63 is unused 64 is old getpagesize (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msync (logior darwinx8664-unix-syscall-mask 65) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::vfork (logior darwinx8664-unix-syscall-mask 66) () ) 68 is obsolete vwrite (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sbrk (logior darwinx8664-unix-syscall-mask 69) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sstk (logior darwinx8664-unix-syscall-mask 70) () ) 71 is old mmap 72 is obsolete vadvise (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::munmap (logior darwinx8664-unix-syscall-mask 73) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mprotect (logior darwinx8664-unix-syscall-mask 74) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::madvise (logior darwinx8664-unix-syscall-mask 75) () ) 76 is obsolete 77 is obsolete vlimit (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mincore (logior darwinx8664-unix-syscall-mask 78) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getgroups (logior darwinx8664-unix-syscall-mask 79) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setgroups (logior darwinx8664-unix-syscall-mask 80) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getpgrp (logior darwinx8664-unix-syscall-mask 81) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setpgid (logior darwinx8664-unix-syscall-mask 82) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setitimer (logior darwinx8664-unix-syscall-mask 83) () ) 84 is old wait (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::swapon (logior darwinx8664-unix-syscall-mask 85) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getitimer (logior darwinx8664-unix-syscall-mask 86) () ) 87 is old gethostname (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getdtablesize (logior darwinx8664-unix-syscall-mask 89) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setpriority (logior darwinx8664-unix-syscall-mask 96) () ) 99 is old accept (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getpriority (logior darwinx8664-unix-syscall-mask 100) () ) 101 is old send 102 is old recv (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigreturn (logior darwinx8664-unix-syscall-mask 103) () ) 107 is obsolete vtimes 108 is old sigvec 109 is old sigblock 110 is old sigsetmask (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sigsuspend (logior darwinx8664-unix-syscall-mask 111) () ) 112 is old sigstack 113 is old recvmsg 114 is old sendmsg 115 is obsolete vtrace 119 is obsolete resuba (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::readv (logior darwinx8664-unix-syscall-mask 120) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::writev (logior darwinx8664-unix-syscall-mask 121) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::settimeofday (logior darwinx8664-unix-syscall-mask 122) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fchown (logior darwinx8664-unix-syscall-mask 123) () ) 125 is old 126 is old 127 is old setregid (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::flock (logior darwinx8664-unix-syscall-mask 131) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mkfifo (logior darwinx8664-unix-syscall-mask 132) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::utimes (logior darwinx8664-unix-syscall-mask 138) () ) 139 is unused (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::adjtime (logior darwinx8664-unix-syscall-mask 140) () ) 141 is old getpeername 142 is old gethostid 143 is old 144 is old getrlimit 145 is old setrlimit 146 is old killpg (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setsid (logior darwinx8664-unix-syscall-mask 147) () ) 148 is obsolete setquota 149 is obsolete quota 150 is old (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setprivexec (logior darwinx8664-unix-syscall-mask 152) () ) 153 is reserved 154 is reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::nfssvc (logior darwinx8664-unix-syscall-mask 155) () ) 156 is old getdirentries (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::statfs (logior darwinx8664-unix-syscall-mask 157) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fstatfs (logior darwinx8664-unix-syscall-mask 158) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::unmount (logior darwinx8664-unix-syscall-mask 159) () ) 160 is obsolete async_daemon (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getfh (logior darwinx8664-unix-syscall-mask 161) () ) 162 is old getdomainname 163 is old setdomainname 164 is obsolete pcfs_mount (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::quotactl (logior darwinx8664-unix-syscall-mask 165) () ) 166 is obsolete exportfs 168 is obsolete ustat 169 is unused (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::table (logior darwinx8664-unix-syscall-mask 170) () ) 171 is old wait_3 172 is obsolete rpause 173 is unused 174 is obsolete getdents (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::gc_control (logior darwinx8664-unix-syscall-mask 175) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::add_profil (logior darwinx8664-unix-syscall-mask 176) () ) 177 is unused 178 is unused 179 is unused (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::kdebug_trace (logior darwinx8664-unix-syscall-mask 180) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setegid (logior darwinx8664-unix-syscall-mask 182) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::seteuid (logior darwinx8664-unix-syscall-mask 183) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lfs_bmapv (logior darwinx8664-unix-syscall-mask 184) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lfs_markv (logior darwinx8664-unix-syscall-mask 185) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lfs_segclean (logior darwinx8664-unix-syscall-mask 186) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lfs_segwait (logior darwinx8664-unix-syscall-mask 187) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::pathconf (logior darwinx8664-unix-syscall-mask 191) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fpathconf (logior darwinx8664-unix-syscall-mask 192) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getrlimit (logior darwinx8664-unix-syscall-mask 194) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setrlimit (logior darwinx8664-unix-syscall-mask 195) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getdirentries (logior darwinx8664-unix-syscall-mask 196) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mmap (logior darwinx8664-unix-syscall-mask 197) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::__syscall (logior darwinx8664-unix-syscall-mask 198) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::__sysctl (logior darwinx8664-unix-syscall-mask 202) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mlock (logior darwinx8664-unix-syscall-mask 203) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::munlock (logior darwinx8664-unix-syscall-mask 204) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::undelete (logior darwinx8664-unix-syscall-mask 205) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATsocket (logior darwinx8664-unix-syscall-mask 206) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATgetmsg (logior darwinx8664-unix-syscall-mask 207) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATputmsg (logior darwinx8664-unix-syscall-mask 208) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATPsndreq (logior darwinx8664-unix-syscall-mask 209) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATPsndrsp (logior darwinx8664-unix-syscall-mask 210) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATPgetreq (logior darwinx8664-unix-syscall-mask 211) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::ATPgetrsp (logior darwinx8664-unix-syscall-mask 212) () ) 213 - 215 are reserved for AppleTalk (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mkcomplex (logior darwinx8664-unix-syscall-mask 216) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::statv (logior darwinx8664-unix-syscall-mask 217) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::lstatv (logior darwinx8664-unix-syscall-mask 218) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::fstatv (logior darwinx8664-unix-syscall-mask 219) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getattrlist (logior darwinx8664-unix-syscall-mask 220) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::setattrlist (logior darwinx8664-unix-syscall-mask 221) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::getdirentriesattr (logior darwinx8664-unix-syscall-mask 222) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::exchangedata (logior darwinx8664-unix-syscall-mask 223) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::checkuseraccess (logior darwinx8664-unix-syscall-mask 224) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::searchfs (logior darwinx8664-unix-syscall-mask 225) () ) 226 - 230 are reserved for HFS expansion 231 - 249 are reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::minherit (logior darwinx8664-unix-syscall-mask 250) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semsys (logior darwinx8664-unix-syscall-mask 251) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgsys (logior darwinx8664-unix-syscall-mask 252) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmsys (logior darwinx8664-unix-syscall-mask 253) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semctl (logior darwinx8664-unix-syscall-mask 254) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semget (logior darwinx8664-unix-syscall-mask 255) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semop (logior darwinx8664-unix-syscall-mask 256) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::semconfig (logior darwinx8664-unix-syscall-mask 257) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgctl (logior darwinx8664-unix-syscall-mask 258) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgget (logior darwinx8664-unix-syscall-mask 259) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgsnd (logior darwinx8664-unix-syscall-mask 260) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::msgrcv (logior darwinx8664-unix-syscall-mask 261) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmat (logior darwinx8664-unix-syscall-mask 262) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmctl (logior darwinx8664-unix-syscall-mask 263) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmdt (logior darwinx8664-unix-syscall-mask 264) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shmget (logior darwinx8664-unix-syscall-mask 265) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shm_open (logior darwinx8664-unix-syscall-mask 266) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::shm_unlink (logior darwinx8664-unix-syscall-mask 267) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_open (logior darwinx8664-unix-syscall-mask 268) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_close (logior darwinx8664-unix-syscall-mask 269) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_unlink (logior darwinx8664-unix-syscall-mask 270) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_wait (logior darwinx8664-unix-syscall-mask 271) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_trywait (logior darwinx8664-unix-syscall-mask 272) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_post (logior darwinx8664-unix-syscall-mask 273) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_getvalue (logior darwinx8664-unix-syscall-mask 274) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_init (logior darwinx8664-unix-syscall-mask 275) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::sem_destroy (logior darwinx8664-unix-syscall-mask 276) () ) 277 - 295 are reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::load_shared_file (logior darwinx8664-unix-syscall-mask 296) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::reset_shared_file (logior darwinx8664-unix-syscall-mask 297) () ) 298 - 323 are reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::mlockall (logior darwinx8664-unix-syscall-mask 324) () ) (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::munlockall (logior darwinx8664-unix-syscall-mask 325) () ) 326 is reserved (define-syscall (logior platform-os-darwin platform-cpu-x86 platform-word-size-64) syscalls::issetugid (logior darwinx8664-unix-syscall-mask 327) () ) )
60a1e46a421b4fa6dd19be0e18d0f42e7aa8d71832a384c8333f3d32542d6d0e
dongcarl/guix
gnome-xyz.scm
;;; GNU Guix --- Functional package management for GNU Copyright Β© 2019 , 2020 , 2021 < > Copyright Β© 2019 , 2021 Theodotou < > Copyright Β© 2019 < > Copyright Β© 2020 < > Copyright Β© 2020 < > Copyright Β© 2020 < > Copyright Β© 2020 < > Copyright Β© 2020 < > Copyright Β© 2020 Prior < > Copyright Β© 2020 > Copyright Β© 2020 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . (define-module (gnu packages gnome-xyz) #:use-module (guix build-system trivial) #:use-module (guix build-system gnu) #:use-module (guix build-system copy) #:use-module (guix build-system meson) #:use-module (guix git-download) #:use-module (guix packages) #:use-module (guix utils) #:use-module ((guix licenses) #:prefix license:) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages bash) #:use-module (gnu packages gettext) #:use-module (gnu packages glib) #:use-module (gnu packages gnome) #:use-module (gnu packages gtk) #:use-module (gnu packages inkscape) #:use-module (gnu packages image) #:use-module (gnu packages pkg-config) #:use-module (gnu packages python-xyz) #:use-module (gnu packages ssh) #:use-module (gnu packages tls) #:use-module (gnu packages ruby) #:use-module (gnu packages web) #:use-module (gnu packages xml)) (define-public arc-icon-theme (package (name "arc-icon-theme") (version "20161122") (source (origin (method git-fetch) (uri (git-reference (url "-icon-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1ch3hp08qri93510hypzz6m2x4xgg2h15wvnhjwh1x1s1b7jvxjd")))) (build-system gnu-build-system) (arguments `(#:phases (modify-phases %standard-phases (add-after 'unpack 'disable-configure-during-bootstrap (lambda _ (substitute* "autogen.sh" (("^\"\\$srcdir/configure\".*") "")) #t))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake))) When Arc is missing an icon , it looks in the Moka icon theme for it . (propagated-inputs `(("moka-icon-theme" ,moka-icon-theme))) (synopsis "Arc icon theme") (description "The Arc icon theme provides a set of icons matching the style of the Arc GTK theme. Icons missing from the Arc theme are provided by the Moka icon theme.") (home-page "-icon-theme") (license license:gpl3+))) (define-public delft-icon-theme (package (name "delft-icon-theme") (version "1.14") (source (origin (method git-fetch) (uri (git-reference (url "-delft") (commit (string-append "v" version)))) (sha256 (base32 "1iw85cxx9lv7irs28qi3815dk9f9vldv2j7jf1x5l1dqzwaxgwpb")) (file-name (git-file-name name version)))) (build-system copy-build-system) (arguments `(#:install-plan `(("." "share/icons" #:exclude ("README.md" "LICENSE" "logo.jpg"))) #:phases (modify-phases %standard-phases (add-after 'unpack 'patch-index.theme (lambda _ (substitute* "Delft/index.theme" (("gnome") "Adwaita")) #t))))) (home-page "-look.org/p/1199881/") (synopsis "Continuation of Faenza icon theme with up to date app icons") (description "Delft is a fork of the popular icon theme Faenza with up to date app icons. It will stay optically close to the original Faenza icons, which haven't been updated for some years. The new app icons are ported from the Obsidian icon theme.") (license license:gpl3))) (define-public faba-icon-theme (package (name "faba-icon-theme") (version "4.3") (source (origin (method git-fetch) (uri (git-reference (url "-icon-theme") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0xh6ppr73p76z60ym49b4d0liwdc96w41cc5p07d48hxjsa6qd6n")))) (build-system meson-build-system) (arguments `(#:phases (modify-phases %standard-phases (add-before 'configure 'disable-post-install (lambda _ (substitute* "meson.build" (("meson.add_install_script.*") ""))))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake))) (synopsis "Faba icon theme") (description "Faba is a minimal icon set used as a basis for other themes such as Moka") (home-page "") (license (list license:lgpl3+ license:cc-by-sa4.0)))) (define-public moka-icon-theme (package (inherit faba-icon-theme) (name "moka-icon-theme") (version "5.4.0") (source (origin (method git-fetch) (uri (git-reference (url "-icon-theme") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "015l02im4mha5z91dbchxf6xkp66d346bg3xskwg0rh3lglhjsrd")))) (propagated-inputs Moka is based on Faba by using it as a fallback icon set instead of ;; bundling it, so we need to add it as a propagated input. `(("faba-icon-theme" ,faba-icon-theme))) (synopsis "Moka icon theme") (description "Moka is a stylized desktop icon set, designed to be clear, simple and consistent.") (license (list license:gpl3+ license:cc-by-sa4.0)))) (define-public papirus-icon-theme (package (name "papirus-icon-theme") (version "20210101") (source (origin (method git-fetch) (uri (git-reference (url "-icon-theme") (commit version))) (sha256 (base32 "0w6qg3zjhfvjg1gg5inranf8ianb4mrp0jm9qgi6hg87ig1rashs")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments '(#:tests? #f #:make-flags (list (string-append "PREFIX=" (assoc-ref %outputs "out"))) #:phases (modify-phases %standard-phases (delete 'bootstrap) (delete 'configure) (delete 'build)))) (native-inputs `(("gtk+:bin" ,gtk+ "bin"))) (home-page "-icon-theme") (synopsis "Fork of Paper icon theme with a lot of new icons and a few extras") (description "Papirus is a fork of the icon theme Paper with a lot of new icons and a few extra features.") (license license:gpl3))) (define-public gnome-shell-extension-appindicator (package (name "gnome-shell-extension-appindicator") (version "33") (source (origin (method git-fetch) (uri (git-reference (url "-shell-extension-appindicator") (commit (string-append "v" version)))) (sha256 (base32 "0qm77s080nbf4gqnfzpwp8a7jf7lliz6fxbsd3lasvrr11pgsk87")) (file-name (git-file-name name version)))) (build-system copy-build-system) (arguments `(#:install-plan '(("." ,(string-append "share/gnome-shell/extensions/" ""))))) (synopsis "Adds KStatusNotifierItem support to GNOME Shell") (description "This extension integrates Ubuntu AppIndicators and KStatusNotifierItems (KDE's successor of the systray) into GNOME Shell.") (home-page "-shell-extension-appindicator/") (license license:gpl2+))) (define-public gnome-shell-extension-clipboard-indicator (package (name "gnome-shell-extension-clipboard-indicator") (version "34") (source (origin (method git-fetch) (uri (git-reference (url (string-append "/" "gnome-shell-extension-clipboard-indicator.git")) (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0i00psc1ky70zljd14jzr627y7nd8xwnwrh4xpajl1f6djabh12s")) (modules '((guix build utils))) (snippet ;; Remove pre-compiled settings schemas and translations from ;; source, as they are generated as part of build. Upstream ;; includes them for people who want to run the software ;; directly from source tree. '(begin (delete-file "schemas/gschemas.compiled") (for-each delete-file (find-files "locale" "\\.mo$")) #t)))) (build-system copy-build-system) (arguments '(#:install-plan '(("." "share/gnome-shell/extensions/" #:include-regexp ("\\.css$" "\\.compiled$" "\\.js(on)?$" "\\.mo$" "\\.xml$"))) #:phases (modify-phases %standard-phases (add-before 'install 'compile-schemas (lambda _ (with-directory-excursion "schemas" (invoke "glib-compile-schemas" ".")) #t)) (add-before 'install 'compile-locales (lambda _ (invoke "./compile-locales.sh") #t))))) (native-inputs `(("gettext" ,gettext-minimal) ("glib:bin" ,glib "bin"))) ; for glib-compile-schemas (home-page "-shell-extension-clipboard-indicator") (synopsis "Clipboard manager extension for GNOME Shell") (description "Clipboard Indicator is a clipboard manager for GNOME Shell that caches clipboard history.") (license license:expat))) (define-public gnome-shell-extension-topicons-redux (package (name "gnome-shell-extension-topicons-redux") (version "6") (source (origin (method git-fetch) (uri (git-reference (url "-planet/TopIcons-Redux.git") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1dli9xb545n3xlj6q4wl0y5gzkm903zs47p8fiq71pdvbr6v38rj")))) (build-system gnu-build-system) (native-inputs `(("glib" ,glib "bin"))) (arguments `(#:tests? #f ;no test defined in the project #:phases (modify-phases %standard-phases (delete 'configure) (delete 'build) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (invoke "make" "install" (string-append "INSTALL_PATH=" out "/share/gnome-shell/extensions")))))))) (home-page "-planet/TopIcons-Redux") (synopsis "Display legacy tray icons in the GNOME Shell top panel") (description "Many applications, such as chat clients, downloaders, and some media players, are meant to run long-term in the background even after you close their window. These applications remain accessible by adding an icon to the GNOME Shell Legacy Tray. However, the Legacy Tray was removed in GNOME 3.26. TopIcons Redux brings those icons back into the top panel so that it's easier to keep track of applications running in the background.") (license license:gpl2+))) (define-public gnome-shell-extension-dash-to-dock (package (name "gnome-shell-extension-dash-to-dock") (version "67") (source (origin (method git-fetch) (uri (git-reference (url "-to-dock") (commit (string-append "extensions.gnome.org-v" version)))) (sha256 (base32 "1746xm0iyvyzj6m3pvjx11smh9w1s7naz426ki0dlr5l7jh3mpy5")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments '(#:tests? #f #:make-flags (list (string-append "INSTALLBASE=" (assoc-ref %outputs "out") "/share/gnome-shell/extensions")) #:phases (modify-phases %standard-phases (delete 'bootstrap) (delete 'configure)))) (native-inputs `(("glib:bin" ,glib "bin") ("intltool" ,intltool) ("pkg-config" ,pkg-config))) (propagated-inputs `(("glib" ,glib))) (synopsis "Transforms GNOME's dash into a dock") (description "This extension moves the dash out of the overview, transforming it into a dock for easier application launching and faster window switching.") (home-page "-to-dock/") (license license:gpl2+))) (define-public gnome-shell-extension-gsconnect (package (name "gnome-shell-extension-gsconnect") v33 is the last version to support GNOME 3.34 (version "33") (source (origin (method git-fetch) (uri (git-reference (url (string-append "" "/gnome-shell-extension-gsconnect.git")) (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1q03axhn75i864vgmd6myhmgwrmnpf01gsd1wl0di5x9q8mic2zn")))) (build-system meson-build-system) (arguments `(#:configure-flags (let* ((out (assoc-ref %outputs "out")) (name+version (strip-store-file-name out)) (gschema-dir (string-append out "/share/gsettings-schemas/" name+version "/glib-2.0/schemas")) (gnome-shell (assoc-ref %build-inputs "gnome-shell")) (openssh (assoc-ref %build-inputs "openssh")) (openssl (assoc-ref %build-inputs "openssl"))) (list (string-append "-Dgnome_shell_libdir=" gnome-shell "/lib") (string-append "-Dgsettings_schemadir=" gschema-dir) (string-append "-Dopenssl_path=" openssl "/bin/openssl") (string-append "-Dsshadd_path=" openssh "/bin/ssh-add") (string-append "-Dsshkeygen_path=" openssh "/bin/ssh-keygen") (string-append "-Dsession_bus_services_dir=" out "/share/dbus-1/services") "-Dpost_install=true")) #:phases (modify-phases %standard-phases (add-before 'configure 'fix-paths (lambda* (#:key inputs #:allow-other-keys) (let* ((glib (assoc-ref inputs "glib:bin")) (gapplication (string-append glib "/bin/gapplication")) (gi-typelib-path (getenv "GI_TYPELIB_PATH"))) (substitute* "data/org.gnome.Shell.Extensions.GSConnect.desktop" (("gapplication") gapplication)) (for-each (lambda (file) (substitute* file (("'use strict';") (string-append "'use strict';\n\n" "'" gi-typelib-path "'.split(':').forEach(" "path => imports.gi.GIRepository.Repository." "prepend_search_path(path));")))) '("src/extension.js" "src/prefs.js")) #t))) (add-after 'install 'wrap-daemons (lambda* (#:key inputs outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (service-dir (string-append out "/share/gnome-shell/extensions" "//service")) (gi-typelib-path (getenv "GI_TYPELIB_PATH"))) (wrap-program (string-append service-dir "/daemon.js") `("GI_TYPELIB_PATH" ":" prefix (,gi-typelib-path))) #t)))))) (inputs `(("at-spi2-core" ,at-spi2-core) ("caribou" ,caribou) ("evolution-data-server" ,evolution-data-server) ("gjs" ,gjs) ("glib" ,glib) ("glib:bin" ,glib "bin") ("gsound" ,gsound) ("gnome-shell" ,gnome-shell) ("gtk+" ,gtk+) ("nautilus" ,nautilus) ("openssh" ,openssh) ("openssl" ,openssl) ("python-nautilus" ,python-nautilus) ("python-pygobject" ,python-pygobject) ("upower" ,upower))) (native-inputs `(("gettext" ,gettext-minimal) ("gobject-introspection" ,gobject-introspection) ("libxml2" ,libxml2) ("pkg-config" ,pkg-config))) (home-page "-shell-extension-gsconnect/wiki") (synopsis "Connect GNOME Shell with your Android phone") (description "GSConnect is a complete implementation of KDE Connect especially for GNOME Shell, allowing devices to securely share content, like notifications or files, and other features like SMS messaging and remote control.") (license license:gpl2))) (define-public gnome-shell-extension-hide-app-icon (let ((commit "4188aa5f4ba24901a053a0c3eb0d83baa8625eab") (revision "0")) (package (name "gnome-shell-extension-hide-app-icon") (version (git-version "2.7" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url (string-append "-rapp" "/gnome-shell-extension-hide-app-icon.git")) (commit commit))) (sha256 (base32 "1i28n4bz6wrhn07vpxkr6l1ljyn7g8frp5xrr11z3z32h2hxxcd6")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments '(#:tests? #f ; no test target #:make-flags (list (string-append "EXTENSIONS_DIR=" (assoc-ref %outputs "out") "/share/gnome-shell/extensions")) #:phases (modify-phases %standard-phases (delete 'configure) ; no configure script (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (pre "/share/gnome-shell/extensions/") (dir "")) (copy-recursively dir (string-append out pre dir)) #t)))))) (native-inputs `(("glib" ,glib "bin") ("intltool" ,intltool))) (propagated-inputs `(("glib" ,glib))) (synopsis "Hide app icon from GNOME's panel") (description "This extension hides the icon and/or title of the currently focused application in the top panel of the GNOME shell.") (home-page "-rapp/gnome-shell-extension-hide-app-icon/") (license README.md and LICENSE.txt disagree -- the former claims v3 , the ;; latter v2. No mention of "or later" in either place or in the code. (list license:gpl2 license:gpl3))))) (define-public gnome-shell-extension-dash-to-panel (package (name "gnome-shell-extension-dash-to-panel") (version "38") (source (origin (method git-fetch) (uri (git-reference (url "-sweet-gnome/dash-to-panel") (commit (string-append "v" version)))) (sha256 (base32 "1kvybb49l1vf0fvh8d0c6xkwnry8m330scamf5x40y63d4i213j1")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments `(#:tests? #f #:make-flags (list (string-append "INSTALLBASE=" (assoc-ref %outputs "out") "/share/gnome-shell/extensions") (string-append "VERSION=" ,(package-version gnome-shell-extension-dash-to-panel))) #:phases (modify-phases %standard-phases (delete 'bootstrap) (delete 'configure)))) (native-inputs `(("intltool" ,intltool) ("pkg-config" ,pkg-config))) (propagated-inputs `(("glib" ,glib) ("glib" ,glib "bin"))) (synopsis "Icon taskbar for GNOME Shell") (description "This extension moves the dash into the gnome main panel so that the application launchers and system tray are combined into a single panel, similar to that found in KDE Plasma and Windows 7+.") (home-page "-sweet-gnome/dash-to-panel/") (license license:gpl2+))) (define-public gnome-shell-extension-noannoyance (package (name "gnome-shell-extension-noannoyance") (version "5") (source (origin (method git-fetch) (uri (git-reference (url "") (commit "e37b5b3c31f577b4698bc6659bc9fec5ea9ac5d4"))) (sha256 (base32 "0fa8l3xlh8kbq07y4385wpb908zm6x53z81q16xlmin97dln32hh")) (file-name (git-file-name name version)))) (build-system copy-build-system) (arguments '(#:install-plan '(("." "share/gnome-shell/extensions/")))) (synopsis "Remove 'Window is ready' annotation") (description "One of the many extensions that remove this message. It uses ES6 syntax and claims to be more actively maintained than others.") (home-page "/") (license license:gpl2))) (define-public gnome-shell-extension-paperwm (package (name "gnome-shell-extension-paperwm") (version "36.0") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1ssnabwxrns36c61ppspjkr9i3qifv08pf2jpwl7cjv3pvyn4kly")) (snippet '(begin (delete-file "schemas/gschemas.compiled"))))) (build-system copy-build-system) (arguments '(#:install-plan '(("." "share/gnome-shell/extensions/paperwm@hedning:matrix.org" #:include-regexp ("\\.js(on)?$" "\\.css$" "\\.ui$" "\\.png$" "\\.xml$" "\\.compiled$"))) #:phases (modify-phases %standard-phases (add-before 'install 'compile-schemas (lambda _ (with-directory-excursion "schemas" (invoke "make")) #t))))) (native-inputs `(("glib:bin" ,glib "bin"))) ; for glib-compile-schemas (home-page "") (synopsis "Tiled scrollable window management for GNOME Shell") (description "PaperWM is an experimental GNOME Shell extension providing scrollable tiling of windows and per monitor workspaces. It's inspired by paper notebooks and tiling window managers.") (license license:gpl3))) (define-public arc-theme (package (name "arc-theme") (version "20201013") (source (origin (method git-fetch) (uri (git-reference (url "-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1x2l1mwjx68dwf3jb1i90c1q8nqsl1wf2zggcn8im6590k5yv39s")))) (build-system gnu-build-system) (arguments '(#:configure-flags (list "--disable-cinnamon") #:phases (modify-phases %standard-phases ;; autogen.sh calls configure at the end of the script. (replace 'bootstrap (lambda _ (invoke "autoreconf" "-vfi"))) (add-before 'build 'set-home ;placate Inkscape (lambda _ (setenv "HOME" (getcwd)) #t))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("glib" ,glib "bin") ; for glib-compile-resources ("gnome-shell" ,gnome-shell) ("gtk+" ,gtk+) ("inkscape" ,inkscape) ("optipng" ,optipng) ("pkg-config" ,pkg-config) ("sassc" ,sassc/libsass-3.5))) (synopsis "A flat GTK+ theme with transparent elements") (description "Arc is a flat theme with transparent elements for GTK 3, GTK 2, and GNOME Shell which supports GTK 3 and GTK 2 based desktop environments like GNOME, Unity, Budgie, Pantheon, XFCE, Mate, etc.") (home-page "-theme") ;; No "or later" language found. (license license:gpl3+))) (define-public greybird-gtk-theme (package (name "greybird-gtk-theme") (version "3.22.13") (source (origin (method git-fetch) (uri (git-reference (url "") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "154qawiga792iimkpk3a6q8f4gm4r158wmsagkbqqbhj33kxgxhg")))) (build-system meson-build-system) (native-inputs `(("gtk+" ,gtk+) ("glib:bin" ,glib "bin") ; for "glib-compile-resources" ("librsvg" ,librsvg) ("pkg-config" ,pkg-config) ("ruby-sass" ,ruby-sass) ("sassc" ,sassc))) (home-page "/") (synopsis "Grey GTK+ theme based on Bluebird") (description "Greybird is a grey derivative of the Bluebird theme by the Shimmer Project. It supports GNOME, Unity, and Xfce.") (license (list license:gpl2+ license:cc-by-sa3.0)))) (define-public matcha-theme (package (name "matcha-theme") (version "2021-01-01") (source (origin (method git-fetch) (uri (git-reference (url "-gtk-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1pa6ra87wlq0gwz4n03l6xv0pxiamr5dygycvppms8v6xyc2aa0r")))) (build-system trivial-build-system) (arguments '(#:modules ((guix build utils)) #:builder (begin (use-modules (guix build utils)) (let* ((out (assoc-ref %outputs "out")) (source (assoc-ref %build-inputs "source")) (bash (assoc-ref %build-inputs "bash")) (coreutils (assoc-ref %build-inputs "coreutils")) (themesdir (string-append out "/share/themes"))) (setenv "PATH" (string-append coreutils "/bin:" (string-append bash "/bin:"))) (copy-recursively source (getcwd)) (patch-shebang "install.sh") (mkdir-p themesdir) (invoke "./install.sh" "-d" themesdir) #t)))) (inputs `(("gtk-engines" ,gtk-engines))) (native-inputs `(("bash" ,bash) ("coreutils" ,coreutils))) (synopsis "Flat design theme for GTK 3, GTK 2 and GNOME-Shell") (description "Matcha is a flat Design theme for GTK 3, GTK 2 and Gnome-Shell which supports GTK 3 and GTK 2 based desktop environments like Gnome, Unity, Budgie, Pantheon, XFCE, Mate and others.") (home-page "") (license license:gpl3+))) (define-public materia-theme (package (name "materia-theme") (version "20200916") (source (origin (method git-fetch) (uri (git-reference (url "-4/materia-theme") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0qaxxafsn5zd2ysgr0jyv5j73360mfdmxyd55askswlsfphssn74")))) (build-system meson-build-system) (native-inputs `(("gtk+" ,gtk+) ("sassc" ,sassc))) (home-page "-4/materia-theme") (synopsis "Material Design theme for a wide range of environments") (description "Materia is a Material Design theme for GNOME/GTK based desktop environments. It supports GTK 2, GTK 3, GNOME Shell, Budgie, Cinnamon, MATE, Unity, Xfce, LightDM, GDM, Chrome theme, etc.") (license license:gpl2+))) (define-public numix-gtk-theme (package (name "numix-gtk-theme") (version "2.6.7") (source (origin (method git-fetch) (uri (git-reference (url "-gtk-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "12mw0kr0kkvg395qlbsvkvaqccr90cmxw5rrsl236zh43kj8grb7")))) (build-system gnu-build-system) (arguments '(#:make-flags (list (string-append "INSTALL_DIR=" (assoc-ref %outputs "out") "/share/themes/Numix")) #:tests? #f #:phases (modify-phases %standard-phases (delete 'configure)))) ; no configure script (native-inputs `(("glib:bin" ,glib "bin") ; for glib-compile-schemas ("gnome-shell" ,gnome-shell) ("gtk+" ,gtk+) ("xmllint" ,libxml2) ("ruby-sass" ,ruby-sass))) (synopsis "Flat theme with light and dark elements") (description "Numix is a modern flat theme with a combination of light and dark elements. It supports GNOME, Unity, Xfce, and Openbox.") (home-page "") (license license:gpl3+))) (define-public numix-theme (deprecated-package "numix-theme" numix-gtk-theme)) (define-public orchis-theme (package (name "orchis-theme") (version "2021-02-28") (source (origin (method git-fetch) (uri (git-reference (url "-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1qp3phiza93qllrjm5xjjca5b7l2sbng8c382khy9m97grxvcq0y")) (modules '((guix build utils) (ice-9 regex) (srfi srfi-26))) (snippet '(begin (for-each (lambda (f) (let* ((r (make-regexp "\\.scss")) (f* (regexp-substitute #f (regexp-exec r f) 'pre ".css"))) (if (file-exists? f*) (delete-file f*)))) (find-files "." ".*\\.scss")) #t)))) (build-system gnu-build-system) (arguments `(#:configure-flags (list "--dest" (string-append (assoc-ref %outputs "out") "/share/themes") "--theme" "all" "--radio-color") #:tests? #f ; no tests #:phases (modify-phases %standard-phases (delete 'bootstrap) (delete 'configure) (replace 'build (lambda _ (invoke "./parse-sass.sh"))) (replace 'install (lambda* (#:key configure-flags #:allow-other-keys) (mkdir-p (cadr (or (member "--dest" configure-flags) (member "-d" configure-flags)))) (apply invoke "./install.sh" configure-flags) #t))))) (inputs `(("gtk-engines" ,gtk-engines))) (native-inputs ( " coreutils " , coreutils ) ("gtk+" ,gtk+) ("sassc" ,sassc))) (home-page "-theme") (synopsis "Material Design theme for a wide range of environments") (description "Orchis is a Material Design them for GNOME/GTK based desktop environments. It is based on materia-theme and adds more color variants.") (license (list license:gpl3 ; According to COPYING. license:lgpl2.1 ; Some style sheets. license:cc-by-sa4.0)))) ; Some icons (define-public markets (package (name "markets") (version "0.4.0") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1jzv74l2jkdiqy1hp0ww5yla50dmrvjw7fgkmb26ynblr1nb3rrb")))) (build-system meson-build-system) (arguments `(#:glib-or-gtk? #t #:phases (modify-phases %standard-phases (add-after 'unpack 'skip-gtk-update-icon-cache ;; Don't create 'icon-theme.cache'. (lambda _ (substitute* "build-aux/meson/postinstall.py" (("gtk-update-icon-cache") "true")) #t)) (add-after 'unpack 'skip-update-desktop-database ;; Don't update desktop file database. (lambda _ (substitute* "build-aux/meson/postinstall.py" (("update-desktop-database") "true")) #t))))) (inputs `(("gtk3" ,gtk+) ("gettext" ,gettext-minimal) ("libgee" ,libgee) ("libhandy0" ,libhandy-0.0) ("libsoup" ,libsoup) ("json-glib" ,json-glib) ("vala" ,vala))) (native-inputs `(("pkg-config" ,pkg-config) ("glib" ,glib "bin"))) ; for 'glib-compile-resources' (home-page "") (synopsis "Stock, currency and cryptocurrency tracker") (description "Markets is a GTK application that displays financial data, helping users track stocks, currencies and cryptocurrencies.") (license license:gpl3))) (define-public vala-language-server (package (name "vala-language-server") Note to maintainer : must be built with a toolchain the same ;; version or newer. Therefore when you update this package you may need to update too . (version "0.48.1") (source (origin (method git-fetch) (uri (git-reference (url "-language-server") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "12k095052jkvbiyz8gzkj6w7r7p16d5m18fyikl48yvh5nln8fw0")))) (build-system meson-build-system) (arguments '(#:glib-or-gtk? #t)) (inputs `(("glib" ,glib) ("json-glib" ,json-glib) ("jsonrpc-glib" ,jsonrpc-glib) ("libgee" ,libgee) ("vala" ,vala-0.50))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "-language-server") (synopsis "Language server for Vala") (description "The Vala language server is an implementation of the Vala language specification for the Language Server Protocol (LSP). This tool is used in text editing environments to provide a complete and integrated feature-set for programming Vala effectively.") (license license:lgpl2.1+))) (define-public nordic-theme (let ((commit "07d764c5ebd5706e73d2e573f1a983e37b318915") (revision "0")) (package (name "nordic-theme") (version (git-version "1.9.0" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "") (commit commit))) (sha256 (base32 "0y2s9d6h1b195s6afp1gb5rb1plfslkpbw2brd30a9d66wfvsqk0")) (file-name (git-file-name name version)))) (build-system copy-build-system) (arguments `(#:install-plan `(("." "share/themes/nord" #:exclude ("README.md" "LICENSE" "Art/" "package.json" "package-lock.json" "Gulpfile.js"))))) (home-page "") (synopsis "Dark Gtk3.20+ theme using the Nord color palette") (description "Nordic is a Gtk3.20+ theme created using the Nord color palette.") (license license:gpl3)))) (define-public tiramisu (let ((commit "8eb946dae0e2f98d3850d89e1bb535640e8c3266") (revision "0")) (package (name "tiramisu") (version (git-version "1.0" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "") (commit commit))) (sha256 (base32 "0wz2r8369d40vnxswknx0zxzbs03gzv0nc8al4g0ffg972p15j25")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments `(#:phases (modify-phases %standard-phases (delete 'configure) (delete 'check) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (install-file "tiramisu" (string-append out "/bin")) #t)))) #:make-flags (list (string-append "CC=" ,(cc-for-target))))) (inputs `(("glib" ,glib))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "") (synopsis "Desktop notifications, the UNIX way") (description "tiramisu is a notification daemon based on dunst that outputs notifications to STDOUT in order to allow the user to process notifications any way they prefer.") (license license:expat))))
null
https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/packages/gnome-xyz.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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. bundling it, so we need to add it as a propagated input. Remove pre-compiled settings schemas and translations from source, as they are generated as part of build. Upstream includes them for people who want to run the software directly from source tree. for glib-compile-schemas no test defined in the project no test target no configure script latter v2. No mention of "or later" in either place or in the code. for glib-compile-schemas autogen.sh calls configure at the end of the script. placate Inkscape for glib-compile-resources No "or later" language found. for "glib-compile-resources" no configure script for glib-compile-schemas no tests According to COPYING. Some style sheets. Some icons Don't create 'icon-theme.cache'. Don't update desktop file database. for 'glib-compile-resources' version or newer. Therefore when you update this package you may need
Copyright Β© 2019 , 2020 , 2021 < > Copyright Β© 2019 , 2021 Theodotou < > Copyright Β© 2019 < > Copyright Β© 2020 < > Copyright Β© 2020 < > Copyright Β© 2020 < > Copyright Β© 2020 < > Copyright Β© 2020 < > Copyright Β© 2020 Prior < > Copyright Β© 2020 > Copyright Β© 2020 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages gnome-xyz) #:use-module (guix build-system trivial) #:use-module (guix build-system gnu) #:use-module (guix build-system copy) #:use-module (guix build-system meson) #:use-module (guix git-download) #:use-module (guix packages) #:use-module (guix utils) #:use-module ((guix licenses) #:prefix license:) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages bash) #:use-module (gnu packages gettext) #:use-module (gnu packages glib) #:use-module (gnu packages gnome) #:use-module (gnu packages gtk) #:use-module (gnu packages inkscape) #:use-module (gnu packages image) #:use-module (gnu packages pkg-config) #:use-module (gnu packages python-xyz) #:use-module (gnu packages ssh) #:use-module (gnu packages tls) #:use-module (gnu packages ruby) #:use-module (gnu packages web) #:use-module (gnu packages xml)) (define-public arc-icon-theme (package (name "arc-icon-theme") (version "20161122") (source (origin (method git-fetch) (uri (git-reference (url "-icon-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1ch3hp08qri93510hypzz6m2x4xgg2h15wvnhjwh1x1s1b7jvxjd")))) (build-system gnu-build-system) (arguments `(#:phases (modify-phases %standard-phases (add-after 'unpack 'disable-configure-during-bootstrap (lambda _ (substitute* "autogen.sh" (("^\"\\$srcdir/configure\".*") "")) #t))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake))) When Arc is missing an icon , it looks in the Moka icon theme for it . (propagated-inputs `(("moka-icon-theme" ,moka-icon-theme))) (synopsis "Arc icon theme") (description "The Arc icon theme provides a set of icons matching the style of the Arc GTK theme. Icons missing from the Arc theme are provided by the Moka icon theme.") (home-page "-icon-theme") (license license:gpl3+))) (define-public delft-icon-theme (package (name "delft-icon-theme") (version "1.14") (source (origin (method git-fetch) (uri (git-reference (url "-delft") (commit (string-append "v" version)))) (sha256 (base32 "1iw85cxx9lv7irs28qi3815dk9f9vldv2j7jf1x5l1dqzwaxgwpb")) (file-name (git-file-name name version)))) (build-system copy-build-system) (arguments `(#:install-plan `(("." "share/icons" #:exclude ("README.md" "LICENSE" "logo.jpg"))) #:phases (modify-phases %standard-phases (add-after 'unpack 'patch-index.theme (lambda _ (substitute* "Delft/index.theme" (("gnome") "Adwaita")) #t))))) (home-page "-look.org/p/1199881/") (synopsis "Continuation of Faenza icon theme with up to date app icons") (description "Delft is a fork of the popular icon theme Faenza with up to date app icons. It will stay optically close to the original Faenza icons, which haven't been updated for some years. The new app icons are ported from the Obsidian icon theme.") (license license:gpl3))) (define-public faba-icon-theme (package (name "faba-icon-theme") (version "4.3") (source (origin (method git-fetch) (uri (git-reference (url "-icon-theme") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0xh6ppr73p76z60ym49b4d0liwdc96w41cc5p07d48hxjsa6qd6n")))) (build-system meson-build-system) (arguments `(#:phases (modify-phases %standard-phases (add-before 'configure 'disable-post-install (lambda _ (substitute* "meson.build" (("meson.add_install_script.*") ""))))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake))) (synopsis "Faba icon theme") (description "Faba is a minimal icon set used as a basis for other themes such as Moka") (home-page "") (license (list license:lgpl3+ license:cc-by-sa4.0)))) (define-public moka-icon-theme (package (inherit faba-icon-theme) (name "moka-icon-theme") (version "5.4.0") (source (origin (method git-fetch) (uri (git-reference (url "-icon-theme") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "015l02im4mha5z91dbchxf6xkp66d346bg3xskwg0rh3lglhjsrd")))) (propagated-inputs Moka is based on Faba by using it as a fallback icon set instead of `(("faba-icon-theme" ,faba-icon-theme))) (synopsis "Moka icon theme") (description "Moka is a stylized desktop icon set, designed to be clear, simple and consistent.") (license (list license:gpl3+ license:cc-by-sa4.0)))) (define-public papirus-icon-theme (package (name "papirus-icon-theme") (version "20210101") (source (origin (method git-fetch) (uri (git-reference (url "-icon-theme") (commit version))) (sha256 (base32 "0w6qg3zjhfvjg1gg5inranf8ianb4mrp0jm9qgi6hg87ig1rashs")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments '(#:tests? #f #:make-flags (list (string-append "PREFIX=" (assoc-ref %outputs "out"))) #:phases (modify-phases %standard-phases (delete 'bootstrap) (delete 'configure) (delete 'build)))) (native-inputs `(("gtk+:bin" ,gtk+ "bin"))) (home-page "-icon-theme") (synopsis "Fork of Paper icon theme with a lot of new icons and a few extras") (description "Papirus is a fork of the icon theme Paper with a lot of new icons and a few extra features.") (license license:gpl3))) (define-public gnome-shell-extension-appindicator (package (name "gnome-shell-extension-appindicator") (version "33") (source (origin (method git-fetch) (uri (git-reference (url "-shell-extension-appindicator") (commit (string-append "v" version)))) (sha256 (base32 "0qm77s080nbf4gqnfzpwp8a7jf7lliz6fxbsd3lasvrr11pgsk87")) (file-name (git-file-name name version)))) (build-system copy-build-system) (arguments `(#:install-plan '(("." ,(string-append "share/gnome-shell/extensions/" ""))))) (synopsis "Adds KStatusNotifierItem support to GNOME Shell") (description "This extension integrates Ubuntu AppIndicators and KStatusNotifierItems (KDE's successor of the systray) into GNOME Shell.") (home-page "-shell-extension-appindicator/") (license license:gpl2+))) (define-public gnome-shell-extension-clipboard-indicator (package (name "gnome-shell-extension-clipboard-indicator") (version "34") (source (origin (method git-fetch) (uri (git-reference (url (string-append "/" "gnome-shell-extension-clipboard-indicator.git")) (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0i00psc1ky70zljd14jzr627y7nd8xwnwrh4xpajl1f6djabh12s")) (modules '((guix build utils))) (snippet '(begin (delete-file "schemas/gschemas.compiled") (for-each delete-file (find-files "locale" "\\.mo$")) #t)))) (build-system copy-build-system) (arguments '(#:install-plan '(("." "share/gnome-shell/extensions/" #:include-regexp ("\\.css$" "\\.compiled$" "\\.js(on)?$" "\\.mo$" "\\.xml$"))) #:phases (modify-phases %standard-phases (add-before 'install 'compile-schemas (lambda _ (with-directory-excursion "schemas" (invoke "glib-compile-schemas" ".")) #t)) (add-before 'install 'compile-locales (lambda _ (invoke "./compile-locales.sh") #t))))) (native-inputs `(("gettext" ,gettext-minimal) (home-page "-shell-extension-clipboard-indicator") (synopsis "Clipboard manager extension for GNOME Shell") (description "Clipboard Indicator is a clipboard manager for GNOME Shell that caches clipboard history.") (license license:expat))) (define-public gnome-shell-extension-topicons-redux (package (name "gnome-shell-extension-topicons-redux") (version "6") (source (origin (method git-fetch) (uri (git-reference (url "-planet/TopIcons-Redux.git") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1dli9xb545n3xlj6q4wl0y5gzkm903zs47p8fiq71pdvbr6v38rj")))) (build-system gnu-build-system) (native-inputs `(("glib" ,glib "bin"))) (arguments #:phases (modify-phases %standard-phases (delete 'configure) (delete 'build) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (invoke "make" "install" (string-append "INSTALL_PATH=" out "/share/gnome-shell/extensions")))))))) (home-page "-planet/TopIcons-Redux") (synopsis "Display legacy tray icons in the GNOME Shell top panel") (description "Many applications, such as chat clients, downloaders, and some media players, are meant to run long-term in the background even after you close their window. These applications remain accessible by adding an icon to the GNOME Shell Legacy Tray. However, the Legacy Tray was removed in GNOME 3.26. TopIcons Redux brings those icons back into the top panel so that it's easier to keep track of applications running in the background.") (license license:gpl2+))) (define-public gnome-shell-extension-dash-to-dock (package (name "gnome-shell-extension-dash-to-dock") (version "67") (source (origin (method git-fetch) (uri (git-reference (url "-to-dock") (commit (string-append "extensions.gnome.org-v" version)))) (sha256 (base32 "1746xm0iyvyzj6m3pvjx11smh9w1s7naz426ki0dlr5l7jh3mpy5")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments '(#:tests? #f #:make-flags (list (string-append "INSTALLBASE=" (assoc-ref %outputs "out") "/share/gnome-shell/extensions")) #:phases (modify-phases %standard-phases (delete 'bootstrap) (delete 'configure)))) (native-inputs `(("glib:bin" ,glib "bin") ("intltool" ,intltool) ("pkg-config" ,pkg-config))) (propagated-inputs `(("glib" ,glib))) (synopsis "Transforms GNOME's dash into a dock") (description "This extension moves the dash out of the overview, transforming it into a dock for easier application launching and faster window switching.") (home-page "-to-dock/") (license license:gpl2+))) (define-public gnome-shell-extension-gsconnect (package (name "gnome-shell-extension-gsconnect") v33 is the last version to support GNOME 3.34 (version "33") (source (origin (method git-fetch) (uri (git-reference (url (string-append "" "/gnome-shell-extension-gsconnect.git")) (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "1q03axhn75i864vgmd6myhmgwrmnpf01gsd1wl0di5x9q8mic2zn")))) (build-system meson-build-system) (arguments `(#:configure-flags (let* ((out (assoc-ref %outputs "out")) (name+version (strip-store-file-name out)) (gschema-dir (string-append out "/share/gsettings-schemas/" name+version "/glib-2.0/schemas")) (gnome-shell (assoc-ref %build-inputs "gnome-shell")) (openssh (assoc-ref %build-inputs "openssh")) (openssl (assoc-ref %build-inputs "openssl"))) (list (string-append "-Dgnome_shell_libdir=" gnome-shell "/lib") (string-append "-Dgsettings_schemadir=" gschema-dir) (string-append "-Dopenssl_path=" openssl "/bin/openssl") (string-append "-Dsshadd_path=" openssh "/bin/ssh-add") (string-append "-Dsshkeygen_path=" openssh "/bin/ssh-keygen") (string-append "-Dsession_bus_services_dir=" out "/share/dbus-1/services") "-Dpost_install=true")) #:phases (modify-phases %standard-phases (add-before 'configure 'fix-paths (lambda* (#:key inputs #:allow-other-keys) (let* ((glib (assoc-ref inputs "glib:bin")) (gapplication (string-append glib "/bin/gapplication")) (gi-typelib-path (getenv "GI_TYPELIB_PATH"))) (substitute* "data/org.gnome.Shell.Extensions.GSConnect.desktop" (("gapplication") gapplication)) (for-each (lambda (file) (substitute* file (("'use strict';") (string-append "'use strict';\n\n" "'" gi-typelib-path "'.split(':').forEach(" "path => imports.gi.GIRepository.Repository." "prepend_search_path(path));")))) '("src/extension.js" "src/prefs.js")) #t))) (add-after 'install 'wrap-daemons (lambda* (#:key inputs outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (service-dir (string-append out "/share/gnome-shell/extensions" "//service")) (gi-typelib-path (getenv "GI_TYPELIB_PATH"))) (wrap-program (string-append service-dir "/daemon.js") `("GI_TYPELIB_PATH" ":" prefix (,gi-typelib-path))) #t)))))) (inputs `(("at-spi2-core" ,at-spi2-core) ("caribou" ,caribou) ("evolution-data-server" ,evolution-data-server) ("gjs" ,gjs) ("glib" ,glib) ("glib:bin" ,glib "bin") ("gsound" ,gsound) ("gnome-shell" ,gnome-shell) ("gtk+" ,gtk+) ("nautilus" ,nautilus) ("openssh" ,openssh) ("openssl" ,openssl) ("python-nautilus" ,python-nautilus) ("python-pygobject" ,python-pygobject) ("upower" ,upower))) (native-inputs `(("gettext" ,gettext-minimal) ("gobject-introspection" ,gobject-introspection) ("libxml2" ,libxml2) ("pkg-config" ,pkg-config))) (home-page "-shell-extension-gsconnect/wiki") (synopsis "Connect GNOME Shell with your Android phone") (description "GSConnect is a complete implementation of KDE Connect especially for GNOME Shell, allowing devices to securely share content, like notifications or files, and other features like SMS messaging and remote control.") (license license:gpl2))) (define-public gnome-shell-extension-hide-app-icon (let ((commit "4188aa5f4ba24901a053a0c3eb0d83baa8625eab") (revision "0")) (package (name "gnome-shell-extension-hide-app-icon") (version (git-version "2.7" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url (string-append "-rapp" "/gnome-shell-extension-hide-app-icon.git")) (commit commit))) (sha256 (base32 "1i28n4bz6wrhn07vpxkr6l1ljyn7g8frp5xrr11z3z32h2hxxcd6")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments #:make-flags (list (string-append "EXTENSIONS_DIR=" (assoc-ref %outputs "out") "/share/gnome-shell/extensions")) #:phases (modify-phases %standard-phases (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (pre "/share/gnome-shell/extensions/") (dir "")) (copy-recursively dir (string-append out pre dir)) #t)))))) (native-inputs `(("glib" ,glib "bin") ("intltool" ,intltool))) (propagated-inputs `(("glib" ,glib))) (synopsis "Hide app icon from GNOME's panel") (description "This extension hides the icon and/or title of the currently focused application in the top panel of the GNOME shell.") (home-page "-rapp/gnome-shell-extension-hide-app-icon/") (license README.md and LICENSE.txt disagree -- the former claims v3 , the (list license:gpl2 license:gpl3))))) (define-public gnome-shell-extension-dash-to-panel (package (name "gnome-shell-extension-dash-to-panel") (version "38") (source (origin (method git-fetch) (uri (git-reference (url "-sweet-gnome/dash-to-panel") (commit (string-append "v" version)))) (sha256 (base32 "1kvybb49l1vf0fvh8d0c6xkwnry8m330scamf5x40y63d4i213j1")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments `(#:tests? #f #:make-flags (list (string-append "INSTALLBASE=" (assoc-ref %outputs "out") "/share/gnome-shell/extensions") (string-append "VERSION=" ,(package-version gnome-shell-extension-dash-to-panel))) #:phases (modify-phases %standard-phases (delete 'bootstrap) (delete 'configure)))) (native-inputs `(("intltool" ,intltool) ("pkg-config" ,pkg-config))) (propagated-inputs `(("glib" ,glib) ("glib" ,glib "bin"))) (synopsis "Icon taskbar for GNOME Shell") (description "This extension moves the dash into the gnome main panel so that the application launchers and system tray are combined into a single panel, similar to that found in KDE Plasma and Windows 7+.") (home-page "-sweet-gnome/dash-to-panel/") (license license:gpl2+))) (define-public gnome-shell-extension-noannoyance (package (name "gnome-shell-extension-noannoyance") (version "5") (source (origin (method git-fetch) (uri (git-reference (url "") (commit "e37b5b3c31f577b4698bc6659bc9fec5ea9ac5d4"))) (sha256 (base32 "0fa8l3xlh8kbq07y4385wpb908zm6x53z81q16xlmin97dln32hh")) (file-name (git-file-name name version)))) (build-system copy-build-system) (arguments '(#:install-plan '(("." "share/gnome-shell/extensions/")))) (synopsis "Remove 'Window is ready' annotation") (description "One of the many extensions that remove this message. It uses ES6 syntax and claims to be more actively maintained than others.") (home-page "/") (license license:gpl2))) (define-public gnome-shell-extension-paperwm (package (name "gnome-shell-extension-paperwm") (version "36.0") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1ssnabwxrns36c61ppspjkr9i3qifv08pf2jpwl7cjv3pvyn4kly")) (snippet '(begin (delete-file "schemas/gschemas.compiled"))))) (build-system copy-build-system) (arguments '(#:install-plan '(("." "share/gnome-shell/extensions/paperwm@hedning:matrix.org" #:include-regexp ("\\.js(on)?$" "\\.css$" "\\.ui$" "\\.png$" "\\.xml$" "\\.compiled$"))) #:phases (modify-phases %standard-phases (add-before 'install 'compile-schemas (lambda _ (with-directory-excursion "schemas" (invoke "make")) #t))))) (native-inputs (home-page "") (synopsis "Tiled scrollable window management for GNOME Shell") (description "PaperWM is an experimental GNOME Shell extension providing scrollable tiling of windows and per monitor workspaces. It's inspired by paper notebooks and tiling window managers.") (license license:gpl3))) (define-public arc-theme (package (name "arc-theme") (version "20201013") (source (origin (method git-fetch) (uri (git-reference (url "-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1x2l1mwjx68dwf3jb1i90c1q8nqsl1wf2zggcn8im6590k5yv39s")))) (build-system gnu-build-system) (arguments '(#:configure-flags (list "--disable-cinnamon") #:phases (modify-phases %standard-phases (replace 'bootstrap (lambda _ (invoke "autoreconf" "-vfi"))) (lambda _ (setenv "HOME" (getcwd)) #t))))) (native-inputs `(("autoconf" ,autoconf) ("automake" ,automake) ("gnome-shell" ,gnome-shell) ("gtk+" ,gtk+) ("inkscape" ,inkscape) ("optipng" ,optipng) ("pkg-config" ,pkg-config) ("sassc" ,sassc/libsass-3.5))) (synopsis "A flat GTK+ theme with transparent elements") (description "Arc is a flat theme with transparent elements for GTK 3, GTK 2, and GNOME Shell which supports GTK 3 and GTK 2 based desktop environments like GNOME, Unity, Budgie, Pantheon, XFCE, Mate, etc.") (home-page "-theme") (license license:gpl3+))) (define-public greybird-gtk-theme (package (name "greybird-gtk-theme") (version "3.22.13") (source (origin (method git-fetch) (uri (git-reference (url "") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "154qawiga792iimkpk3a6q8f4gm4r158wmsagkbqqbhj33kxgxhg")))) (build-system meson-build-system) (native-inputs `(("gtk+" ,gtk+) ("librsvg" ,librsvg) ("pkg-config" ,pkg-config) ("ruby-sass" ,ruby-sass) ("sassc" ,sassc))) (home-page "/") (synopsis "Grey GTK+ theme based on Bluebird") (description "Greybird is a grey derivative of the Bluebird theme by the Shimmer Project. It supports GNOME, Unity, and Xfce.") (license (list license:gpl2+ license:cc-by-sa3.0)))) (define-public matcha-theme (package (name "matcha-theme") (version "2021-01-01") (source (origin (method git-fetch) (uri (git-reference (url "-gtk-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1pa6ra87wlq0gwz4n03l6xv0pxiamr5dygycvppms8v6xyc2aa0r")))) (build-system trivial-build-system) (arguments '(#:modules ((guix build utils)) #:builder (begin (use-modules (guix build utils)) (let* ((out (assoc-ref %outputs "out")) (source (assoc-ref %build-inputs "source")) (bash (assoc-ref %build-inputs "bash")) (coreutils (assoc-ref %build-inputs "coreutils")) (themesdir (string-append out "/share/themes"))) (setenv "PATH" (string-append coreutils "/bin:" (string-append bash "/bin:"))) (copy-recursively source (getcwd)) (patch-shebang "install.sh") (mkdir-p themesdir) (invoke "./install.sh" "-d" themesdir) #t)))) (inputs `(("gtk-engines" ,gtk-engines))) (native-inputs `(("bash" ,bash) ("coreutils" ,coreutils))) (synopsis "Flat design theme for GTK 3, GTK 2 and GNOME-Shell") (description "Matcha is a flat Design theme for GTK 3, GTK 2 and Gnome-Shell which supports GTK 3 and GTK 2 based desktop environments like Gnome, Unity, Budgie, Pantheon, XFCE, Mate and others.") (home-page "") (license license:gpl3+))) (define-public materia-theme (package (name "materia-theme") (version "20200916") (source (origin (method git-fetch) (uri (git-reference (url "-4/materia-theme") (commit (string-append "v" version)))) (file-name (git-file-name name version)) (sha256 (base32 "0qaxxafsn5zd2ysgr0jyv5j73360mfdmxyd55askswlsfphssn74")))) (build-system meson-build-system) (native-inputs `(("gtk+" ,gtk+) ("sassc" ,sassc))) (home-page "-4/materia-theme") (synopsis "Material Design theme for a wide range of environments") (description "Materia is a Material Design theme for GNOME/GTK based desktop environments. It supports GTK 2, GTK 3, GNOME Shell, Budgie, Cinnamon, MATE, Unity, Xfce, LightDM, GDM, Chrome theme, etc.") (license license:gpl2+))) (define-public numix-gtk-theme (package (name "numix-gtk-theme") (version "2.6.7") (source (origin (method git-fetch) (uri (git-reference (url "-gtk-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "12mw0kr0kkvg395qlbsvkvaqccr90cmxw5rrsl236zh43kj8grb7")))) (build-system gnu-build-system) (arguments '(#:make-flags (list (string-append "INSTALL_DIR=" (assoc-ref %outputs "out") "/share/themes/Numix")) #:tests? #f #:phases (modify-phases %standard-phases (native-inputs ("gnome-shell" ,gnome-shell) ("gtk+" ,gtk+) ("xmllint" ,libxml2) ("ruby-sass" ,ruby-sass))) (synopsis "Flat theme with light and dark elements") (description "Numix is a modern flat theme with a combination of light and dark elements. It supports GNOME, Unity, Xfce, and Openbox.") (home-page "") (license license:gpl3+))) (define-public numix-theme (deprecated-package "numix-theme" numix-gtk-theme)) (define-public orchis-theme (package (name "orchis-theme") (version "2021-02-28") (source (origin (method git-fetch) (uri (git-reference (url "-theme") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1qp3phiza93qllrjm5xjjca5b7l2sbng8c382khy9m97grxvcq0y")) (modules '((guix build utils) (ice-9 regex) (srfi srfi-26))) (snippet '(begin (for-each (lambda (f) (let* ((r (make-regexp "\\.scss")) (f* (regexp-substitute #f (regexp-exec r f) 'pre ".css"))) (if (file-exists? f*) (delete-file f*)))) (find-files "." ".*\\.scss")) #t)))) (build-system gnu-build-system) (arguments `(#:configure-flags (list "--dest" (string-append (assoc-ref %outputs "out") "/share/themes") "--theme" "all" "--radio-color") #:phases (modify-phases %standard-phases (delete 'bootstrap) (delete 'configure) (replace 'build (lambda _ (invoke "./parse-sass.sh"))) (replace 'install (lambda* (#:key configure-flags #:allow-other-keys) (mkdir-p (cadr (or (member "--dest" configure-flags) (member "-d" configure-flags)))) (apply invoke "./install.sh" configure-flags) #t))))) (inputs `(("gtk-engines" ,gtk-engines))) (native-inputs ( " coreutils " , coreutils ) ("gtk+" ,gtk+) ("sassc" ,sassc))) (home-page "-theme") (synopsis "Material Design theme for a wide range of environments") (description "Orchis is a Material Design them for GNOME/GTK based desktop environments. It is based on materia-theme and adds more color variants.") (define-public markets (package (name "markets") (version "0.4.0") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "1jzv74l2jkdiqy1hp0ww5yla50dmrvjw7fgkmb26ynblr1nb3rrb")))) (build-system meson-build-system) (arguments `(#:glib-or-gtk? #t #:phases (modify-phases %standard-phases (add-after 'unpack 'skip-gtk-update-icon-cache (lambda _ (substitute* "build-aux/meson/postinstall.py" (("gtk-update-icon-cache") "true")) #t)) (add-after 'unpack 'skip-update-desktop-database (lambda _ (substitute* "build-aux/meson/postinstall.py" (("update-desktop-database") "true")) #t))))) (inputs `(("gtk3" ,gtk+) ("gettext" ,gettext-minimal) ("libgee" ,libgee) ("libhandy0" ,libhandy-0.0) ("libsoup" ,libsoup) ("json-glib" ,json-glib) ("vala" ,vala))) (native-inputs `(("pkg-config" ,pkg-config) (home-page "") (synopsis "Stock, currency and cryptocurrency tracker") (description "Markets is a GTK application that displays financial data, helping users track stocks, currencies and cryptocurrencies.") (license license:gpl3))) (define-public vala-language-server (package (name "vala-language-server") Note to maintainer : must be built with a toolchain the same to update too . (version "0.48.1") (source (origin (method git-fetch) (uri (git-reference (url "-language-server") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "12k095052jkvbiyz8gzkj6w7r7p16d5m18fyikl48yvh5nln8fw0")))) (build-system meson-build-system) (arguments '(#:glib-or-gtk? #t)) (inputs `(("glib" ,glib) ("json-glib" ,json-glib) ("jsonrpc-glib" ,jsonrpc-glib) ("libgee" ,libgee) ("vala" ,vala-0.50))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "-language-server") (synopsis "Language server for Vala") (description "The Vala language server is an implementation of the Vala language specification for the Language Server Protocol (LSP). This tool is used in text editing environments to provide a complete and integrated feature-set for programming Vala effectively.") (license license:lgpl2.1+))) (define-public nordic-theme (let ((commit "07d764c5ebd5706e73d2e573f1a983e37b318915") (revision "0")) (package (name "nordic-theme") (version (git-version "1.9.0" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "") (commit commit))) (sha256 (base32 "0y2s9d6h1b195s6afp1gb5rb1plfslkpbw2brd30a9d66wfvsqk0")) (file-name (git-file-name name version)))) (build-system copy-build-system) (arguments `(#:install-plan `(("." "share/themes/nord" #:exclude ("README.md" "LICENSE" "Art/" "package.json" "package-lock.json" "Gulpfile.js"))))) (home-page "") (synopsis "Dark Gtk3.20+ theme using the Nord color palette") (description "Nordic is a Gtk3.20+ theme created using the Nord color palette.") (license license:gpl3)))) (define-public tiramisu (let ((commit "8eb946dae0e2f98d3850d89e1bb535640e8c3266") (revision "0")) (package (name "tiramisu") (version (git-version "1.0" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "") (commit commit))) (sha256 (base32 "0wz2r8369d40vnxswknx0zxzbs03gzv0nc8al4g0ffg972p15j25")) (file-name (git-file-name name version)))) (build-system gnu-build-system) (arguments `(#:phases (modify-phases %standard-phases (delete 'configure) (delete 'check) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (install-file "tiramisu" (string-append out "/bin")) #t)))) #:make-flags (list (string-append "CC=" ,(cc-for-target))))) (inputs `(("glib" ,glib))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "") (synopsis "Desktop notifications, the UNIX way") (description "tiramisu is a notification daemon based on dunst that outputs notifications to STDOUT in order to allow the user to process notifications any way they prefer.") (license license:expat))))
10ee58b3df72dff94d2dd92a7cd15ad236f8c5d8d94998fe6e17916e9ab282f9
alesya-h/live-components
deps.clj
(ns live-components.build.deps (:require [boot.core :as boot])) (println "Defining deps.") (def deps {:build '[[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.9.946"] [adzerk/boot-cljs "2.1.4"] [adzerk/boot-reload "0.5.2"] [ org.clojure/tools.namespace " 0.2.11 " ] ;; [org.clojure/tools.reader "0.10.0-alpha3"] [ org.clojure/tools.macro " 0.1.5 " ] [org.clojure/tools.nrepl "0.2.12"] [com.cemerick/piggieback "0.2.2"] [weasel "0.7.0"] [adzerk/boot-cljs-repl "0.3.3"] [adzerk/bootlaces "0.1.13"] ] :app '[[reagent "0.8.0-alpha2"] ;; ui [datascript "0.16.3"] ;; for storing subscriptions [org.clojure/data.json "0.2.6"] [org.immutant/web "2.1.9"] ]}) (defn request-dependencies [category] (println "Requesting" (name category) "dependencies.") (boot/set-env! :dependencies #(into % (deps category))) (println "Loaded" (name category) "dependencies.")) (request-dependencies :build)
null
https://raw.githubusercontent.com/alesya-h/live-components/8ca7f9dcabaa452a67bb18d24a8661e8de83aecc/src/live_components/build/deps.clj
clojure
[org.clojure/tools.reader "0.10.0-alpha3"] ui for storing subscriptions
(ns live-components.build.deps (:require [boot.core :as boot])) (println "Defining deps.") (def deps {:build '[[org.clojure/clojure "1.9.0"] [org.clojure/clojurescript "1.9.946"] [adzerk/boot-cljs "2.1.4"] [adzerk/boot-reload "0.5.2"] [ org.clojure/tools.namespace " 0.2.11 " ] [ org.clojure/tools.macro " 0.1.5 " ] [org.clojure/tools.nrepl "0.2.12"] [com.cemerick/piggieback "0.2.2"] [weasel "0.7.0"] [adzerk/boot-cljs-repl "0.3.3"] [adzerk/bootlaces "0.1.13"] ] :app [org.clojure/data.json "0.2.6"] [org.immutant/web "2.1.9"] ]}) (defn request-dependencies [category] (println "Requesting" (name category) "dependencies.") (boot/set-env! :dependencies #(into % (deps category))) (println "Loaded" (name category) "dependencies.")) (request-dependencies :build)
29e2620b9d01ecb244b5909ef1678dc1eb06766cc802fa74e9495211f1955579
jfrederickson/dotfiles
jfred-packages.scm
(use-modules ( gnu packages ) (guix packages) ;; (guix profiles) (guix download) (guix git-download) (guix build-system gnu) (guix build-system python) (gnu packages audio) (gnu packages python-xyz) (gnu packages python-web) (gnu packages pkg-config) ((guix licenses) #:prefix license:)) (define-public jfred:python-linode-api4 (package (name "python-linode-api4") (version "2.3.3") (source (origin (method git-fetch) (uri (git-reference (url "-python.git") (commit version))) (sha256 (base32 "09j5ym7k543mz1w733zib6289xddsla6w9xyriwy58mbrk9b7623")))) (build-system python-build-system) (arguments `(#:phases (modify-phases %standard-phases ;;(replace 'check ;; (lambda _ ;; (invoke "tox")))))) (delete 'check)))) ;;(native-inputs ;; `(("python-mock" ,python-mock) ;; ("python-tox" ,python-tox) ;; ("python-pytest" ,python-pytest) ;; ("python-coverage" ,python-coverage) ;; ("python-pytest-mock" ,python-pytest-mock) ;; ("python-pylint" ,python-pylint))) (propagated-inputs `(("python-future" ,python-future) ("python-requests" ,python-requests))) (home-page "-python") (synopsis "The official python SDK for Linode API v4") (description "The official python SDK for Linode API v4") (license license:bsd-3))) (define-public jfred:ladspa-bs2b (package (name "ladspa-bs2b") (version "0.9.1") (source (origin (method url-fetch) (uri (string-append "/" version "/" name "-" version ".tar.gz")) (sha256 (base32 "1b4aipbj1ba5k99gbc7gmgy14sywyrjd8rpyqj5l905j0mjv8jg2")))) (build-system gnu-build-system) (native-inputs `(("pkg-config" ,pkg-config))) ;;(native-inputs `(("libbs2b" ,libbs2b))) (inputs `(("ladspa" ,ladspa) ("libbs2b" ,libbs2b))) (home-page "/") (synopsis "Bauer stereophonic-to-binaural DSP - LADSPA plugin") (description "The Bauer stereophonic-to-binaural DSP (bs2b) library and plugins is designed to improve headphone listening of stereo audio records. Recommended for headphone prolonged listening to disable superstereo fatigue without essential distortions. This package contains a LADSPA plugin for use with applications that support them (e.g. PulseAudio).") (license license:gpl2)))
null
https://raw.githubusercontent.com/jfrederickson/dotfiles/ac002a0f57e253dfbacd990a40aaaa3fb89a6b53/guix/guix/jfred-packages.scm
scheme
(guix profiles) (replace 'check (lambda _ (invoke "tox")))))) (native-inputs `(("python-mock" ,python-mock) ("python-tox" ,python-tox) ("python-pytest" ,python-pytest) ("python-coverage" ,python-coverage) ("python-pytest-mock" ,python-pytest-mock) ("python-pylint" ,python-pylint))) (native-inputs `(("libbs2b" ,libbs2b)))
(use-modules ( gnu packages ) (guix packages) (guix download) (guix git-download) (guix build-system gnu) (guix build-system python) (gnu packages audio) (gnu packages python-xyz) (gnu packages python-web) (gnu packages pkg-config) ((guix licenses) #:prefix license:)) (define-public jfred:python-linode-api4 (package (name "python-linode-api4") (version "2.3.3") (source (origin (method git-fetch) (uri (git-reference (url "-python.git") (commit version))) (sha256 (base32 "09j5ym7k543mz1w733zib6289xddsla6w9xyriwy58mbrk9b7623")))) (build-system python-build-system) (arguments `(#:phases (modify-phases %standard-phases (delete 'check)))) (propagated-inputs `(("python-future" ,python-future) ("python-requests" ,python-requests))) (home-page "-python") (synopsis "The official python SDK for Linode API v4") (description "The official python SDK for Linode API v4") (license license:bsd-3))) (define-public jfred:ladspa-bs2b (package (name "ladspa-bs2b") (version "0.9.1") (source (origin (method url-fetch) (uri (string-append "/" version "/" name "-" version ".tar.gz")) (sha256 (base32 "1b4aipbj1ba5k99gbc7gmgy14sywyrjd8rpyqj5l905j0mjv8jg2")))) (build-system gnu-build-system) (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("ladspa" ,ladspa) ("libbs2b" ,libbs2b))) (home-page "/") (synopsis "Bauer stereophonic-to-binaural DSP - LADSPA plugin") (description "The Bauer stereophonic-to-binaural DSP (bs2b) library and plugins is designed to improve headphone listening of stereo audio records. Recommended for headphone prolonged listening to disable superstereo fatigue without essential distortions. This package contains a LADSPA plugin for use with applications that support them (e.g. PulseAudio).") (license license:gpl2)))
44ca743cc5064290a64e9ed5347f9b9d64c48e789d5ddef62a8f5c233e428371
ghcjs/jsaddle-dom
SVGMatrix.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.SVGMatrix (multiply, multiply_, inverse, inverse_, translate, translate_, scale, scale_, scaleNonUniform, scaleNonUniform_, rotate, rotate_, rotateFromVector, rotateFromVector_, flipX, flipX_, flipY, flipY_, skewX, skewX_, skewY, skewY_, setA, getA, setB, getB, setC, getC, setD, getD, setE, getE, setF, getF, SVGMatrix(..), gTypeSVGMatrix) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/SVGMatrix.multiply Mozilla SVGMatrix.multiply documentation > multiply :: (MonadDOM m) => SVGMatrix -> SVGMatrix -> m SVGMatrix multiply self secondMatrix = liftDOM ((self ^. jsf "multiply" [toJSVal secondMatrix]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.multiply Mozilla SVGMatrix.multiply documentation > multiply_ :: (MonadDOM m) => SVGMatrix -> SVGMatrix -> m () multiply_ self secondMatrix = liftDOM (void (self ^. jsf "multiply" [toJSVal secondMatrix])) | < -US/docs/Web/API/SVGMatrix.inverse Mozilla SVGMatrix.inverse documentation > inverse :: (MonadDOM m) => SVGMatrix -> m SVGMatrix inverse self = liftDOM ((self ^. jsf "inverse" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.inverse Mozilla SVGMatrix.inverse documentation > inverse_ :: (MonadDOM m) => SVGMatrix -> m () inverse_ self = liftDOM (void (self ^. jsf "inverse" ())) | < -US/docs/Web/API/SVGMatrix.translate Mozilla SVGMatrix.translate documentation > translate :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m SVGMatrix translate self x y = liftDOM ((self ^. jsf "translate" [toJSVal x, toJSVal y]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.translate Mozilla SVGMatrix.translate documentation > translate_ :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m () translate_ self x y = liftDOM (void (self ^. jsf "translate" [toJSVal x, toJSVal y])) | < -US/docs/Web/API/SVGMatrix.scale Mozilla SVGMatrix.scale documentation > scale :: (MonadDOM m) => SVGMatrix -> Float -> m SVGMatrix scale self scaleFactor = liftDOM ((self ^. jsf "scale" [toJSVal scaleFactor]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.scale Mozilla SVGMatrix.scale documentation > scale_ :: (MonadDOM m) => SVGMatrix -> Float -> m () scale_ self scaleFactor = liftDOM (void (self ^. jsf "scale" [toJSVal scaleFactor])) -- | <-US/docs/Web/API/SVGMatrix.scaleNonUniform Mozilla SVGMatrix.scaleNonUniform documentation> scaleNonUniform :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m SVGMatrix scaleNonUniform self scaleFactorX scaleFactorY = liftDOM ((self ^. jsf "scaleNonUniform" [toJSVal scaleFactorX, toJSVal scaleFactorY]) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/SVGMatrix.scaleNonUniform Mozilla SVGMatrix.scaleNonUniform documentation> scaleNonUniform_ :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m () scaleNonUniform_ self scaleFactorX scaleFactorY = liftDOM (void (self ^. jsf "scaleNonUniform" [toJSVal scaleFactorX, toJSVal scaleFactorY])) | < -US/docs/Web/API/SVGMatrix.rotate Mozilla SVGMatrix.rotate documentation > rotate :: (MonadDOM m) => SVGMatrix -> Float -> m SVGMatrix rotate self angle = liftDOM ((self ^. jsf "rotate" [toJSVal angle]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.rotate Mozilla SVGMatrix.rotate documentation > rotate_ :: (MonadDOM m) => SVGMatrix -> Float -> m () rotate_ self angle = liftDOM (void (self ^. jsf "rotate" [toJSVal angle])) | < -US/docs/Web/API/SVGMatrix.rotateFromVector Mozilla SVGMatrix.rotateFromVector documentation > rotateFromVector :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m SVGMatrix rotateFromVector self x y = liftDOM ((self ^. jsf "rotateFromVector" [toJSVal x, toJSVal y]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.rotateFromVector Mozilla SVGMatrix.rotateFromVector documentation > rotateFromVector_ :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m () rotateFromVector_ self x y = liftDOM (void (self ^. jsf "rotateFromVector" [toJSVal x, toJSVal y])) | < -US/docs/Web/API/SVGMatrix.flipX Mozilla SVGMatrix.flipX documentation > flipX :: (MonadDOM m) => SVGMatrix -> m SVGMatrix flipX self = liftDOM ((self ^. jsf "flipX" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.flipX Mozilla SVGMatrix.flipX documentation > flipX_ :: (MonadDOM m) => SVGMatrix -> m () flipX_ self = liftDOM (void (self ^. jsf "flipX" ())) -- | <-US/docs/Web/API/SVGMatrix.flipY Mozilla SVGMatrix.flipY documentation> flipY :: (MonadDOM m) => SVGMatrix -> m SVGMatrix flipY self = liftDOM ((self ^. jsf "flipY" ()) >>= fromJSValUnchecked) -- | <-US/docs/Web/API/SVGMatrix.flipY Mozilla SVGMatrix.flipY documentation> flipY_ :: (MonadDOM m) => SVGMatrix -> m () flipY_ self = liftDOM (void (self ^. jsf "flipY" ())) | < -US/docs/Web/API/SVGMatrix.skewX Mozilla SVGMatrix.skewX documentation > skewX :: (MonadDOM m) => SVGMatrix -> Float -> m SVGMatrix skewX self angle = liftDOM ((self ^. jsf "skewX" [toJSVal angle]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.skewX Mozilla SVGMatrix.skewX documentation > skewX_ :: (MonadDOM m) => SVGMatrix -> Float -> m () skewX_ self angle = liftDOM (void (self ^. jsf "skewX" [toJSVal angle])) | < -US/docs/Web/API/SVGMatrix.skewY Mozilla SVGMatrix.skewY documentation > skewY :: (MonadDOM m) => SVGMatrix -> Float -> m SVGMatrix skewY self angle = liftDOM ((self ^. jsf "skewY" [toJSVal angle]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.skewY Mozilla SVGMatrix.skewY documentation > skewY_ :: (MonadDOM m) => SVGMatrix -> Float -> m () skewY_ self angle = liftDOM (void (self ^. jsf "skewY" [toJSVal angle])) -- | <-US/docs/Web/API/SVGMatrix.a Mozilla SVGMatrix.a documentation> setA :: (MonadDOM m) => SVGMatrix -> Double -> m () setA self val = liftDOM (self ^. jss "a" (toJSVal val)) -- | <-US/docs/Web/API/SVGMatrix.a Mozilla SVGMatrix.a documentation> getA :: (MonadDOM m) => SVGMatrix -> m Double getA self = liftDOM ((self ^. js "a") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.b Mozilla SVGMatrix.b documentation > setB :: (MonadDOM m) => SVGMatrix -> Double -> m () setB self val = liftDOM (self ^. jss "b" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.b Mozilla SVGMatrix.b documentation > getB :: (MonadDOM m) => SVGMatrix -> m Double getB self = liftDOM ((self ^. js "b") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.c Mozilla SVGMatrix.c documentation > setC :: (MonadDOM m) => SVGMatrix -> Double -> m () setC self val = liftDOM (self ^. jss "c" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.c Mozilla SVGMatrix.c documentation > getC :: (MonadDOM m) => SVGMatrix -> m Double getC self = liftDOM ((self ^. js "c") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.d Mozilla documentation > setD :: (MonadDOM m) => SVGMatrix -> Double -> m () setD self val = liftDOM (self ^. jss "d" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.d Mozilla documentation > getD :: (MonadDOM m) => SVGMatrix -> m Double getD self = liftDOM ((self ^. js "d") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.e Mozilla SVGMatrix.e documentation > setE :: (MonadDOM m) => SVGMatrix -> Double -> m () setE self val = liftDOM (self ^. jss "e" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.e Mozilla SVGMatrix.e documentation > getE :: (MonadDOM m) => SVGMatrix -> m Double getE self = liftDOM ((self ^. js "e") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.f Mozilla SVGMatrix.f documentation > setF :: (MonadDOM m) => SVGMatrix -> Double -> m () setF self val = liftDOM (self ^. jss "f" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.f Mozilla SVGMatrix.f documentation > getF :: (MonadDOM m) => SVGMatrix -> m Double getF self = liftDOM ((self ^. js "f") >>= valToNumber)
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/SVGMatrix.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | <-US/docs/Web/API/SVGMatrix.scaleNonUniform Mozilla SVGMatrix.scaleNonUniform documentation> | <-US/docs/Web/API/SVGMatrix.scaleNonUniform Mozilla SVGMatrix.scaleNonUniform documentation> | <-US/docs/Web/API/SVGMatrix.flipY Mozilla SVGMatrix.flipY documentation> | <-US/docs/Web/API/SVGMatrix.flipY Mozilla SVGMatrix.flipY documentation> | <-US/docs/Web/API/SVGMatrix.a Mozilla SVGMatrix.a documentation> | <-US/docs/Web/API/SVGMatrix.a Mozilla SVGMatrix.a documentation>
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.SVGMatrix (multiply, multiply_, inverse, inverse_, translate, translate_, scale, scale_, scaleNonUniform, scaleNonUniform_, rotate, rotate_, rotateFromVector, rotateFromVector_, flipX, flipX_, flipY, flipY_, skewX, skewX_, skewY, skewY_, setA, getA, setB, getB, setC, getC, setD, getD, setE, getE, setF, getF, SVGMatrix(..), gTypeSVGMatrix) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/SVGMatrix.multiply Mozilla SVGMatrix.multiply documentation > multiply :: (MonadDOM m) => SVGMatrix -> SVGMatrix -> m SVGMatrix multiply self secondMatrix = liftDOM ((self ^. jsf "multiply" [toJSVal secondMatrix]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.multiply Mozilla SVGMatrix.multiply documentation > multiply_ :: (MonadDOM m) => SVGMatrix -> SVGMatrix -> m () multiply_ self secondMatrix = liftDOM (void (self ^. jsf "multiply" [toJSVal secondMatrix])) | < -US/docs/Web/API/SVGMatrix.inverse Mozilla SVGMatrix.inverse documentation > inverse :: (MonadDOM m) => SVGMatrix -> m SVGMatrix inverse self = liftDOM ((self ^. jsf "inverse" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.inverse Mozilla SVGMatrix.inverse documentation > inverse_ :: (MonadDOM m) => SVGMatrix -> m () inverse_ self = liftDOM (void (self ^. jsf "inverse" ())) | < -US/docs/Web/API/SVGMatrix.translate Mozilla SVGMatrix.translate documentation > translate :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m SVGMatrix translate self x y = liftDOM ((self ^. jsf "translate" [toJSVal x, toJSVal y]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.translate Mozilla SVGMatrix.translate documentation > translate_ :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m () translate_ self x y = liftDOM (void (self ^. jsf "translate" [toJSVal x, toJSVal y])) | < -US/docs/Web/API/SVGMatrix.scale Mozilla SVGMatrix.scale documentation > scale :: (MonadDOM m) => SVGMatrix -> Float -> m SVGMatrix scale self scaleFactor = liftDOM ((self ^. jsf "scale" [toJSVal scaleFactor]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.scale Mozilla SVGMatrix.scale documentation > scale_ :: (MonadDOM m) => SVGMatrix -> Float -> m () scale_ self scaleFactor = liftDOM (void (self ^. jsf "scale" [toJSVal scaleFactor])) scaleNonUniform :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m SVGMatrix scaleNonUniform self scaleFactorX scaleFactorY = liftDOM ((self ^. jsf "scaleNonUniform" [toJSVal scaleFactorX, toJSVal scaleFactorY]) >>= fromJSValUnchecked) scaleNonUniform_ :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m () scaleNonUniform_ self scaleFactorX scaleFactorY = liftDOM (void (self ^. jsf "scaleNonUniform" [toJSVal scaleFactorX, toJSVal scaleFactorY])) | < -US/docs/Web/API/SVGMatrix.rotate Mozilla SVGMatrix.rotate documentation > rotate :: (MonadDOM m) => SVGMatrix -> Float -> m SVGMatrix rotate self angle = liftDOM ((self ^. jsf "rotate" [toJSVal angle]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.rotate Mozilla SVGMatrix.rotate documentation > rotate_ :: (MonadDOM m) => SVGMatrix -> Float -> m () rotate_ self angle = liftDOM (void (self ^. jsf "rotate" [toJSVal angle])) | < -US/docs/Web/API/SVGMatrix.rotateFromVector Mozilla SVGMatrix.rotateFromVector documentation > rotateFromVector :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m SVGMatrix rotateFromVector self x y = liftDOM ((self ^. jsf "rotateFromVector" [toJSVal x, toJSVal y]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.rotateFromVector Mozilla SVGMatrix.rotateFromVector documentation > rotateFromVector_ :: (MonadDOM m) => SVGMatrix -> Float -> Float -> m () rotateFromVector_ self x y = liftDOM (void (self ^. jsf "rotateFromVector" [toJSVal x, toJSVal y])) | < -US/docs/Web/API/SVGMatrix.flipX Mozilla SVGMatrix.flipX documentation > flipX :: (MonadDOM m) => SVGMatrix -> m SVGMatrix flipX self = liftDOM ((self ^. jsf "flipX" ()) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.flipX Mozilla SVGMatrix.flipX documentation > flipX_ :: (MonadDOM m) => SVGMatrix -> m () flipX_ self = liftDOM (void (self ^. jsf "flipX" ())) flipY :: (MonadDOM m) => SVGMatrix -> m SVGMatrix flipY self = liftDOM ((self ^. jsf "flipY" ()) >>= fromJSValUnchecked) flipY_ :: (MonadDOM m) => SVGMatrix -> m () flipY_ self = liftDOM (void (self ^. jsf "flipY" ())) | < -US/docs/Web/API/SVGMatrix.skewX Mozilla SVGMatrix.skewX documentation > skewX :: (MonadDOM m) => SVGMatrix -> Float -> m SVGMatrix skewX self angle = liftDOM ((self ^. jsf "skewX" [toJSVal angle]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.skewX Mozilla SVGMatrix.skewX documentation > skewX_ :: (MonadDOM m) => SVGMatrix -> Float -> m () skewX_ self angle = liftDOM (void (self ^. jsf "skewX" [toJSVal angle])) | < -US/docs/Web/API/SVGMatrix.skewY Mozilla SVGMatrix.skewY documentation > skewY :: (MonadDOM m) => SVGMatrix -> Float -> m SVGMatrix skewY self angle = liftDOM ((self ^. jsf "skewY" [toJSVal angle]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGMatrix.skewY Mozilla SVGMatrix.skewY documentation > skewY_ :: (MonadDOM m) => SVGMatrix -> Float -> m () skewY_ self angle = liftDOM (void (self ^. jsf "skewY" [toJSVal angle])) setA :: (MonadDOM m) => SVGMatrix -> Double -> m () setA self val = liftDOM (self ^. jss "a" (toJSVal val)) getA :: (MonadDOM m) => SVGMatrix -> m Double getA self = liftDOM ((self ^. js "a") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.b Mozilla SVGMatrix.b documentation > setB :: (MonadDOM m) => SVGMatrix -> Double -> m () setB self val = liftDOM (self ^. jss "b" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.b Mozilla SVGMatrix.b documentation > getB :: (MonadDOM m) => SVGMatrix -> m Double getB self = liftDOM ((self ^. js "b") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.c Mozilla SVGMatrix.c documentation > setC :: (MonadDOM m) => SVGMatrix -> Double -> m () setC self val = liftDOM (self ^. jss "c" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.c Mozilla SVGMatrix.c documentation > getC :: (MonadDOM m) => SVGMatrix -> m Double getC self = liftDOM ((self ^. js "c") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.d Mozilla documentation > setD :: (MonadDOM m) => SVGMatrix -> Double -> m () setD self val = liftDOM (self ^. jss "d" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.d Mozilla documentation > getD :: (MonadDOM m) => SVGMatrix -> m Double getD self = liftDOM ((self ^. js "d") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.e Mozilla SVGMatrix.e documentation > setE :: (MonadDOM m) => SVGMatrix -> Double -> m () setE self val = liftDOM (self ^. jss "e" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.e Mozilla SVGMatrix.e documentation > getE :: (MonadDOM m) => SVGMatrix -> m Double getE self = liftDOM ((self ^. js "e") >>= valToNumber) | < -US/docs/Web/API/SVGMatrix.f Mozilla SVGMatrix.f documentation > setF :: (MonadDOM m) => SVGMatrix -> Double -> m () setF self val = liftDOM (self ^. jss "f" (toJSVal val)) | < -US/docs/Web/API/SVGMatrix.f Mozilla SVGMatrix.f documentation > getF :: (MonadDOM m) => SVGMatrix -> m Double getF self = liftDOM ((self ^. js "f") >>= valToNumber)
80a96a37379078d9f236a19d8fbf65ab6f9850cc3230057ad416813513ccf4b8
jimrthy/frereth
routes.clj
(ns backend.web.routes (:require [backend.web.handlers :as handlers] [cheshire.core :as json] [clojure.pprint :refer [pprint]] [clojure.spec.alpha :as s] [frereth.apps.shared.lamport :as lamport] [frereth.weald.logging :as log] [frereth.weald.specs :as weald] [integrant.core :as ig] [io.pedestal.http.content-negotiation :as conneg] [io.pedestal.http.route :as route] [renderer.sessions :as sessions]) (:import [clojure.lang ExceptionInfo IFn])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Specs ;; TODO: Surely I can come up with something more restrictive ;; Actual spec: ;; Starts with a "/" ;; Consists of 0 or mor path segments separated by slashes Each path segment is one of : ;; * string literal ;; * colon (\:) followed by a legal clojure identifier name. ;; This is a path parameter (highly discouraged) ;; * asterisk (\*) followed by a legal clojure identifier name. ;; This is a wildcard path (s/def ::path string?) ;; Q: Restrict to legal HTTP verbs? ;; Pretty much anything is legal here now, but this really is all ;; about the HTTP routes (s/def ::verb #_ #{:any :get :put :post :delete :patch :options :head} keyword?) (s/def ::interceptor-view (s/or :name symbol? :function #(instance? IFn %))) (s/def ::interceptors (s/or :chain (s/coll-of ::interceptor-view) :handler symbol? Var fits here . I 'm not sure how clojure.lang . Var fits . ;; I've tried calling instance? on various ;; things that seem like they should be, ;; but they all returned false. :var any? :map map? :list list?)) (s/def ::route-name keyword?) (s/def ::constraints map?) ;;; Basic idea is [path verb interceptors (optional route-name-clause) (optional constraints)] (s/def ::route (s/or :base (s/tuple ::path ::verb ::interceptors) :named (s/tuple ::path ::verb ::interceptors #(= :route-name %) ::route-name) :constrained (s/tuple ::path ::verb ::interceptors #(= :constraints %) ::constraints) :named&constrained (s/tuple ::path ::verb ::interceptors #(= :route-name %) ::route-name #(= :constraints %) ::constraints))) (s/def ::route-set (s/coll-of ::route)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Interceptors ;;;; Q: Do these belong in their own ns? (def error-logger "Interceptor for last-ditch error logging efforts" {:name ::error-handler :error (fn [ctx ex] (println "**** Ooopsie") (pprint (ex-data ex)) (println "Caused by") (pprint ctx) (assoc ctx :io.pedestal.interceptor.chain/error ex))}) (defn accepted-type [{:keys [:request] :as context}] (get-in request [:accept :field] "text/plain")) (defn transform-content "Convert content to a string, based on type" [body content-type] (case content-type "application/edn" (pr-str body) "application/json" (json/generate-string body) ;; Q: What about transit? ;; Default to no coercion body)) (defn coerce-to "Coerce the response body and Content-Type header" [response content-type] (-> response (update :body transform-content content-type) (assoc-in [:headers "Content-Type"] content-type))) (def coerce-content-type "If no content-type header, try to deduce one and transform body" {:name ::coerce-content-type :leave (fn [context] (cond-> context (nil? (get-in context [:response :headers "Content-Type"])) (update-in [:response] coerce-to (accepted-type context))))}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Internal (s/fdef build-pedestal-routes :args (s/keys :req [::lamport/clock ::sessions/session-atom ::weald/logger ::weald/state-atom]) :ret ::route-set) (defn build-pedestal-routes [{:keys [::lamport/clock ::sessions/session-atom ::weald/logger] log-state-atom ::weald/state-atom :as component}] (let [content-neg-intc (conneg/negotiate-content ["text/html" "application/edn" "text/plain"]) default-intc [coerce-content-type content-neg-intc] definition #{["/" :get (conj default-intc handlers/index-page) :route-name ::default] ["/index" :get (conj default-intc handlers/index-page) :route-name ::default-index] ["/index.html" :get (conj default-intc handlers/index-page) :route-name ::default-html] ["/index.php" :get (conj default-intc handlers/index-page) :route-name ::default-php] ["/api/fork" :get (conj default-intc (handlers/create-world-interceptor logger log-state-atom session-atom)) :route-name ::connect-world] ["/echo" :any (conj default-intc handlers/echo-page) :route-name ::echo] ["/test" :any (conj default-intc handlers/test-page) :route-name ::test] ["/ws" :get (handlers/build-renderer-connection component) :route-name ::renderer-ws]}] (route/expand-routes definition))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Public (defmethod ig/init-key ::handler-map [_ {:keys [::debug? ::weald/logger] log-state-atom ::weald/state-atom :as opts}] (swap! log-state-atom #(log/flush-logs! logger (log/info % ::handler-map-init-key "Setting up router" (dissoc opts ::weald/state-atom ::weald/logger)))) ;; It seems like there's an interesting implementation issue here: ;; This doesn't really play nicely with route/url-for-routes. ;; In order to use that, the individual handlers really should ;; have access to the routes table. ;; This is a non-issue. ;; This is why the routing interceptor adds the :url-for key ;; to the context map. {::routes (if-not debug? (build-pedestal-routes opts) ;; Use this to set routes to be reloadable without a ;; full (reset). ;; Note that this will rebuild on every request, which slows it ;; down. (fn [] (build-pedestal-routes opts)))})
null
https://raw.githubusercontent.com/jimrthy/frereth/e1c4a5c031355ff1ff3bb60741eb03dff2377e1d/apps/log-viewer/src/clj/backend/web/routes.clj
clojure
TODO: Surely I can come up with something more restrictive Actual spec: Starts with a "/" Consists of 0 or mor path segments separated by slashes * string literal * colon (\:) followed by a legal clojure identifier name. This is a path parameter (highly discouraged) * asterisk (\*) followed by a legal clojure identifier name. This is a wildcard path Q: Restrict to legal HTTP verbs? Pretty much anything is legal here now, but this really is all about the HTTP routes I've tried calling instance? on various things that seem like they should be, but they all returned false. Basic idea is [path verb interceptors (optional route-name-clause) (optional constraints)] Interceptors Q: Do these belong in their own ns? Q: What about transit? Default to no coercion Public It seems like there's an interesting implementation issue here: This doesn't really play nicely with route/url-for-routes. In order to use that, the individual handlers really should have access to the routes table. This is a non-issue. This is why the routing interceptor adds the :url-for key to the context map. Use this to set routes to be reloadable without a full (reset). Note that this will rebuild on every request, which slows it down.
(ns backend.web.routes (:require [backend.web.handlers :as handlers] [cheshire.core :as json] [clojure.pprint :refer [pprint]] [clojure.spec.alpha :as s] [frereth.apps.shared.lamport :as lamport] [frereth.weald.logging :as log] [frereth.weald.specs :as weald] [integrant.core :as ig] [io.pedestal.http.content-negotiation :as conneg] [io.pedestal.http.route :as route] [renderer.sessions :as sessions]) (:import [clojure.lang ExceptionInfo IFn])) Specs Each path segment is one of : (s/def ::path string?) (s/def ::verb #_ #{:any :get :put :post :delete :patch :options :head} keyword?) (s/def ::interceptor-view (s/or :name symbol? :function #(instance? IFn %))) (s/def ::interceptors (s/or :chain (s/coll-of ::interceptor-view) :handler symbol? Var fits here . I 'm not sure how clojure.lang . Var fits . :var any? :map map? :list list?)) (s/def ::route-name keyword?) (s/def ::constraints map?) (s/def ::route (s/or :base (s/tuple ::path ::verb ::interceptors) :named (s/tuple ::path ::verb ::interceptors #(= :route-name %) ::route-name) :constrained (s/tuple ::path ::verb ::interceptors #(= :constraints %) ::constraints) :named&constrained (s/tuple ::path ::verb ::interceptors #(= :route-name %) ::route-name #(= :constraints %) ::constraints))) (s/def ::route-set (s/coll-of ::route)) (def error-logger "Interceptor for last-ditch error logging efforts" {:name ::error-handler :error (fn [ctx ex] (println "**** Ooopsie") (pprint (ex-data ex)) (println "Caused by") (pprint ctx) (assoc ctx :io.pedestal.interceptor.chain/error ex))}) (defn accepted-type [{:keys [:request] :as context}] (get-in request [:accept :field] "text/plain")) (defn transform-content "Convert content to a string, based on type" [body content-type] (case content-type "application/edn" (pr-str body) "application/json" (json/generate-string body) body)) (defn coerce-to "Coerce the response body and Content-Type header" [response content-type] (-> response (update :body transform-content content-type) (assoc-in [:headers "Content-Type"] content-type))) (def coerce-content-type "If no content-type header, try to deduce one and transform body" {:name ::coerce-content-type :leave (fn [context] (cond-> context (nil? (get-in context [:response :headers "Content-Type"])) (update-in [:response] coerce-to (accepted-type context))))}) Internal (s/fdef build-pedestal-routes :args (s/keys :req [::lamport/clock ::sessions/session-atom ::weald/logger ::weald/state-atom]) :ret ::route-set) (defn build-pedestal-routes [{:keys [::lamport/clock ::sessions/session-atom ::weald/logger] log-state-atom ::weald/state-atom :as component}] (let [content-neg-intc (conneg/negotiate-content ["text/html" "application/edn" "text/plain"]) default-intc [coerce-content-type content-neg-intc] definition #{["/" :get (conj default-intc handlers/index-page) :route-name ::default] ["/index" :get (conj default-intc handlers/index-page) :route-name ::default-index] ["/index.html" :get (conj default-intc handlers/index-page) :route-name ::default-html] ["/index.php" :get (conj default-intc handlers/index-page) :route-name ::default-php] ["/api/fork" :get (conj default-intc (handlers/create-world-interceptor logger log-state-atom session-atom)) :route-name ::connect-world] ["/echo" :any (conj default-intc handlers/echo-page) :route-name ::echo] ["/test" :any (conj default-intc handlers/test-page) :route-name ::test] ["/ws" :get (handlers/build-renderer-connection component) :route-name ::renderer-ws]}] (route/expand-routes definition))) (defmethod ig/init-key ::handler-map [_ {:keys [::debug? ::weald/logger] log-state-atom ::weald/state-atom :as opts}] (swap! log-state-atom #(log/flush-logs! logger (log/info % ::handler-map-init-key "Setting up router" (dissoc opts ::weald/state-atom ::weald/logger)))) {::routes (if-not debug? (build-pedestal-routes opts) (fn [] (build-pedestal-routes opts)))})
ae2a0f483905447b3210d0946f6343abd3058f6e6889720b33fc776a3dfcee3f
janestreet/hardcaml
test_rtl.ml
open! Import open Signal let rtl_write_null outputs = Rtl.print Verilog (Circuit.create_exn ~name:"test" outputs) let%expect_test "Port names must be unique" = require_does_raise [%here] (fun () -> rtl_write_null [ output "a" (input "a" 1) ]); [%expect {| ("Port names are not unique" (circuit_name test) (input_and_output_names (a))) |}] ;; let%expect_test "Port names must be legal" = require_does_raise [%here] (fun () -> rtl_write_null [ output "a" (input "1^7" 1) ]); [%expect {| ("Error while writing circuit" (circuit_name test) (hierarchy_path (test)) (output ((language Verilog) (mode (To_channel <stdout>)))) (exn ( "illegal port name" (name 1^7) (legal_name _1_7) (note "Hardcaml will not change ports names.") (port ( wire (names (1^7)) (width 1) (data_in empty)))))) |}] ;; let%expect_test "Port name clashes with reserved name" = require_does_raise [%here] (fun () -> rtl_write_null [ output "module" (input "x" 1) ]); [%expect {| ("Error while writing circuit" (circuit_name test) (hierarchy_path (test)) (output ((language Verilog) (mode (To_channel <stdout>)))) (exn ( "port name has already been defined or matches a reserved identifier" (port ( wire (names (module)) (width 1) (data_in x)))))) |}] ;; let%expect_test "output wire is width 0 (or empty)" = (* The exception is raised by the [output] function. *) require_does_raise [%here] (fun () -> rtl_write_null [ output "x" (empty +: empty) ]); [%expect {| ("width of wire was specified as 0" ( wire ( wire (width 0) (data_in empty)))) |}] ;; let%expect_test "instantiation input is empty" = require_does_raise [%here] (fun () -> let a = Signal.empty in let inst = Instantiation.create () ~name:"example" ~inputs:[ "a", a ] ~outputs:[ "b", 1 ] in Circuit.create_exn ~name:"example" [ Signal.output "b" (Map.find_exn inst "b") ] |> Rtl.print Verilog); [%expect {| module example ( b ); output b; /* signal declarations */ wire _4; wire _1; /* logic */ example the_example ("Error while writing circuit" (circuit_name example) (hierarchy_path (example)) (output ((language Verilog) (mode (To_channel <stdout>)))) (exn ( "failed to connect instantiation port" (inst_name the_example) (port_name a) (signal empty) (indexes ()) (exn ( "[Rtl.SignalNameManager] internal error while looking up signal name" (index 0) (for_signal empty)))))) |}] ;;
null
https://raw.githubusercontent.com/janestreet/hardcaml/15727795c2bf922dd852cc0cd895a4ed1d9527e5/test/lib/test_rtl.ml
ocaml
The exception is raised by the [output] function.
open! Import open Signal let rtl_write_null outputs = Rtl.print Verilog (Circuit.create_exn ~name:"test" outputs) let%expect_test "Port names must be unique" = require_does_raise [%here] (fun () -> rtl_write_null [ output "a" (input "a" 1) ]); [%expect {| ("Port names are not unique" (circuit_name test) (input_and_output_names (a))) |}] ;; let%expect_test "Port names must be legal" = require_does_raise [%here] (fun () -> rtl_write_null [ output "a" (input "1^7" 1) ]); [%expect {| ("Error while writing circuit" (circuit_name test) (hierarchy_path (test)) (output ((language Verilog) (mode (To_channel <stdout>)))) (exn ( "illegal port name" (name 1^7) (legal_name _1_7) (note "Hardcaml will not change ports names.") (port ( wire (names (1^7)) (width 1) (data_in empty)))))) |}] ;; let%expect_test "Port name clashes with reserved name" = require_does_raise [%here] (fun () -> rtl_write_null [ output "module" (input "x" 1) ]); [%expect {| ("Error while writing circuit" (circuit_name test) (hierarchy_path (test)) (output ((language Verilog) (mode (To_channel <stdout>)))) (exn ( "port name has already been defined or matches a reserved identifier" (port ( wire (names (module)) (width 1) (data_in x)))))) |}] ;; let%expect_test "output wire is width 0 (or empty)" = require_does_raise [%here] (fun () -> rtl_write_null [ output "x" (empty +: empty) ]); [%expect {| ("width of wire was specified as 0" ( wire ( wire (width 0) (data_in empty)))) |}] ;; let%expect_test "instantiation input is empty" = require_does_raise [%here] (fun () -> let a = Signal.empty in let inst = Instantiation.create () ~name:"example" ~inputs:[ "a", a ] ~outputs:[ "b", 1 ] in Circuit.create_exn ~name:"example" [ Signal.output "b" (Map.find_exn inst "b") ] |> Rtl.print Verilog); [%expect {| module example ( b ); output b; /* signal declarations */ wire _4; wire _1; /* logic */ example the_example ("Error while writing circuit" (circuit_name example) (hierarchy_path (example)) (output ((language Verilog) (mode (To_channel <stdout>)))) (exn ( "failed to connect instantiation port" (inst_name the_example) (port_name a) (signal empty) (indexes ()) (exn ( "[Rtl.SignalNameManager] internal error while looking up signal name" (index 0) (for_signal empty)))))) |}] ;;
a7c08a8fafade444dc60f5ac69f198c6c72349b5ca7f58cae0e07517eeadaf2d
exoscale/clojure-kubernetes-client
v1beta1_non_resource_rule.clj
(ns clojure-kubernetes-client.specs.v1beta1-non-resource-rule (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] ) (:import (java.io File))) (declare v1beta1-non-resource-rule-data v1beta1-non-resource-rule) (def v1beta1-non-resource-rule-data { (ds/opt :nonResourceURLs) (s/coll-of string?) (ds/req :verbs) (s/coll-of string?) }) (def v1beta1-non-resource-rule (ds/spec {:name ::v1beta1-non-resource-rule :spec v1beta1-non-resource-rule-data}))
null
https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1beta1_non_resource_rule.clj
clojure
(ns clojure-kubernetes-client.specs.v1beta1-non-resource-rule (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] ) (:import (java.io File))) (declare v1beta1-non-resource-rule-data v1beta1-non-resource-rule) (def v1beta1-non-resource-rule-data { (ds/opt :nonResourceURLs) (s/coll-of string?) (ds/req :verbs) (s/coll-of string?) }) (def v1beta1-non-resource-rule (ds/spec {:name ::v1beta1-non-resource-rule :spec v1beta1-non-resource-rule-data}))
22337fd7191fe61a5b17ff3dd1bf33d570910aad05cb29a6973b9fedcde20dfe
mbal/swank-racket
eval.rkt
;;; Provides the functions for the evaluation thread. ;;; ;;; In the normal implementation of swank (so, the common lisp one, or even the ;;; clojure one), the evaluation thread only evaluates stuff. However, in this ;;; version, the evaluation thread does more: basically all the things pass ;;; through this thread, since it's the only one that can access the namespace ;;; currently in use. #lang racket (require racket/base racket/rerequire (only-in srfi/13 string-prefix-ci?) "complete.rkt" "repl.rkt" "modutil.rkt" "describe.rkt" "util.rkt") (provide swank-evaluation) (define (swank-evaluation parent-thread) ;; we don't use make-evaluator in racket/sandbox because we can assume ;; to trust the user herself (that is, ourselves, since it's mainly ;; run locally). There are two namespaces that share the module ` repl.rkt ` : the one in which the REPL runs and the namespace of this module . (let ([new-ns (make-base-namespace)]) (namespace-attach-module (namespace-anchor->empty-namespace repl-anchor) (string->path "repl.rkt") new-ns) (parameterize ([current-namespace new-ns]) (namespace-require "repl.rkt") (continuously (dispatch-eval parent-thread (thread-receive)))))) (define (dispatch-eval pthread cmd) (match cmd [(list 'eval string-sexp cont) (let ([stripped (trim-code-for-eval string-sexp)]) (when (not (string=? stripped "")) (let* ([stx (string->datum stripped)] [output-port (open-output-string)] [result (try-eval stx output-port)] [output (get-output-string output-port)]) (when (not (string=? output "")) (thread-send pthread (list 'return `(:write-string ,output)))) (thread-send pthread (list 'return `(:return ,result ,cont))))))] [(list 'complete pattern cont) ;; now, there is a problem: ;; if you define a function in the repl, the auto-completer finds it ;; even in the racket buffer. When you load the buffer with ;; `compile and load`, you get an error (if you called that ;; function), since the namespace used for compilation is different ;; from the one used to do the rest of the things. (send-back-to pthread (list (simple-complete pattern) pattern) cont)] [(list 'expand times string-form cont) (let ([form (string->datum string-form)]) (send-back-to pthread (pprint-eval-result (syntax->datum ((if (= times 1) expand-once expand) form))) cont))] [(list 'arglist fnsym cont) (let ([fnobj (with-handlers ([exn:fail? (lambda (exn) #f)]) (namespace-variable-value fnsym))]) (if fnobj (let* ([fnarity (procedure-arity fnobj)] [prntarity (make-string-from-arity fnarity)]) (send-back-to pthread prntarity cont)) (send-back-to pthread 'nil cont)))] [(list 'undefine-function fname cont) (let ([fnsym (string->symbol fname)]) (if (namespace-variable-value fnsym #t (lambda () #f)) (begin (namespace-undefine-variable! (string->symbol fname)) (send-back-to pthread fname cont)) (send-back-to pthread 'nil cont)))] [(list 'describe strsym cont) TODO (send-back-to pthread (description (read (open-input-string strsym))) cont)] [(list 'compile modname load? cont) ( compile modname load ? ) (with-handlers ([exn:fail? ;; well, yes, we could be a little more specific, but there ;; are many ways in which the compilation process may fail: ;; we will handle them in the `build-error-message`. (lambda (exn) (thread-send pthread (list 'return `(:return (:ok (:compilation-result ,(list (build-error-message exn)) nil 0.0 nil nil)) ,cont))))]) (let-values ([(_ time __ ___) (time-apply dynamic-rerequire (list (string->path modname)))]) (thread-send pthread (list 'return `(:return (:ok (:compilation-result nil t ,(/ time 1000.0) nil nil)) ,cont)))) (when load? ;; enter the namespace of the module (current-namespace (module->namespace (string->path modname))) ;; notify slime that we are in a new `package` (thread-send pthread (list 'return `(:new-package ,modname ,(get-prefix)))) ;; we have to require again repl.rkt in order to access ;; the * variables. (namespace-require "repl.rkt")))])) (define (try-eval stx out) ;; Wraps evaluation of `stx` in a try/except block and redirects the ;; output to `out`. Returns the correct message to be sent to emacs. (with-handlers ([exn:fail? (lambda (exn) `(:abort ,(print-exception exn)))]) (let ([result (parameterize ([current-output-port out]) (eval stx))]) ;; variables in a module can be updated only from within the ;; module itself. (update-vars! result *1 *2 (syntax->datum stx)) `(:ok (:values ,(pprint-eval-result result)))))) (define (build-error-message exn) (displayln exn) (flush-output (current-output-port)) `(:message ,(exn-message exn) ;; TODO: possibilities for severity are: :error, :read-error, :warning : style - warning : note : redefinition . Probably all but the first two are ;; useless in Racket. I still need to figure out a way to get the list ;; of all errors in the racket module being compiled. :severity ,(if (exn:fail:read? exn) ':read-error ':error) :location ,(build-source-error-location exn))) (define (build-source-error-location e) (if (exn:srclocs? e) (let ([srclcs (car ((exn:srclocs-accessor e) e))]) `(:location ;; TODO: i have to check this: reading slime's source it seems that ;; either (:file :line) or (:buffer :offset) should be present. ;; ;; XXX: aside, there's a small bug in this paredit, ( in comments are ;; highlighted with ) not in comments. (:file ,(path->string (srcloc-source srclcs))) (:position ,(srcloc-position srclcs)) (:line ,(srcloc-line srclcs)))) '(:error "No source location"))) (define (make-string-from-arity fnarity) ;; we use this function with swank:operator-arglist it's not very smart, and ;; there isn't a nice way to handle functions with optional arguments ;; SLIMV uses only swank:operator-arglist, but slime doesn't send that ;; message, it prefers a more advanced version, which allows us to check with ;; more precision which arity to show (and highlight arguments in the ;; minibuffer) (define (prototype-from-int int) ;; unluckily, racket doesn't provide a way to get the argument list ( i.e. ccl : arglist or clojure 's metadata of the variable ) . ;; Therefore, we will invent the names of the arguments ;; well, geiser *does* contain the code to do that, so I will look into it. ;; even though it seems that it parses the code, so for now I will ;; just be happy with this little hack. (string-join (map string (map integer->char (map let 's just use letters from # \a (range 0 int)))))) (cond ([exact-nonnegative-integer? fnarity] (string-append "(" (prototype-from-int fnarity) ")")) ([arity-at-least? fnarity] (let ([args (prototype-from-int (arity-at-least-value fnarity))]) (string-append "(" args (if (string=? args "") "" " ") "...)"))) (else ;; it's a list of possible arities: which to show? "([x])"))) (define (pprint-eval-result res) (if (void? res) "; No value" (~s res #:max-width 100))) (define (print-exception exn) ;; the exception has already been handled. We should only print it (string-append (exn-message exn) (if (exn:srclocs? exn) (srcloc-position (car ((exn:srclocs-accessor exn) exn))) ""))) (define (string->datum string-sexp) (let ([in (open-input-string string-sexp)]) ((current-read-interaction) (object-name in) in))) (define (send-back-to thread data cont) (thread-send thread (list 'return `(:return (:ok ,data) ,cont)))) (define (multiple-nsvv vars vals) (map namespace-set-variable-value! vars vals))
null
https://raw.githubusercontent.com/mbal/swank-racket/8a2efd2737700a795f301ec8ab47e11734336076/eval.rkt
racket
Provides the functions for the evaluation thread. In the normal implementation of swank (so, the common lisp one, or even the clojure one), the evaluation thread only evaluates stuff. However, in this version, the evaluation thread does more: basically all the things pass through this thread, since it's the only one that can access the namespace currently in use. we don't use make-evaluator in racket/sandbox because we can assume to trust the user herself (that is, ourselves, since it's mainly run locally). now, there is a problem: if you define a function in the repl, the auto-completer finds it even in the racket buffer. When you load the buffer with `compile and load`, you get an error (if you called that function), since the namespace used for compilation is different from the one used to do the rest of the things. well, yes, we could be a little more specific, but there are many ways in which the compilation process may fail: we will handle them in the `build-error-message`. enter the namespace of the module notify slime that we are in a new `package` we have to require again repl.rkt in order to access the * variables. Wraps evaluation of `stx` in a try/except block and redirects the output to `out`. Returns the correct message to be sent to emacs. variables in a module can be updated only from within the module itself. TODO: possibilities for severity are: :error, :read-error, :warning useless in Racket. I still need to figure out a way to get the list of all errors in the racket module being compiled. TODO: i have to check this: reading slime's source it seems that either (:file :line) or (:buffer :offset) should be present. XXX: aside, there's a small bug in this paredit, ( in comments are highlighted with ) not in comments. we use this function with swank:operator-arglist it's not very smart, and there isn't a nice way to handle functions with optional arguments SLIMV uses only swank:operator-arglist, but slime doesn't send that message, it prefers a more advanced version, which allows us to check with more precision which arity to show (and highlight arguments in the minibuffer) unluckily, racket doesn't provide a way to get the argument list Therefore, we will invent the names of the arguments well, geiser *does* contain the code to do that, so I will look into it. even though it seems that it parses the code, so for now I will just be happy with this little hack. it's a list of possible arities: which to show? the exception has already been handled. We should only print it
#lang racket (require racket/base racket/rerequire (only-in srfi/13 string-prefix-ci?) "complete.rkt" "repl.rkt" "modutil.rkt" "describe.rkt" "util.rkt") (provide swank-evaluation) (define (swank-evaluation parent-thread) There are two namespaces that share the module ` repl.rkt ` : the one in which the REPL runs and the namespace of this module . (let ([new-ns (make-base-namespace)]) (namespace-attach-module (namespace-anchor->empty-namespace repl-anchor) (string->path "repl.rkt") new-ns) (parameterize ([current-namespace new-ns]) (namespace-require "repl.rkt") (continuously (dispatch-eval parent-thread (thread-receive)))))) (define (dispatch-eval pthread cmd) (match cmd [(list 'eval string-sexp cont) (let ([stripped (trim-code-for-eval string-sexp)]) (when (not (string=? stripped "")) (let* ([stx (string->datum stripped)] [output-port (open-output-string)] [result (try-eval stx output-port)] [output (get-output-string output-port)]) (when (not (string=? output "")) (thread-send pthread (list 'return `(:write-string ,output)))) (thread-send pthread (list 'return `(:return ,result ,cont))))))] [(list 'complete pattern cont) (send-back-to pthread (list (simple-complete pattern) pattern) cont)] [(list 'expand times string-form cont) (let ([form (string->datum string-form)]) (send-back-to pthread (pprint-eval-result (syntax->datum ((if (= times 1) expand-once expand) form))) cont))] [(list 'arglist fnsym cont) (let ([fnobj (with-handlers ([exn:fail? (lambda (exn) #f)]) (namespace-variable-value fnsym))]) (if fnobj (let* ([fnarity (procedure-arity fnobj)] [prntarity (make-string-from-arity fnarity)]) (send-back-to pthread prntarity cont)) (send-back-to pthread 'nil cont)))] [(list 'undefine-function fname cont) (let ([fnsym (string->symbol fname)]) (if (namespace-variable-value fnsym #t (lambda () #f)) (begin (namespace-undefine-variable! (string->symbol fname)) (send-back-to pthread fname cont)) (send-back-to pthread 'nil cont)))] [(list 'describe strsym cont) TODO (send-back-to pthread (description (read (open-input-string strsym))) cont)] [(list 'compile modname load? cont) ( compile modname load ? ) (with-handlers ([exn:fail? (lambda (exn) (thread-send pthread (list 'return `(:return (:ok (:compilation-result ,(list (build-error-message exn)) nil 0.0 nil nil)) ,cont))))]) (let-values ([(_ time __ ___) (time-apply dynamic-rerequire (list (string->path modname)))]) (thread-send pthread (list 'return `(:return (:ok (:compilation-result nil t ,(/ time 1000.0) nil nil)) ,cont)))) (when load? (current-namespace (module->namespace (string->path modname))) (thread-send pthread (list 'return `(:new-package ,modname ,(get-prefix)))) (namespace-require "repl.rkt")))])) (define (try-eval stx out) (with-handlers ([exn:fail? (lambda (exn) `(:abort ,(print-exception exn)))]) (let ([result (parameterize ([current-output-port out]) (eval stx))]) (update-vars! result *1 *2 (syntax->datum stx)) `(:ok (:values ,(pprint-eval-result result)))))) (define (build-error-message exn) (displayln exn) (flush-output (current-output-port)) `(:message ,(exn-message exn) : style - warning : note : redefinition . Probably all but the first two are :severity ,(if (exn:fail:read? exn) ':read-error ':error) :location ,(build-source-error-location exn))) (define (build-source-error-location e) (if (exn:srclocs? e) (let ([srclcs (car ((exn:srclocs-accessor e) e))]) `(:location (:file ,(path->string (srcloc-source srclcs))) (:position ,(srcloc-position srclcs)) (:line ,(srcloc-line srclcs)))) '(:error "No source location"))) (define (make-string-from-arity fnarity) (define (prototype-from-int int) ( i.e. ccl : arglist or clojure 's metadata of the variable ) . (string-join (map string (map integer->char (map let 's just use letters from # \a (range 0 int)))))) (cond ([exact-nonnegative-integer? fnarity] (string-append "(" (prototype-from-int fnarity) ")")) ([arity-at-least? fnarity] (let ([args (prototype-from-int (arity-at-least-value fnarity))]) (string-append "(" args (if (string=? args "") "" " ") "...)"))) "([x])"))) (define (pprint-eval-result res) (if (void? res) "; No value" (~s res #:max-width 100))) (define (print-exception exn) (string-append (exn-message exn) (if (exn:srclocs? exn) (srcloc-position (car ((exn:srclocs-accessor exn) exn))) ""))) (define (string->datum string-sexp) (let ([in (open-input-string string-sexp)]) ((current-read-interaction) (object-name in) in))) (define (send-back-to thread data cont) (thread-send thread (list 'return `(:return (:ok ,data) ,cont)))) (define (multiple-nsvv vars vals) (map namespace-set-variable-value! vars vals))
ffd610dba440082eaa0f5833e64d19909961405eee131b649c11239bf2a9745c
NorfairKing/the-notes
Terms.hs
module Relations.Preorders.Terms where import Notes makeDefs [ "preorder" ] makeEx "powsetSubsetPreorder"
null
https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Relations/Preorders/Terms.hs
haskell
module Relations.Preorders.Terms where import Notes makeDefs [ "preorder" ] makeEx "powsetSubsetPreorder"
2bb5d2648d504290ee2f1cc7a9d587520d688bd22bdd78a4b634a2bfddbee147
dyzsr/ocaml-selectml
t110-orint.ml
TEST include tool - ocaml - lib flags = " -w -a " ocaml_script_as_argument = " true " * setup - ocaml - build - env * * include tool-ocaml-lib flags = "-w -a" ocaml_script_as_argument = "true" * setup-ocaml-build-env ** ocaml *) open Lib;; if (3 lor 6) <> 7 then raise Not_found;; * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 9 CONSTINT 7 11 PUSHCONSTINT 6 13 PUSHCONST3 14 ORINT 15 NEQ 16 BRANCHIFNOT 23 18 GETGLOBAL Not_found 20 MAKEBLOCK1 0 22 RAISE 23 ATOM0 24 26 STOP * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 SETGLOBAL Lib 9 CONSTINT 7 11 PUSHCONSTINT 6 13 PUSHCONST3 14 ORINT 15 NEQ 16 BRANCHIFNOT 23 18 GETGLOBAL Not_found 20 MAKEBLOCK1 0 22 RAISE 23 ATOM0 24 SETGLOBAL T110-orint 26 STOP **)
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/tool-ocaml/t110-orint.ml
ocaml
TEST include tool - ocaml - lib flags = " -w -a " ocaml_script_as_argument = " true " * setup - ocaml - build - env * * include tool-ocaml-lib flags = "-w -a" ocaml_script_as_argument = "true" * setup-ocaml-build-env ** ocaml *) open Lib;; if (3 lor 6) <> 7 then raise Not_found;; * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 9 CONSTINT 7 11 PUSHCONSTINT 6 13 PUSHCONST3 14 ORINT 15 NEQ 16 BRANCHIFNOT 23 18 GETGLOBAL Not_found 20 MAKEBLOCK1 0 22 RAISE 23 ATOM0 24 26 STOP * 0 CONSTINT 42 2 PUSHACC0 3 MAKEBLOCK1 0 5 POP 1 7 SETGLOBAL Lib 9 CONSTINT 7 11 PUSHCONSTINT 6 13 PUSHCONST3 14 ORINT 15 NEQ 16 BRANCHIFNOT 23 18 GETGLOBAL Not_found 20 MAKEBLOCK1 0 22 RAISE 23 ATOM0 24 SETGLOBAL T110-orint 26 STOP **)
9c5e336e76412684822581de0bcc9e1705a75a85deea0d3ad7af79d728fe3add
LPCIC/matita
notationPt.ml
Copyright ( C ) 2005 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * 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 . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) $ I d : notationPt.ml 13145 2016 - 03 - 13 17:30:14Z fguidi $ (** CIC Notation Parse Tree *) type binder_kind = [ `Lambda | `Pi | `Exists | `Forall ] type induction_kind = [ `Inductive | `CoInductive ] type sort_kind = [ `Prop | `Set | `NType of string |`NCProp of string] type fold_kind = [ `Left | `Right ] type location = Stdpp.location let fail floc msg = let (x, y) = HExtlib.loc_of_floc floc in failwith (Printf.sprintf "Error at characters %d - %d: %s" x y msg) type href = NReference.reference type child_pos = [ `Left | `Right | `Inner ] type term_attribute = [ `Loc of location (* source file location *) ACic pointer | `Level of int | `XmlAttrs of (string option * string * string) list list of XML attributes : namespace , name , value | `Raw of string (* unparsed version *) ] type literal = [ `Symbol of string | `Keyword of string | `Number of string ] type case_indtype = string * href option type 'term capture_variable = 'term * 'term option (** To be increased each time the term type below changes, used for "safe" * marshalling *) let magic = 8 type term = CIC AST | AttributedTerm of term_attribute * term | Appl of term list | Binder of binder_kind * term capture_variable * term (* kind, name, body *) | Case of term * case_indtype option * term option * (case_pattern * term) list (* what to match, inductive type, out type, <pattern,action> list *) | Cast of term * term | LetIn of term capture_variable * term * term (* name, body, where *) | Ident of string * subst list option (* literal, substitutions. * Some [] -> user has given an empty explicit substitution list * None -> user has given no explicit substitution list *) | Implicit of [`Vector | `JustOne | `Tagged of string] | Meta of int * meta_subst list | Num of string * int (* literal, instance *) | Sort of sort_kind | Symbol of string * int (* canonical name, instance *) place holder for user input , used by MatitaConsole , not to be used elsewhere used elsewhere *) | Uri of string * subst list option (* as Ident, for long names *) | NRef of NReference.reference | NCic of NCic.term (* Syntax pattern extensions *) | Literal of literal | Layout of layout_pattern | Magic of magic_term | Variable of pattern_variable name , type . First component must be Ident or Variable ( FreshVar _ ) and meta_subst = term option and subst = string * term and case_pattern = Pattern of string * href option * term capture_variable list | Wildcard and box_kind = H | V | HV | HOV and box_spec = box_kind * bool * bool (* kind, spacing, indent *) and layout_pattern = | Sub of term * term | Sup of term * term | Below of term * term | Above of term * term | Frac of term * term | Over of term * term | Atop of term * term | InfRule of term * term * term (* | array of term * literal option * literal option |+ column separator, row separator +| *) | Maction of term list | Sqrt of term | Root of term * term (* argument, index *) | Break | Box of box_spec * term list | Group of term list | Mstyle of (string * string) list * term list | Mpadded of (string * string) list * term list and magic_term = level 1 magics | List0 of term * literal option (* pattern, separator *) | List1 of term * literal option (* pattern, separator *) | Opt of term level 2 magics | Fold of fold_kind * term * string list * term (* base case pattern, recursive case bound names, recursive case pattern *) | Default of term * term (* "some" case pattern, "none" case pattern *) | Fail | If of term * term * term (* test, pattern if true, pattern if false *) and term_level = Self of int | Level of int and pattern_variable = level 1 and 2 variables | NumVar of string | IdentVar of string | TermVar of string * term_level level 1 variables | Ascription of term * string level 2 variables | FreshVar of string type argument_pattern = | IdentArg of int * string (* eta-depth, name *) type cic_appl_pattern = | NRefPattern of NReference.reference | VarPattern of string | ImplicitPattern | ApplPattern of cic_appl_pattern list (** <name, inductive/coinductive, type, constructor list> * true means inductive, false coinductive *) type 'term inductive_type = string * bool * 'term * (string * 'term) list type 'term obj = | Inductive of 'term capture_variable list * 'term inductive_type list * NCic.source (** parameters, list of loc * mutual inductive types *) | Theorem of string * 'term * 'term option * NCic.c_attr * name , type , body , attributes * - name is absent when an unnamed theorem is being proved , tipically in * interactive usage * - body is present when its given along with the command , otherwise it * will be given in proof editing mode using the tactical language , * unless the flavour is an Axiom * - name is absent when an unnamed theorem is being proved, tipically in * interactive usage * - body is present when its given along with the command, otherwise it * will be given in proof editing mode using the tactical language, * unless the flavour is an Axiom *) | Record of 'term capture_variable list * string * 'term * (string * 'term * bool * int) list * NCic.source (** left parameters, name, type, fields *) | LetRec of induction_kind * ('term capture_variable list * 'term capture_variable * 'term * int) list * NCic.f_attr (* (params, name, body, decreasing arg) list, attributes *) * { 2 Standard precedences } let let_in_prec = 10 let binder_prec = 20 let apply_prec = 70 let simple_prec = 90
null
https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/content/notationPt.ml
ocaml
* CIC Notation Parse Tree source file location unparsed version * To be increased each time the term type below changes, used for "safe" * marshalling kind, name, body what to match, inductive type, out type, <pattern,action> list name, body, where literal, substitutions. * Some [] -> user has given an empty explicit substitution list * None -> user has given no explicit substitution list literal, instance canonical name, instance as Ident, for long names Syntax pattern extensions kind, spacing, indent | array of term * literal option * literal option |+ column separator, row separator +| argument, index pattern, separator pattern, separator base case pattern, recursive case bound names, recursive case pattern "some" case pattern, "none" case pattern test, pattern if true, pattern if false eta-depth, name * <name, inductive/coinductive, type, constructor list> * true means inductive, false coinductive * parameters, list of loc * mutual inductive types * left parameters, name, type, fields (params, name, body, decreasing arg) list, attributes
Copyright ( C ) 2005 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * 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 . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) $ I d : notationPt.ml 13145 2016 - 03 - 13 17:30:14Z fguidi $ type binder_kind = [ `Lambda | `Pi | `Exists | `Forall ] type induction_kind = [ `Inductive | `CoInductive ] type sort_kind = [ `Prop | `Set | `NType of string |`NCProp of string] type fold_kind = [ `Left | `Right ] type location = Stdpp.location let fail floc msg = let (x, y) = HExtlib.loc_of_floc floc in failwith (Printf.sprintf "Error at characters %d - %d: %s" x y msg) type href = NReference.reference type child_pos = [ `Left | `Right | `Inner ] type term_attribute = ACic pointer | `Level of int | `XmlAttrs of (string option * string * string) list list of XML attributes : namespace , name , value ] type literal = [ `Symbol of string | `Keyword of string | `Number of string ] type case_indtype = string * href option type 'term capture_variable = 'term * 'term option let magic = 8 type term = CIC AST | AttributedTerm of term_attribute * term | Appl of term list | Case of term * case_indtype option * term option * (case_pattern * term) list | Cast of term * term | Ident of string * subst list option | Implicit of [`Vector | `JustOne | `Tagged of string] | Meta of int * meta_subst list | Sort of sort_kind place holder for user input , used by MatitaConsole , not to be used elsewhere used elsewhere *) | NRef of NReference.reference | NCic of NCic.term | Literal of literal | Layout of layout_pattern | Magic of magic_term | Variable of pattern_variable name , type . First component must be Ident or Variable ( FreshVar _ ) and meta_subst = term option and subst = string * term and case_pattern = Pattern of string * href option * term capture_variable list | Wildcard and box_kind = H | V | HV | HOV and layout_pattern = | Sub of term * term | Sup of term * term | Below of term * term | Above of term * term | Frac of term * term | Over of term * term | Atop of term * term | InfRule of term * term * term | Maction of term list | Sqrt of term | Break | Box of box_spec * term list | Group of term list | Mstyle of (string * string) list * term list | Mpadded of (string * string) list * term list and magic_term = level 1 magics | Opt of term level 2 magics | Fold of fold_kind * term * string list * term | Fail and term_level = Self of int | Level of int and pattern_variable = level 1 and 2 variables | NumVar of string | IdentVar of string | TermVar of string * term_level level 1 variables | Ascription of term * string level 2 variables | FreshVar of string type argument_pattern = type cic_appl_pattern = | NRefPattern of NReference.reference | VarPattern of string | ImplicitPattern | ApplPattern of cic_appl_pattern list type 'term inductive_type = string * bool * 'term * (string * 'term) list type 'term obj = | Inductive of 'term capture_variable list * 'term inductive_type list * NCic.source | Theorem of string * 'term * 'term option * NCic.c_attr * name , type , body , attributes * - name is absent when an unnamed theorem is being proved , tipically in * interactive usage * - body is present when its given along with the command , otherwise it * will be given in proof editing mode using the tactical language , * unless the flavour is an Axiom * - name is absent when an unnamed theorem is being proved, tipically in * interactive usage * - body is present when its given along with the command, otherwise it * will be given in proof editing mode using the tactical language, * unless the flavour is an Axiom *) | Record of 'term capture_variable list * string * 'term * (string * 'term * bool * int) list * NCic.source | LetRec of induction_kind * ('term capture_variable list * 'term capture_variable * 'term * int) list * NCic.f_attr * { 2 Standard precedences } let let_in_prec = 10 let binder_prec = 20 let apply_prec = 70 let simple_prec = 90
c0c50159f260d2532a5563add8e091b315fb35161b6744bcf49daafe7a5b9453
BitGameEN/bitgamex
log_player_login.erl
%%%-------------------------------------------------------- @Module : %%% @Description: θ‡ͺεŠ¨η”Ÿζˆ %%%-------------------------------------------------------- -module(log_player_login). -export([get_one/1, set_one/1, build_record_from_row/1]). -include("common.hrl"). -include("record_log_player_login.hrl"). get_one(Id) -> case db_esql:get_row(?DB_LOG, <<"select id,game_id,game_package_id,player_id,device_id,device_model,os_type,os_ver,ip,lang,time from player_login where id=?">>, [Id]) of [] -> []; Row -> build_record_from_row(Row) end. set_one(R0) when is_record(R0, log_player_login) -> case R0#log_player_login.key_id =:= undefined of false -> syncdb(R0), R0#log_player_login.key_id; true -> #log_player_login{ id = Id, game_id = Game_id, game_package_id = Game_package_id, player_id = Player_id, device_id = Device_id, device_model = Device_model, os_type = Os_type, os_ver = Os_ver, ip = Ip, lang = Lang, time = Time } = R0, spawn(fun() -> {ok, [[Insert_id|_]]} = db_esql:multi_execute(?DB_LOG, io_lib:format(<<"insert into player_login(id,game_id,game_package_id,player_id,device_id,device_model,os_type,os_ver,ip,lang,time) values(~p,~p,~p,~p,'~s','~s','~s','~s','~s','~s',~p); select last_insert_id()">>, [Id, Game_id, Game_package_id, Player_id, Device_id, Device_model, Os_type, Os_ver, Ip, Lang, Time])) end) end. syncdb(R) when is_record(R, log_player_login) -> #log_player_login{ id = Id, game_id = Game_id, game_package_id = Game_package_id, player_id = Player_id, device_id = Device_id, device_model = Device_model, os_type = Os_type, os_ver = Os_ver, ip = Ip, lang = Lang, time = Time } = R, spawn(fun() -> db_esql:execute(?DB_LOG, <<"replace into player_login(id,game_id,game_package_id,player_id,device_id,device_model,os_type,os_ver,ip,lang,time) values(?,?,?,?,?,?,?,?,?,?,?)">>, [Id, Game_id, Game_package_id, Player_id, Device_id, Device_model, Os_type, Os_ver, Ip, Lang, Time]) end). build_record_from_row([Id, Game_id, Game_package_id, Player_id, Device_id, Device_model, Os_type, Os_ver, Ip, Lang, Time]) -> #log_player_login{ key_id = Id, id = Id, game_id = Game_id, game_package_id = Game_package_id, player_id = Player_id, device_id = Device_id, device_model = Device_model, os_type = Os_type, os_ver = Os_ver, ip = Ip, lang = Lang, time = Time }.
null
https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/data/log_player_login.erl
erlang
-------------------------------------------------------- @Description: θ‡ͺεŠ¨η”Ÿζˆ --------------------------------------------------------
@Module : -module(log_player_login). -export([get_one/1, set_one/1, build_record_from_row/1]). -include("common.hrl"). -include("record_log_player_login.hrl"). get_one(Id) -> case db_esql:get_row(?DB_LOG, <<"select id,game_id,game_package_id,player_id,device_id,device_model,os_type,os_ver,ip,lang,time from player_login where id=?">>, [Id]) of [] -> []; Row -> build_record_from_row(Row) end. set_one(R0) when is_record(R0, log_player_login) -> case R0#log_player_login.key_id =:= undefined of false -> syncdb(R0), R0#log_player_login.key_id; true -> #log_player_login{ id = Id, game_id = Game_id, game_package_id = Game_package_id, player_id = Player_id, device_id = Device_id, device_model = Device_model, os_type = Os_type, os_ver = Os_ver, ip = Ip, lang = Lang, time = Time } = R0, spawn(fun() -> {ok, [[Insert_id|_]]} = db_esql:multi_execute(?DB_LOG, io_lib:format(<<"insert into player_login(id,game_id,game_package_id,player_id,device_id,device_model,os_type,os_ver,ip,lang,time) values(~p,~p,~p,~p,'~s','~s','~s','~s','~s','~s',~p); select last_insert_id()">>, [Id, Game_id, Game_package_id, Player_id, Device_id, Device_model, Os_type, Os_ver, Ip, Lang, Time])) end) end. syncdb(R) when is_record(R, log_player_login) -> #log_player_login{ id = Id, game_id = Game_id, game_package_id = Game_package_id, player_id = Player_id, device_id = Device_id, device_model = Device_model, os_type = Os_type, os_ver = Os_ver, ip = Ip, lang = Lang, time = Time } = R, spawn(fun() -> db_esql:execute(?DB_LOG, <<"replace into player_login(id,game_id,game_package_id,player_id,device_id,device_model,os_type,os_ver,ip,lang,time) values(?,?,?,?,?,?,?,?,?,?,?)">>, [Id, Game_id, Game_package_id, Player_id, Device_id, Device_model, Os_type, Os_ver, Ip, Lang, Time]) end). build_record_from_row([Id, Game_id, Game_package_id, Player_id, Device_id, Device_model, Os_type, Os_ver, Ip, Lang, Time]) -> #log_player_login{ key_id = Id, id = Id, game_id = Game_id, game_package_id = Game_package_id, player_id = Player_id, device_id = Device_id, device_model = Device_model, os_type = Os_type, os_ver = Os_ver, ip = Ip, lang = Lang, time = Time }.
1681a5ecb7db052ed91af804cb58bd5718cfcf94eac0fecc973a2fbeba423c84
jberryman/directory-tree
Examples.hs
module Main where import System.Directory.Tree import qualified Data.Foldable as F import qualified Data.Traversable as T -- for main2: import Data.Digest.Pure.MD5 import qualified Data.ByteString.Lazy as B main = darcsInitialize -- simple example of creating a directory by hand and writing to disk: here we -- replicate (kind of) running the command "darcs initialize" in the current -- directory: darcsInitialize = writeDirectory ("source_dir" :/ darcs_d) where darcs_d = Dir "_darcs" [prist_d, prefs_d, patch_d, inven_f, forma_f] prist_d = Dir "pristine.hashed" [hash_f] prefs_d = Dir "prefs" [motd_f, bori_f, bina_f] patch_d = Dir "patches" [] inven_f = File "hashed_inventory" "" forma_f = File "format" "hashed\ndarcs-2\n" hash_f = File "da39a3ee5..." "" motd_f = File "motd" "" bori_f = File "boring" "# Boring file regexps:\n..." bina_f = File "binaries" "# Binary file regexps:\n..." -- here we read directories from different locations on the disk and combine -- them into a new directory structure, ignoring the anchored base directory, -- then simply 'print' the structure to screen: combineDirectories = do (_:/d1) <- readDirectory "../dir1/" (b:/d2) <- readDirectory "/home/me/dir2" let readme = File "README" "nothing to see here" -- anchor to the parent directory: print $ b:/Dir "Combined_Dir_Test" [d1,d2,readme] read two directory structures using readFile from Data . ByteString , and build up an MD5 hash of all the files in each directory , compare the two hashes -- to see if the directories are identical in their files. (note: doesn't take -- into account directory name mis-matches) verifyDirectories = do (_:/bsd1) <- readByteStrs "./dir_modified" (_:/bsd2) <- readByteStrs "./dir" let hash1 = hashDir bsd1 let hash2 = hashDir bsd2 print $ if hash1 == hash2 then "directories match with hash: " ++ show hash1 else show hash1 ++ " doesn't match " ++ show hash2 where readByteStrs = readDirectoryWith B.readFile hashDir = md5Finalize. F.foldl' md5Update md5InitialContext
null
https://raw.githubusercontent.com/jberryman/directory-tree/bfd31a37ba4af34ed25b2e55865db8c30b175510/EXAMPLES/Examples.hs
haskell
for main2: simple example of creating a directory by hand and writing to disk: here we replicate (kind of) running the command "darcs initialize" in the current directory: here we read directories from different locations on the disk and combine them into a new directory structure, ignoring the anchored base directory, then simply 'print' the structure to screen: anchor to the parent directory: to see if the directories are identical in their files. (note: doesn't take into account directory name mis-matches)
module Main where import System.Directory.Tree import qualified Data.Foldable as F import qualified Data.Traversable as T import Data.Digest.Pure.MD5 import qualified Data.ByteString.Lazy as B main = darcsInitialize darcsInitialize = writeDirectory ("source_dir" :/ darcs_d) where darcs_d = Dir "_darcs" [prist_d, prefs_d, patch_d, inven_f, forma_f] prist_d = Dir "pristine.hashed" [hash_f] prefs_d = Dir "prefs" [motd_f, bori_f, bina_f] patch_d = Dir "patches" [] inven_f = File "hashed_inventory" "" forma_f = File "format" "hashed\ndarcs-2\n" hash_f = File "da39a3ee5..." "" motd_f = File "motd" "" bori_f = File "boring" "# Boring file regexps:\n..." bina_f = File "binaries" "# Binary file regexps:\n..." combineDirectories = do (_:/d1) <- readDirectory "../dir1/" (b:/d2) <- readDirectory "/home/me/dir2" let readme = File "README" "nothing to see here" print $ b:/Dir "Combined_Dir_Test" [d1,d2,readme] read two directory structures using readFile from Data . ByteString , and build up an MD5 hash of all the files in each directory , compare the two hashes verifyDirectories = do (_:/bsd1) <- readByteStrs "./dir_modified" (_:/bsd2) <- readByteStrs "./dir" let hash1 = hashDir bsd1 let hash2 = hashDir bsd2 print $ if hash1 == hash2 then "directories match with hash: " ++ show hash1 else show hash1 ++ " doesn't match " ++ show hash2 where readByteStrs = readDirectoryWith B.readFile hashDir = md5Finalize. F.foldl' md5Update md5InitialContext
a36b64e47eee9c21fa04713a67d5f39774eab1c6da48ce7bac5677d284ceda2d
yuriy-chumak/ol
zero_to_the_zero_power.scm
(print "0^0: " (expt 0 0)) (print "0.0^0: " (expt #i0 0))
null
https://raw.githubusercontent.com/yuriy-chumak/ol/73230a893bee928c0111ad2416fd527e7d6749ee/tests/rosettacode/zero_to_the_zero_power.scm
scheme
(print "0^0: " (expt 0 0)) (print "0.0^0: " (expt #i0 0))
fb83545a901b3d0a483c70e1f5c0c3091c6c371ad550a346b0facb0465a885d0
kawasima/supreme-uploading
user.cljs
(ns cljs.user (:require [figwheel.client :as figwheel] [supreme-uploading.core])) (js/console.info "Starting in development mode") (enable-console-print!) (figwheel/start {:websocket-url "ws:3449/figwheel-ws"})
null
https://raw.githubusercontent.com/kawasima/supreme-uploading/35837b737719f7cca9f5a7ff67f21f486100331b/dev/cljs/user.cljs
clojure
(ns cljs.user (:require [figwheel.client :as figwheel] [supreme-uploading.core])) (js/console.info "Starting in development mode") (enable-console-print!) (figwheel/start {:websocket-url "ws:3449/figwheel-ws"})
199d1694b8ad37a7f5365e3f794bad58e173c62de559ee287af86dd52ce1e00d
semperos/clj-webdriver
firefox.clj
(ns webdriver.firefox (:require [clojure.java.io :as io]) (:import org.openqa.selenium.firefox.FirefoxProfile)) (defn new-profile "Create an instance of `FirefoxProfile`" ([] (FirefoxProfile.)) ([profile-dir] (FirefoxProfile. (io/file profile-dir)))) (defn enable-extension "Given a `FirefoxProfile` object, enable an extension. The `extension` argument should be something clojure.java.io/as-file will accept." [^FirefoxProfile profile extension] (.addExtension profile (io/as-file extension))) (defn set-preferences "Given a `FirefoxProfile` object and a map of preferences, set the preferences for the profile." [^FirefoxProfile profile pref-map] (doseq [[k v] pref-map :let [key (name k)]] ;; reflection warnings (cond (string? v) (.setPreference profile key ^String v) (instance? Boolean v) (.setPreference profile key ^Boolean v) (number? v) (.setPreference profile key ^int v)))) (defn accept-untrusted-certs "Set whether or not Firefox should accept untrusted certificates." [^FirefoxProfile profile bool] (.setAcceptUntrustedCertificates profile bool)) (defn enable-native-events "Set whether or not native events should be enabled (true by default on Windows, false on other platforms)." [^FirefoxProfile profile bool] (.setEnableNativeEvents profile bool)) (defn write-to-disk "Write the given profile to disk. Makes sense when building up an anonymous profile via clj-webdriver." [^FirefoxProfile profile] (.layoutOnDisk profile)) (defn json "Return JSON representation of the given `profile` (can be used to read the profile back in via `profile-from-json`" [^FirefoxProfile profile] (.toJson profile)) (defn profile-from-json "Instantiate a new FirefoxProfile from a proper JSON representation." [^String json] (FirefoxProfile/fromJson json))
null
https://raw.githubusercontent.com/semperos/clj-webdriver/508eb95cb6ad8a5838ff0772b2a5852dc802dde1/src/webdriver/firefox.clj
clojure
reflection warnings
(ns webdriver.firefox (:require [clojure.java.io :as io]) (:import org.openqa.selenium.firefox.FirefoxProfile)) (defn new-profile "Create an instance of `FirefoxProfile`" ([] (FirefoxProfile.)) ([profile-dir] (FirefoxProfile. (io/file profile-dir)))) (defn enable-extension "Given a `FirefoxProfile` object, enable an extension. The `extension` argument should be something clojure.java.io/as-file will accept." [^FirefoxProfile profile extension] (.addExtension profile (io/as-file extension))) (defn set-preferences "Given a `FirefoxProfile` object and a map of preferences, set the preferences for the profile." [^FirefoxProfile profile pref-map] (doseq [[k v] pref-map :let [key (name k)]] (cond (string? v) (.setPreference profile key ^String v) (instance? Boolean v) (.setPreference profile key ^Boolean v) (number? v) (.setPreference profile key ^int v)))) (defn accept-untrusted-certs "Set whether or not Firefox should accept untrusted certificates." [^FirefoxProfile profile bool] (.setAcceptUntrustedCertificates profile bool)) (defn enable-native-events "Set whether or not native events should be enabled (true by default on Windows, false on other platforms)." [^FirefoxProfile profile bool] (.setEnableNativeEvents profile bool)) (defn write-to-disk "Write the given profile to disk. Makes sense when building up an anonymous profile via clj-webdriver." [^FirefoxProfile profile] (.layoutOnDisk profile)) (defn json "Return JSON representation of the given `profile` (can be used to read the profile back in via `profile-from-json`" [^FirefoxProfile profile] (.toJson profile)) (defn profile-from-json "Instantiate a new FirefoxProfile from a proper JSON representation." [^String json] (FirefoxProfile/fromJson json))
0a8af880042c112743005f6d80b8dc7c71f4acb9f969d40ad3b6f3573462c4df
nvim-treesitter/nvim-treesitter
folds.scm
[ (meta_map) (map) (array) ] @fold
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/c38646edf2bdfac157ca619697ecad9ea87fd469/queries/cpon/folds.scm
scheme
[ (meta_map) (map) (array) ] @fold
6fcc291c041fabde231520f631fc3d4a4973facece71c2a4d4040ae93dba3274
nickzuber/infrared
command.mli
type t = { name: string; aliases: string list; doc: string; flags: Flag.t list } val create : name:string -> aliases:string list -> doc:string -> flags:Flag.t list -> t
null
https://raw.githubusercontent.com/nickzuber/infrared/b67bc728458047650439649605af7a8072357b3c/Infrared/commands/command.mli
ocaml
type t = { name: string; aliases: string list; doc: string; flags: Flag.t list } val create : name:string -> aliases:string list -> doc:string -> flags:Flag.t list -> t
837ec51295ae123c9f334ff5372553a4c11b99433b77ac97d34a2507b6088617
RichiH/git-annex
FileMatcher.hs
git - annex file matching - - Copyright 2012 - 2016 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2012-2016 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} # LANGUAGE CPP # module Annex.FileMatcher ( GetFileMatcher, checkFileMatcher, checkMatcher, matchAll, preferredContentParser, parsedToMatcher, mkLargeFilesParser, largeFilesMatcher, ) where import qualified Data.Map as M import Annex.Common import Limit import Utility.Matcher import Types.Group import qualified Annex import Types.FileMatcher import Git.FilePath import Types.Remote (RemoteConfig) import Annex.CheckAttr import Git.CheckAttr (unspecifiedAttr) #ifdef WITH_MAGICMIME import Magic import Utility.Env #endif import Data.Either import qualified Data.Set as S type GetFileMatcher = FilePath -> Annex (FileMatcher Annex) checkFileMatcher :: GetFileMatcher -> FilePath -> Annex Bool checkFileMatcher getmatcher file = do matcher <- getmatcher file checkMatcher matcher Nothing (AssociatedFile (Just file)) S.empty True checkMatcher :: FileMatcher Annex -> Maybe Key -> AssociatedFile -> AssumeNotPresent -> Bool -> Annex Bool checkMatcher matcher mkey afile notpresent d | isEmpty matcher = return d | otherwise = case (mkey, afile) of (_, AssociatedFile (Just file)) -> go =<< fileMatchInfo file (Just key, _) -> go (MatchingKey key) _ -> return d where go mi = matchMrun matcher $ \a -> a notpresent mi fileMatchInfo :: FilePath -> Annex MatchInfo fileMatchInfo file = do matchfile <- getTopFilePath <$> inRepo (toTopFilePath file) return $ MatchingFile FileInfo { matchFile = matchfile , currFile = file } matchAll :: FileMatcher Annex matchAll = generate [] parsedToMatcher :: [ParseResult] -> Either String (FileMatcher Annex) parsedToMatcher parsed = case partitionEithers parsed of ([], vs) -> Right $ generate vs (es, _) -> Left $ unwords $ map ("Parse failure: " ++) es data ParseToken = SimpleToken String ParseResult | ValueToken String (String -> ParseResult) type ParseResult = Either String (Token (MatchFiles Annex)) parseToken :: [ParseToken] -> String -> ParseResult parseToken l t | t `elem` tokens = Right $ token t | otherwise = go l where go [] = Left $ "near " ++ show t go (SimpleToken s r : _) | s == t = r go (ValueToken s mkr : _) | s == k = mkr v go (_ : ps) = go ps (k, v) = separate (== '=') t commonTokens :: [ParseToken] commonTokens = [ SimpleToken "unused" (simply limitUnused) , SimpleToken "anything" (simply limitAnything) , SimpleToken "nothing" (simply limitNothing) , ValueToken "include" (usev limitInclude) , ValueToken "exclude" (usev limitExclude) , ValueToken "largerthan" (usev $ limitSize (>)) , ValueToken "smallerthan" (usev $ limitSize (<)) ] {- This is really dumb tokenization; there's no support for quoted values. - Open and close parens are always treated as standalone tokens; - otherwise tokens must be separated by whitespace. -} tokenizeMatcher :: String -> [String] tokenizeMatcher = filter (not . null ) . concatMap splitparens . words where splitparens = segmentDelim (`elem` "()") preferredContentParser :: FileMatcher Annex -> FileMatcher Annex -> Annex GroupMap -> M.Map UUID RemoteConfig -> Maybe UUID -> String -> [ParseResult] preferredContentParser matchstandard matchgroupwanted getgroupmap configmap mu expr = map parse $ tokenizeMatcher expr where parse = parseToken $ [ SimpleToken "standard" (call matchstandard) , SimpleToken "groupwanted" (call matchgroupwanted) , SimpleToken "present" (simply $ limitPresent mu) , SimpleToken "inpreferreddir" (simply $ limitInDir preferreddir) , SimpleToken "securehash" (simply limitSecureHash) , ValueToken "copies" (usev limitCopies) , ValueToken "lackingcopies" (usev $ limitLackingCopies False) , ValueToken "approxlackingcopies" (usev $ limitLackingCopies True) , ValueToken "inbacked" (usev limitInBackend) , ValueToken "metadata" (usev limitMetaData) , ValueToken "inallgroup" (usev $ limitInAllGroup getgroupmap) ] ++ commonTokens preferreddir = fromMaybe "public" $ M.lookup "preferreddir" =<< (`M.lookup` configmap) =<< mu mkLargeFilesParser :: Annex (String -> [ParseResult]) mkLargeFilesParser = do #ifdef WITH_MAGICMIME magicmime <- liftIO $ catchMaybeIO $ do m <- magicOpen [MagicMimeType] liftIO $ getEnv "GIT_ANNEX_DIR" >>= \case Nothing -> magicLoadDefault m Just d -> magicLoad m (d </> "magic" </> "magic.mgc") return m #endif let parse = parseToken $ commonTokens #ifdef WITH_MAGICMIME ++ [ ValueToken "mimetype" (usev $ matchMagic magicmime) ] #else ++ [ ValueToken "mimetype" (const $ Left "\"mimetype\" not supported; not built with MagicMime support") ] #endif return $ map parse . tokenizeMatcher {- Generates a matcher for files large enough (or meeting other criteria) - to be added to the annex, rather than directly to git. -} largeFilesMatcher :: Annex GetFileMatcher largeFilesMatcher = go =<< annexLargeFiles <$> Annex.getGitConfig where go (Just expr) = do matcher <- mkmatcher expr return $ const $ return matcher go Nothing = return $ \file -> do expr <- checkAttr "annex.largefiles" file if null expr || expr == unspecifiedAttr then return matchAll else mkmatcher expr mkmatcher expr = do parser <- mkLargeFilesParser either badexpr return $ parsedToMatcher $ parser expr badexpr e = giveup $ "bad annex.largefiles configuration: " ++ e simply :: MatchFiles Annex -> ParseResult simply = Right . Operation usev :: MkLimit Annex -> String -> ParseResult usev a v = Operation <$> a v call :: FileMatcher Annex -> ParseResult call sub = Right $ Operation $ \notpresent mi -> matchMrun sub $ \a -> a notpresent mi
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Annex/FileMatcher.hs
haskell
This is really dumb tokenization; there's no support for quoted values. - Open and close parens are always treated as standalone tokens; - otherwise tokens must be separated by whitespace. Generates a matcher for files large enough (or meeting other criteria) - to be added to the annex, rather than directly to git.
git - annex file matching - - Copyright 2012 - 2016 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2012-2016 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} # LANGUAGE CPP # module Annex.FileMatcher ( GetFileMatcher, checkFileMatcher, checkMatcher, matchAll, preferredContentParser, parsedToMatcher, mkLargeFilesParser, largeFilesMatcher, ) where import qualified Data.Map as M import Annex.Common import Limit import Utility.Matcher import Types.Group import qualified Annex import Types.FileMatcher import Git.FilePath import Types.Remote (RemoteConfig) import Annex.CheckAttr import Git.CheckAttr (unspecifiedAttr) #ifdef WITH_MAGICMIME import Magic import Utility.Env #endif import Data.Either import qualified Data.Set as S type GetFileMatcher = FilePath -> Annex (FileMatcher Annex) checkFileMatcher :: GetFileMatcher -> FilePath -> Annex Bool checkFileMatcher getmatcher file = do matcher <- getmatcher file checkMatcher matcher Nothing (AssociatedFile (Just file)) S.empty True checkMatcher :: FileMatcher Annex -> Maybe Key -> AssociatedFile -> AssumeNotPresent -> Bool -> Annex Bool checkMatcher matcher mkey afile notpresent d | isEmpty matcher = return d | otherwise = case (mkey, afile) of (_, AssociatedFile (Just file)) -> go =<< fileMatchInfo file (Just key, _) -> go (MatchingKey key) _ -> return d where go mi = matchMrun matcher $ \a -> a notpresent mi fileMatchInfo :: FilePath -> Annex MatchInfo fileMatchInfo file = do matchfile <- getTopFilePath <$> inRepo (toTopFilePath file) return $ MatchingFile FileInfo { matchFile = matchfile , currFile = file } matchAll :: FileMatcher Annex matchAll = generate [] parsedToMatcher :: [ParseResult] -> Either String (FileMatcher Annex) parsedToMatcher parsed = case partitionEithers parsed of ([], vs) -> Right $ generate vs (es, _) -> Left $ unwords $ map ("Parse failure: " ++) es data ParseToken = SimpleToken String ParseResult | ValueToken String (String -> ParseResult) type ParseResult = Either String (Token (MatchFiles Annex)) parseToken :: [ParseToken] -> String -> ParseResult parseToken l t | t `elem` tokens = Right $ token t | otherwise = go l where go [] = Left $ "near " ++ show t go (SimpleToken s r : _) | s == t = r go (ValueToken s mkr : _) | s == k = mkr v go (_ : ps) = go ps (k, v) = separate (== '=') t commonTokens :: [ParseToken] commonTokens = [ SimpleToken "unused" (simply limitUnused) , SimpleToken "anything" (simply limitAnything) , SimpleToken "nothing" (simply limitNothing) , ValueToken "include" (usev limitInclude) , ValueToken "exclude" (usev limitExclude) , ValueToken "largerthan" (usev $ limitSize (>)) , ValueToken "smallerthan" (usev $ limitSize (<)) ] tokenizeMatcher :: String -> [String] tokenizeMatcher = filter (not . null ) . concatMap splitparens . words where splitparens = segmentDelim (`elem` "()") preferredContentParser :: FileMatcher Annex -> FileMatcher Annex -> Annex GroupMap -> M.Map UUID RemoteConfig -> Maybe UUID -> String -> [ParseResult] preferredContentParser matchstandard matchgroupwanted getgroupmap configmap mu expr = map parse $ tokenizeMatcher expr where parse = parseToken $ [ SimpleToken "standard" (call matchstandard) , SimpleToken "groupwanted" (call matchgroupwanted) , SimpleToken "present" (simply $ limitPresent mu) , SimpleToken "inpreferreddir" (simply $ limitInDir preferreddir) , SimpleToken "securehash" (simply limitSecureHash) , ValueToken "copies" (usev limitCopies) , ValueToken "lackingcopies" (usev $ limitLackingCopies False) , ValueToken "approxlackingcopies" (usev $ limitLackingCopies True) , ValueToken "inbacked" (usev limitInBackend) , ValueToken "metadata" (usev limitMetaData) , ValueToken "inallgroup" (usev $ limitInAllGroup getgroupmap) ] ++ commonTokens preferreddir = fromMaybe "public" $ M.lookup "preferreddir" =<< (`M.lookup` configmap) =<< mu mkLargeFilesParser :: Annex (String -> [ParseResult]) mkLargeFilesParser = do #ifdef WITH_MAGICMIME magicmime <- liftIO $ catchMaybeIO $ do m <- magicOpen [MagicMimeType] liftIO $ getEnv "GIT_ANNEX_DIR" >>= \case Nothing -> magicLoadDefault m Just d -> magicLoad m (d </> "magic" </> "magic.mgc") return m #endif let parse = parseToken $ commonTokens #ifdef WITH_MAGICMIME ++ [ ValueToken "mimetype" (usev $ matchMagic magicmime) ] #else ++ [ ValueToken "mimetype" (const $ Left "\"mimetype\" not supported; not built with MagicMime support") ] #endif return $ map parse . tokenizeMatcher largeFilesMatcher :: Annex GetFileMatcher largeFilesMatcher = go =<< annexLargeFiles <$> Annex.getGitConfig where go (Just expr) = do matcher <- mkmatcher expr return $ const $ return matcher go Nothing = return $ \file -> do expr <- checkAttr "annex.largefiles" file if null expr || expr == unspecifiedAttr then return matchAll else mkmatcher expr mkmatcher expr = do parser <- mkLargeFilesParser either badexpr return $ parsedToMatcher $ parser expr badexpr e = giveup $ "bad annex.largefiles configuration: " ++ e simply :: MatchFiles Annex -> ParseResult simply = Right . Operation usev :: MkLimit Annex -> String -> ParseResult usev a v = Operation <$> a v call :: FileMatcher Annex -> ParseResult call sub = Right $ Operation $ \notpresent mi -> matchMrun sub $ \a -> a notpresent mi
15fae1967ca0b48748958fd417ac57ef6e91fb1187715a37b39476425d685c9b
dbuenzli/remat
br.mli
--------------------------------------------------------------------------- Copyright ( c ) 2015 . All rights reserved . Distributed under the BSD3 license , see license at the end of the file . % % NAME%% release % % --------------------------------------------------------------------------- Copyright (c) 2015 Daniel C. BΓΌnzli. All rights reserved. Distributed under the BSD3 license, see license at the end of the file. %%NAME%% release %%VERSION%% ---------------------------------------------------------------------------*) (** Minimal browser interaction. *) open React * { 1 Browser strings } type str = Js.js_string Js.t (** The type for browser strings. *) val str : string -> str (** [str s] is [s] as a browser string. *) val fstr : ('a, Format.formatter, unit, str) format4 -> 'a * [ fmt ... ] is a formatted browser string . (** Browser strings. *) module Str : sig (** {1 Empty string} *) val empty : str (** [empty] is an empty string. *) val is_empty : str -> bool (** [is_empty s] is [true] if [s] is an empty string. *) (** {1 String operations} *) val app : str -> str -> str (** [app s0 s1] appends [s1] to [s0]. *) val split : sep:str -> str -> str list (** [split sep s] is the list of all (possibly empty) substrings of [s] that are delimited by matches of the non empty separator string [sep]. *) val concat : sep:str -> str list -> str (** [concat sep ss] is the concatenates the list of strings [ss] inserting [sep] between each of them. *) val slice : ?start:int -> ?stop:int -> str -> str * [ slice ~start ~stop s ] is the string s.[start ] , s.[start+1 ] , ... s.[stop - 1 ] . [ start ] defaults to [ 0 ] and [ stop ] to [ String.length s ] . If [ start ] or [ stop ] are negative they are subtracted from [ String.length s ] . This means that [ -1 ] denotes the last character of the string . s.[stop - 1]. [start] defaults to [0] and [stop] to [String.length s]. If [start] or [stop] are negative they are subtracted from [String.length s]. This means that [-1] denotes the last character of the string. *) val trim : str -> str (** [trim s] is [s] without whitespace from the beginning and end of the string. *) val chop : prefix:str -> str -> str option (** [chop prefix s] is [s] without the prefix [prefix] or [None] if [prefix] is not a prefix of [s]. *) val rchop : suffix:str -> str -> str option (** [rchop suffix s] is [s] without the suffix [suffix] or [None] if [suffix] is not a suffix of [s]. *) val to_string : str -> string (** [to_string s] is [s] as an OCaml string. *) val pp : Format.formatter -> str -> unit * [ pp s ] prints [ s ] on [ ppf ] . end * { 1 Location and history } * Browser location { b Warning . } We use the terminology and return data according to { { : }RFC 3986 } , not according to the broken HTML URLUtils interface . {b Warning.} We use the terminology and return data according to {{:}RFC 3986}, not according to the broken HTML URLUtils interface. *) module Loc : sig * { 1 : info Location URI } val uri : unit -> str (** [uri ()] is the browser's location full URI. *) val scheme : unit -> str (** [scheme ()] is the scheme of {!uri}[ ()]. *) val host : unit -> str (** [host ()] is the host of {!uri}[ ()]. *) val port : unit -> int option (** [port ()] is the port of {!uri}[ ()]. *) val path : unit -> str (** [path ()] is the path of {!uri}[ ()]. *) val query : unit -> str (** [query ()] is the query of {!uri}[ ()]. *) val fragment : unit -> str (** [fragment ()] is fragment of {!uri}[ ()]. *) val set_fragment : str -> unit (** [set_fragment frag] sets the fragment of {!uri}[ ()] to [frag]. This does not reload the page but triggers the {!Ev.hashchange} event. *) val update : ?scheme:str -> ?host:str -> ?port:int option -> ?path:str -> ?query:str -> ?fragment:str -> unit -> unit * [ update ~scheme ~hostname ~port ~path ~query ~fragment ( ) ] updates the corresponding parts of the location 's URI . corresponding parts of the location's URI. *) * { 1 : info Location changes } val set : ?replace:bool -> str -> unit (** [set replace uri] sets to browser location to [uri], if [replace] is [true] the current location is removed from the session history (defaults to [false]). *) val reload : unit -> unit (** [reload ()] reloads the current location. *) end (** Browser history. *) module History : sig (** {1 Moving in history} *) val length : unit -> int (** [length ()] is the number of elements in the history including the currently loaded page. *) val go : int -> unit (** [go step] goes [step] numbers forward (positive) or backward (negative) in history. *) val back : unit -> unit (** [back ()] is [go ~-1]. *) val forward : unit -> unit * [ forward ( ) ] is [ go 1 ] . * { 1 History state } { b Warning . } History state is unsafe if you do n't properly version you state . Any change in state representation should entail a new version . {b Warning.} History state is unsafe if you don't properly version you state. Any change in state representation should entail a new version. *) type 'a state (** The type for state. *) val create_state : version:str -> 'a -> 'a state (** [create_state version v] is state [v] with version [version]. *) val state : version:str -> default:'a -> unit -> 'a * [ state version ( ) ] is the current state if it matches [ version ] . If it does n't match or there is no state [ default ] is returned . [version]. If it doesn't match or there is no state [default] is returned. *) (** {1 Making history} *) val push : ?replace:bool -> ?state:'a state -> title:str -> str -> unit * [ push ~replace ~state ~title uri ] changes the browser location to [ uri ] but does n't load the URI . [ title ] is a human title for the location to which we are moving and [ state ] is a possible value associated to the location . If [ replace ] is [ true ] ( defaults to [ false ] ) the current location is replaced rather than added to history . [uri] but doesn't load the URI. [title] is a human title for the location to which we are moving and [state] is a possible value associated to the location. If [replace] is [true] (defaults to [false]) the current location is replaced rather than added to history. *) end (** Browser information *) module Info : sig val languages : unit -> str list * [ languages ( ) ] is the user 's preferred languages as BCP 47 language tags . FIXME support languagechange event on window . tags. FIXME support languagechange event on window. *) end * { 1 Monotonic time } (** Monotonic time. *) module Time : sig * { 1 Time span } type span = float * The type for time spans , in seconds . * { 1 Passing time } val elapsed : unit -> span * [ elapsed ( ) ] is the number of seconds elapsed since the beginning of the program . beginning of the program. *) (** {1 Counters} *) type counter (** The type for time counters. *) val counter : unit -> counter (** [counter ()] is a counter counting time from call time on. *) val counter_value : counter -> span * [ counter_value c ] is the current counter value in seconds . * { 1 Pretty printing time } val pp_s : Format.formatter -> span -> unit * [ pp_s s ] prints [ s ] seconds in seconds . val pp_ms : Format.formatter -> span -> unit (** [pp_ms ppf s] prints [s] seconds in milliseconds. *) val pp_mus : Format.formatter -> span -> unit (** [pp_mus ppf s] prints [s] seconds in microseconds. *) end (** {1 Storage} *) * Persistent storage . key - value store implemented over { { : /}webstorage } . Safe if no one tampers with the storage outside of the program . Persisent key-value store implemented over {{:/}webstorage}. Safe if no one tampers with the storage outside of the program. *) module Store : sig (** {1 Storage scope} *) type scope = [ `Session | `Persist ] (** The storage scope. *) val support : scope -> bool (** [support scope] is [true] iff values can be stored in [scope]. *) (** {1 Keys} *) type 'a key (** The type for keys whose lookup value is 'a *) val key : ?ns:str -> unit -> 'a key (** [key ~ns ()] is a new storage key in namespace [ns]. If [ns] is unspecified, the key lives in a global namespace. {b Warning.} Reordering invocations of {!key} in the same namespace will most of the time corrupt existing storage. This means that all {!key} calls should always be performed at initialization time. {!Store.force_version} can be used to easily version your store and aleviate this problem. *) (** {1 Storage} In the functions below [scope] defaults to [`Persist]. *) val mem : ?scope:scope -> 'a key -> bool (** [mem k] is [true] iff [k] has a mapping. *) val add : ?scope:scope -> 'a key -> 'a -> unit (** [add k v] maps [k] to [v]. *) val rem : ?scope:scope -> 'a key -> unit (** [rem k] unbinds [k]. *) val find : ?scope:scope -> 'a key -> 'a option (** [find k] is [k]'s mapping in [m], if any. *) val get : ?scope:scope -> ?absent:'a -> 'a key -> 'a * [ get k ] is [ k ] 's mapping . If [ absent ] is provided and [ m ] has not binding for [ k ] , [ absent ] is returned . @raise Invalid_argument if [ k ] is not bound and [ absent ] is unspecified or if [ scope ] is not { ! . not binding for [k], [absent] is returned. @raise Invalid_argument if [k] is not bound and [absent] is unspecified or if [scope] is not {!support}ed. *) val clear : ?scope:scope -> unit -> unit (** [clear ()], clears all mapping. *) (** {1 Versioning} *) val force_version : ?scope:scope -> string -> unit (** [force_version v] checks that the version of the store is [v]. If it's not it {!clear}s the store and sets the version to [v]. *) end (** {1 DOM} *) type el = Dom_html.element Js.t (** The type for elements. *) (** DOM elements *) module El : sig * { 1 : elements Elements } type name (** The type for element names, see {!element_names}. *) type child = [ `El of el | `Txt of str ] (** The type for element childs. *) type t = el (** The type for elements. *) val v : ?id:str -> ?title:str -> ?classes:str list -> ?atts:(str * str) list -> name -> child list -> el * [ v i d title classes atts name children ] is a DOM element [ name ] with i d [ i d ] , title [ title ] , classes [ classes ] , attribute [ atts ] , and children [ children ] . with id [id], title [title], classes [classes], attribute [atts], and children [children]. *) val of_id : str -> el option (** [of_id id] looks for and element with id [id] in the document. *) (** {1 Attributes} *) val att : el -> str -> str option * [ att e a ] is the value of attribute [ a ] of [ e ] ( if any ) . val set_att : el -> str -> str -> unit (** [set_att e a v] sets the value of attribute [a] of [e] to [v]. *) val rem_att : el -> str -> unit (** [rem_att e a] remove the attribute [a] from [e]. *) (** {1 Classes} *) val has_class : el -> str -> bool (** [has_class e class] is [true] iff [e] has class [class]. *) val classify : el -> str -> bool -> unit (** [classify e class pred] classifies [e] as being a member of class [class] according to [pred]. *) val class_list : el -> str list (** [class_list e] is the list of classes of [e]. *) val set_class_list : el -> str list -> unit (** [set_class_list cl] sets the classes of [e] to [cl]. *) (** {1 Children} *) val set_children : el -> child list -> unit (** [set_children e children] sets [e]'s children to [children] *) (** {1 Finalizers} *) val add_finalizer : el -> (unit -> unit) -> unit (** [finalizer e f] sets [f] as a finalisation function for [e]. *) val finalize : el -> unit (** [finalize el] finalizes [el] and its descendents elements. *) * { 1 : element_names Element names } See { { : #element-interfaces}spec } . See {{:#element-interfaces}spec}. *) val name : str -> name (** [name s] is an element name [s]. *) val a : name (** {{:}a} *) val abbr : name (** {{:}abbr} *) val address : name (** {{:}address} *) val area : name (** {{:}area} *) val article : name (** {{:}article} *) val aside : name (** {{:}aside} *) val audio : name (** {{:}audio} *) val b : name (** {{:}b} *) val base : name (** {{:}base} *) val bdi : name (** {{:}bdi} *) val bdo : name (** {{:}bdo} *) val blockquote : name (** {{:}blockquote} *) val body : name (** {{:}body} *) val br : name (** {{:}br} *) val button : name (** {{:}button} *) val canvas : name (** {{:}canvas} *) val caption : name (** {{:}caption} *) val cite : name * { { : } val code : name (** {{:}code} *) val col : name (** {{:}col} *) val colgroup : name * { { : } val command : name (** {{:}command} *) val datalist : name (** {{:}datalist} *) val dd : name * { { : }dd } val del : name (** {{:}del} *) val details : name (** {{:}details} *) val dfn : name (** {{:}dfn} *) val div : name (** {{:}div} *) val dl : name (** {{:}dl} *) val dt : name (** {{:}dt} *) val em : name * { { : } val embed : name (** {{:}embed} *) val fieldset : name (** {{:}fieldset} *) val figcaption : name (** {{:}figcaption} *) val figure : name (** {{:}figure} *) val footer : name * { { : } val form : name (** {{:}form} *) val h1 : name (** {{:}h1} *) val h2 : name * { { : } val h3 : name (** {{:}h3} *) val h4 : name (** {{:}h4} *) val h5 : name (** {{:}h5} *) val h6 : name (** {{:}h6} *) val head : name * { { : } val header : name (** {{:}header} *) val hgroup : name * { { : val hr : name (** {{:}hr} *) val html : name (** {{:}html} *) val i : name * { { : }i } val iframe : name (** {{:}iframe} *) val img : name (** {{:}img} *) val input : name * { { : } val ins : name (** {{:}ins} *) val kbd : name (** {{:}kbd} *) val keygen : name (** {{:}keygen} *) val label : name (** {{:}label} *) val legend : name (** {{:}legend} *) val li : name (** {{:}li} *) val link : name (** {{:}link} *) val map : name (** {{:}map} *) val mark : name (** {{:}mark} *) val menu : name (** {{:}menu} *) val meta : name (** {{:}meta} *) val meter : name (** {{:}meter} *) val nav : name (** {{:}nav} *) val noscript : name (** {{:}noscript} *) val object_ : name (** {{:}object} *) val ol : name (** {{:}ol} *) val optgroup : name (** {{:}optgroup} *) val option : name (** {{:}option} *) val output : name (** {{:}output} *) val p : name (** {{:}p} *) val param : name (** {{:}param} *) val pre : name (** {{:}pre} *) val progress : name (** {{:}progress} *) val q : name (** {{:}q} *) val rp : name (** {{:}rp} *) val rt : name (** {{:}rt} *) val ruby : name * { { : }ruby } val s : name (** {{:}s} *) val samp : name (** {{:}samp} *) val script : name (** {{:}script} *) val section : name (** {{:}section} *) val select : name (** {{:}select} *) val small : name (** {{:}small} *) val source : name (** {{:}source} *) val span : name * { { : val strong : name * { { : }strong } val style : name (** {{:}style} *) val sub : name * { { : }sub } val summary : name * { { : } val sup : name (** {{:}sup} *) val table : name (** {{:}table} *) val tbody : name (** {{:}tbody} *) val td : name (** {{:}td} *) val textarea : name (** {{:}textarea} *) val tfoot : name * { { : val th : name * { { : }th } val thead : name * { { : } val time : name (** {{:}time} *) val title : name (** {{:}title} *) val tr : name (** {{:}tr} *) val track : name (** {{:}track} *) val u : name (** {{:}u} *) val ul : name * { { : } val var : name (** {{:}var} *) val video : name (** {{:}video} *) val wbr : name * { { : }wbr } end val el : ?id:str -> ?title:str -> ?classes:str list -> ?atts:(str * str) list -> El.name -> El.child list -> el (** DOM element attribute names. *) module Att : sig (** {1 Attribute names} *) val height : str val href : str val id : str val name : str val placeholder : str val src : str val tabindex : str val target : str val title : str val type_ : str val width : str end * DOM events module Ev : sig * { 1 : events Events and event kinds } type 'a target = (#Dom_html.eventTarget as 'a) Js.t (** The type for event targets. *) type 'a kind = (#Dom_html.event as 'a) Js.t Dom_html.Event.typ (** The type for kind of events. See {!kinds}. *) type 'a t = (#Dom_html.event as 'a) Js.t (** The type for events. *) * { 1 : cb Event callbacks } type cb (** The type for event callbacks. *) type cb_ret (** The type for callback return. *) val add_cb : ?capture:bool -> 'a target -> 'b kind -> ('a target -> 'b t -> cb_ret) -> cb (** [add_cb capture e k f] is calls [f e ev] whenever an event [ev] of kind [k] occurs on [e]. If [capture] is [true] the callback occurs during the capture phase (defaults to [false]). *) val rem_cb : cb -> unit (** [rem_cb cb] removes the callback [cb]. *) val propagate : ?default:bool -> 'a t -> bool -> cb_ret (** [propogate default e propagate] propagate event [e] if it is [propagate] is [true]. The default action is performed iff [default] is [true] (defaults to [false] if [propagate] is [false] and [true] if [propagate] is [true]). *) * { 1 : kinds Event kinds } See { { : #events-0}spec } . See {{:#events-0}spec}. *) val kind : string -> 'a kind val abort : Dom_html.event kind val afterprint : Dom_html.event kind val beforeprint : Dom_html.event kind FIXME make more precise val blur : Dom_html.event kind val change : Dom_html.event kind val click : Dom_html.event kind val domContentLoaded : Dom_html.event kind val error : Dom_html.event kind val focus : Dom_html.event kind FIXME make more precise val input : Dom_html.event kind val invalid : Dom_html.event kind val load : Dom_html.event kind FIXME make more precise val offline : Dom_html.event kind val online : Dom_html.event kind FIXME make more precise FIXME make more precise FIXME make more precise val readystatechange : Dom_html.event kind val reset : Dom_html.event kind val submit : Dom_html.event kind val unload : Dom_html.event kind end val window : Dom_html.window Js.t (** [window] is {!Dom_html.window}. *) val document : Dom_html.document Js.t (** [document] is {!Dom_html.document}. *) (** {1 Log and debug} *) (** Browser log. {b TODO} Adjust documentation, assert sensitiveness, recheck with command line Log module. *) module Log : sig * { 1 Log level } (** The type for log levels. *) type level = Show | Error | Warning | Info | Debug val msg : ?header:string -> level -> ('a, Format.formatter, unit, unit) format4 -> 'a (** [msg header l fmt ...] logs a message with level [l]. [header] is the message header, default depends on [l]. *) val kmsg : ?header:string -> (unit -> 'a) -> level -> ('b, Format.formatter, unit, 'a) format4 -> 'b * [ kmsg header k l fmt ... ] is like [ msg header l fmt ] but calls [ k ( ) ] before returning . before returning. *) val show : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a (** [show fmt ...] logs a message with level [Show]. [header] defaults to [None]. *) val err : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a (** [err fmt ...] logs a message with level [Error]. [header] defaults to ["ERROR"]. *) val warn : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a (** [warn fmt ...] logs a message with level [Warning]. [header] defaults to ["WARNING"]. *) val info : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a (** [info fmt ...] logs a message with level [Info]. [header] defaults to ["INFO"]. *) val debug : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a (** [debug info ...] logs a message with level [Debug]. [header] defaults to ["DEBUG"]. *) * { 1 Log level and output } val level : unit -> level option (** [level ()] is the log level (if any). If the log level is [(Some l)] any message whose level is [<= l] is logged. If level is [None] no message is ever logged. Initially the level is [(Some Warning)]. *) val set_level : level option -> unit (** [set_level l] sets the log level to [l]. See {!level}. *) val set_formatter : [`All | `Level of level ] -> Format.formatter -> unit * [ set_formatter spec ppf ] sets the formatter for a given level or for all the levels according to [ spec ] . Initially the formatter of level [ Show ] is { ! Format.std_formatter } and all the other level formatters are { ! . for all the levels according to [spec]. Initially the formatter of level [Show] is {!Format.std_formatter} and all the other level formatters are {!Format.err_formatter}. *) * { 1 Log monitoring } val err_count : unit -> int * [ err_count ( ) ] is the number of messages logged with level [ Error ] . val warn_count : unit -> int (** [warn_count ()] is the number of messages logged with level [Warning]. *) end (** Debugging tools. *) module Debug : sig (** {1 Debug} *) val enter : unit -> unit * [ enter ( ) ] stops and enters the JavaScript debugger ( if available ) . val pp_v : Format.formatter -> < .. > Js.t -> unit * [ pp_v v ] applies the method [ toString ] to [ v ] and prints the the resulting string on [ ppf ] . the resulting string on [ppf]. *) val log : < .. > Js.t -> unit (** [log v] logs [v] on the browser console with level debug. *) end --------------------------------------------------------------------------- Copyright ( c ) 2015 . All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . 3 . Neither the name of nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . --------------------------------------------------------------------------- Copyright (c) 2015 Daniel C. BΓΌnzli. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Daniel C. BΓΌnzli nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/remat/28d572e77bbd1ad46bbfde87c0ba8bd0ab99ed28/src-www/br.mli
ocaml
* Minimal browser interaction. * The type for browser strings. * [str s] is [s] as a browser string. * Browser strings. * {1 Empty string} * [empty] is an empty string. * [is_empty s] is [true] if [s] is an empty string. * {1 String operations} * [app s0 s1] appends [s1] to [s0]. * [split sep s] is the list of all (possibly empty) substrings of [s] that are delimited by matches of the non empty separator string [sep]. * [concat sep ss] is the concatenates the list of strings [ss] inserting [sep] between each of them. * [trim s] is [s] without whitespace from the beginning and end of the string. * [chop prefix s] is [s] without the prefix [prefix] or [None] if [prefix] is not a prefix of [s]. * [rchop suffix s] is [s] without the suffix [suffix] or [None] if [suffix] is not a suffix of [s]. * [to_string s] is [s] as an OCaml string. * [uri ()] is the browser's location full URI. * [scheme ()] is the scheme of {!uri}[ ()]. * [host ()] is the host of {!uri}[ ()]. * [port ()] is the port of {!uri}[ ()]. * [path ()] is the path of {!uri}[ ()]. * [query ()] is the query of {!uri}[ ()]. * [fragment ()] is fragment of {!uri}[ ()]. * [set_fragment frag] sets the fragment of {!uri}[ ()] to [frag]. This does not reload the page but triggers the {!Ev.hashchange} event. * [set replace uri] sets to browser location to [uri], if [replace] is [true] the current location is removed from the session history (defaults to [false]). * [reload ()] reloads the current location. * Browser history. * {1 Moving in history} * [length ()] is the number of elements in the history including the currently loaded page. * [go step] goes [step] numbers forward (positive) or backward (negative) in history. * [back ()] is [go ~-1]. * The type for state. * [create_state version v] is state [v] with version [version]. * {1 Making history} * Browser information * Monotonic time. * {1 Counters} * The type for time counters. * [counter ()] is a counter counting time from call time on. * [pp_ms ppf s] prints [s] seconds in milliseconds. * [pp_mus ppf s] prints [s] seconds in microseconds. * {1 Storage} * {1 Storage scope} * The storage scope. * [support scope] is [true] iff values can be stored in [scope]. * {1 Keys} * The type for keys whose lookup value is 'a * [key ~ns ()] is a new storage key in namespace [ns]. If [ns] is unspecified, the key lives in a global namespace. {b Warning.} Reordering invocations of {!key} in the same namespace will most of the time corrupt existing storage. This means that all {!key} calls should always be performed at initialization time. {!Store.force_version} can be used to easily version your store and aleviate this problem. * {1 Storage} In the functions below [scope] defaults to [`Persist]. * [mem k] is [true] iff [k] has a mapping. * [add k v] maps [k] to [v]. * [rem k] unbinds [k]. * [find k] is [k]'s mapping in [m], if any. * [clear ()], clears all mapping. * {1 Versioning} * [force_version v] checks that the version of the store is [v]. If it's not it {!clear}s the store and sets the version to [v]. * {1 DOM} * The type for elements. * DOM elements * The type for element names, see {!element_names}. * The type for element childs. * The type for elements. * [of_id id] looks for and element with id [id] in the document. * {1 Attributes} * [set_att e a v] sets the value of attribute [a] of [e] to [v]. * [rem_att e a] remove the attribute [a] from [e]. * {1 Classes} * [has_class e class] is [true] iff [e] has class [class]. * [classify e class pred] classifies [e] as being a member of class [class] according to [pred]. * [class_list e] is the list of classes of [e]. * [set_class_list cl] sets the classes of [e] to [cl]. * {1 Children} * [set_children e children] sets [e]'s children to [children] * {1 Finalizers} * [finalizer e f] sets [f] as a finalisation function for [e]. * [finalize el] finalizes [el] and its descendents elements. * [name s] is an element name [s]. * {{:}a} * {{:}abbr} * {{:}address} * {{:}area} * {{:}article} * {{:}aside} * {{:}audio} * {{:}b} * {{:}base} * {{:}bdi} * {{:}bdo} * {{:}blockquote} * {{:}body} * {{:}br} * {{:}button} * {{:}canvas} * {{:}caption} * {{:}code} * {{:}col} * {{:}command} * {{:}datalist} * {{:}del} * {{:}details} * {{:}dfn} * {{:}div} * {{:}dl} * {{:}dt} * {{:}embed} * {{:}fieldset} * {{:}figcaption} * {{:}figure} * {{:}form} * {{:}h1} * {{:}h3} * {{:}h4} * {{:}h5} * {{:}h6} * {{:}header} * {{:}hr} * {{:}html} * {{:}iframe} * {{:}img} * {{:}ins} * {{:}kbd} * {{:}keygen} * {{:}label} * {{:}legend} * {{:}li} * {{:}link} * {{:}map} * {{:}mark} * {{:}menu} * {{:}meta} * {{:}meter} * {{:}nav} * {{:}noscript} * {{:}object} * {{:}ol} * {{:}optgroup} * {{:}option} * {{:}output} * {{:}p} * {{:}param} * {{:}pre} * {{:}progress} * {{:}q} * {{:}rp} * {{:}rt} * {{:}s} * {{:}samp} * {{:}script} * {{:}section} * {{:}select} * {{:}small} * {{:}source} * {{:}style} * {{:}sup} * {{:}table} * {{:}tbody} * {{:}td} * {{:}textarea} * {{:}time} * {{:}title} * {{:}tr} * {{:}track} * {{:}u} * {{:}var} * {{:}video} * DOM element attribute names. * {1 Attribute names} * The type for event targets. * The type for kind of events. See {!kinds}. * The type for events. * The type for event callbacks. * The type for callback return. * [add_cb capture e k f] is calls [f e ev] whenever an event [ev] of kind [k] occurs on [e]. If [capture] is [true] the callback occurs during the capture phase (defaults to [false]). * [rem_cb cb] removes the callback [cb]. * [propogate default e propagate] propagate event [e] if it is [propagate] is [true]. The default action is performed iff [default] is [true] (defaults to [false] if [propagate] is [false] and [true] if [propagate] is [true]). * [window] is {!Dom_html.window}. * [document] is {!Dom_html.document}. * {1 Log and debug} * Browser log. {b TODO} Adjust documentation, assert sensitiveness, recheck with command line Log module. * The type for log levels. * [msg header l fmt ...] logs a message with level [l]. [header] is the message header, default depends on [l]. * [show fmt ...] logs a message with level [Show]. [header] defaults to [None]. * [err fmt ...] logs a message with level [Error]. [header] defaults to ["ERROR"]. * [warn fmt ...] logs a message with level [Warning]. [header] defaults to ["WARNING"]. * [info fmt ...] logs a message with level [Info]. [header] defaults to ["INFO"]. * [debug info ...] logs a message with level [Debug]. [header] defaults to ["DEBUG"]. * [level ()] is the log level (if any). If the log level is [(Some l)] any message whose level is [<= l] is logged. If level is [None] no message is ever logged. Initially the level is [(Some Warning)]. * [set_level l] sets the log level to [l]. See {!level}. * [warn_count ()] is the number of messages logged with level [Warning]. * Debugging tools. * {1 Debug} * [log v] logs [v] on the browser console with level debug.
--------------------------------------------------------------------------- Copyright ( c ) 2015 . All rights reserved . Distributed under the BSD3 license , see license at the end of the file . % % NAME%% release % % --------------------------------------------------------------------------- Copyright (c) 2015 Daniel C. BΓΌnzli. All rights reserved. Distributed under the BSD3 license, see license at the end of the file. %%NAME%% release %%VERSION%% ---------------------------------------------------------------------------*) open React * { 1 Browser strings } type str = Js.js_string Js.t val str : string -> str val fstr : ('a, Format.formatter, unit, str) format4 -> 'a * [ fmt ... ] is a formatted browser string . module Str : sig val empty : str val is_empty : str -> bool val app : str -> str -> str val split : sep:str -> str -> str list val concat : sep:str -> str list -> str val slice : ?start:int -> ?stop:int -> str -> str * [ slice ~start ~stop s ] is the string s.[start ] , s.[start+1 ] , ... s.[stop - 1 ] . [ start ] defaults to [ 0 ] and [ stop ] to [ String.length s ] . If [ start ] or [ stop ] are negative they are subtracted from [ String.length s ] . This means that [ -1 ] denotes the last character of the string . s.[stop - 1]. [start] defaults to [0] and [stop] to [String.length s]. If [start] or [stop] are negative they are subtracted from [String.length s]. This means that [-1] denotes the last character of the string. *) val trim : str -> str val chop : prefix:str -> str -> str option val rchop : suffix:str -> str -> str option val to_string : str -> string val pp : Format.formatter -> str -> unit * [ pp s ] prints [ s ] on [ ppf ] . end * { 1 Location and history } * Browser location { b Warning . } We use the terminology and return data according to { { : }RFC 3986 } , not according to the broken HTML URLUtils interface . {b Warning.} We use the terminology and return data according to {{:}RFC 3986}, not according to the broken HTML URLUtils interface. *) module Loc : sig * { 1 : info Location URI } val uri : unit -> str val scheme : unit -> str val host : unit -> str val port : unit -> int option val path : unit -> str val query : unit -> str val fragment : unit -> str val set_fragment : str -> unit val update : ?scheme:str -> ?host:str -> ?port:int option -> ?path:str -> ?query:str -> ?fragment:str -> unit -> unit * [ update ~scheme ~hostname ~port ~path ~query ~fragment ( ) ] updates the corresponding parts of the location 's URI . corresponding parts of the location's URI. *) * { 1 : info Location changes } val set : ?replace:bool -> str -> unit val reload : unit -> unit end module History : sig val length : unit -> int val go : int -> unit val back : unit -> unit val forward : unit -> unit * [ forward ( ) ] is [ go 1 ] . * { 1 History state } { b Warning . } History state is unsafe if you do n't properly version you state . Any change in state representation should entail a new version . {b Warning.} History state is unsafe if you don't properly version you state. Any change in state representation should entail a new version. *) type 'a state val create_state : version:str -> 'a -> 'a state val state : version:str -> default:'a -> unit -> 'a * [ state version ( ) ] is the current state if it matches [ version ] . If it does n't match or there is no state [ default ] is returned . [version]. If it doesn't match or there is no state [default] is returned. *) val push : ?replace:bool -> ?state:'a state -> title:str -> str -> unit * [ push ~replace ~state ~title uri ] changes the browser location to [ uri ] but does n't load the URI . [ title ] is a human title for the location to which we are moving and [ state ] is a possible value associated to the location . If [ replace ] is [ true ] ( defaults to [ false ] ) the current location is replaced rather than added to history . [uri] but doesn't load the URI. [title] is a human title for the location to which we are moving and [state] is a possible value associated to the location. If [replace] is [true] (defaults to [false]) the current location is replaced rather than added to history. *) end module Info : sig val languages : unit -> str list * [ languages ( ) ] is the user 's preferred languages as BCP 47 language tags . FIXME support languagechange event on window . tags. FIXME support languagechange event on window. *) end * { 1 Monotonic time } module Time : sig * { 1 Time span } type span = float * The type for time spans , in seconds . * { 1 Passing time } val elapsed : unit -> span * [ elapsed ( ) ] is the number of seconds elapsed since the beginning of the program . beginning of the program. *) type counter val counter : unit -> counter val counter_value : counter -> span * [ counter_value c ] is the current counter value in seconds . * { 1 Pretty printing time } val pp_s : Format.formatter -> span -> unit * [ pp_s s ] prints [ s ] seconds in seconds . val pp_ms : Format.formatter -> span -> unit val pp_mus : Format.formatter -> span -> unit end * Persistent storage . key - value store implemented over { { : /}webstorage } . Safe if no one tampers with the storage outside of the program . Persisent key-value store implemented over {{:/}webstorage}. Safe if no one tampers with the storage outside of the program. *) module Store : sig type scope = [ `Session | `Persist ] val support : scope -> bool type 'a key val key : ?ns:str -> unit -> 'a key val mem : ?scope:scope -> 'a key -> bool val add : ?scope:scope -> 'a key -> 'a -> unit val rem : ?scope:scope -> 'a key -> unit val find : ?scope:scope -> 'a key -> 'a option val get : ?scope:scope -> ?absent:'a -> 'a key -> 'a * [ get k ] is [ k ] 's mapping . If [ absent ] is provided and [ m ] has not binding for [ k ] , [ absent ] is returned . @raise Invalid_argument if [ k ] is not bound and [ absent ] is unspecified or if [ scope ] is not { ! . not binding for [k], [absent] is returned. @raise Invalid_argument if [k] is not bound and [absent] is unspecified or if [scope] is not {!support}ed. *) val clear : ?scope:scope -> unit -> unit val force_version : ?scope:scope -> string -> unit end type el = Dom_html.element Js.t module El : sig * { 1 : elements Elements } type name type child = [ `El of el | `Txt of str ] type t = el val v : ?id:str -> ?title:str -> ?classes:str list -> ?atts:(str * str) list -> name -> child list -> el * [ v i d title classes atts name children ] is a DOM element [ name ] with i d [ i d ] , title [ title ] , classes [ classes ] , attribute [ atts ] , and children [ children ] . with id [id], title [title], classes [classes], attribute [atts], and children [children]. *) val of_id : str -> el option val att : el -> str -> str option * [ att e a ] is the value of attribute [ a ] of [ e ] ( if any ) . val set_att : el -> str -> str -> unit val rem_att : el -> str -> unit val has_class : el -> str -> bool val classify : el -> str -> bool -> unit val class_list : el -> str list val set_class_list : el -> str list -> unit val set_children : el -> child list -> unit val add_finalizer : el -> (unit -> unit) -> unit val finalize : el -> unit * { 1 : element_names Element names } See { { : #element-interfaces}spec } . See {{:#element-interfaces}spec}. *) val name : str -> name val a : name val abbr : name val address : name val area : name val article : name val aside : name val audio : name val b : name val base : name val bdi : name val bdo : name val blockquote : name val body : name val br : name val button : name val canvas : name val caption : name val cite : name * { { : } val code : name val col : name val colgroup : name * { { : } val command : name val datalist : name val dd : name * { { : }dd } val del : name val details : name val dfn : name val div : name val dl : name val dt : name val em : name * { { : } val embed : name val fieldset : name val figcaption : name val figure : name val footer : name * { { : } val form : name val h1 : name val h2 : name * { { : } val h3 : name val h4 : name val h5 : name val h6 : name val head : name * { { : } val header : name val hgroup : name * { { : val hr : name val html : name val i : name * { { : }i } val iframe : name val img : name val input : name * { { : } val ins : name val kbd : name val keygen : name val label : name val legend : name val li : name val link : name val map : name val mark : name val menu : name val meta : name val meter : name val nav : name val noscript : name val object_ : name val ol : name val optgroup : name val option : name val output : name val p : name val param : name val pre : name val progress : name val q : name val rp : name val rt : name val ruby : name * { { : }ruby } val s : name val samp : name val script : name val section : name val select : name val small : name val source : name val span : name * { { : val strong : name * { { : }strong } val style : name val sub : name * { { : }sub } val summary : name * { { : } val sup : name val table : name val tbody : name val td : name val textarea : name val tfoot : name * { { : val th : name * { { : }th } val thead : name * { { : } val time : name val title : name val tr : name val track : name val u : name val ul : name * { { : } val var : name val video : name val wbr : name * { { : }wbr } end val el : ?id:str -> ?title:str -> ?classes:str list -> ?atts:(str * str) list -> El.name -> El.child list -> el module Att : sig val height : str val href : str val id : str val name : str val placeholder : str val src : str val tabindex : str val target : str val title : str val type_ : str val width : str end * DOM events module Ev : sig * { 1 : events Events and event kinds } type 'a target = (#Dom_html.eventTarget as 'a) Js.t type 'a kind = (#Dom_html.event as 'a) Js.t Dom_html.Event.typ type 'a t = (#Dom_html.event as 'a) Js.t * { 1 : cb Event callbacks } type cb type cb_ret val add_cb : ?capture:bool -> 'a target -> 'b kind -> ('a target -> 'b t -> cb_ret) -> cb val rem_cb : cb -> unit val propagate : ?default:bool -> 'a t -> bool -> cb_ret * { 1 : kinds Event kinds } See { { : #events-0}spec } . See {{:#events-0}spec}. *) val kind : string -> 'a kind val abort : Dom_html.event kind val afterprint : Dom_html.event kind val beforeprint : Dom_html.event kind FIXME make more precise val blur : Dom_html.event kind val change : Dom_html.event kind val click : Dom_html.event kind val domContentLoaded : Dom_html.event kind val error : Dom_html.event kind val focus : Dom_html.event kind FIXME make more precise val input : Dom_html.event kind val invalid : Dom_html.event kind val load : Dom_html.event kind FIXME make more precise val offline : Dom_html.event kind val online : Dom_html.event kind FIXME make more precise FIXME make more precise FIXME make more precise val readystatechange : Dom_html.event kind val reset : Dom_html.event kind val submit : Dom_html.event kind val unload : Dom_html.event kind end val window : Dom_html.window Js.t val document : Dom_html.document Js.t module Log : sig * { 1 Log level } type level = Show | Error | Warning | Info | Debug val msg : ?header:string -> level -> ('a, Format.formatter, unit, unit) format4 -> 'a val kmsg : ?header:string -> (unit -> 'a) -> level -> ('b, Format.formatter, unit, 'a) format4 -> 'b * [ kmsg header k l fmt ... ] is like [ msg header l fmt ] but calls [ k ( ) ] before returning . before returning. *) val show : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a val err : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a val warn : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a val info : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a val debug : ?header:string -> ('a, Format.formatter, unit, unit) format4 -> 'a * { 1 Log level and output } val level : unit -> level option val set_level : level option -> unit val set_formatter : [`All | `Level of level ] -> Format.formatter -> unit * [ set_formatter spec ppf ] sets the formatter for a given level or for all the levels according to [ spec ] . Initially the formatter of level [ Show ] is { ! Format.std_formatter } and all the other level formatters are { ! . for all the levels according to [spec]. Initially the formatter of level [Show] is {!Format.std_formatter} and all the other level formatters are {!Format.err_formatter}. *) * { 1 Log monitoring } val err_count : unit -> int * [ err_count ( ) ] is the number of messages logged with level [ Error ] . val warn_count : unit -> int end module Debug : sig val enter : unit -> unit * [ enter ( ) ] stops and enters the JavaScript debugger ( if available ) . val pp_v : Format.formatter -> < .. > Js.t -> unit * [ pp_v v ] applies the method [ toString ] to [ v ] and prints the the resulting string on [ ppf ] . the resulting string on [ppf]. *) val log : < .. > Js.t -> unit end --------------------------------------------------------------------------- Copyright ( c ) 2015 . All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . 3 . Neither the name of nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . --------------------------------------------------------------------------- Copyright (c) 2015 Daniel C. BΓΌnzli. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Daniel C. BΓΌnzli nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*)
878a54c7317bff8479ce418f79b5f3324d0dd9f8b65f3ad141ce28fdb71264ce
walmartlabs/lacinia
schema-1.clj
(ns my.clojure-game-geek.schema "Contains custom resolvers and a function to provide the full schema." (:require [clojure.java.io :as io] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.schema :as schema] [clojure.edn :as edn])) (defn resolve-game-by-id [games-map context args value] (let [{:keys [id]} args] (get games-map id))) (defn resolver-map [] (let [cgg-data (-> (io/resource "cgg-data.edn") slurp edn/read-string) games-map (->> cgg-data :games (reduce #(assoc %1 (:id %2) %2) {}))] {:Query/gameById (partial resolve-game-by-id games-map)})) (defn load-schema [] (-> (io/resource "cgg-schema.edn") slurp edn/read-string (util/inject-resolvers (resolver-map)) schema/compile))
null
https://raw.githubusercontent.com/walmartlabs/lacinia/66056ff3588a7966e7ae3e34b79ad876d4982af2/docs/_examples/tutorial/schema-1.clj
clojure
(ns my.clojure-game-geek.schema "Contains custom resolvers and a function to provide the full schema." (:require [clojure.java.io :as io] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.schema :as schema] [clojure.edn :as edn])) (defn resolve-game-by-id [games-map context args value] (let [{:keys [id]} args] (get games-map id))) (defn resolver-map [] (let [cgg-data (-> (io/resource "cgg-data.edn") slurp edn/read-string) games-map (->> cgg-data :games (reduce #(assoc %1 (:id %2) %2) {}))] {:Query/gameById (partial resolve-game-by-id games-map)})) (defn load-schema [] (-> (io/resource "cgg-schema.edn") slurp edn/read-string (util/inject-resolvers (resolver-map)) schema/compile))
f90900b5d660b5d140f375949293a9154958fd75afaacd19416d80a521ed1357
ryukinix/dotfiles
client.lisp
;;;; client.lisp (in-package #:quicklisp-client) (defvar *quickload-verbose* nil "When NIL, show terse output when quickloading a system. Otherwise, show normal compile and load output.") (defvar *quickload-prompt* nil "When NIL, quickload systems without prompting for enter to continue, otherwise proceed directly without user intervention.") (defvar *quickload-explain* t) (define-condition system-not-quickloadable (error) ((system :initarg :system :reader not-quickloadable-system))) (defun maybe-silence (silent stream) (or (and silent (make-broadcast-stream)) stream)) (defgeneric quickload (systems &key verbose silent prompt explain &allow-other-keys) (:documentation "Load SYSTEMS the quicklisp way. SYSTEMS is a designator for a list of things to be loaded.") (:method (systems &key (prompt *quickload-prompt*) (silent nil) (verbose *quickload-verbose*) &allow-other-keys) (let ((*standard-output* (maybe-silence silent *standard-output*)) (*trace-output* (maybe-silence silent *trace-output*))) (unless (listp systems) (setf systems (list systems))) (dolist (thing systems systems) (flet ((ql () (autoload-system-and-dependencies thing :prompt prompt))) (tagbody :start (restart-case (if verbose (ql) (call-with-quiet-compilation #'ql)) (register-local-projects () :report "Register local projects and try again." (register-local-projects) (go :start))))))))) (defmethod quickload :around (systems &key verbose prompt explain &allow-other-keys) (declare (ignorable systems verbose prompt explain)) (with-consistent-dists (call-next-method))) (defun system-list () (provided-systems t)) (defun update-dist (dist &key (prompt t)) (when (stringp dist) (setf dist (find-dist dist))) (let ((new (available-update dist))) (cond (new (show-update-report dist new) (when (or (not prompt) (press-enter-to-continue)) (update-in-place dist new))) ((not (subscribedp dist)) (format t "~&You are not subscribed to ~S." (name dist))) (t (format t "~&You already have the latest version of ~S: ~A.~%" (name dist) (version dist)))))) (defun update-all-dists (&key (prompt t)) (let ((dists (remove-if-not 'subscribedp (all-dists)))) (format t "~&~D dist~:P to check.~%" (length dists)) (dolist (old dists) (with-simple-restart (skip "Skip update of dist ~S" (name old)) (update-dist old :prompt prompt))))) (defun available-dist-versions (name) (available-versions (find-dist-or-lose name))) (defun help () "For help with Quicklisp, see /") (defun uninstall (system-name) (let ((system (find-system system-name))) (cond (system (ql-dist:uninstall system)) (t (warn "Unknown system ~S" system-name) nil)))) (defun uninstall-dist (name) (let ((dist (find-dist name))) (when dist (ql-dist:uninstall dist)))) (defun write-asdf-manifest-file (output-file &key (if-exists :rename-and-delete) exclude-local-projects) "Write a list of system file pathnames to OUTPUT-FILE, one per line, in order of descending QL-DIST:PREFERENCE." (when (or (eql output-file nil) (eql output-file t)) (setf output-file (qmerge "manifest.txt"))) (with-open-file (stream output-file :direction :output :if-exists if-exists) (unless exclude-local-projects (register-local-projects) (dolist (system-file (list-local-projects)) (let* ((enough (enough-namestring system-file output-file)) (native (native-namestring enough))) (write-line native stream)))) (with-consistent-dists (let ((systems (provided-systems t)) (already-seen (make-hash-table :test 'equal))) (dolist (system (sort systems #'> :key #'preference)) ;; FIXME: find-asdf-system-file does another find-system ;; behind the scenes. Bogus. Should be a better way to go ;; from system object to system file. (let* ((system-file (find-asdf-system-file (name system))) (enough (and system-file (enough-namestring system-file output-file))) (native (and enough (native-namestring enough)))) (when (and native (not (gethash native already-seen))) (setf (gethash native already-seen) native) (format stream "~A~%" native))))))) (probe-file output-file)) (defun where-is-system (name) "Return the pathname to the source directory of ASDF system with the given NAME, or NIL if no system by that name can be found known." (let ((system (asdf:find-system name nil))) (when system (asdf:system-source-directory system))))
null
https://raw.githubusercontent.com/ryukinix/dotfiles/19678ea571c9afde8bd662a2bf4eae0bfea840d0/.quicklisp/quicklisp/client.lisp
lisp
client.lisp FIXME: find-asdf-system-file does another find-system behind the scenes. Bogus. Should be a better way to go from system object to system file.
(in-package #:quicklisp-client) (defvar *quickload-verbose* nil "When NIL, show terse output when quickloading a system. Otherwise, show normal compile and load output.") (defvar *quickload-prompt* nil "When NIL, quickload systems without prompting for enter to continue, otherwise proceed directly without user intervention.") (defvar *quickload-explain* t) (define-condition system-not-quickloadable (error) ((system :initarg :system :reader not-quickloadable-system))) (defun maybe-silence (silent stream) (or (and silent (make-broadcast-stream)) stream)) (defgeneric quickload (systems &key verbose silent prompt explain &allow-other-keys) (:documentation "Load SYSTEMS the quicklisp way. SYSTEMS is a designator for a list of things to be loaded.") (:method (systems &key (prompt *quickload-prompt*) (silent nil) (verbose *quickload-verbose*) &allow-other-keys) (let ((*standard-output* (maybe-silence silent *standard-output*)) (*trace-output* (maybe-silence silent *trace-output*))) (unless (listp systems) (setf systems (list systems))) (dolist (thing systems systems) (flet ((ql () (autoload-system-and-dependencies thing :prompt prompt))) (tagbody :start (restart-case (if verbose (ql) (call-with-quiet-compilation #'ql)) (register-local-projects () :report "Register local projects and try again." (register-local-projects) (go :start))))))))) (defmethod quickload :around (systems &key verbose prompt explain &allow-other-keys) (declare (ignorable systems verbose prompt explain)) (with-consistent-dists (call-next-method))) (defun system-list () (provided-systems t)) (defun update-dist (dist &key (prompt t)) (when (stringp dist) (setf dist (find-dist dist))) (let ((new (available-update dist))) (cond (new (show-update-report dist new) (when (or (not prompt) (press-enter-to-continue)) (update-in-place dist new))) ((not (subscribedp dist)) (format t "~&You are not subscribed to ~S." (name dist))) (t (format t "~&You already have the latest version of ~S: ~A.~%" (name dist) (version dist)))))) (defun update-all-dists (&key (prompt t)) (let ((dists (remove-if-not 'subscribedp (all-dists)))) (format t "~&~D dist~:P to check.~%" (length dists)) (dolist (old dists) (with-simple-restart (skip "Skip update of dist ~S" (name old)) (update-dist old :prompt prompt))))) (defun available-dist-versions (name) (available-versions (find-dist-or-lose name))) (defun help () "For help with Quicklisp, see /") (defun uninstall (system-name) (let ((system (find-system system-name))) (cond (system (ql-dist:uninstall system)) (t (warn "Unknown system ~S" system-name) nil)))) (defun uninstall-dist (name) (let ((dist (find-dist name))) (when dist (ql-dist:uninstall dist)))) (defun write-asdf-manifest-file (output-file &key (if-exists :rename-and-delete) exclude-local-projects) "Write a list of system file pathnames to OUTPUT-FILE, one per line, in order of descending QL-DIST:PREFERENCE." (when (or (eql output-file nil) (eql output-file t)) (setf output-file (qmerge "manifest.txt"))) (with-open-file (stream output-file :direction :output :if-exists if-exists) (unless exclude-local-projects (register-local-projects) (dolist (system-file (list-local-projects)) (let* ((enough (enough-namestring system-file output-file)) (native (native-namestring enough))) (write-line native stream)))) (with-consistent-dists (let ((systems (provided-systems t)) (already-seen (make-hash-table :test 'equal))) (dolist (system (sort systems #'> :key #'preference)) (let* ((system-file (find-asdf-system-file (name system))) (enough (and system-file (enough-namestring system-file output-file))) (native (and enough (native-namestring enough)))) (when (and native (not (gethash native already-seen))) (setf (gethash native already-seen) native) (format stream "~A~%" native))))))) (probe-file output-file)) (defun where-is-system (name) "Return the pathname to the source directory of ASDF system with the given NAME, or NIL if no system by that name can be found known." (let ((system (asdf:find-system name nil))) (when system (asdf:system-source-directory system))))
2ecaee47bb39c135a04f2c6fbe1cde349a1af4b17b2bdce3eeb140c5f4ecc340
argp/bap
netchan_cat.ml
Yet another ( slower ) " cat " implementation , it is just meant to be a showcase for integration with ocamlnet 's . showcase for integration with ocamlnet's Netchannels. *) let oc = Netchannels.lift_out (`Rec (new Netchannels.channel_of_output IO.stdout :> Netchannels.rec_out_channel)) let _ = Netchannels.with_in_obj_channel (Netchannels.lift_in (`Rec (new Netchannels.channel_of_input IO.stdin))) (fun ic -> try while true do oc # output_string (ic # input_line () ^ "\n"); oc # flush () done with End_of_file -> ())
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/examples/snippets/netchan_cat.ml
ocaml
Yet another ( slower ) " cat " implementation , it is just meant to be a showcase for integration with ocamlnet 's . showcase for integration with ocamlnet's Netchannels. *) let oc = Netchannels.lift_out (`Rec (new Netchannels.channel_of_output IO.stdout :> Netchannels.rec_out_channel)) let _ = Netchannels.with_in_obj_channel (Netchannels.lift_in (`Rec (new Netchannels.channel_of_input IO.stdin))) (fun ic -> try while true do oc # output_string (ic # input_line () ^ "\n"); oc # flush () done with End_of_file -> ())
ef2162a685e0e239329a6994af5f2d47ee39cc9d9be39eda867cf5bf5a38c9b3
ndmitchell/safe
Test.hs
# LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -fno - warn - orphans # module Main(main) where import Safe import Safe.Exact import qualified Safe.Foldable as F import Control.DeepSeq import Control.Exception import Control.Monad import Data.Char import Data.List import Data.Maybe import System.IO.Unsafe import Test.QuickCheck.Test import Test.QuickCheck hiding ((===)) --------------------------------------------------------------------- -- TESTS main :: IO () main = do -- All from the docs, so check they match tailMay dNil === Nothing tailMay [1,3,4] === Just [3,4] tailDef [12] [] === [12] tailDef [12] [1,3,4] === [3,4] tailNote "help me" dNil `err` "Safe.tailNote [], help me" tailNote "help me" [1,3,4] === [3,4] tailSafe [] === dNil tailSafe [1,3,4] === [3,4] findJust (== 2) [d1,2,3] === 2 findJust (== 4) [d1,2,3] `err` "Safe.findJust" F.findJust (== 2) [d1,2,3] === 2 F.findJust (== 4) [d1,2,3] `err` "Safe.Foldable.findJust" F.findJustDef 20 (== 4) [d1,2,3] === 20 F.findJustNote "my note" (== 4) [d1,2,3] `errs` ["Safe.Foldable.findJustNote","my note"] takeExact 3 [d1,2] `errs` ["Safe.Exact.takeExact","index=3","length=2"] takeExact (-1) [d1,2] `errs` ["Safe.Exact.takeExact","negative","index=-1"] takeExact 1 (takeExact 3 [d1,2]) === [1] -- test is lazy quickCheck_ $ \(Int10 i) (List10 (xs :: [Int])) -> do let (t,d) = splitAt i xs let good = length t == i let f name exact may note res = if good then do exact i xs === res note "foo" i xs === res may i xs === Just res else do exact i xs `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" i xs `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may i xs === Nothing f "take" takeExact takeExactMay takeExactNote t f "drop" dropExact dropExactMay dropExactNote d f "splitAt" splitAtExact splitAtExactMay splitAtExactNote (t, d) return True take 2 (zipExact [1,2,3] [1,2]) === [(1,1),(2,2)] zipExact [d1,2,3] [d1,2] `errs` ["Safe.Exact.zipExact","first list is longer than the second"] zipExact [d1,2] [d1,2,3] `errs` ["Safe.Exact.zipExact","second list is longer than the first"] zipExact dNil dNil === [] predMay (minBound :: Int) === Nothing succMay (maxBound :: Int) === Nothing predMay ((minBound + 1) :: Int) === Just minBound succMay ((maxBound - 1) :: Int) === Just maxBound quickCheck_ $ \(List10 (xs :: [Int])) x -> do let ys = maybeToList x ++ xs let res = zip xs ys let f name exact may note = if isNothing x then do exact xs ys === res note "foo" xs ys === res may xs ys === Just res else do exact xs ys `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" xs ys `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may xs ys === Nothing f "zip" zipExact zipExactMay zipExactNote f "zipWith" (zipWithExact (,)) (zipWithExactMay (,)) (`zipWithExactNote` (,)) return True take 2 (zip3Exact [1,2,3] [1,2,3] [1,2]) === [(1,1,1),(2,2,2)] zip3Exact [d1,2] [d1,2,3] [d1,2,3] `errs` ["Safe.Exact.zip3Exact","first list is shorter than the others"] zip3Exact [d1,2,3] [d1,2] [d1,2,3] `errs` ["Safe.Exact.zip3Exact","second list is shorter than the others"] zip3Exact [d1,2,3] [d1,2,3] [d1,2] `errs` ["Safe.Exact.zip3Exact","third list is shorter than the others"] zip3Exact dNil dNil dNil === [] quickCheck_ $ \(List10 (xs :: [Int])) x1 x2 -> do let ys = maybeToList x1 ++ xs let zs = maybeToList x2 ++ xs let res = zip3 xs ys zs let f name exact may note = if isNothing x1 && isNothing x2 then do exact xs ys zs === res note "foo" xs ys zs === res may xs ys zs === Just res else do exact xs ys zs `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" xs ys zs `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may xs ys zs === Nothing f "zip3" zip3Exact zip3ExactMay zip3ExactNote f "zipWith3" (zipWith3Exact (,,)) (zipWith3ExactMay (,,)) (flip zipWith3ExactNote (,,)) return True --------------------------------------------------------------------- UTILITIES quickCheck_ prop = do r <- quickCheckResult prop unless (isSuccess r) $ error "Test failed" d1 = 1 :: Double dNil = [] :: [Double] (===) :: (Show a, Eq a) => a -> a -> IO () (===) a b = when (a /= b) $ error $ "Mismatch: " ++ show a ++ " /= " ++ show b err :: NFData a => a -> String -> IO () err a b = errs a [b] errs :: NFData a => a -> [String] -> IO () errs a bs = do res <- try $ evaluate $ rnf a case res of Right v -> error $ "Expected error, but succeeded: " ++ show bs Left (msg :: SomeException) -> forM_ bs $ \b -> do let s = show msg unless (b `isInfixOf` s) $ error $ "Invalid error string, got " ++ show s ++ ", want " ++ show b let f xs = " " ++ map (\x -> if sepChar x then ' ' else x) xs ++ " " unless (f b `isInfixOf` f s) $ error $ "Not standalone error string, got " ++ show s ++ ", want " ++ show b sepChar x = isSpace x || x `elem` ",;." newtype Int10 = Int10 Int deriving Show instance Arbitrary Int10 where arbitrary = fmap Int10 $ choose (-3, 10) newtype List10 a = List10 [a] deriving Show instance Arbitrary a => Arbitrary (List10 a) where arbitrary = do i <- choose (0, 10); fmap List10 $ vector i instance Testable a => Testable (IO a) where property = property . unsafePerformIO
null
https://raw.githubusercontent.com/ndmitchell/safe/c490d6b36b461159ab29b3da9133948e4ec1db45/Test.hs
haskell
------------------------------------------------------------------- TESTS All from the docs, so check they match test is lazy -------------------------------------------------------------------
# LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -fno - warn - orphans # module Main(main) where import Safe import Safe.Exact import qualified Safe.Foldable as F import Control.DeepSeq import Control.Exception import Control.Monad import Data.Char import Data.List import Data.Maybe import System.IO.Unsafe import Test.QuickCheck.Test import Test.QuickCheck hiding ((===)) main :: IO () main = do tailMay dNil === Nothing tailMay [1,3,4] === Just [3,4] tailDef [12] [] === [12] tailDef [12] [1,3,4] === [3,4] tailNote "help me" dNil `err` "Safe.tailNote [], help me" tailNote "help me" [1,3,4] === [3,4] tailSafe [] === dNil tailSafe [1,3,4] === [3,4] findJust (== 2) [d1,2,3] === 2 findJust (== 4) [d1,2,3] `err` "Safe.findJust" F.findJust (== 2) [d1,2,3] === 2 F.findJust (== 4) [d1,2,3] `err` "Safe.Foldable.findJust" F.findJustDef 20 (== 4) [d1,2,3] === 20 F.findJustNote "my note" (== 4) [d1,2,3] `errs` ["Safe.Foldable.findJustNote","my note"] takeExact 3 [d1,2] `errs` ["Safe.Exact.takeExact","index=3","length=2"] takeExact (-1) [d1,2] `errs` ["Safe.Exact.takeExact","negative","index=-1"] quickCheck_ $ \(Int10 i) (List10 (xs :: [Int])) -> do let (t,d) = splitAt i xs let good = length t == i let f name exact may note res = if good then do exact i xs === res note "foo" i xs === res may i xs === Just res else do exact i xs `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" i xs `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may i xs === Nothing f "take" takeExact takeExactMay takeExactNote t f "drop" dropExact dropExactMay dropExactNote d f "splitAt" splitAtExact splitAtExactMay splitAtExactNote (t, d) return True take 2 (zipExact [1,2,3] [1,2]) === [(1,1),(2,2)] zipExact [d1,2,3] [d1,2] `errs` ["Safe.Exact.zipExact","first list is longer than the second"] zipExact [d1,2] [d1,2,3] `errs` ["Safe.Exact.zipExact","second list is longer than the first"] zipExact dNil dNil === [] predMay (minBound :: Int) === Nothing succMay (maxBound :: Int) === Nothing predMay ((minBound + 1) :: Int) === Just minBound succMay ((maxBound - 1) :: Int) === Just maxBound quickCheck_ $ \(List10 (xs :: [Int])) x -> do let ys = maybeToList x ++ xs let res = zip xs ys let f name exact may note = if isNothing x then do exact xs ys === res note "foo" xs ys === res may xs ys === Just res else do exact xs ys `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" xs ys `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may xs ys === Nothing f "zip" zipExact zipExactMay zipExactNote f "zipWith" (zipWithExact (,)) (zipWithExactMay (,)) (`zipWithExactNote` (,)) return True take 2 (zip3Exact [1,2,3] [1,2,3] [1,2]) === [(1,1,1),(2,2,2)] zip3Exact [d1,2] [d1,2,3] [d1,2,3] `errs` ["Safe.Exact.zip3Exact","first list is shorter than the others"] zip3Exact [d1,2,3] [d1,2] [d1,2,3] `errs` ["Safe.Exact.zip3Exact","second list is shorter than the others"] zip3Exact [d1,2,3] [d1,2,3] [d1,2] `errs` ["Safe.Exact.zip3Exact","third list is shorter than the others"] zip3Exact dNil dNil dNil === [] quickCheck_ $ \(List10 (xs :: [Int])) x1 x2 -> do let ys = maybeToList x1 ++ xs let zs = maybeToList x2 ++ xs let res = zip3 xs ys zs let f name exact may note = if isNothing x1 && isNothing x2 then do exact xs ys zs === res note "foo" xs ys zs === res may xs ys zs === Just res else do exact xs ys zs `err` ("Safe.Exact." ++ name ++ "Exact") note "foo" xs ys zs `errs` ["Safe.Exact." ++ name ++ "ExactNote","foo"] may xs ys zs === Nothing f "zip3" zip3Exact zip3ExactMay zip3ExactNote f "zipWith3" (zipWith3Exact (,,)) (zipWith3ExactMay (,,)) (flip zipWith3ExactNote (,,)) return True UTILITIES quickCheck_ prop = do r <- quickCheckResult prop unless (isSuccess r) $ error "Test failed" d1 = 1 :: Double dNil = [] :: [Double] (===) :: (Show a, Eq a) => a -> a -> IO () (===) a b = when (a /= b) $ error $ "Mismatch: " ++ show a ++ " /= " ++ show b err :: NFData a => a -> String -> IO () err a b = errs a [b] errs :: NFData a => a -> [String] -> IO () errs a bs = do res <- try $ evaluate $ rnf a case res of Right v -> error $ "Expected error, but succeeded: " ++ show bs Left (msg :: SomeException) -> forM_ bs $ \b -> do let s = show msg unless (b `isInfixOf` s) $ error $ "Invalid error string, got " ++ show s ++ ", want " ++ show b let f xs = " " ++ map (\x -> if sepChar x then ' ' else x) xs ++ " " unless (f b `isInfixOf` f s) $ error $ "Not standalone error string, got " ++ show s ++ ", want " ++ show b sepChar x = isSpace x || x `elem` ",;." newtype Int10 = Int10 Int deriving Show instance Arbitrary Int10 where arbitrary = fmap Int10 $ choose (-3, 10) newtype List10 a = List10 [a] deriving Show instance Arbitrary a => Arbitrary (List10 a) where arbitrary = do i <- choose (0, 10); fmap List10 $ vector i instance Testable a => Testable (IO a) where property = property . unsafePerformIO
f6e479a1bdb5d035275e8e919677f7b1ae0b48f21564beb0c1c02abb09d83684
ragkousism/Guix-on-Hurd
irc.scm
;;; GNU Guix --- Functional package management for GNU Copyright Β© 2013 < > Copyright Β© 2014 < > Copyright Β© 2015 < > Copyright Β© 2015 , 2016 < > Copyright Β© 2016 ng0 < > Copyright Β© 2017 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . (define-module (gnu packages irc) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix download) #:use-module (guix packages) #:use-module (guix build-system cmake) #:use-module (guix build-system gnu) #:use-module (guix build-system python) #:use-module (gnu packages) #:use-module (gnu packages aspell) #:use-module (gnu packages autogen) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages backup) #:use-module (gnu packages compression) #:use-module (gnu packages curl) #:use-module (gnu packages cyrus-sasl) #:use-module (gnu packages databases) #:use-module (gnu packages file) #:use-module (gnu packages gettext) #:use-module (gnu packages glib) #:use-module (gnu packages gnupg) #:use-module (gnu packages guile) #:use-module (gnu packages lua) #:use-module (gnu packages ncurses) #:use-module (gnu packages kde) #:use-module (gnu packages kde-frameworks) #:use-module (gnu packages perl) #:use-module (gnu packages pkg-config) #:use-module (gnu packages python) #:use-module (gnu packages ruby) #:use-module (gnu packages qt) #:use-module (gnu packages tcl) #:use-module (gnu packages tls) #:use-module (gnu packages web)) (define-public quassel (package (name "quassel") (version "0.12.4") (source (origin (method url-fetch) (uri (string-append "-irc.org/pub/quassel-" version ".tar.bz2")) (sha256 (base32 "0ka456fb8ha3w7g74xlzfg6w4azxjjxgrhl4aqpbwg3lnd6fbr4k")))) (build-system cmake-build-system) (arguments The three binaries are not mutually exlusive , and are all built ;; by default. " -DWANT_QTCLIENT = OFF " ; 5.0 MiB " -DWANT_CORE = OFF " ; 2.3 MiB " -DWANT_MONO = OFF " ; 6.3 MiB "-DUSE_QT5=ON" ; default is qt4 "-DWITH_KDE=OFF" ; no to integration "-DWITH_OXYGEN=ON" ; on=embed icons "-DWITH_WEBKIT=OFF") ; qtwebkit isn't packaged #:tests? #f)) ; no test target (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("extra-cmake-modules" ,extra-cmake-modules) ("oxygen-icons" ,oxygen-icons) ("qca" ,qca) ("qtbase", qtbase) ("qttools" ,qttools) ("qtscript" ,qtscript) ("snorenotify" ,snorenotify) ("zlib" ,zlib))) (home-page "-irc.org/") (synopsis "Distributed IRC client") (description "Quassel is a distributed IRC client, meaning that one or more clients can attach to and detach from the central core. It resembles the popular combination of screen and a text-based IRC client such as WeeChat or irssi, but graphical.") (license (list license:gpl2 license:gpl3)))) ;; dual licensed (define-public irssi (package (name "irssi") (version "1.0.0") (source (origin (method url-fetch) (uri (string-append "/" "releases/download/" version "/irssi-" version ".tar.xz")) (sha256 (base32 "1f2gmr5nynagwi4wx3yprhzfpg4ww6r7ff395b0a48d0qqgkr2ka")))) (build-system gnu-build-system) (arguments `(#:phases (modify-phases %standard-phases (replace 'configure (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (setenv "CONFIG_SHELL" (which "bash")) (zero? (system* "./configure" (string-append "--prefix=" out) (string-append "--with-proxy") (string-append "--with-socks") (string-append "--with-bot"))))))))) (inputs `(("glib" ,glib) ("ncurses" ,ncurses) ("openssl" ,openssl) ("perl" ,perl))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "/") (synopsis "Terminal-based IRC client") (description "Irssi is a terminal based IRC client for UNIX systems. It also supports SILC and ICB protocols via plugins.") (license license:gpl2+))) (define-public weechat (package (name "weechat") (version "1.7") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.xz")) (sha256 (base32 "1crdwlxj5liik32svflfac0s87vm6p8xm208yndigzsbg8rli4sr")) (patches (search-patches "weechat-python.patch")))) (build-system gnu-build-system) (native-inputs `(("autoconf" ,autoconf) ("pkg-config" ,pkg-config) ("file" ,file) ("autogen" ,autogen) ("automake" ,automake) ("libtool" ,libtool))) (inputs `(("ncurses" ,ncurses) ("diffutils" ,diffutils) ("gettext" ,gettext-minimal) ("libltdl" ,libltdl) ("libgcrypt" ,libgcrypt "out") ("zlib" ,zlib) ("aspell" ,aspell) ("curl" ,curl) ("gnutls" ,gnutls) ("guile" ,guile-2.0) ("openssl" ,openssl) ("cyrus-sasl" ,cyrus-sasl) ("lua" ,lua-5.1) ("python" ,python-2) ("perl" ,perl) ("tcl" ,tcl))) (arguments `(#:configure-flags (list (string-append "--with-tclconfig=" (assoc-ref %build-inputs "tcl") "/lib")) #:phases (modify-phases %standard-phases (add-before 'configure 'autogen (lambda _ (zero? (system* "./autogen.sh")))) (add-after 'install 'wrap (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (py2 (assoc-ref inputs "python"))) (wrap-program (string-append out "/bin/weechat") `("PATH" ":" prefix (,(string-append py2 "/bin")))) #t)))))) (synopsis "Extensible chat client") (description "WeeChat (Wee Enhanced Environment for Chat) is an Internet Relay Chat client, which is designed to be light and fast. The client uses a curses frontend, and there are remote interfaces for Web, Qt, Android and Emacs. In WeeChat everything can be done with a keyboard, though it also supports mouse. It is customizable and extensible with plugins and scripts.") (home-page "/") (license license:gpl3))) (define-public ircii (package (name "ircii") (version "20151120") (source (origin (method url-fetch) (uri (string-append "/" name "-" version ".tar.gz")) (sha256 (base32 "178dc279f5j894qvp96dzz7c0jpryqlcqw5g0dc9yaxg9kgw1lqm")))) (build-system gnu-build-system) TODO : We should package a small socks4/5 library / server to configure ircii with socks client . ` ghc - socks ' pulls in lots of haskell , which ;; is too big. (arguments `(#:tests? #f #:configure-flags (list "--enable-ipv6" "--with-emacs-meta-keys" (string-append "--with-openssl=" (assoc-ref %build-inputs "openssl"))) #:phases (modify-phases %standard-phases (add-after 'unpack 'patch-bsdinstall-absolute-path-bins (lambda* (#:key inputs #:allow-other-keys) (substitute* "bsdinstall" (("/bin/strip") "strip") (("/bin/cp") "cp") (("/bin/chmod") "chmod") (("/etc/chown") "chown") (("/bin/chgrp") "chgrp") (("/bin/mkdir") "mkdir") (("/bin/rm") "rm") (("/bin/mv") "mv"))))))) (inputs `(("ncurses" ,ncurses) ("openssl" ,openssl))) (native-inputs `(("pkg-config" ,pkg-config) ("perl" ,perl))) (home-page "/") (synopsis "Terminal-based IRC and ICB client") (description "ircII is a terminal based IRC and ICB client for UNIX systems.") (license license:bsd-3))) (define-public ii (package (name "ii") (version "1.7") (source (origin (method url-fetch) (uri (string-append "/" name "-" version ".tar.gz")) (sha256 (base32 "176cqwnn6h7w4kbfd66hzqa243l26pqp2b06bii0nmnm0rkaqwis")))) (build-system gnu-build-system) (arguments `(#:tests? #f ; no tests #:make-flags (list (string-append "PREFIX=" %output) "CC=gcc") #:phases (modify-phases %standard-phases (delete 'configure)))) ; no configure (home-page "/") (synopsis "FIFO and file system based IRC client") (description "ii (Irc it) is a minimalist FIFO and file system based IRC client.") (license license:expat))) (define-public sic (package (name "sic") (version "1.2") (source (origin (method url-fetch) (uri (string-append "/" name "-" version ".tar.gz")) (sha256 (base32 "11aiavxp44yayibc58bvimi8mrxvbw1plbci8cnbl4syk42zj1xc")))) (build-system gnu-build-system) (arguments `(#:tests? #f ; no tests #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:phases (modify-phases %standard-phases (delete 'configure)))) ; no configure (home-page "/") (synopsis "Simple IRC client") (description "sic is a simple IRC client, even more minimalistic than ii.") (license license:expat))) (define-public limnoria (package (name "limnoria") (version "2016.08.07") (source (origin (method url-fetch) (uri (pypi-uri "limnoria" version)) (sha256 (base32 "0w1d98hfhn4iqrczam7zahhqsvxa79n3xfcrm4jwkg5lba4f9ccm")))) (build-system python-build-system) (inputs `(("python-pytz" ,python-pytz) ("python-chardet" ,python-chardet) ("python-dateutil" ,python-dateutil) ("python-gnupg" ,python-gnupg) ("python-feedparser" ,python-feedparser) ("python-sqlalchemy" ,python-sqlalchemy) ("python-socksipy-branch" ,python-socksipy-branch) ("python-ecdsa" ,python-ecdsa))) (native-inputs `(("python-mock" ,python-mock))) ;; Despite the existence of a test folder there is no test phase. ;; We need to package and write ;; our own testphase. (arguments `(#:tests? #f)) (home-page "") (synopsis "Modified version of Supybot (an IRC bot and framework)") (description "Modified version of Supybot with Python 3 and IRCv3 support, embedded web server, translations (fr, fi, it, hu, de), and many other enhancements and bug fixes.") (license license:bsd-3))) (define-public epic5 (package (name "epic5") (version "2.0.1") (source (origin (method url-fetch) (uri (string-append "/" "epic/EPIC5-PRODUCTION/" name "-" version ".tar.xz")) (sha256 (base32 "1ap73d5f4vccxjaaq249zh981z85106vvqmxfm4plvy76b40y9jm")))) (build-system gnu-build-system) (arguments `(#:test-target "test" #:phases (modify-phases %standard-phases (add-after 'unpack 'patch-perl (lambda _ (substitute* "regress/crash-irc" (("perl5") (which "perl"))) #t)) (add-after 'unpack 'patch-bsdinstall ;; If we just remove /bin/ some part of the bsdinstall breaks. Furthermore bsdinstalls has a reference to /etc / here , which ;; means if we leave /etc/ in, install fails. (lambda _ (substitute* "bsdinstall" (("/bin/strip") "strip") (("/bin/cp") "cp") (("/bin/chmod") "chmod") (("/bin/chgrp") "chgrp") (("/bin/mkdir") "mkdir") (("/bin/rm") "rm") (("/bin/mv") "mv") (("/etc/") "")) #t)) (replace 'configure (lambda* (#:key outputs #:allow-other-keys) ;; The tarball uses a very old version of autconf. It does not ;; understand extra flags like `--enable-fast-install', so ;; we need to invoke it with just what it understands. (let ((out (assoc-ref outputs "out"))) ;; 'configure' doesn't understand '--host'. ,@(if (%current-target-system) `((setenv "CHOST" ,(%current-target-system))) '()) (setenv "CONFIG_SHELL" (which "bash")) (setenv "SHELL" (which "bash")) (zero? (system* "./configure" (string-append "--prefix=" out) "--with-ipv6" "--with-libarchive" ;; We use libressl because openssl does not come ;; with the lib/libssl.a which is needed for epic5. ;; XXX: No matter which implementation is chosen, ;; epic5 fails to connect to tls ports of roundrobin ;; irc networks. This however is believed to be an protocol issue at epic5 related to ircd . (string-append "--with-ssl=" (assoc-ref %build-inputs "libressl")) (string-append "--with-tcl=" (assoc-ref %build-inputs "tcl") "/lib/tclConfig.sh"))))))))) (inputs `(("libressl" ,libressl) ("ncurses" ,ncurses) ("libarchive" ,libarchive) ; CHANGELOG: "Support for loading zip files" ("perl" ,perl) ("tcl" ,tcl) ("ruby" ,ruby))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "") (synopsis "Epic5 IRC Client") (description "EPIC is a IRC client that has been under active development for over 20 years. It is stable and mature, and offers an excellent ircII interface for those who are accustomed to the ircII way of doing things.") (license (list license:bsd-3 license:isc license:bsd-4 The epic license is equal to the standard three - clause BSD license except that you are not permitted to remove the ;; "Redistribution is permitted" clause of the license if you ;; distribute binaries. (license:non-copyleft "")))))
null
https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/irc.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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. by default. 5.0 MiB 2.3 MiB 6.3 MiB default is qt4 no to integration on=embed icons qtwebkit isn't packaged no test target dual licensed is too big. no tests no configure no tests no configure Despite the existence of a test folder there is no test phase. We need to package and write our own testphase. If we just remove /bin/ some part of the bsdinstall breaks. means if we leave /etc/ in, install fails. The tarball uses a very old version of autconf. It does not understand extra flags like `--enable-fast-install', so we need to invoke it with just what it understands. 'configure' doesn't understand '--host'. We use libressl because openssl does not come with the lib/libssl.a which is needed for epic5. XXX: No matter which implementation is chosen, epic5 fails to connect to tls ports of roundrobin irc networks. This however is believed to be an CHANGELOG: "Support for loading zip files" "Redistribution is permitted" clause of the license if you distribute binaries.
Copyright Β© 2013 < > Copyright Β© 2014 < > Copyright Β© 2015 < > Copyright Β© 2015 , 2016 < > Copyright Β© 2016 ng0 < > Copyright Β© 2017 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages irc) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix download) #:use-module (guix packages) #:use-module (guix build-system cmake) #:use-module (guix build-system gnu) #:use-module (guix build-system python) #:use-module (gnu packages) #:use-module (gnu packages aspell) #:use-module (gnu packages autogen) #:use-module (gnu packages autotools) #:use-module (gnu packages base) #:use-module (gnu packages backup) #:use-module (gnu packages compression) #:use-module (gnu packages curl) #:use-module (gnu packages cyrus-sasl) #:use-module (gnu packages databases) #:use-module (gnu packages file) #:use-module (gnu packages gettext) #:use-module (gnu packages glib) #:use-module (gnu packages gnupg) #:use-module (gnu packages guile) #:use-module (gnu packages lua) #:use-module (gnu packages ncurses) #:use-module (gnu packages kde) #:use-module (gnu packages kde-frameworks) #:use-module (gnu packages perl) #:use-module (gnu packages pkg-config) #:use-module (gnu packages python) #:use-module (gnu packages ruby) #:use-module (gnu packages qt) #:use-module (gnu packages tcl) #:use-module (gnu packages tls) #:use-module (gnu packages web)) (define-public quassel (package (name "quassel") (version "0.12.4") (source (origin (method url-fetch) (uri (string-append "-irc.org/pub/quassel-" version ".tar.bz2")) (sha256 (base32 "0ka456fb8ha3w7g74xlzfg6w4azxjjxgrhl4aqpbwg3lnd6fbr4k")))) (build-system cmake-build-system) (arguments The three binaries are not mutually exlusive , and are all built (native-inputs `(("pkg-config" ,pkg-config))) (inputs `(("extra-cmake-modules" ,extra-cmake-modules) ("oxygen-icons" ,oxygen-icons) ("qca" ,qca) ("qtbase", qtbase) ("qttools" ,qttools) ("qtscript" ,qtscript) ("snorenotify" ,snorenotify) ("zlib" ,zlib))) (home-page "-irc.org/") (synopsis "Distributed IRC client") (description "Quassel is a distributed IRC client, meaning that one or more clients can attach to and detach from the central core. It resembles the popular combination of screen and a text-based IRC client such as WeeChat or irssi, but graphical.") (define-public irssi (package (name "irssi") (version "1.0.0") (source (origin (method url-fetch) (uri (string-append "/" "releases/download/" version "/irssi-" version ".tar.xz")) (sha256 (base32 "1f2gmr5nynagwi4wx3yprhzfpg4ww6r7ff395b0a48d0qqgkr2ka")))) (build-system gnu-build-system) (arguments `(#:phases (modify-phases %standard-phases (replace 'configure (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) (setenv "CONFIG_SHELL" (which "bash")) (zero? (system* "./configure" (string-append "--prefix=" out) (string-append "--with-proxy") (string-append "--with-socks") (string-append "--with-bot"))))))))) (inputs `(("glib" ,glib) ("ncurses" ,ncurses) ("openssl" ,openssl) ("perl" ,perl))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "/") (synopsis "Terminal-based IRC client") (description "Irssi is a terminal based IRC client for UNIX systems. It also supports SILC and ICB protocols via plugins.") (license license:gpl2+))) (define-public weechat (package (name "weechat") (version "1.7") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.xz")) (sha256 (base32 "1crdwlxj5liik32svflfac0s87vm6p8xm208yndigzsbg8rli4sr")) (patches (search-patches "weechat-python.patch")))) (build-system gnu-build-system) (native-inputs `(("autoconf" ,autoconf) ("pkg-config" ,pkg-config) ("file" ,file) ("autogen" ,autogen) ("automake" ,automake) ("libtool" ,libtool))) (inputs `(("ncurses" ,ncurses) ("diffutils" ,diffutils) ("gettext" ,gettext-minimal) ("libltdl" ,libltdl) ("libgcrypt" ,libgcrypt "out") ("zlib" ,zlib) ("aspell" ,aspell) ("curl" ,curl) ("gnutls" ,gnutls) ("guile" ,guile-2.0) ("openssl" ,openssl) ("cyrus-sasl" ,cyrus-sasl) ("lua" ,lua-5.1) ("python" ,python-2) ("perl" ,perl) ("tcl" ,tcl))) (arguments `(#:configure-flags (list (string-append "--with-tclconfig=" (assoc-ref %build-inputs "tcl") "/lib")) #:phases (modify-phases %standard-phases (add-before 'configure 'autogen (lambda _ (zero? (system* "./autogen.sh")))) (add-after 'install 'wrap (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (py2 (assoc-ref inputs "python"))) (wrap-program (string-append out "/bin/weechat") `("PATH" ":" prefix (,(string-append py2 "/bin")))) #t)))))) (synopsis "Extensible chat client") (description "WeeChat (Wee Enhanced Environment for Chat) is an Internet Relay Chat client, which is designed to be light and fast. The client uses a curses frontend, and there are remote interfaces for Web, Qt, Android and Emacs. In WeeChat everything can be done with a keyboard, though it also supports mouse. It is customizable and extensible with plugins and scripts.") (home-page "/") (license license:gpl3))) (define-public ircii (package (name "ircii") (version "20151120") (source (origin (method url-fetch) (uri (string-append "/" name "-" version ".tar.gz")) (sha256 (base32 "178dc279f5j894qvp96dzz7c0jpryqlcqw5g0dc9yaxg9kgw1lqm")))) (build-system gnu-build-system) TODO : We should package a small socks4/5 library / server to configure ircii with socks client . ` ghc - socks ' pulls in lots of haskell , which (arguments `(#:tests? #f #:configure-flags (list "--enable-ipv6" "--with-emacs-meta-keys" (string-append "--with-openssl=" (assoc-ref %build-inputs "openssl"))) #:phases (modify-phases %standard-phases (add-after 'unpack 'patch-bsdinstall-absolute-path-bins (lambda* (#:key inputs #:allow-other-keys) (substitute* "bsdinstall" (("/bin/strip") "strip") (("/bin/cp") "cp") (("/bin/chmod") "chmod") (("/etc/chown") "chown") (("/bin/chgrp") "chgrp") (("/bin/mkdir") "mkdir") (("/bin/rm") "rm") (("/bin/mv") "mv"))))))) (inputs `(("ncurses" ,ncurses) ("openssl" ,openssl))) (native-inputs `(("pkg-config" ,pkg-config) ("perl" ,perl))) (home-page "/") (synopsis "Terminal-based IRC and ICB client") (description "ircII is a terminal based IRC and ICB client for UNIX systems.") (license license:bsd-3))) (define-public ii (package (name "ii") (version "1.7") (source (origin (method url-fetch) (uri (string-append "/" name "-" version ".tar.gz")) (sha256 (base32 "176cqwnn6h7w4kbfd66hzqa243l26pqp2b06bii0nmnm0rkaqwis")))) (build-system gnu-build-system) (arguments #:make-flags (list (string-append "PREFIX=" %output) "CC=gcc") #:phases (modify-phases %standard-phases (home-page "/") (synopsis "FIFO and file system based IRC client") (description "ii (Irc it) is a minimalist FIFO and file system based IRC client.") (license license:expat))) (define-public sic (package (name "sic") (version "1.2") (source (origin (method url-fetch) (uri (string-append "/" name "-" version ".tar.gz")) (sha256 (base32 "11aiavxp44yayibc58bvimi8mrxvbw1plbci8cnbl4syk42zj1xc")))) (build-system gnu-build-system) (arguments #:make-flags (list "CC=gcc" (string-append "PREFIX=" %output)) #:phases (modify-phases %standard-phases (home-page "/") (synopsis "Simple IRC client") (description "sic is a simple IRC client, even more minimalistic than ii.") (license license:expat))) (define-public limnoria (package (name "limnoria") (version "2016.08.07") (source (origin (method url-fetch) (uri (pypi-uri "limnoria" version)) (sha256 (base32 "0w1d98hfhn4iqrczam7zahhqsvxa79n3xfcrm4jwkg5lba4f9ccm")))) (build-system python-build-system) (inputs `(("python-pytz" ,python-pytz) ("python-chardet" ,python-chardet) ("python-dateutil" ,python-dateutil) ("python-gnupg" ,python-gnupg) ("python-feedparser" ,python-feedparser) ("python-sqlalchemy" ,python-sqlalchemy) ("python-socksipy-branch" ,python-socksipy-branch) ("python-ecdsa" ,python-ecdsa))) (native-inputs `(("python-mock" ,python-mock))) (arguments `(#:tests? #f)) (home-page "") (synopsis "Modified version of Supybot (an IRC bot and framework)") (description "Modified version of Supybot with Python 3 and IRCv3 support, embedded web server, translations (fr, fi, it, hu, de), and many other enhancements and bug fixes.") (license license:bsd-3))) (define-public epic5 (package (name "epic5") (version "2.0.1") (source (origin (method url-fetch) (uri (string-append "/" "epic/EPIC5-PRODUCTION/" name "-" version ".tar.xz")) (sha256 (base32 "1ap73d5f4vccxjaaq249zh981z85106vvqmxfm4plvy76b40y9jm")))) (build-system gnu-build-system) (arguments `(#:test-target "test" #:phases (modify-phases %standard-phases (add-after 'unpack 'patch-perl (lambda _ (substitute* "regress/crash-irc" (("perl5") (which "perl"))) #t)) (add-after 'unpack 'patch-bsdinstall Furthermore bsdinstalls has a reference to /etc / here , which (lambda _ (substitute* "bsdinstall" (("/bin/strip") "strip") (("/bin/cp") "cp") (("/bin/chmod") "chmod") (("/bin/chgrp") "chgrp") (("/bin/mkdir") "mkdir") (("/bin/rm") "rm") (("/bin/mv") "mv") (("/etc/") "")) #t)) (replace 'configure (lambda* (#:key outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out"))) ,@(if (%current-target-system) `((setenv "CHOST" ,(%current-target-system))) '()) (setenv "CONFIG_SHELL" (which "bash")) (setenv "SHELL" (which "bash")) (zero? (system* "./configure" (string-append "--prefix=" out) "--with-ipv6" "--with-libarchive" protocol issue at epic5 related to ircd . (string-append "--with-ssl=" (assoc-ref %build-inputs "libressl")) (string-append "--with-tcl=" (assoc-ref %build-inputs "tcl") "/lib/tclConfig.sh"))))))))) (inputs `(("libressl" ,libressl) ("ncurses" ,ncurses) ("perl" ,perl) ("tcl" ,tcl) ("ruby" ,ruby))) (native-inputs `(("pkg-config" ,pkg-config))) (home-page "") (synopsis "Epic5 IRC Client") (description "EPIC is a IRC client that has been under active development for over 20 years. It is stable and mature, and offers an excellent ircII interface for those who are accustomed to the ircII way of doing things.") (license (list license:bsd-3 license:isc license:bsd-4 The epic license is equal to the standard three - clause BSD license except that you are not permitted to remove the (license:non-copyleft "")))))
bc03d5c651a34b6e67e580c2f4acaaf86a6837e33f3bbaa858d540b904f8b1e5
ParaPhraseAGH/erlang-mas
mas_conc_supervisor.erl
@author jstypka < > %% @version 1.0 -module(mas_conc_supervisor). -behaviour(gen_server). -include("mas.hrl"). %% API -export([start/2, go/1, close/1]). %% gen_server -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export_type([arenas/0]). -type sim_params() :: mas:sim_params(). -type arenas() :: dict:dict(mas:agent_behaviour(), pid()). %% ==================================================================== %% API functions %% ==================================================================== -spec start(sim_params(), config()) -> pid(). start(SP, Cf) -> {ok,Pid} = gen_server:start(?MODULE, [SP, Cf], []), Pid. -spec go(pid()) -> ok. go(Pid) -> gen_server:cast(Pid, go). -spec close(pid()) -> ok. close(Pid) -> gen_server:call(Pid, close, infinity). %% ==================================================================== %% Callbacks %% ==================================================================== -record(state, {arenas = dict:new() :: arenas(), sim_params :: sim_params(), config :: config()}). -type state() :: #state{}. -spec init(term()) -> {ok,state()} | {ok,state(),non_neg_integer()}. init([SP, Cf]) -> mas_misc_util:seed_random(), Interactions = mas_misc_util:determine_behaviours(Cf), ArenaList = [{Interaction, mas_conc_arena:start_link(self(), Interaction, SP, Cf)} || Interaction <- Interactions], Arenas = dict:from_list(ArenaList), [ok = mas_conc_arena:give_arenas(Pid, Arenas) || {_Interaction, Pid} <- ArenaList], mas_io_util:printArenas(ArenaList), {ok, #state{arenas = Arenas, config = Cf, sim_params = SP}}. -spec handle_call(term(),{pid(),term()},state()) -> {reply,term(),state()} | {reply,term(),state(),hibernate | infinity | non_neg_integer()} | {noreply,state()} | {noreply,state(),hibernate | infinity | non_neg_integer()} | {stop,term(),term(),state()} | {stop,term(),state()}. handle_call(close, _From, St) -> [mas_conc_arena:close(Pid) || {_Name,Pid} <- dict:to_list(St#state.arenas)], {stop, normal, ok, St}. -spec handle_cast(term(),state()) -> {noreply,state()} | {noreply,state(),hibernate | infinity | non_neg_integer()} | {stop,term(),state()}. handle_cast(go, St = #state{config = Cf, sim_params = SP}) -> Agents = mas_misc_util:generate_population(SP, Cf), _InitPopulation = [spawn(mas_conc_agent, start, [A, St#state.arenas, SP, Cf]) || A <- Agents], {noreply, St}. -spec handle_info(term(),state()) -> {noreply,state()} | {noreply,state(),hibernate | infinity | non_neg_integer()} | {stop,term(),state()}. handle_info(timeout, State) -> {stop, timeout, State}. -spec terminate(term(),state()) -> no_return(). terminate(_Reason, _State) -> ok. -spec code_change(term(),state(),term()) -> {ok, state()}. code_change(_OldVsn, State, _Extra) -> {ok, State}.
null
https://raw.githubusercontent.com/ParaPhraseAGH/erlang-mas/e53ac7ace59b50696bd5e89a1e710d88213e2b1d/src/concurrent/mas_conc_supervisor.erl
erlang
@version 1.0 API gen_server ==================================================================== API functions ==================================================================== ==================================================================== Callbacks ====================================================================
@author jstypka < > -module(mas_conc_supervisor). -behaviour(gen_server). -include("mas.hrl"). -export([start/2, go/1, close/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export_type([arenas/0]). -type sim_params() :: mas:sim_params(). -type arenas() :: dict:dict(mas:agent_behaviour(), pid()). -spec start(sim_params(), config()) -> pid(). start(SP, Cf) -> {ok,Pid} = gen_server:start(?MODULE, [SP, Cf], []), Pid. -spec go(pid()) -> ok. go(Pid) -> gen_server:cast(Pid, go). -spec close(pid()) -> ok. close(Pid) -> gen_server:call(Pid, close, infinity). -record(state, {arenas = dict:new() :: arenas(), sim_params :: sim_params(), config :: config()}). -type state() :: #state{}. -spec init(term()) -> {ok,state()} | {ok,state(),non_neg_integer()}. init([SP, Cf]) -> mas_misc_util:seed_random(), Interactions = mas_misc_util:determine_behaviours(Cf), ArenaList = [{Interaction, mas_conc_arena:start_link(self(), Interaction, SP, Cf)} || Interaction <- Interactions], Arenas = dict:from_list(ArenaList), [ok = mas_conc_arena:give_arenas(Pid, Arenas) || {_Interaction, Pid} <- ArenaList], mas_io_util:printArenas(ArenaList), {ok, #state{arenas = Arenas, config = Cf, sim_params = SP}}. -spec handle_call(term(),{pid(),term()},state()) -> {reply,term(),state()} | {reply,term(),state(),hibernate | infinity | non_neg_integer()} | {noreply,state()} | {noreply,state(),hibernate | infinity | non_neg_integer()} | {stop,term(),term(),state()} | {stop,term(),state()}. handle_call(close, _From, St) -> [mas_conc_arena:close(Pid) || {_Name,Pid} <- dict:to_list(St#state.arenas)], {stop, normal, ok, St}. -spec handle_cast(term(),state()) -> {noreply,state()} | {noreply,state(),hibernate | infinity | non_neg_integer()} | {stop,term(),state()}. handle_cast(go, St = #state{config = Cf, sim_params = SP}) -> Agents = mas_misc_util:generate_population(SP, Cf), _InitPopulation = [spawn(mas_conc_agent, start, [A, St#state.arenas, SP, Cf]) || A <- Agents], {noreply, St}. -spec handle_info(term(),state()) -> {noreply,state()} | {noreply,state(),hibernate | infinity | non_neg_integer()} | {stop,term(),state()}. handle_info(timeout, State) -> {stop, timeout, State}. -spec terminate(term(),state()) -> no_return(). terminate(_Reason, _State) -> ok. -spec code_change(term(),state(),term()) -> {ok, state()}. code_change(_OldVsn, State, _Extra) -> {ok, State}.
55d802f9b3881834ebe5d7e872e716770a8a71da5bb600759599fc015a10bd99
WorksHub/client
tag_test.cljc
(ns wh.components.tag-test (:require [clojure.test :refer :all] [wh.components.tag :refer :all])) (def default-tags [{:id 1 :label "Clojure" :type :tech :subtype :software} {:id 2 :label "Common Lisp" :type :tech :subtype :software} {:id 3 :label "Smartphone" :type :tech :subtype :gadget} {:id -1 :label "Cat"}]) (deftest select-tags-test (testing "An empty search text returns all `tags`" (is (= default-tags (select-tags "" default-tags {:include-ids #{}})))) (testing "Tags should be searchable regardless of text case" (is (= [{:id 1, :label "Clojure", :type :tech, :subtype :software}] (select-tags "clojure" default-tags {:include-ids #{}})))) (testing "Tags w/ included IDs are picked up and marked `selected`" (is (= [{:id 2, :label "Common Lisp", :type :tech, :subtype :software, :selected true}] (select-tags "???" default-tags {:include-ids #{2}})))) (testing "Selected tags come first, before non-selected matching ones" (is (= [{:id 2, :label "Common Lisp", :type :tech, :subtype :software, :selected true} {:id 1, :label "Clojure", :type :tech, :subtype :software}] (select-tags "Clojure" default-tags {:include-ids #{2}})))) (testing "It is possible to filter tags by their type and/or subtype" (is (empty? (select-tags "Clojure" default-tags {:include-ids #{} :type :non-tech}))) (is (= [{:id 1, :label "Clojure", :type :tech, :subtype :software} {:id 2, :label "Common Lisp", :type :tech, :subtype :software} {:id 3, :label "Smartphone", :type :tech, :subtype :gadget}] (select-tags "" default-tags {:include-ids #{} :type :tech}))) (is (= [{:id 1, :label "Clojure", :type :tech, :subtype :software} {:id 2, :label "Common Lisp", :type :tech, :subtype :software}] (select-tags "" default-tags {:include-ids #{} :type :tech :subtype :software}))) (is (= [{:id 1, :label "Clojure", :type :tech, :subtype :software}] (select-tags "Clo" default-tags {:include-ids #{} :type :tech})))))
null
https://raw.githubusercontent.com/WorksHub/client/add3a9a37eb3e9baa57b5c845ffed2e4d11b8714/common/test/wh/components/tag_test.cljc
clojure
(ns wh.components.tag-test (:require [clojure.test :refer :all] [wh.components.tag :refer :all])) (def default-tags [{:id 1 :label "Clojure" :type :tech :subtype :software} {:id 2 :label "Common Lisp" :type :tech :subtype :software} {:id 3 :label "Smartphone" :type :tech :subtype :gadget} {:id -1 :label "Cat"}]) (deftest select-tags-test (testing "An empty search text returns all `tags`" (is (= default-tags (select-tags "" default-tags {:include-ids #{}})))) (testing "Tags should be searchable regardless of text case" (is (= [{:id 1, :label "Clojure", :type :tech, :subtype :software}] (select-tags "clojure" default-tags {:include-ids #{}})))) (testing "Tags w/ included IDs are picked up and marked `selected`" (is (= [{:id 2, :label "Common Lisp", :type :tech, :subtype :software, :selected true}] (select-tags "???" default-tags {:include-ids #{2}})))) (testing "Selected tags come first, before non-selected matching ones" (is (= [{:id 2, :label "Common Lisp", :type :tech, :subtype :software, :selected true} {:id 1, :label "Clojure", :type :tech, :subtype :software}] (select-tags "Clojure" default-tags {:include-ids #{2}})))) (testing "It is possible to filter tags by their type and/or subtype" (is (empty? (select-tags "Clojure" default-tags {:include-ids #{} :type :non-tech}))) (is (= [{:id 1, :label "Clojure", :type :tech, :subtype :software} {:id 2, :label "Common Lisp", :type :tech, :subtype :software} {:id 3, :label "Smartphone", :type :tech, :subtype :gadget}] (select-tags "" default-tags {:include-ids #{} :type :tech}))) (is (= [{:id 1, :label "Clojure", :type :tech, :subtype :software} {:id 2, :label "Common Lisp", :type :tech, :subtype :software}] (select-tags "" default-tags {:include-ids #{} :type :tech :subtype :software}))) (is (= [{:id 1, :label "Clojure", :type :tech, :subtype :software}] (select-tags "Clo" default-tags {:include-ids #{} :type :tech})))))
4c39acf0d3034e8912f8a50c851a4ed1d282d060fd16eb616481cf226aadba1f
grin-compiler/ghc-wpc-sample-programs
HtmlParsec.hs
{-# LANGUAGE CPP #-} -- ------------------------------------------------------------ | Module : Text . . HtmlParsec Copyright : Copyright ( C ) 2005 License : MIT Maintainer : ( ) Stability : stable Portability : portable This parser tries to interprete everything as HTML no errors are emitted during parsing . If something looks weired , warning messages are inserted in the document tree . All filter are pure , errror handling and IO is done in ' Text . XML.HXT.Parser . HtmlParser ' or other modules Module : Text.XML.HXT.Parser.HtmlParsec Copyright : Copyright (C) 2005 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt () Stability : stable Portability: portable This parser tries to interprete everything as HTML no errors are emitted during parsing. If something looks weired, warning messages are inserted in the document tree. All filter are pure XmlFilter, errror handling and IO is done in 'Text.XML.HXT.Parser.HtmlParser' or other modules -} -- ------------------------------------------------------------ module Text.XML.HXT.Parser.HtmlParsec ( parseHtmlText , parseHtmlDocument , parseHtmlContent , isEmptyHtmlTag , isInnerHtmlTagOf , closesHtmlTag , emptyHtmlTags ) where #if MIN_VERSION_base(4,8,2) #else import Control.Applicative ((<$>)) #endif import Data.Char ( toLower , toUpper ) import Data.Char.Properties.XMLCharProps ( isXmlChar ) import Data.Maybe ( fromMaybe , fromJust ) import qualified Data.Map as M import Text.ParserCombinators.Parsec ( SourcePos , anyChar , between -- , char , eof , getPosition , many , many1 , noneOf , option , runParser , satisfy , string , try , (<|>) ) import Text.XML.HXT.DOM.Interface import Text.XML.HXT.DOM.XmlNode ( mkText' , mkError' , mkCdata' , mkCmt' , mkCharRef' , mkElement' , mkAttr' , mkDTDElem' , mkPi' , isEntityRef , getEntityRef ) import Text.XML.HXT.Parser.XmlTokenParser ( allBut , amp , dq , eq , gt , lt , name , pubidLiteral , skipS , skipS0 , sPace , sq , systemLiteral , checkString , singleCharsT , referenceT , mergeTextNodes ) import Text.XML.HXT.Parser.XmlParsec ( misc , parseXmlText , xMLDecl' ) import Text.XML.HXT.Parser.XmlCharParser ( xmlChar , SimpleXParser , withNormNewline ) import Text.XML.HXT.Parser.XhtmlEntities ( xhtmlEntities ) -- ------------------------------------------------------------ parseHtmlText :: String -> XmlTree -> XmlTrees parseHtmlText loc t = parseXmlText htmlDocument (withNormNewline ()) loc $ t -- ------------------------------------------------------------ parseHtmlFromString :: SimpleXParser XmlTrees -> String -> String -> XmlTrees parseHtmlFromString parser loc = either ((:[]) . mkError' c_err . (++ "\n") . show) id . runParser parser (withNormNewline ()) loc parseHtmlDocument :: String -> String -> XmlTrees parseHtmlDocument = parseHtmlFromString htmlDocument parseHtmlContent :: String -> XmlTrees parseHtmlContent = parseHtmlFromString htmlContent "string" -- ------------------------------------------------------------ type Context = (XmlTreeFl, OpenTags) type XmlTreeFl = XmlTrees -> XmlTrees type OpenTags = [(String, XmlTrees, XmlTreeFl)] -- ------------------------------------------------------------ htmlDocument :: SimpleXParser XmlTrees htmlDocument = do pl <- htmlProlog el <- htmlContent eof return (pl ++ el) htmlProlog :: SimpleXParser XmlTrees htmlProlog = do xml <- option [] ( try xMLDecl' <|> ( do pos <- getPosition checkString "<?" return $ [mkError' c_warn (show pos ++ " wrong XML declaration")] ) ) misc1 <- many misc dtdPart <- option [] ( try doctypedecl <|> ( do pos <- getPosition upperCaseString "<!DOCTYPE" return $ [mkError' c_warn (show pos ++ " HTML DOCTYPE declaration ignored")] ) ) return (xml ++ misc1 ++ dtdPart) doctypedecl :: SimpleXParser XmlTrees doctypedecl = between (upperCaseString "<!DOCTYPE") gt ( do skipS n <- name exId <- ( do skipS option [] externalID ) skipS0 return [mkDTDElem' DOCTYPE ((a_name, n) : exId) []] ) externalID :: SimpleXParser Attributes externalID = do upperCaseString k_public skipS pl <- pubidLiteral sl <- option "" $ try ( do skipS systemLiteral ) return $ (k_public, pl) : if null sl then [] else [(k_system, sl)] htmlContent :: SimpleXParser XmlTrees htmlContent = mergeTextNodes <$> htmlContent' htmlContent' :: SimpleXParser XmlTrees htmlContent' = option [] ( do context <- hContent (id, []) pos <- getPosition return $ closeTags pos context ) where closeTags _pos (body, []) = body [] closeTags pos' (body, ((tn, al, body1) : restOpen)) = closeTags pos' ( addHtmlWarn (show pos' ++ ": no closing tag found for \"<" ++ tn ++ " ...>\"") . addHtmlTag tn al body $ (body1, restOpen) ) -- ------------------------------------------------------------ hElement :: Context -> SimpleXParser Context hElement context = ( do t <- hSimpleData return (addHtmlElem t context) ) <|> hCloseTag context <|> hOpenTag context <|> ( do -- wrong tag, take it as text pos <- getPosition c <- xmlChar return ( addHtmlWarn (show pos ++ " markup char " ++ show c ++ " not allowed in this context") . addHtmlElem (mkText' [c]) $ context ) ) <|> ( do pos <- getPosition c <- anyChar return ( addHtmlWarn ( show pos ++ " illegal data in input or illegal XML char " ++ show c ++ " found and ignored, possibly wrong encoding scheme used") $ context ) ) hSimpleData :: SimpleXParser XmlTree hSimpleData = charData'' <|> hReference' <|> hComment <|> hpI <|> hcDSect where charData'' = do t <- many1 (satisfy (\ x -> isXmlChar x && not (x == '<' || x == '&'))) return (mkText' t) hCloseTag :: Context -> SimpleXParser Context hCloseTag context = do checkString "</" n <- lowerCaseName skipS0 pos <- getPosition checkSymbol gt ("closing > in tag \"</" ++ n ++ "\" expected") (closeTag pos n context) hOpenTag :: Context -> SimpleXParser Context hOpenTag context = ( do e <- hOpenTagStart hOpenTagRest e context ) hOpenTagStart :: SimpleXParser ((SourcePos, String), XmlTrees) hOpenTagStart = do np <- try ( do lt pos <- getPosition n <- lowerCaseName return (pos, n) ) skipS0 as <- hAttrList return (np, as) hOpenTagRest :: ((SourcePos, String), XmlTrees) -> Context -> SimpleXParser Context hOpenTagRest ((pos, tn), al) context = ( do checkString "/>" return (addHtmlTag tn al id context) ) <|> ( do context1 <- checkSymbol gt ("closing > in tag \"<" ++ tn ++ "...\" expected") context return ( let context2 = closePrevTag pos tn context1 in ( if isEmptyHtmlTag tn then addHtmlTag tn al id else openTag tn al ) context2 ) ) hAttrList :: SimpleXParser XmlTrees hAttrList = many (try hAttribute) where hAttribute = do n <- lowerCaseName v <- hAttrValue skipS0 return $ mkAttr' (mkName n) v hAttrValue :: SimpleXParser XmlTrees hAttrValue = option [] ( eq >> hAttrValue' ) hAttrValue' :: SimpleXParser XmlTrees hAttrValue' = try ( between dq dq (hAttrValue'' "&\"") ) <|> try ( between sq sq (hAttrValue'' "&\'") ) <|> ( do -- HTML allows unquoted attribute values cs <- many (noneOf " \r\t\n>\"\'") return [mkText' cs] ) hAttrValue'' :: String -> SimpleXParser XmlTrees hAttrValue'' notAllowed = many ( hReference' <|> singleCharsT notAllowed) hReference' :: SimpleXParser XmlTree hReference' = try hReferenceT <|> ( do amp return (mkText' "&") ) hReferenceT :: SimpleXParser XmlTree hReferenceT = do r <- referenceT return ( if isEntityRef r then substRef r else r ) where -- optimization: HTML entity refs are substituted by char refs, so a later entity ref substituion isn't required substRef r = case (lookup en xhtmlEntities) of Just i -> mkCharRef' i Nothing -> r -- not found: the entity ref remains as it is this is also done in the XML parser {- alternative def Nothing -> mkText' ("&" ++ en ++ ";") -- not found: the entity ref is taken as text -} where en = fromJust . getEntityRef $ r hContent :: Context -> SimpleXParser Context hContent context = option context ( hElement context >>= hContent ) -- ------------------------------------------------------------ -- hComment allows "--" in comments -- comment from XML spec does not hComment :: SimpleXParser XmlTree hComment = do checkString "<!--" pos <- getPosition c <- allBut many "-->" closeCmt pos c where closeCmt pos c = ( do checkString "-->" return (mkCmt' c) ) <|> ( return $ mkError' c_warn (show pos ++ " no closing comment sequence \"-->\" found") ) -- ------------------------------------------------------------ hpI :: SimpleXParser XmlTree hpI = checkString "<?" >> ( try ( do n <- name p <- sPace >> allBut many "?>" string "?>" >> return (mkPi' (mkName n) [mkAttr' (mkName a_value) [mkText' p]]) ) <|> ( do pos <- getPosition return $ mkError' c_warn (show pos ++ " illegal PI found") ) ) -- ------------------------------------------------------------ hcDSect :: SimpleXParser XmlTree hcDSect = do checkString "<![CDATA[" pos <- getPosition t <- allBut many "]]>" closeCD pos t where closeCD pos t = ( do checkString "]]>" return (mkCdata' t) ) <|> ( return $ mkError' c_warn (show pos ++ " no closing CDATA sequence \"]]>\" found") ) -- ------------------------------------------------------------ checkSymbol :: SimpleXParser () -> String -> Context -> SimpleXParser Context checkSymbol p msg context = ( p >> return context ) <|> ( do pos <- getPosition return $ addHtmlWarn (show pos ++ " " ++ msg) context ) lowerCaseName :: SimpleXParser String lowerCaseName = do n <- name return (map toLower n) upperCaseString :: String -> SimpleXParser () upperCaseString s = try (sequence (map (\ c -> satisfy (( == c) . toUpper)) s)) >> return () -- ------------------------------------------------------------ addHtmlTag :: String -> XmlTrees -> XmlTreeFl -> Context -> Context addHtmlTag tn al body context = e `seq` addHtmlElem e context where e = mkElement' (mkName tn) al (body []) addHtmlWarn :: String -> Context -> Context addHtmlWarn msg = addHtmlElem (mkError' c_warn msg) addHtmlElem :: XmlTree -> Context -> Context addHtmlElem elem' (body, openTags) = (body . (elem' :), openTags) openTag :: String -> XmlTrees -> Context -> Context openTag tn al (body, openTags) = (id, (tn, al, body) : openTags) closeTag :: SourcePos -> String -> Context -> Context closeTag pos n context | n `elem` (map ( \ (n1, _, _) -> n1) $ snd context) = closeTag' n context | otherwise = addHtmlWarn (show pos ++ " no opening tag found for </" ++ n ++ ">") . addHtmlTag n [] id $ context where closeTag' n' (body', (n1, al1, body1) : restOpen) = close context1 where context1 = addHtmlTag n1 al1 body' (body1, restOpen) close | n' == n1 = id | n1 `isInnerHtmlTagOf` n' = closeTag pos n' | otherwise = addHtmlWarn (show pos ++ " no closing tag found for \"<" ++ n1 ++ " ...>\"") . closeTag' n' closeTag' _ _ = error "illegal argument for closeTag'" closePrevTag :: SourcePos -> String -> Context -> Context closePrevTag _pos _n context@(_body, []) = context closePrevTag pos n context@(body, (n1, al1, body1) : restOpen) | n `closesHtmlTag` n1 = closePrevTag pos n ( addHtmlWarn (show pos ++ " tag \"<" ++ n1 ++ " ...>\" implicitly closed by opening tag \"<" ++ n ++ " ...>\"") . addHtmlTag n1 al1 body $ (body1, restOpen) ) | otherwise = context -- ------------------------------------------------------------ -- taken from HaXml and extended isEmptyHtmlTag :: String -> Bool isEmptyHtmlTag n = n `elem` emptyHtmlTags emptyHtmlTags :: [String] emptyHtmlTags = [ "area" , "base" , "br" , "col" , "frame" , "hr" , "img" , "input" , "link" , "meta" , "param" ] # INLINE emptyHtmlTags # isInnerHtmlTagOf :: String -> String -> Bool n `isInnerHtmlTagOf` tn = n `elem` ( fromMaybe [] . lookup tn $ [ ("body", ["p"]) , ("caption", ["p"]) , ("dd", ["p"]) , ("div", ["p"]) , ("dl", ["dt","dd"]) , ("dt", ["p"]) , ("li", ["p"]) , ("map", ["p"]) , ("object", ["p"]) , ("ol", ["li"]) , ("table", ["th","tr","td","thead","tfoot","tbody"]) , ("tbody", ["th","tr","td"]) , ("td", ["p"]) , ("tfoot", ["th","tr","td"]) , ("th", ["p"]) , ("thead", ["th","tr","td"]) , ("tr", ["th","td"]) , ("ul", ["li"]) ] ) -- a bit more efficient implementation of closes closesHtmlTag :: String -> String -> Bool closesHtmlTag t t2 = fromMaybe False . fmap ($ t) . M.lookup t2 $ closedByTable # INLINE closesHtmlTag # closedByTable :: M.Map String (String -> Bool) closedByTable = M.fromList $ [ ("a", (== "a")) , ("li", (== "li" )) , ("th", (`elem` ["th", "td", "tr"] )) , ("td", (`elem` ["th", "td", "tr"] )) , ("tr", (== "tr")) , ("dt", (`elem` ["dt", "dd"] )) , ("dd", (`elem` ["dt", "dd"] )) , ("p", (`elem` ["hr" , "h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("colgroup", (`elem` ["colgroup", "thead", "tfoot", "tbody"] )) , ("form", (`elem` ["form"] )) , ("label", (`elem` ["label"] )) , ("map", (`elem` ["map"] )) , ("option", const True) , ("script", const True) , ("style", const True) , ("textarea", const True) , ("title", const True) , ("select", ( /= "option")) , ("thead", (`elem` ["tfoot","tbody"] )) , ("tbody", (== "tbody" )) , ("tfoot", (== "tbody" )) , ("h1", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h2", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h3", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h4", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h5", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h6", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) ] closesHtmlTag : : String - > String - > Bool closesHtmlTag = closes closes : : String - > String - > Bool " a " ` closes ` " a " = True " li " ` closes ` " li " = True " th " ` closes ` t | t ` elem ` [ " th","td " ] = True " td " ` closes ` t | t ` elem ` [ " th","td " ] = True " tr " ` closes ` t | t ` elem ` [ " th","td","tr " ] = True " dt " ` closes ` t | t ` elem ` [ " dt","dd " ] = True " dd " ` closes ` t | t ` elem ` [ " dt","dd " ] = True " hr " ` closes ` " p " = True " colgroup " ` closes ` " colgroup " = True " form " ` closes ` " form " = True " label " ` closes ` " label " = True " map " ` closes ` " map " = True " object " ` closes ` " object " = True _ ` closes ` t | t ` elem ` [ " option " , " script " , " style " , " textarea " , " title " ] = True t ` closes ` " select " | t /= " option " = True " thead " ` closes ` t | t ` elem ` [ " colgroup " ] = True " tfoot " ` closes ` t | t ` elem ` [ " thead " , " colgroup " ] = True " tbody " ` closes ` t | t ` elem ` [ " tbody " , " tfoot " , " thead " , " colgroup " ] = True t ` closes ` t2 | t ` elem ` [ " h1","h2","h3 " , " h4","h5","h6 " , " dl","ol","ul " , " table " , " div","p " ] & & t2 ` elem ` [ " h1","h2","h3 " , " h4","h5","h6 " , " p " -- not " div " ] = True _ ` closes ` _ = False closesHtmlTag :: String -> String -> Bool closesHtmlTag = closes closes :: String -> String -> Bool "a" `closes` "a" = True "li" `closes` "li" = True "th" `closes` t | t `elem` ["th","td"] = True "td" `closes` t | t `elem` ["th","td"] = True "tr" `closes` t | t `elem` ["th","td","tr"] = True "dt" `closes` t | t `elem` ["dt","dd"] = True "dd" `closes` t | t `elem` ["dt","dd"] = True "hr" `closes` "p" = True "colgroup" `closes` "colgroup" = True "form" `closes` "form" = True "label" `closes` "label" = True "map" `closes` "map" = True "object" `closes` "object" = True _ `closes` t | t `elem` ["option" ,"script" ,"style" ,"textarea" ,"title" ] = True t `closes` "select" | t /= "option" = True "thead" `closes` t | t `elem` ["colgroup"] = True "tfoot" `closes` t | t `elem` ["thead" ,"colgroup"] = True "tbody" `closes` t | t `elem` ["tbody" ,"tfoot" ,"thead" ,"colgroup"] = True t `closes` t2 | t `elem` ["h1","h2","h3" ,"h4","h5","h6" ,"dl","ol","ul" ,"table" ,"div","p" ] && t2 `elem` ["h1","h2","h3" ,"h4","h5","h6" ,"p" -- not "div" ] = True _ `closes` _ = False -} -- ------------------------------------------------------------
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/hxt-9.3.1.18/src/Text/XML/HXT/Parser/HtmlParsec.hs
haskell
# LANGUAGE CPP # ------------------------------------------------------------ ------------------------------------------------------------ , char ------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ wrong tag, take it as text HTML allows unquoted attribute values optimization: HTML entity refs are substituted by char refs, so a later entity ref substituion isn't required not found: the entity ref remains as it is alternative def Nothing -> mkText' ("&" ++ en ++ ";") -- not found: the entity ref is taken as text ------------------------------------------------------------ hComment allows "--" in comments comment from XML spec does not >\" found") ------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ ------------------------------------------------------------ a bit more efficient implementation of closes not " div " not "div" ------------------------------------------------------------
| Module : Text . . HtmlParsec Copyright : Copyright ( C ) 2005 License : MIT Maintainer : ( ) Stability : stable Portability : portable This parser tries to interprete everything as HTML no errors are emitted during parsing . If something looks weired , warning messages are inserted in the document tree . All filter are pure , errror handling and IO is done in ' Text . XML.HXT.Parser . HtmlParser ' or other modules Module : Text.XML.HXT.Parser.HtmlParsec Copyright : Copyright (C) 2005 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt () Stability : stable Portability: portable This parser tries to interprete everything as HTML no errors are emitted during parsing. If something looks weired, warning messages are inserted in the document tree. All filter are pure XmlFilter, errror handling and IO is done in 'Text.XML.HXT.Parser.HtmlParser' or other modules -} module Text.XML.HXT.Parser.HtmlParsec ( parseHtmlText , parseHtmlDocument , parseHtmlContent , isEmptyHtmlTag , isInnerHtmlTagOf , closesHtmlTag , emptyHtmlTags ) where #if MIN_VERSION_base(4,8,2) #else import Control.Applicative ((<$>)) #endif import Data.Char ( toLower , toUpper ) import Data.Char.Properties.XMLCharProps ( isXmlChar ) import Data.Maybe ( fromMaybe , fromJust ) import qualified Data.Map as M import Text.ParserCombinators.Parsec ( SourcePos , anyChar , between , eof , getPosition , many , many1 , noneOf , option , runParser , satisfy , string , try , (<|>) ) import Text.XML.HXT.DOM.Interface import Text.XML.HXT.DOM.XmlNode ( mkText' , mkError' , mkCdata' , mkCmt' , mkCharRef' , mkElement' , mkAttr' , mkDTDElem' , mkPi' , isEntityRef , getEntityRef ) import Text.XML.HXT.Parser.XmlTokenParser ( allBut , amp , dq , eq , gt , lt , name , pubidLiteral , skipS , skipS0 , sPace , sq , systemLiteral , checkString , singleCharsT , referenceT , mergeTextNodes ) import Text.XML.HXT.Parser.XmlParsec ( misc , parseXmlText , xMLDecl' ) import Text.XML.HXT.Parser.XmlCharParser ( xmlChar , SimpleXParser , withNormNewline ) import Text.XML.HXT.Parser.XhtmlEntities ( xhtmlEntities ) parseHtmlText :: String -> XmlTree -> XmlTrees parseHtmlText loc t = parseXmlText htmlDocument (withNormNewline ()) loc $ t parseHtmlFromString :: SimpleXParser XmlTrees -> String -> String -> XmlTrees parseHtmlFromString parser loc = either ((:[]) . mkError' c_err . (++ "\n") . show) id . runParser parser (withNormNewline ()) loc parseHtmlDocument :: String -> String -> XmlTrees parseHtmlDocument = parseHtmlFromString htmlDocument parseHtmlContent :: String -> XmlTrees parseHtmlContent = parseHtmlFromString htmlContent "string" type Context = (XmlTreeFl, OpenTags) type XmlTreeFl = XmlTrees -> XmlTrees type OpenTags = [(String, XmlTrees, XmlTreeFl)] htmlDocument :: SimpleXParser XmlTrees htmlDocument = do pl <- htmlProlog el <- htmlContent eof return (pl ++ el) htmlProlog :: SimpleXParser XmlTrees htmlProlog = do xml <- option [] ( try xMLDecl' <|> ( do pos <- getPosition checkString "<?" return $ [mkError' c_warn (show pos ++ " wrong XML declaration")] ) ) misc1 <- many misc dtdPart <- option [] ( try doctypedecl <|> ( do pos <- getPosition upperCaseString "<!DOCTYPE" return $ [mkError' c_warn (show pos ++ " HTML DOCTYPE declaration ignored")] ) ) return (xml ++ misc1 ++ dtdPart) doctypedecl :: SimpleXParser XmlTrees doctypedecl = between (upperCaseString "<!DOCTYPE") gt ( do skipS n <- name exId <- ( do skipS option [] externalID ) skipS0 return [mkDTDElem' DOCTYPE ((a_name, n) : exId) []] ) externalID :: SimpleXParser Attributes externalID = do upperCaseString k_public skipS pl <- pubidLiteral sl <- option "" $ try ( do skipS systemLiteral ) return $ (k_public, pl) : if null sl then [] else [(k_system, sl)] htmlContent :: SimpleXParser XmlTrees htmlContent = mergeTextNodes <$> htmlContent' htmlContent' :: SimpleXParser XmlTrees htmlContent' = option [] ( do context <- hContent (id, []) pos <- getPosition return $ closeTags pos context ) where closeTags _pos (body, []) = body [] closeTags pos' (body, ((tn, al, body1) : restOpen)) = closeTags pos' ( addHtmlWarn (show pos' ++ ": no closing tag found for \"<" ++ tn ++ " ...>\"") . addHtmlTag tn al body $ (body1, restOpen) ) hElement :: Context -> SimpleXParser Context hElement context = ( do t <- hSimpleData return (addHtmlElem t context) ) <|> hCloseTag context <|> hOpenTag context <|> pos <- getPosition c <- xmlChar return ( addHtmlWarn (show pos ++ " markup char " ++ show c ++ " not allowed in this context") . addHtmlElem (mkText' [c]) $ context ) ) <|> ( do pos <- getPosition c <- anyChar return ( addHtmlWarn ( show pos ++ " illegal data in input or illegal XML char " ++ show c ++ " found and ignored, possibly wrong encoding scheme used") $ context ) ) hSimpleData :: SimpleXParser XmlTree hSimpleData = charData'' <|> hReference' <|> hComment <|> hpI <|> hcDSect where charData'' = do t <- many1 (satisfy (\ x -> isXmlChar x && not (x == '<' || x == '&'))) return (mkText' t) hCloseTag :: Context -> SimpleXParser Context hCloseTag context = do checkString "</" n <- lowerCaseName skipS0 pos <- getPosition checkSymbol gt ("closing > in tag \"</" ++ n ++ "\" expected") (closeTag pos n context) hOpenTag :: Context -> SimpleXParser Context hOpenTag context = ( do e <- hOpenTagStart hOpenTagRest e context ) hOpenTagStart :: SimpleXParser ((SourcePos, String), XmlTrees) hOpenTagStart = do np <- try ( do lt pos <- getPosition n <- lowerCaseName return (pos, n) ) skipS0 as <- hAttrList return (np, as) hOpenTagRest :: ((SourcePos, String), XmlTrees) -> Context -> SimpleXParser Context hOpenTagRest ((pos, tn), al) context = ( do checkString "/>" return (addHtmlTag tn al id context) ) <|> ( do context1 <- checkSymbol gt ("closing > in tag \"<" ++ tn ++ "...\" expected") context return ( let context2 = closePrevTag pos tn context1 in ( if isEmptyHtmlTag tn then addHtmlTag tn al id else openTag tn al ) context2 ) ) hAttrList :: SimpleXParser XmlTrees hAttrList = many (try hAttribute) where hAttribute = do n <- lowerCaseName v <- hAttrValue skipS0 return $ mkAttr' (mkName n) v hAttrValue :: SimpleXParser XmlTrees hAttrValue = option [] ( eq >> hAttrValue' ) hAttrValue' :: SimpleXParser XmlTrees hAttrValue' = try ( between dq dq (hAttrValue'' "&\"") ) <|> try ( between sq sq (hAttrValue'' "&\'") ) <|> cs <- many (noneOf " \r\t\n>\"\'") return [mkText' cs] ) hAttrValue'' :: String -> SimpleXParser XmlTrees hAttrValue'' notAllowed = many ( hReference' <|> singleCharsT notAllowed) hReference' :: SimpleXParser XmlTree hReference' = try hReferenceT <|> ( do amp return (mkText' "&") ) hReferenceT :: SimpleXParser XmlTree hReferenceT = do r <- referenceT return ( if isEntityRef r then substRef r else r ) where substRef r = case (lookup en xhtmlEntities) of Just i -> mkCharRef' i this is also done in the XML parser where en = fromJust . getEntityRef $ r hContent :: Context -> SimpleXParser Context hContent context = option context ( hElement context >>= hContent ) hComment :: SimpleXParser XmlTree hComment = do checkString "<!--" pos <- getPosition c <- allBut many "-->" closeCmt pos c where closeCmt pos c = ( do checkString "-->" return (mkCmt' c) ) <|> ( return $ ) hpI :: SimpleXParser XmlTree hpI = checkString "<?" >> ( try ( do n <- name p <- sPace >> allBut many "?>" string "?>" >> return (mkPi' (mkName n) [mkAttr' (mkName a_value) [mkText' p]]) ) <|> ( do pos <- getPosition return $ mkError' c_warn (show pos ++ " illegal PI found") ) ) hcDSect :: SimpleXParser XmlTree hcDSect = do checkString "<![CDATA[" pos <- getPosition t <- allBut many "]]>" closeCD pos t where closeCD pos t = ( do checkString "]]>" return (mkCdata' t) ) <|> ( return $ mkError' c_warn (show pos ++ " no closing CDATA sequence \"]]>\" found") ) checkSymbol :: SimpleXParser () -> String -> Context -> SimpleXParser Context checkSymbol p msg context = ( p >> return context ) <|> ( do pos <- getPosition return $ addHtmlWarn (show pos ++ " " ++ msg) context ) lowerCaseName :: SimpleXParser String lowerCaseName = do n <- name return (map toLower n) upperCaseString :: String -> SimpleXParser () upperCaseString s = try (sequence (map (\ c -> satisfy (( == c) . toUpper)) s)) >> return () addHtmlTag :: String -> XmlTrees -> XmlTreeFl -> Context -> Context addHtmlTag tn al body context = e `seq` addHtmlElem e context where e = mkElement' (mkName tn) al (body []) addHtmlWarn :: String -> Context -> Context addHtmlWarn msg = addHtmlElem (mkError' c_warn msg) addHtmlElem :: XmlTree -> Context -> Context addHtmlElem elem' (body, openTags) = (body . (elem' :), openTags) openTag :: String -> XmlTrees -> Context -> Context openTag tn al (body, openTags) = (id, (tn, al, body) : openTags) closeTag :: SourcePos -> String -> Context -> Context closeTag pos n context | n `elem` (map ( \ (n1, _, _) -> n1) $ snd context) = closeTag' n context | otherwise = addHtmlWarn (show pos ++ " no opening tag found for </" ++ n ++ ">") . addHtmlTag n [] id $ context where closeTag' n' (body', (n1, al1, body1) : restOpen) = close context1 where context1 = addHtmlTag n1 al1 body' (body1, restOpen) close | n' == n1 = id | n1 `isInnerHtmlTagOf` n' = closeTag pos n' | otherwise = addHtmlWarn (show pos ++ " no closing tag found for \"<" ++ n1 ++ " ...>\"") . closeTag' n' closeTag' _ _ = error "illegal argument for closeTag'" closePrevTag :: SourcePos -> String -> Context -> Context closePrevTag _pos _n context@(_body, []) = context closePrevTag pos n context@(body, (n1, al1, body1) : restOpen) | n `closesHtmlTag` n1 = closePrevTag pos n ( addHtmlWarn (show pos ++ " tag \"<" ++ n1 ++ " ...>\" implicitly closed by opening tag \"<" ++ n ++ " ...>\"") . addHtmlTag n1 al1 body $ (body1, restOpen) ) | otherwise = context taken from HaXml and extended isEmptyHtmlTag :: String -> Bool isEmptyHtmlTag n = n `elem` emptyHtmlTags emptyHtmlTags :: [String] emptyHtmlTags = [ "area" , "base" , "br" , "col" , "frame" , "hr" , "img" , "input" , "link" , "meta" , "param" ] # INLINE emptyHtmlTags # isInnerHtmlTagOf :: String -> String -> Bool n `isInnerHtmlTagOf` tn = n `elem` ( fromMaybe [] . lookup tn $ [ ("body", ["p"]) , ("caption", ["p"]) , ("dd", ["p"]) , ("div", ["p"]) , ("dl", ["dt","dd"]) , ("dt", ["p"]) , ("li", ["p"]) , ("map", ["p"]) , ("object", ["p"]) , ("ol", ["li"]) , ("table", ["th","tr","td","thead","tfoot","tbody"]) , ("tbody", ["th","tr","td"]) , ("td", ["p"]) , ("tfoot", ["th","tr","td"]) , ("th", ["p"]) , ("thead", ["th","tr","td"]) , ("tr", ["th","td"]) , ("ul", ["li"]) ] ) closesHtmlTag :: String -> String -> Bool closesHtmlTag t t2 = fromMaybe False . fmap ($ t) . M.lookup t2 $ closedByTable # INLINE closesHtmlTag # closedByTable :: M.Map String (String -> Bool) closedByTable = M.fromList $ [ ("a", (== "a")) , ("li", (== "li" )) , ("th", (`elem` ["th", "td", "tr"] )) , ("td", (`elem` ["th", "td", "tr"] )) , ("tr", (== "tr")) , ("dt", (`elem` ["dt", "dd"] )) , ("dd", (`elem` ["dt", "dd"] )) , ("p", (`elem` ["hr" , "h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("colgroup", (`elem` ["colgroup", "thead", "tfoot", "tbody"] )) , ("form", (`elem` ["form"] )) , ("label", (`elem` ["label"] )) , ("map", (`elem` ["map"] )) , ("option", const True) , ("script", const True) , ("style", const True) , ("textarea", const True) , ("title", const True) , ("select", ( /= "option")) , ("thead", (`elem` ["tfoot","tbody"] )) , ("tbody", (== "tbody" )) , ("tfoot", (== "tbody" )) , ("h1", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h2", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h3", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h4", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h5", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) , ("h6", (`elem` ["h1", "h2", "h3", "h4", "h5", "h6", "dl", "ol", "ul", "table", "div", "p"] )) ] closesHtmlTag : : String - > String - > Bool closesHtmlTag = closes closes : : String - > String - > Bool " a " ` closes ` " a " = True " li " ` closes ` " li " = True " th " ` closes ` t | t ` elem ` [ " th","td " ] = True " td " ` closes ` t | t ` elem ` [ " th","td " ] = True " tr " ` closes ` t | t ` elem ` [ " th","td","tr " ] = True " dt " ` closes ` t | t ` elem ` [ " dt","dd " ] = True " dd " ` closes ` t | t ` elem ` [ " dt","dd " ] = True " hr " ` closes ` " p " = True " colgroup " ` closes ` " colgroup " = True " form " ` closes ` " form " = True " label " ` closes ` " label " = True " map " ` closes ` " map " = True " object " ` closes ` " object " = True _ ` closes ` t | t ` elem ` [ " option " , " script " , " style " , " textarea " , " title " ] = True t ` closes ` " select " | t /= " option " = True " thead " ` closes ` t | t ` elem ` [ " colgroup " ] = True " tfoot " ` closes ` t | t ` elem ` [ " thead " , " colgroup " ] = True " tbody " ` closes ` t | t ` elem ` [ " tbody " , " tfoot " , " thead " , " colgroup " ] = True t ` closes ` t2 | t ` elem ` [ " h1","h2","h3 " , " h4","h5","h6 " , " dl","ol","ul " , " table " , " div","p " ] & & t2 ` elem ` [ " h1","h2","h3 " , " h4","h5","h6 " ] = True _ ` closes ` _ = False closesHtmlTag :: String -> String -> Bool closesHtmlTag = closes closes :: String -> String -> Bool "a" `closes` "a" = True "li" `closes` "li" = True "th" `closes` t | t `elem` ["th","td"] = True "td" `closes` t | t `elem` ["th","td"] = True "tr" `closes` t | t `elem` ["th","td","tr"] = True "dt" `closes` t | t `elem` ["dt","dd"] = True "dd" `closes` t | t `elem` ["dt","dd"] = True "hr" `closes` "p" = True "colgroup" `closes` "colgroup" = True "form" `closes` "form" = True "label" `closes` "label" = True "map" `closes` "map" = True "object" `closes` "object" = True _ `closes` t | t `elem` ["option" ,"script" ,"style" ,"textarea" ,"title" ] = True t `closes` "select" | t /= "option" = True "thead" `closes` t | t `elem` ["colgroup"] = True "tfoot" `closes` t | t `elem` ["thead" ,"colgroup"] = True "tbody" `closes` t | t `elem` ["tbody" ,"tfoot" ,"thead" ,"colgroup"] = True t `closes` t2 | t `elem` ["h1","h2","h3" ,"h4","h5","h6" ,"dl","ol","ul" ,"table" ,"div","p" ] && t2 `elem` ["h1","h2","h3" ,"h4","h5","h6" ] = True _ `closes` _ = False -}
dd14419430528f42c9008c736fcd28f1586b9c8100733fc0b850c49138fe8f4d
YellPika/constraint-rules
Cache.hs
# # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ImplicitParams #-} # LANGUAGE UnicodeSyntax # {-# LANGUAGE ViewPatterns #-} module Data.Constraint.Rule.Plugin.Cache where import Data.Constraint.Rule.Plugin.Definitions import Data.Constraint.Rule.Plugin.Prelude import Data.Constraint (Dict (..)) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.List (findIndex) type Cache = (?cache ∷ IORef [Type]) newCache ∷ TcPluginM (Dict Cache) newCache = tcPluginIO do ref ← newIORef [] let ?cache = ref return Dict typeIndex ∷ Cache β‡’ Type β†’ TcPluginM Integer typeIndex t = tcPluginIO do cache ← readIORef ?cache case findIndex (eqType t) cache of Just i β†’ return (fromIntegral i) Nothing β†’ do writeIORef ?cache (cache ++ [t]) return (fromIntegral (length cache)) indexType ∷ Cache β‡’ Integer β†’ TcPluginM Type indexType i = tcPluginIO do cache ← readIORef ?cache return (cache !! fromIntegral i) cached ∷ (Definitions, Cache) β‡’ Type β†’ TcPluginM EvExpr cached t = do i ← typeIndex t return (CachedExpr [Type (CachedTy [NumLitTy i])]) type Cached = (Cache, ?cached ∷ [Type]) isCached ∷ Cached β‡’ Type β†’ Bool isCached t = any (eqType t) ?cached findCached ∷ (Cache, Definitions) β‡’ [Ct] β†’ TcPluginM (Dict Cached, [Ct]) findCached = fmap (\(tys, cts) β†’ let ?cached = tys in (Dict, cts)) . go where go [] = return ([], []) go ((ctPred β†’ CachedTy [NumLitTy i]) : cts) = do t ← indexType i (ts, cts') ← go cts return (t:ts, cts') go (ct:cts) = do (ts, cts') ← go cts return (ts, ct:cts')
null
https://raw.githubusercontent.com/YellPika/constraint-rules/b06dfae3fe01c45c1d78e5611c031ab6591d2e66/src/Data/Constraint/Rule/Plugin/Cache.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE ImplicitParams # # LANGUAGE ViewPatterns #
# # # LANGUAGE UnicodeSyntax # module Data.Constraint.Rule.Plugin.Cache where import Data.Constraint.Rule.Plugin.Definitions import Data.Constraint.Rule.Plugin.Prelude import Data.Constraint (Dict (..)) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.List (findIndex) type Cache = (?cache ∷ IORef [Type]) newCache ∷ TcPluginM (Dict Cache) newCache = tcPluginIO do ref ← newIORef [] let ?cache = ref return Dict typeIndex ∷ Cache β‡’ Type β†’ TcPluginM Integer typeIndex t = tcPluginIO do cache ← readIORef ?cache case findIndex (eqType t) cache of Just i β†’ return (fromIntegral i) Nothing β†’ do writeIORef ?cache (cache ++ [t]) return (fromIntegral (length cache)) indexType ∷ Cache β‡’ Integer β†’ TcPluginM Type indexType i = tcPluginIO do cache ← readIORef ?cache return (cache !! fromIntegral i) cached ∷ (Definitions, Cache) β‡’ Type β†’ TcPluginM EvExpr cached t = do i ← typeIndex t return (CachedExpr [Type (CachedTy [NumLitTy i])]) type Cached = (Cache, ?cached ∷ [Type]) isCached ∷ Cached β‡’ Type β†’ Bool isCached t = any (eqType t) ?cached findCached ∷ (Cache, Definitions) β‡’ [Ct] β†’ TcPluginM (Dict Cached, [Ct]) findCached = fmap (\(tys, cts) β†’ let ?cached = tys in (Dict, cts)) . go where go [] = return ([], []) go ((ctPred β†’ CachedTy [NumLitTy i]) : cts) = do t ← indexType i (ts, cts') ← go cts return (t:ts, cts') go (ct:cts) = do (ts, cts') ← go cts return (ts, ct:cts')
86ffefa7ebc6c1fdc431c5d3e3032550dbfd9ee67bbd4a6c1780c54aaa50f6f4
Storkle/clj-forex
socket_service.clj
;;forex.backend.mql.socket-service: provide background sockets which allow us to connect with metatrader. Provides functions to interact with the background socket (clojure.core/use 'nstools.ns) (ns+ forex.backend.mql.socket-service (:clone clj.core) (:require clojure.contrib.core [forex.util.fiber.mbox :as m] [clojure.contrib.logging :as l]) (:import (java.io DataInputStream ByteArrayInputStream)) (:use forex.backend.mql.error forex.backend.mql.utils forex.util.emacs forex.util.core forex.util.general forex.util.zmq forex.util.log forex.util.spawn)) (defvar mql-socket-recv-address "tcp:3010") (defvar mql-socket-send-address "tcp:3005") (defonce- *ids* (atom {})) ;;socket service (defn invalid-msg? [msg] (if (clojure.contrib.core/seqable? msg) (if (empty? msg) true false) (not (string? msg)))) (defn mql-to-java [type info] (cond (= type "long") (Long/parseLong (String. info)) (= type "boolean") (let [a (Integer/parseInt (String. info))] (condp = a 1 true 0 false (Exception. (str "unkown boolean return result of " a)))) (= type "double[]") (into-doubles info) (= type "double") (Double/parseDouble (String. info)) (= type "int") (Integer/parseInt (String. info)) (= type "string") (String. info) (= type "error") (new-mql-error (parse-int (String. info))) (= type "global") (String. info) true (Exception. (str "Unkown mql type " type)))) (defn mql-parse-recv [msg] (let [[^bytes id & info] msg id (String. id)] ;;(println (format "id is %s info is %s" id info)) (when id [id (doall (for [[type val] (group info)] (mql-to-java (String. type) val)))]))) (defn mql-recv [msg] (catch-unexpected (let [[id result] (mql-parse-recv msg)] (when id (let [msg-ask (get @*ids* id)] (if msg-ask (do (deliver msg-ask result) (swap! *ids* dissoc id)) (warn "msg-ask corresponding to id %s is nil" id))))))) ;;TODO: get rid of reflection warnings? FIXME : snd crashes when not given a string ? (defn snd-multi [socket id msg] (when-not (invalid-msg? msg) (when (snd socket (str id) (bit-or +noblock+ +more+)) (if (or (vector? msg) (list? msg)) (loop [m msg] (if (= 1 (count m)) (snd socket (str (first m)) +noblock+) (if (snd socket (str (first m)) (bit-or +more+ +noblock+)) (recur (next m)) false))) (snd socket (str msg) +noblock+))))) ;;TODO: make shorter (defn- socket-service-match [events send receive] (let [event (first events)] (match event [local "STOP"] (do (info "closing ...") "STOP") [local ["REQUEST" ?msg ?askin]] (when-not (invalid-msg? msg) (let [id (msg-id) result (snd-multi send id msg)] (if result (when-not (nil? askin) (swap! *ids* assoc id askin)) (when-not (nil? askin) (catch-unexpected (deliver askin (list (new-mql-error +error-clj-service-queue+))))) ))) [receive ?msg] (future (mql-recv msg)) ?msg (warn "Ignoring invalid message %s" msg)))) ;;TODO: weird bug when stopping everything with an ea. (defn spawn-mql-socket-service [] (debugging "MQL Socket Service: " {:pid (spawn-log #(with-open [send (doto (new-socket +push+) (.bind mql-socket-send-address)) receive (doto (new-socket +pull+) (.bind mql-socket-recv-address))] (loop [events (event-seq [receive local])] (when-not (= "STOP" (socket-service-match events send receive)) (recur (rest events))))) "MQL Socket Service")})) ;;global socket service (defonce- *s* (atom nil)) (defn alive? [] (pid? (:pid @*s*))) (defn start [] (if (alive?) (warn "mql socket is already alive!") (do (reset! *ids* {}) (reset! *s* (spawn-mql-socket-service))))) (defn stop [] (if (alive?) (! (:pid @*s*) "STOP") (warn "mql socket service is already stopped"))) interact with TODO : if is nt alive and we retry/ ? ? ? ? (defn request ([msg] (request msg nil)) ([msg askin] (io! (if (pid? (:pid @*s*)) (! (:pid @*s*) ["REQUEST" msg askin]) (deliver askin (list (new-mql-error +error-clj-service-dead+))))))) ;;FIXME: invalid messages, like array of ints? ;;we added a debug message ;;so when we get the really annoying failures to ;;stop we can examine this:) ;;TODO: map of options (defn receive ([msg] (receive msg 3 false)) ([msg resend] (receive msg resend false)) ([msg resend wait-on] (when-not (invalid-msg? msg) (let [ask-obj (promise)] (request msg ask-obj) (loop [i 0 ask ask-obj] (if (wait-for ask 5000) (let [result @ask] (cond (instance? Exception result) (throw result) (or result (false? result)) result true (throwf "invalid result received %s" result))) (if (and resend (< i resend)) (let [ask (promise)] (debug "resending message %s" msg) (recur (+ i 1) ask)) (if wait-on (do (debug "too much time for msg %s" msg) (recur (+ i 1) ask)) (do (debug "too much time for msg %s... ending request" msg) (list (new-mql-error +error-socket-repeat+)))))))))))
null
https://raw.githubusercontent.com/Storkle/clj-forex/1800b982037b821732b9df1e2e5ea1eda70f941f/src/forex/backend/mql/socket_service.clj
clojure
forex.backend.mql.socket-service: provide background sockets which allow us to connect with metatrader. Provides functions to interact with the background socket socket service (println (format "id is %s info is %s" id info)) TODO: get rid of reflection warnings? TODO: make shorter TODO: weird bug when stopping everything with an ea. global socket service FIXME: invalid messages, like array of ints? we added a debug message so when we get the really annoying failures to stop we can examine this:) TODO: map of options
(clojure.core/use 'nstools.ns) (ns+ forex.backend.mql.socket-service (:clone clj.core) (:require clojure.contrib.core [forex.util.fiber.mbox :as m] [clojure.contrib.logging :as l]) (:import (java.io DataInputStream ByteArrayInputStream)) (:use forex.backend.mql.error forex.backend.mql.utils forex.util.emacs forex.util.core forex.util.general forex.util.zmq forex.util.log forex.util.spawn)) (defvar mql-socket-recv-address "tcp:3010") (defvar mql-socket-send-address "tcp:3005") (defonce- *ids* (atom {})) (defn invalid-msg? [msg] (if (clojure.contrib.core/seqable? msg) (if (empty? msg) true false) (not (string? msg)))) (defn mql-to-java [type info] (cond (= type "long") (Long/parseLong (String. info)) (= type "boolean") (let [a (Integer/parseInt (String. info))] (condp = a 1 true 0 false (Exception. (str "unkown boolean return result of " a)))) (= type "double[]") (into-doubles info) (= type "double") (Double/parseDouble (String. info)) (= type "int") (Integer/parseInt (String. info)) (= type "string") (String. info) (= type "error") (new-mql-error (parse-int (String. info))) (= type "global") (String. info) true (Exception. (str "Unkown mql type " type)))) (defn mql-parse-recv [msg] (let [[^bytes id & info] msg id (String. id)] (when id [id (doall (for [[type val] (group info)] (mql-to-java (String. type) val)))]))) (defn mql-recv [msg] (catch-unexpected (let [[id result] (mql-parse-recv msg)] (when id (let [msg-ask (get @*ids* id)] (if msg-ask (do (deliver msg-ask result) (swap! *ids* dissoc id)) (warn "msg-ask corresponding to id %s is nil" id))))))) FIXME : snd crashes when not given a string ? (defn snd-multi [socket id msg] (when-not (invalid-msg? msg) (when (snd socket (str id) (bit-or +noblock+ +more+)) (if (or (vector? msg) (list? msg)) (loop [m msg] (if (= 1 (count m)) (snd socket (str (first m)) +noblock+) (if (snd socket (str (first m)) (bit-or +more+ +noblock+)) (recur (next m)) false))) (snd socket (str msg) +noblock+))))) (defn- socket-service-match [events send receive] (let [event (first events)] (match event [local "STOP"] (do (info "closing ...") "STOP") [local ["REQUEST" ?msg ?askin]] (when-not (invalid-msg? msg) (let [id (msg-id) result (snd-multi send id msg)] (if result (when-not (nil? askin) (swap! *ids* assoc id askin)) (when-not (nil? askin) (catch-unexpected (deliver askin (list (new-mql-error +error-clj-service-queue+))))) ))) [receive ?msg] (future (mql-recv msg)) ?msg (warn "Ignoring invalid message %s" msg)))) (defn spawn-mql-socket-service [] (debugging "MQL Socket Service: " {:pid (spawn-log #(with-open [send (doto (new-socket +push+) (.bind mql-socket-send-address)) receive (doto (new-socket +pull+) (.bind mql-socket-recv-address))] (loop [events (event-seq [receive local])] (when-not (= "STOP" (socket-service-match events send receive)) (recur (rest events))))) "MQL Socket Service")})) (defonce- *s* (atom nil)) (defn alive? [] (pid? (:pid @*s*))) (defn start [] (if (alive?) (warn "mql socket is already alive!") (do (reset! *ids* {}) (reset! *s* (spawn-mql-socket-service))))) (defn stop [] (if (alive?) (! (:pid @*s*) "STOP") (warn "mql socket service is already stopped"))) interact with TODO : if is nt alive and we retry/ ? ? ? ? (defn request ([msg] (request msg nil)) ([msg askin] (io! (if (pid? (:pid @*s*)) (! (:pid @*s*) ["REQUEST" msg askin]) (deliver askin (list (new-mql-error +error-clj-service-dead+))))))) (defn receive ([msg] (receive msg 3 false)) ([msg resend] (receive msg resend false)) ([msg resend wait-on] (when-not (invalid-msg? msg) (let [ask-obj (promise)] (request msg ask-obj) (loop [i 0 ask ask-obj] (if (wait-for ask 5000) (let [result @ask] (cond (instance? Exception result) (throw result) (or result (false? result)) result true (throwf "invalid result received %s" result))) (if (and resend (< i resend)) (let [ask (promise)] (debug "resending message %s" msg) (recur (+ i 1) ask)) (if wait-on (do (debug "too much time for msg %s" msg) (recur (+ i 1) ask)) (do (debug "too much time for msg %s... ending request" msg) (list (new-mql-error +error-socket-repeat+)))))))))))
abebda90aec7bdd2152d59ad52a4d784e26fb9876412627b357777191cbc13c7
Clozure/ccl-tests
ftruncate.lsp
;-*- Mode: Lisp -*- Author : Created : We d Aug 20 06:36:35 2003 ;;;; Contains: Tests of FTRUNCATE (in-package :cl-test) (compile-and-load "numbers-aux.lsp") (compile-and-load "ftruncate-aux.lsp") ;;; Error tests (deftest ftruncate.error.1 (signals-error (ftruncate) program-error) t) (deftest ftruncate.error.2 (signals-error (ftruncate 1.0 1 nil) program-error) t) ;;; Non-error tests (deftest ftruncate.1 (ftruncate.1-fn) nil) (deftest ftruncate.10 (loop for x in (remove-if #'zerop *reals*) for (q r) = (multiple-value-list (ftruncate x x)) unless (and (floatp q) (if (floatp x) (eql q (float 1 x)) (= q 1)) (zerop r) (if (floatp x) (eql r (float 0 x)) (= r 0))) collect x) nil) (deftest ftruncate.11 (loop for x in (remove-if-not #'floatp (remove-if #'zerop *reals*)) for (q r) = (multiple-value-list (ftruncate (- x) x)) unless (and (floatp q) (if (floatp x) (eql q (float -1 x)) (= q -1)) (zerop r) (if (floatp x) (eql r (float 0 x)) (= r 0))) collect x) nil) (deftest ftruncate.12 (let* ((radix (float-radix 1.0s0)) (rad (float radix 1.0s0)) (rrad (/ 1.0s0 rad))) (loop for i from 1 to 1000 for x = (+ i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce i 'short-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.13 (let* ((radix (float-radix 1.0s0)) (rad (float radix 1.0s0)) (rrad (/ 1.0s0 rad))) (loop for i from 1 to 1000 for x = (- i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce (1- i) 'short-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.14 (let* ((radix (float-radix 1.0f0)) (rad (float radix 1.0f0)) (rrad (/ 1.0f0 rad))) (loop for i from 1 to 1000 for x = (+ i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce i 'single-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.15 (let* ((radix (float-radix 1.0f0)) (rad (float radix 1.0f0)) (rrad (/ 1.0f0 rad))) (loop for i from 1 to 1000 for x = (- i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce (1- i) 'single-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.16 (let* ((radix (float-radix 1.0d0)) (rad (float radix 1.0d0)) (rrad (/ 1.0d0 rad))) (loop for i from 1 to 1000 for x = (+ i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce i 'double-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.17 (let* ((radix (float-radix 1.0d0)) (rad (float radix 1.0d0)) (rrad (/ 1.0d0 rad))) (loop for i from 1 to 1000 for x = (- i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce (1- i) 'double-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.18 (let* ((radix (float-radix 1.0l0)) (rad (float radix 1.0l0)) (rrad (/ 1.0l0 rad))) (loop for i from 1 to 1000 for x = (+ i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce i 'long-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.19 (let* ((radix (float-radix 1.0l0)) (rad (float radix 1.0l0)) (rrad (/ 1.0l0 rad))) (loop for i from 1 to 1000 for x = (- i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce (1- i) 'long-float)) (eql r rrad)) collect (list i x q r))) nil) ;;; To add: tests that involve adding/subtracting EPSILON constants ;;; (suitably scaled) to floated integers.
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/ftruncate.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of FTRUNCATE Error tests Non-error tests To add: tests that involve adding/subtracting EPSILON constants (suitably scaled) to floated integers.
Author : Created : We d Aug 20 06:36:35 2003 (in-package :cl-test) (compile-and-load "numbers-aux.lsp") (compile-and-load "ftruncate-aux.lsp") (deftest ftruncate.error.1 (signals-error (ftruncate) program-error) t) (deftest ftruncate.error.2 (signals-error (ftruncate 1.0 1 nil) program-error) t) (deftest ftruncate.1 (ftruncate.1-fn) nil) (deftest ftruncate.10 (loop for x in (remove-if #'zerop *reals*) for (q r) = (multiple-value-list (ftruncate x x)) unless (and (floatp q) (if (floatp x) (eql q (float 1 x)) (= q 1)) (zerop r) (if (floatp x) (eql r (float 0 x)) (= r 0))) collect x) nil) (deftest ftruncate.11 (loop for x in (remove-if-not #'floatp (remove-if #'zerop *reals*)) for (q r) = (multiple-value-list (ftruncate (- x) x)) unless (and (floatp q) (if (floatp x) (eql q (float -1 x)) (= q -1)) (zerop r) (if (floatp x) (eql r (float 0 x)) (= r 0))) collect x) nil) (deftest ftruncate.12 (let* ((radix (float-radix 1.0s0)) (rad (float radix 1.0s0)) (rrad (/ 1.0s0 rad))) (loop for i from 1 to 1000 for x = (+ i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce i 'short-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.13 (let* ((radix (float-radix 1.0s0)) (rad (float radix 1.0s0)) (rrad (/ 1.0s0 rad))) (loop for i from 1 to 1000 for x = (- i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce (1- i) 'short-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.14 (let* ((radix (float-radix 1.0f0)) (rad (float radix 1.0f0)) (rrad (/ 1.0f0 rad))) (loop for i from 1 to 1000 for x = (+ i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce i 'single-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.15 (let* ((radix (float-radix 1.0f0)) (rad (float radix 1.0f0)) (rrad (/ 1.0f0 rad))) (loop for i from 1 to 1000 for x = (- i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce (1- i) 'single-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.16 (let* ((radix (float-radix 1.0d0)) (rad (float radix 1.0d0)) (rrad (/ 1.0d0 rad))) (loop for i from 1 to 1000 for x = (+ i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce i 'double-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.17 (let* ((radix (float-radix 1.0d0)) (rad (float radix 1.0d0)) (rrad (/ 1.0d0 rad))) (loop for i from 1 to 1000 for x = (- i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce (1- i) 'double-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.18 (let* ((radix (float-radix 1.0l0)) (rad (float radix 1.0l0)) (rrad (/ 1.0l0 rad))) (loop for i from 1 to 1000 for x = (+ i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce i 'long-float)) (eql r rrad)) collect (list i x q r))) nil) (deftest ftruncate.19 (let* ((radix (float-radix 1.0l0)) (rad (float radix 1.0l0)) (rrad (/ 1.0l0 rad))) (loop for i from 1 to 1000 for x = (- i rrad) for (q r) = (multiple-value-list (ftruncate x)) unless (and (eql q (coerce (1- i) 'long-float)) (eql r rrad)) collect (list i x q r))) nil)
d72acdb32e7b62c5512159d5e472bc40e41c64b9008b9631820204b2534cea81
skanev/playground
17-tests.scm
(require rackunit rackunit/text-ui) (load "helpers/simulator.scm") (load "../17.scm") (define instructions '()) (define (get-instructions) (reverse instructions)) (define (collect-instructions inst) (set! instructions (cons inst instructions))) (define (reset-tracing!) (set! instructions '())) (define machine (make-machine '(a) '() '(begin (goto (label middle)) (assign a (const 1)) middle (assign a (const 2)) (assign a (const 3)) end))) (define sicp-5.17-tests (test-suite "Tests for SICP exercise 5.17" (test-begin "Tracing labels" (reset-tracing!) (machine 'trace-on) ((machine 'install-trace-proc) collect-instructions) (start machine) (check-eq? (machine 'instruction-count) 3) (check-equal? (get-instructions) '(begin (goto (label middle)) middle (assign a (const 2)) (assign a (const 3))))) )) (run-tests sicp-5.17-tests)
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/05/tests/17-tests.scm
scheme
(require rackunit rackunit/text-ui) (load "helpers/simulator.scm") (load "../17.scm") (define instructions '()) (define (get-instructions) (reverse instructions)) (define (collect-instructions inst) (set! instructions (cons inst instructions))) (define (reset-tracing!) (set! instructions '())) (define machine (make-machine '(a) '() '(begin (goto (label middle)) (assign a (const 1)) middle (assign a (const 2)) (assign a (const 3)) end))) (define sicp-5.17-tests (test-suite "Tests for SICP exercise 5.17" (test-begin "Tracing labels" (reset-tracing!) (machine 'trace-on) ((machine 'install-trace-proc) collect-instructions) (start machine) (check-eq? (machine 'instruction-count) 3) (check-equal? (get-instructions) '(begin (goto (label middle)) middle (assign a (const 2)) (assign a (const 3))))) )) (run-tests sicp-5.17-tests)
946879404728de6b9aec45f7ffd34a6321119faf0420ee6a11803b0d7398a803
NorfairKing/validity
UUID.hs
# OPTIONS_GHC -fno - warn - orphans # module Data.Validity.UUID where import Data.UUID import Data.Validity -- | A 'UUID' is valid according to the contained words instance Validity UUID where validate = delve "words" . toWords
null
https://raw.githubusercontent.com/NorfairKing/validity/1c3671a662673e21a1c5e8056eef5a7b0e8720ea/validity-uuid/src/Data/Validity/UUID.hs
haskell
| A 'UUID' is valid according to the contained words
# OPTIONS_GHC -fno - warn - orphans # module Data.Validity.UUID where import Data.UUID import Data.Validity instance Validity UUID where validate = delve "words" . toWords