_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
941d97485565740e8e979b930b204aab47324a327c7de6eae9f1ae4b98f14549
the-real-blackh/cassandra-cql
test-set.hs
# LANGUAGE OverloadedStrings , import Database.Cassandra.CQL import Control.Monad import Control.Monad.CatchIO import Control.Monad.Trans (liftIO) import Data.Int import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as C import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import Data.UUID import System.Random dropLists :: Query Schema () () dropLists = "drop table sets" createLists :: Query Schema () () createLists = "create table sets (id uuid PRIMARY KEY, items set<text>)" insert :: Query Write (UUID, Set Text) () insert = "insert into sets (id, items) values (?, ?)" select :: Query Rows () (Set Text) select = "select items from sets" ignoreDropFailure :: Cas () -> Cas () ignoreDropFailure code = code `catch` \exc -> case exc of ConfigError _ _ -> return () -- Ignore the error if the table doesn't exist Invalid _ _ -> return () _ -> throw exc main = do let auth = Just ( PasswordAuthenticator " cassandra " " " ) let auth = Nothing servers , keyspace , auth runCas pool $ do ignoreDropFailure $ liftIO . print =<< executeSchema QUORUM dropLists () liftIO . print =<< executeSchema QUORUM createLists () u1 <- liftIO randomIO u2 <- liftIO randomIO u3 <- liftIO randomIO executeWrite QUORUM insert (u1, S.fromList ["one", "two"]) executeWrite QUORUM insert (u2, S.fromList ["hundred", "two hundred"]) executeWrite QUORUM insert (u3, S.fromList ["dozen"]) liftIO . print =<< executeRows QUORUM select ()
null
https://raw.githubusercontent.com/the-real-blackh/cassandra-cql/681d900fadcede786d1008eac2270166ca915e8b/tests/test-set.hs
haskell
Ignore the error if the table doesn't exist
# LANGUAGE OverloadedStrings , import Database.Cassandra.CQL import Control.Monad import Control.Monad.CatchIO import Control.Monad.Trans (liftIO) import Data.Int import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as C import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import Data.UUID import System.Random dropLists :: Query Schema () () dropLists = "drop table sets" createLists :: Query Schema () () createLists = "create table sets (id uuid PRIMARY KEY, items set<text>)" insert :: Query Write (UUID, Set Text) () insert = "insert into sets (id, items) values (?, ?)" select :: Query Rows () (Set Text) select = "select items from sets" ignoreDropFailure :: Cas () -> Cas () ignoreDropFailure code = code `catch` \exc -> case exc of Invalid _ _ -> return () _ -> throw exc main = do let auth = Just ( PasswordAuthenticator " cassandra " " " ) let auth = Nothing servers , keyspace , auth runCas pool $ do ignoreDropFailure $ liftIO . print =<< executeSchema QUORUM dropLists () liftIO . print =<< executeSchema QUORUM createLists () u1 <- liftIO randomIO u2 <- liftIO randomIO u3 <- liftIO randomIO executeWrite QUORUM insert (u1, S.fromList ["one", "two"]) executeWrite QUORUM insert (u2, S.fromList ["hundred", "two hundred"]) executeWrite QUORUM insert (u3, S.fromList ["dozen"]) liftIO . print =<< executeRows QUORUM select ()
299a00726a82accae0f5836b8caa4e1ed05c11e0e5e8e152eb9e584fbd259e82
ijp/guildhall
solver.scm
;;; solver.scm --- Dependency solver, algorithm Copyright ( C ) 2009 - 2011 < > Copyright ( C ) 2009 Author : < > ;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. ;;; Commentary: ;; This file corresponds to aptitude's "problemresolver.h" and ;; "solution.h". ;;; Code: #!r6rs (library (guildhall solver) (export make-solver solver? find-next-solution! solution? solution-choices logger:dorodango.solver) (import (rnrs) (srfi :2 and-let*) (srfi :8 receive) (srfi :67 compare-procedures) (guildhall spells hash-utils) (guildhall spells record-types) (only (guile) assq-ref or-map and=>) (guildhall spells logging) (guildhall ext fmt) (guildhall ext foof-loop) (guildhall ext wt-tree) (guildhall private utils) (guildhall solver logging) (guildhall solver choice) (guildhall solver search-graph) (guildhall solver promotions) (guildhall solver universe) (guildhall solver expression)) ;;; The solver (define-record-type* solver (really-make-solver find-next) ()) (define make-solver (case-lambda ((universe options) (construct-solver universe options)) ((universe) (make-solver universe '())))) ;; The solver constructor -- the solver is obviously an abomination of ;; state, but what do you expect from an algorithm implementation ;; taken from an imperative language? (define (construct-solver universe options) (letrec* ((promotion-retracted (lambda (promotion) (log/debug "Retracting all tier assignments that might be linked to " (dsp-promotion promotion)))) ;; Options (option (lambda (name) (option-ref options name))) (score/step (option 'step-score)) (score/broken (option 'broken-score)) (score/infinity (option 'infinity)) (score/goal (option 'goal-score)) (score/full-solution (option 'full-solution-score)) (future-horizon (option 'future-horizon)) (remove-stupid? (option 'remove-stupid?)) (initial-state (extend-installation (make-empty-installation) (option 'initial-choices))) (joint-scores (make-joint-score-set initial-state (option 'joint-scores))) (version-scores (make-version-scores universe (option 'version-scores))) ;; Immutable (initial-broken (universe-broken-dependency-set universe initial-state)) (minimum-score (- score/infinity)) ;; Solver state (finished? #f) (promotions (make-promotion-set universe promotion-retracted)) (graph (make-search-graph promotions)) (graph-wt-type (search-graph->wt-tree-type graph)) (pending (make-wt-tree graph-wt-type)) (num-deferred 0) (minimum-search-tier minimum-tier) (maximum-search-tier minimum-tier) (closed (make-hashtable step-contents-hash step-contents=?)) (pending-future-solutions (make-wt-tree graph-wt-type)) (promotion-queue-tail (make-promotion-queue 0 0)) (version-tiers (make-vector (universe-version-count universe) minimum-tier))) ;;; Public procedures (define (find-next max-steps) (and (not finished?) (begin (when (and (wt-tree/empty? pending) (wt-tree/empty? pending-future-solutions) (= 0 (hashtable-size closed))) (start-search)) (loop continue ((for remaining-steps (down-from max-steps (to 0))) (with most-future-solution-steps 0) (while (contains-canditate? pending))) => (prepare-result most-future-solution-steps) (when (> most-future-solution-steps 0) (log/debug "Speculative \"future\" resolver tick (" most-future-solution-steps "/" future-horizon ").")) (let ((cur-step-num (wt-tree/min pending))) (wt-tree/delete! pending cur-step-num) (process-step cur-step-num)) (let ((new-most-future-solutions-steps (if (contains-canditate? pending-future-solutions) (+ most-future-solution-steps 1) 0))) (log/trace "Done generating successors.") (search-graph-run-scheduled-promotion-propagations! graph add-promotion) (continue (=> most-future-solution-steps new-most-future-solutions-steps))))))) ;;; Private procedures (define (prepare-result most-future-solution-steps) (log/trace (cond ((> most-future-solution-steps future-horizon) "Done examining future steps for a better solution.") ((not (contains-canditate? pending)) "Exhausted all search branches.") (else "Ran out of time."))) (cond ((contains-canditate? pending-future-solutions) (let* ((best-future-solution (wt-tree/min pending-future-solutions)) (best-future-solution-step (search-graph-step graph best-future-solution))) (sanity-check-not-deferred best-future-solution) (let ((result (make-solution (step-actions best-future-solution-step) (step-score best-future-solution-step) (step-tier best-future-solution-step)))) (log/info "--- Returning the future solution " (dsp-solution result) " from step " best-future-solution) (wt-tree/delete! pending-future-solutions best-future-solution) result))) ((contains-canditate? pending) (raise (condition (make-out-of-time-condition)))) (else (set! finished? #t) #f))) (define (contains-canditate? step-set) (and (not (wt-tree/empty? step-set)) (tier<? (step-tier (search-graph-step graph (wt-tree/min step-set))) defer-tier))) (define (current-search-tier) (if (wt-tree/empty? pending) minimum-tier (step-tier (search-graph-step graph (wt-tree/min pending))))) (define (start-search) (log/info "Starting a new search.") (let* ((broken-size (wt-tree/size initial-broken)) (root-score (+ (* broken-size score/broken) (if (= 0 broken-size) score/full-solution 0))) (root (search-graph-add-root-step! graph root-score))) (set-step-promotion-queue-location! root promotion-queue-tail) (wt-tree/for-each (lambda (dependency true) (add-unresolved-dep root dependency)) initial-broken) (log/debug "Inserting the root at step " (step-num root) " with tier " (dsp-tier (step-tier root))) (wt-tree/add! pending (step-num root) #t))) (define (process-step step-num) (loop continue ((with step-num step-num)) (let ((step (search-graph-step graph step-num))) (log/info "Examining step " step-num " " (dsp-step step)) (when (tier>=? (step-tier step) defer-tier) (internal-error "the tier of step " step-num " is an unprocessed tier, so why is it a candidate?")) (check-for-new-promotions step-num) (sanity-check-promotions step) (cond ((already-seen? step-num) (log/debug "Dropping already visited search node in step " step-num)) ((irrelevant? step) (log/debug "Dropping irrelevant step " step-num)) ((tier>=? (step-tier step) defer-tier) (log/debug "Skipping newly deferred step " step-num) (wt-tree/add! pending step-num #t)) (else (log/trace "Processing step " step-num) (hashtable-set! closed step step-num) (cond ((step-solution? step) (log/info " --- Found solution at step " step-num ": " (dsp-step step)) (add-promotion step-num (make-promotion (generalize-choice-set (step-actions step)) already-generated-tier)) (set-step-blessed-solution?! step #t) (wt-tree/add! pending-future-solutions step-num #t)) (else (generate-successors step-num) (and-let* ((child-num (step-first-child step)) (child (search-graph-step graph child-num)) ((step-last-child? child)) ((tier<? (step-tier child) defer-tier))) (log/trace "Following forced dependency resolution from step " step-num " to step " child-num) (wt-tree/delete! pending child-num) (continue (=> step-num child-num)))))))))) (define (generate-successors step-num) (log/trace "Generating successors for step " step-num) (let ((parent (search-graph-step graph step-num))) (receive (best-dep best-solvers) (step-unresolved-deps-min parent) (let ((num-solvers (solver-tracker-size best-solvers))) (unless (> num-solvers 0) (internal-error "A step containing a dependency with no solvers" " was not promoted to the conflict tier.")) (log/trace "Generating successors for step " step-num " for the dependency " (dsp-solver-tracker best-solvers) " with " num-solvers " solvers: " (dsp-solver-tracker-solvers best-solvers))) (solver-tracker-fold (lambda (solver info first?) (check-for-new-promotions step-num) (unless first? (set-step-last-child?! (search-graph-last-step graph) #f)) (generate-single-successor parent solver (max-compare tier-compare (solver-info-tier info) (step-tier parent))) #f) #t best-solvers)))) (define (generate-single-successor parent original-choice tier) (let* ((reason (choice-with-id original-choice (choice-set-size (step-actions parent)))) (step (search-graph-add-step! graph parent tier reason (build-is-deferred-listener reason)))) (set-step-promotion-queue-location! step promotion-queue-tail) (log/trace "Generating a successor to step " (step-num parent) " for the action " (dsp-choice reason) " with tier " (dsp-tier tier) " and outputting to step " (step-num step)) (unless (choice-dep reason) (internal-error "No dependency attached to the choice " (dsp-choice reason) " used to generate step " (step-num step))) includes steps 1 and 2 steps 3 , 4 step 5 step 6 (extend-score-to-new-step step reason) (log/trace "Generated step " (step-num step) " (" (choice-set-size (step-actions step)) " actions): " (dsp-choice-set (step-actions step)) ";T" (dsp-tier (step-tier step)) "S" (step-score step)) (when (and (tier>=? (step-tier step) defer-tier) (tier<? (step-tier step) already-generated-tier)) (set! num-deferred (+ num-deferred 1))) (wt-tree/add! pending (step-num step) #t))) (define (extend-score-to-new-step step choice) (step-increase-action-score! step score/step) (let* ((version (choice-version choice)) (old-version (version-of (version-package version) initial-state)) (new-score (vector-ref version-scores (version-id version))) (old-score (vector-ref version-scores (version-id old-version)))) (log/trace "Modifying the score of step " (step-num step) " by " (num/sign (- new-score old-score)) " to account for the replacement of " (dsp-version old-version) " (score " old-score ") by " (dsp-version version) " (score " new-score ")") (step-increase-action-score! step (- new-score old-score)) (joint-score-set-visit joint-scores choice (lambda (choices score) (when (choice-set-subset? choices (step-actions step)) (log/trace "Adjusting the score of " (step-num step) " by " (num/sign score) " for a joint score constraint on " (dsp-choice-set choices)) (step-increase-action-score! step score) #f ;don't stop ))) (let ((num-unresolved-deps (step-num-unresolved-deps step))) (set-step-score! step (+ (step-action-score step) (* score/broken num-unresolved-deps))) (when (= 0 num-unresolved-deps) (log/trace "Modifying the score of step " (step-num step) " by " (num/sign score/full-solution) " because it is a full solution.") (step-increase-score! step score/full-solution))) (log/trace "Updated the score of step " (step-num step) " to " (step-score step)))) (define (find-new-incipient-promotions step choice) (let ((triggered-promotions (find-highest-incipient-promotions-containing promotions (step-actions step) choice (step-deps-solved-by-choice step) (make-blessed-discarder step)))) (loop ((for choice promotion (in-hashtable triggered-promotions))) (increase-solver-tier step promotion choice)))) (define (add-new-unresolved-deps step choice) (let ((test-installation (extend-installation initial-state (step-actions step)))) (define (add-broken-deps! deps) (loop ((for dep (in-list deps))) (when (broken-under? test-installation dep) (add-unresolved-dep step dep)))) (let ((new-version (choice-version choice)) (old-version (version-of (version-package (choice-version choice)) initial-state))) (log/trace "Finding new unresolved dependencies in step " (step-num step) " caused by replacing " (dsp-version old-version) " with " (dsp-version new-version) ".") (add-broken-deps! (version-reverse-dependencies old-version)) (add-broken-deps! (version-reverse-dependencies new-version)) (add-broken-deps! (version-dependencies new-version))))) (define (add-unresolved-dep step dep) (define (collect-infos+reasons versions choice-constructor) (loop ((for version (in-list versions)) (let-values (solver info reason) (solver-info-and-reason step dep (choice-constructor version dep #f))) (for infos (listing (cons solver info) (if info))) (for reasons (listing reason (if reason)))) => (values infos reasons) (when info (log/trace "Adding the solver " (dsp-choice solver) " with initial tier " (dsp-tier (solver-info-tier info))) (step-add-dep-solved-by-choice! step solver dep) (search-graph-bind-choice! graph solver (step-num step) dep)))) (cond ((step-unresolved-deps-ref step dep) (log/trace "The dependency " (dsp-dependency dep) " is already unresolved in step " (step-num step) ", not adding it again")) (else (log/trace "Marking the dependency " (dsp-dependency dep) " as unresolved in step " (step-num step)) (let-values (((target-infos target-reasons) (collect-infos+reasons (dependency-targets dep) make-install-choice)) ((source-infos source-reasons) (collect-infos+reasons (filter (lambda (version) (not (version=? version (dependency-source dep)))) (package-versions (version-package (dependency-source dep)))) make-install-from-dep-source-choice))) (let ((solvers (make-solver-tracker (append target-infos source-infos) (append target-reasons source-reasons)))) (log/trace "Marked the dependency " (dsp-dependency dep) " as unresolved in step " (step-num step) " with solver list " (dsp-solver-tracker solvers)) (step-add-unresolved-dep! step dep solvers) (find-promotions-for-dep-solvers step dep) (check-solvers-tier step solvers)))))) (define (solver-info-and-reason step dep solver) (assert (choice-dep solver)) (assert (dependency=? (choice-dep solver) dep)) (let* ((version (choice-version solver)) (package (version-package version))) (cond ((choice-set-version-of (step-actions step) package) => (lambda (selected) (when (version=? selected version) (internal-error "The solver " (dsp-choice solver) " of a supposedly unresolved dependency " " is already installed in step " (step-num step))) (log/trace "Not adding " (dsp-choice solver) ": monotonicity violation due to " (dsp-version selected)) (values solver #f (make-install-choice selected #f)))) ((version=? (version-of (version-package version) initial-state) version) (log/trace "Not adding " (dsp-choice solver) ": it is the current version of the package " (dsp-package package)) (values solver #f #f)) ((wt-tree/lookup (step-forbidden-versions step) version #f) => (lambda (forbidden) (log/trace "Not adding " (dsp-choice solver) ": it is forbidden due to the action " (dsp-choice forbidden)) (values solver #f forbidden))) (else (values solver (solver-info solver) #f))))) (define (solver-info choice) (let ((is-deferred (build-is-deferred-listener choice))) (if (expression/value is-deferred) (make-solver-info defer-tier (make-choice-set) (expression/child is-deferred) is-deferred) (make-solver-info (vector-ref version-tiers (version-id (choice-version choice))) (make-choice-set) #f is-deferred)))) (define (find-promotions-for-dep-solvers step dep) (cond ((step-unresolved-deps-ref step dep) => (lambda (tracker) (solver-tracker-for-each (lambda (solver info) (find-promotions-for-solver step solver)) tracker))))) (define (find-promotions-for-solver step solver) (let ((output-domain (make-choice-table)) (discarder (make-blessed-discarder step))) (choice-table-set! output-domain solver #t) (let ((triggered-promotions (find-highest-incipient-promotions-containing promotions (step-actions step) solver output-domain discarder))) (when (< 1 (hashtable-size triggered-promotions)) (internal-error "Found " (hashtable-size triggered-promotions) " (choice -> promotion) mappings for a single choice.")) (loop ((for choice promotion (in-hashtable triggered-promotions))) (increase-solver-tier step promotion choice))))) (define (strike-structurally-forbidden step choice) (let ((reason (singleton-choice-set (choice-with-from-dep-source? choice #f)))) (loop ((for version (in-list (package-versions (version-package (choice-version choice)))))) (unless (version=? version (choice-version choice)) (log/trace "Discarding " (dsp-version version) ": monotonicity violation") (strike-choice step (make-install-choice version #f) reason)))) (when (choice-from-dep-source? choice) (let ((version (choice-version choice)) (reason (singleton-choice-set choice))) (loop ((for target (in-list (dependency-targets (choice-dep choice))))) (unless (version=? target version) (log/trace "Discarding " (dsp-version target) ": forbidden by the resolution of " (dsp-dependency (choice-dep choice))) (strike-choice step (make-install-choice target #f) reason) (step-add-forbidden-version! step target choice)))))) (define (add-promotion step-num promotion) (define p (dsp-promotion promotion)) (cond ((= 0 (choice-set-size (promotion-choices promotion))) (log/debug "Ignoring the empty promotion " p)) ((promotion-set-insert! promotions promotion) (log/debug "Added the promotion " p " to the global promotion set.") (promotion-queue-push! promotion-queue-tail promotion) (let ((new-tail (promotion-queue-next promotion-queue-tail))) (set! promotion-queue-tail new-tail) (log/debug "The promotion queue now contains " (promotion-queue-index new-tail) " promotions with " (promotion-queue-action-sum new-tail) " total actions."))) (else (log/debug "Did not add " p " to the global promotion set: it was redundant" " with an existing promotion."))) (search-graph-schedule-promotion-propagation! graph step-num promotion)) (define (check-for-new-promotions step-num) (let* ((step (search-graph-step graph step-num)) (current-tail promotion-queue-tail) (step-location (step-promotion-queue-location step)) (tail-action-sum (promotion-queue-action-sum current-tail)) (step-action-sum (promotion-queue-action-sum step-location)) (action-delta (- tail-action-sum step-action-sum))) (log/trace (let ((tail-index (promotion-queue-index current-tail)) (step-index (promotion-queue-index step-location))) (cat "The current promotion tail has index " tail-index " and action sum " tail-action-sum "; step " step-num " points to a promotion cell with index " step-index " and action sum " step-action-sum ", for a difference of " (- tail-index step-index) " steps and " action-delta " actions."))) (cond ((<= action-delta (+ (choice-set-size (step-actions step)) (choice-table-size (step-deps-solved-by-choice step)))) (log/trace "Applying each new promotion to step " step-num ".") (loop ((for entry (in-promotion-queue step-location))) (apply-promotion step (promotion-queue-promotion entry))) (set-step-promotion-queue-location! step promotion-queue-tail)) (else (receive (incipient-promotions non-incipient-promotion) (find-highest-incipient-promotions promotions (step-actions step) (step-deps-solved-by-choice step)) (when non-incipient-promotion (log/trace "Found a new promotion in the action set of step " step-num ": " (dsp-promotion non-incipient-promotion)) (increase-step-tier step non-incipient-promotion)) (set-step-promotion-queue-location! step promotion-queue-tail) (loop ((for choice promotion (in-hashtable incipient-promotions))) (increase-solver-tier step promotion choice))))))) (define (apply-promotion step promotion) (define p (dsp-promotion promotion)) (let ((choices (promotion-choices promotion)) (step-num (step-num step))) (cond ((not (tier<? (step-tier step) (promotion-tier promotion))) (log/trace "Not applying " p " to step " step-num ": the step tier " (dsp-tier (step-tier step)) " is not below the promotion tier.")) (else (log/trace "Testing the promotion " p " against step " step-num) (let-values (((action-hits mismatch) (count-action-hits step choices)) ((p-size) (choice-set-size choices))) (cond ((not action-hits) (log/trace "Too many mismatches against " p ", not applying it.")) ((= action-hits p-size) (log/trace "Step " step-num " contains " p " as an active promotion.") (assign-step-tier step-num (step-tier step))) ((< (+ action-hits 1) p-size) (log/trace "Step " step-num " does not contain " p ".")) ((not mismatch) (internal-error "Found an incipient promotion with no mismatches!")) ((not (choice-table-contains? (step-deps-solved-by-choice step) mismatch)) (log/trace "Step " step-num " almost contains " p " as an incipient promotion, but the choice " (dsp-choice mismatch) " is not a solver.")) (else (log/trace "Step " step-num " contains " p " as an incipient promotion for the choice " (dsp-choice mismatch) ".") (increase-solver-tier step promotion mismatch)))))))) (define (increase-solver-tier step promotion solver) (define p (dsp-promotion promotion)) (log/trace "Applying the promotion " p " to the solver " (dsp-choice solver) " in the step " (step-num step)) (let ((new-tier (promotion-tier promotion))) (cond ((or (tier>=? new-tier conflict-tier) (tier>=? new-tier already-generated-tier)) (strike-choice step solver (promotion-choices promotion))) (else (let ((new-choices (choice-set-remove-overlaps (promotion-choices promotion) solver))) (log/trace "Increasing the tier of " (dsp-choice solver) " to " (dsp-tier new-tier) " in all solver lists in step " (step-num step) " with the reason set " (dsp-choice-set new-choices)) (choice-table-visit (step-deps-solved-by-choice step) solver (lambda (solver solved) (do-increase-tier solver solved step new-tier new-choices (promotion-valid-condition promotion)) #f))))))) (define (do-increase-tier solver solved step new-tier new-choices valid-condition) (loop ((for dep (in-list solved))) (let* ((solver-with-dep (choice-with-dep solver dep)) (current-solvers (step-unresolved-deps-ref step dep)) (info (solver-tracker-lookup current-solvers solver-with-dep))) (unless info (internal-error "In step " (step-num step) ", the solver " (dsp-choice solver) "is claimed to be a solver of " (dsp-dependency dep) " but does not appear in its solvers list.")) (when (tier<? (solver-info-tier info) new-tier) (let* ((new-info (make-solver-info new-tier new-choices valid-condition (solver-info-is-deferred-listener info))) (new-solvers (solver-tracker-update current-solvers solver-with-dep new-info))) (step-add-unresolved-dep! step dep new-solvers) (check-solvers-tier step new-solvers) (log/trace "Increased the tier of " (dsp-choice solver-with-dep) "to " (dsp-tier new-tier) " in the solvers list of " (dsp-dependency dep) " in step " (step-num step) " with the reason set " (dsp-choice-set new-choices) " and validity condition " (expression/dsp valid-condition) " ; new solvers list: " (dsp-solver-tracker new-solvers))))))) (define (check-solvers-tier step solvers) (let ((tier (calculate-tier solvers))) (when (tier<? (current-search-tier) tier) (let ((promotion (build-promotion solvers tier))) (log/trace "Emitting a new promotion " (dsp-promotion promotion) " at step " (step-num step)) (add-promotion (step-num step) promotion))) (when (tier<? (step-tier step) tier) (assign-step-tier (step-num step) tier)))) (define (assign-step-tier step-num tier) (let ((step (search-graph-step graph step-num))) (cond ((tier=? (step-tier step) tier) (values)) ((and (step-blessed-solution? step) (tier>=? tier already-generated-tier)) (log/trace "Step " step-num "is a blessed solution" "; ignoring the attempt to promote it to tier" (dsp-tier tier))) (else (log/trace "Setting the tier of step " step-num " to " (dsp-tier tier)) (let* ((was-in-pending? (wt-tree/member? step-num pending)) (was-in-pending-future-solutions? (wt-tree/member? step-num pending-future-solutions)) (step-pending-count (+ (if was-in-pending? 1 0) (if was-in-pending-future-solutions? 1 0)))) (when (step-in-defer-tier? step) (set! num-deferred (- num-deferred step-pending-count))) (set-step-tier! step tier) (when was-in-pending? (wt-tree/add! pending step-num #t)) (when was-in-pending-future-solutions? (wt-tree/add! pending-future-solutions step-num #t)) (cond ((step-in-defer-tier? step) (set! num-deferred step-pending-count)) ((tier<? (step-tier step) defer-tier) (when finished? (set! finished? (> step-pending-count 0)))))))))) (define (strike-choice step victim reasons) the choice set by removing the solver that 's being ;; struck. (let ((generalized-reasons (choice-set-remove-overlaps reasons victim))) (log/trace "Striking " (dsp-choice victim) " from all solver lists in step " (step-num step) " with the reason set " (dsp-choice-set generalized-reasons)) (choice-table-visit (step-deps-solved-by-choice step) victim (lambda (victim solved-by-victim) (log/trace "Removing the choice " (dsp-choice victim) " from the solver lists of [" (fmt-join dsp-dependency solved-by-victim " ") "] in step " (step-num step)) (loop ((for dep (in-list solved-by-victim))) (let ((victim-with-dep (choice-with-dep victim dep))) (define (solvers-modifier current-solvers) (let ((new-solvers (solver-tracker-remove current-solvers victim-with-dep reasons))) (log/trace "Removing the choice " (dsp-choice victim-with-dep) " from the solver set of " (dsp-dependency dep) " in step " (step-num step) ", new solvers: " (dsp-solver-tracker-solvers new-solvers)) new-solvers)) (search-graph-remove-choice! graph victim-with-dep (step-num step) dep) (cond ((step-modify-unresolved-dep! step dep solvers-modifier) => (lambda (new-solvers) Rescan the solvers , maybe updating the step 's tier . (check-solvers-tier step new-solvers))) (else (log/trace "The dependency " (dsp-dependency dep) " has no solver set, assuming it was already solved."))) (log/trace "Removing all solved-by links for " (dsp-choice victim) " in step " (step-num step)) (choice-table-delete! (step-deps-solved-by-choice step) victim) #f ; don't stop )))))) (define (increase-step-tier step promotion) (let ((p-tier (promotion-tier promotion))) (if (tier<? (step-tier step) p-tier) (assign-step-tier (step-num step) p-tier)))) (define (already-seen? step-num) (and-let* ((closed-step-num (hashtable-ref closed (search-graph-step graph step-num) #f))) (cond ((= closed-step-num step-num) #f) (else (log/trace "Step " step-num " is irrelevant: it was already encountered" " in this search.") (search-graph-add-clone! graph closed-step-num step-num) #t)))) (define (irrelevant? step) (let ((tier (step-tier step))) (cond ((or (tier>=? tier conflict-tier) (tier>=? tier already-generated-tier) (< (step-score step) minimum-score)) #t) (else (sanity-check-not-deferred step) #f)))) (define (build-is-deferred-listener choice) (make-expression-wrapper #f)) (define (sanity-check-promotions step) 'FIXME) (define (sanity-check-not-deferred step) 'FIXME) (really-make-solver find-next))) (define (find-next-solution! solver max-steps) ((solver-find-next solver) max-steps)) ;;; Solution (define-record-type* solution (make-solution choices score tier) ()) (define (dsp-solution solution) (let ((choices (choice-set->list (solution-choices solution)))) (cat "<" (fmt-join dsp-choice choices ", ") ">;T" (dsp-tier (solution-tier solution)) "S" (solution-score solution)))) (define-condition-type &out-of-time-condition &condition make-out-of-time-condition out-of-time-condition?) ;;; Installation (define (make-empty-installation) (lambda (package) (package-current-version package))) (define (version-of package installation) (installation package)) (define (extend-installation installation choices) (lambda (package) (or (choice-set-version-of choices package) (version-of package installation)))) (define (broken-under? installation dependency) (let ((source (dependency-source dependency))) (cond ((not (version=? (version-of (version-package source) installation) source)) #f) ((or-map (lambda (target) (version=? (version-of (version-package target) installation) target)) (dependency-targets dependency)) #f) (else #t)))) ;;; Misc utilities (define-record-type* joint-score (make-joint-score choices score) ()) (define (choice-by-action-compare c1 c2) (version-compare (choice-version c1) (choice-version c2))) (define choice-by-action<? (<? choice-by-action-compare)) (define choice-by-action-wt-type (make-wt-tree-type choice-by-action<?)) (define (make-joint-score-set initial-state versions.score-list) (define (versions->choice-set versions) (loop continue ((for version (in-list versions)) (with choices (make-choice-set) (choice-set-insert-or-narrow choices (make-install-choice version #f)))) => choices (if (version=? version (version-of (version-package version) initial-state)) #f (continue)))) (define (add-versions-score joint-scores versions score) (cond ((versions->choice-set versions) => (lambda (choices) (let ((joint-score (make-joint-score choices score))) (choice-set-fold (lambda (choice joint-scores) (wt-tree/update joint-scores choice (lambda (joint-scores) (cons joint-score joint-scores)) '())) joint-scores choices)))) (else joint-scores))) (loop ((for versions.score (in-list versions.score-list)) (with joint-scores (make-wt-tree choice-by-action-wt-type) (add-versions-score joint-scores (car versions.score) (cdr versions.score)))) => joint-scores)) (define (joint-score-set-visit joint-scores choice proc) (and=> (wt-tree/lookup joint-scores choice #f) (lambda (joint-scores) (loop continue ((for joint-score (in-list joint-scores))) (cond ((proc (joint-score-choices joint-score) (joint-score-score joint-score)) => values) (else (continue))))))) (define (make-version-scores universe version.score-list) (let ((version-scores (make-vector (universe-version-count universe) 0))) (loop ((for version.score (in-list version.score-list))) => version-scores (vector-set! version-scores (version-id (car version.score)) (cdr version.score))))) (define option-ref (let ((default-options `((step-score . 10) (broken-score . 10) (infinity . 10000) (goal-score . 10) (full-solution-score . 10) (future-horizon . 50) (initial-choices . ,(make-choice-set)) (remove-stupid? . #t) (joint-scores . ()) (version-scores . ())))) (lambda (options name) (cond ((or (assq name options) (assq name default-options)) => cdr) (else (assertion-violation 'option-ref "invalid solver option" name)))))) (define (universe-broken-dependency-set universe installation) (let ((set (make-wt-tree dependency-wt-type))) (loop ((for dependency (in-stream (universe-dependency-stream universe)))) => set (when (broken-under? installation dependency) (wt-tree/add! set dependency #t))))) ;; Compares steps, according to their "goodness" (the better, the ;; lower, hence the reversed ordering for the scores and actions). (define (step-goodness-compare step1 step2) (refine-compare (tier-compare (step-tier step1) (step-tier step2)) (number-compare (step-score step2) (step-score step1)) (choice-set-compare (step-actions step2) (step-actions step1)))) ;; Returns a wt-type that compares steps in `graph' (indexed by their ;; numbers), according to their "goodness" (the better, the lower, ;; hence the reversed ordering for the scores). (define (search-graph->wt-tree-type graph) (make-wt-tree-type (lambda (step-num1 step-num2) (and (not (= step-num1 step-num2)) ;optimization (let ((step1 (search-graph-step graph step-num1)) (step2 (search-graph-step graph step-num2))) (< (step-goodness-compare step1 step2) 0)))))) These two procedure replace aptitude 's step_contents structure (define (step-contents=? s1 s2) (and (= (step-score s1) (step-score s2)) (= (step-action-score s1) (step-action-score s2)) (choice-set=? (step-actions s1) (step-actions s2)))) (define (step-contents-hash step) (hash-combine (step-score step) (hash-combine (step-action-score step) (choice-set-hash (step-actions step))))) (define (calculate-tier solvers) (loop continue ((for solver info (in-solver-tracker solvers)) (with tier maximum-tier)) => tier (if (tier<? (solver-info-tier info) tier) (continue (=> tier (solver-info-tier info))) (continue)))) (define (build-promotion solvers tier) (loop ((for solver (in-solver-tracker solvers)) (with reasons (make-choice-set) (choice-set-merge reasons (solver-info-reasons solver))) (for valid-conditions (listing (solver-info-tier-valid solver) => values))) => (make-promotion (choice-set-adjoin reasons (solver-tracker-structural-reasons solvers)) tier (cond ((null? valid-conditions) #f) ((null? (cdr valid-conditions)) (car valid-conditions)) (else (make-and-expression valid-conditions)))))) (define (count-action-hits step choices) (let ((actions (step-actions step))) (loop continue ((for choice (in-choice-set choices)) (with hits 0) (with mismatch #f)) => (values hits mismatch) (cond ((choice-set-has-contained-choice? actions choice) (continue (=> hits (+ 1 hits)))) ((not mismatch) (continue (=> mismatch choice))) (else (values #f #f)))))) (define (make-blessed-discarder step) (if (step-blessed-solution? step) (lambda (promotion) (tier<? (promotion-tier promotion) already-generated-tier)) (lambda (promotion) #t))) (define (step-in-defer-tier? step) (and (tier>=? (step-tier step) defer-tier) (tier<? (step-tier step) already-generated-tier))) (define (num/sign n) (num n 10 #f #t)) ) ;; Local Variables: ;; scheme-indent-styles: (foof-loop) ;; End:
null
https://raw.githubusercontent.com/ijp/guildhall/2fe2cc539f4b811bbcd69e58738db03eb5a2b778/guildhall/solver.scm
scheme
solver.scm --- Dependency solver, algorithm This program is free software; you can redistribute it and/or either version 3 This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. Commentary: This file corresponds to aptitude's "problemresolver.h" and "solution.h". Code: The solver The solver constructor -- the solver is obviously an abomination of state, but what do you expect from an algorithm implementation taken from an imperative language? Options Immutable Solver state Public procedures Private procedures don't stop struck. don't stop Solution Installation Misc utilities Compares steps, according to their "goodness" (the better, the lower, hence the reversed ordering for the scores and actions). Returns a wt-type that compares steps in `graph' (indexed by their numbers), according to their "goodness" (the better, the lower, hence the reversed ordering for the scores). optimization Local Variables: scheme-indent-styles: (foof-loop) End:
Copyright ( C ) 2009 - 2011 < > Copyright ( C ) 2009 Author : < > modify it under the terms of the GNU General Public License of the License , or ( at your option ) any later version . You should have received a copy of the GNU General Public License #!r6rs (library (guildhall solver) (export make-solver solver? find-next-solution! solution? solution-choices logger:dorodango.solver) (import (rnrs) (srfi :2 and-let*) (srfi :8 receive) (srfi :67 compare-procedures) (guildhall spells hash-utils) (guildhall spells record-types) (only (guile) assq-ref or-map and=>) (guildhall spells logging) (guildhall ext fmt) (guildhall ext foof-loop) (guildhall ext wt-tree) (guildhall private utils) (guildhall solver logging) (guildhall solver choice) (guildhall solver search-graph) (guildhall solver promotions) (guildhall solver universe) (guildhall solver expression)) (define-record-type* solver (really-make-solver find-next) ()) (define make-solver (case-lambda ((universe options) (construct-solver universe options)) ((universe) (make-solver universe '())))) (define (construct-solver universe options) (letrec* ((promotion-retracted (lambda (promotion) (log/debug "Retracting all tier assignments that might be linked to " (dsp-promotion promotion)))) (option (lambda (name) (option-ref options name))) (score/step (option 'step-score)) (score/broken (option 'broken-score)) (score/infinity (option 'infinity)) (score/goal (option 'goal-score)) (score/full-solution (option 'full-solution-score)) (future-horizon (option 'future-horizon)) (remove-stupid? (option 'remove-stupid?)) (initial-state (extend-installation (make-empty-installation) (option 'initial-choices))) (joint-scores (make-joint-score-set initial-state (option 'joint-scores))) (version-scores (make-version-scores universe (option 'version-scores))) (initial-broken (universe-broken-dependency-set universe initial-state)) (minimum-score (- score/infinity)) (finished? #f) (promotions (make-promotion-set universe promotion-retracted)) (graph (make-search-graph promotions)) (graph-wt-type (search-graph->wt-tree-type graph)) (pending (make-wt-tree graph-wt-type)) (num-deferred 0) (minimum-search-tier minimum-tier) (maximum-search-tier minimum-tier) (closed (make-hashtable step-contents-hash step-contents=?)) (pending-future-solutions (make-wt-tree graph-wt-type)) (promotion-queue-tail (make-promotion-queue 0 0)) (version-tiers (make-vector (universe-version-count universe) minimum-tier))) (define (find-next max-steps) (and (not finished?) (begin (when (and (wt-tree/empty? pending) (wt-tree/empty? pending-future-solutions) (= 0 (hashtable-size closed))) (start-search)) (loop continue ((for remaining-steps (down-from max-steps (to 0))) (with most-future-solution-steps 0) (while (contains-canditate? pending))) => (prepare-result most-future-solution-steps) (when (> most-future-solution-steps 0) (log/debug "Speculative \"future\" resolver tick (" most-future-solution-steps "/" future-horizon ").")) (let ((cur-step-num (wt-tree/min pending))) (wt-tree/delete! pending cur-step-num) (process-step cur-step-num)) (let ((new-most-future-solutions-steps (if (contains-canditate? pending-future-solutions) (+ most-future-solution-steps 1) 0))) (log/trace "Done generating successors.") (search-graph-run-scheduled-promotion-propagations! graph add-promotion) (continue (=> most-future-solution-steps new-most-future-solutions-steps))))))) (define (prepare-result most-future-solution-steps) (log/trace (cond ((> most-future-solution-steps future-horizon) "Done examining future steps for a better solution.") ((not (contains-canditate? pending)) "Exhausted all search branches.") (else "Ran out of time."))) (cond ((contains-canditate? pending-future-solutions) (let* ((best-future-solution (wt-tree/min pending-future-solutions)) (best-future-solution-step (search-graph-step graph best-future-solution))) (sanity-check-not-deferred best-future-solution) (let ((result (make-solution (step-actions best-future-solution-step) (step-score best-future-solution-step) (step-tier best-future-solution-step)))) (log/info "--- Returning the future solution " (dsp-solution result) " from step " best-future-solution) (wt-tree/delete! pending-future-solutions best-future-solution) result))) ((contains-canditate? pending) (raise (condition (make-out-of-time-condition)))) (else (set! finished? #t) #f))) (define (contains-canditate? step-set) (and (not (wt-tree/empty? step-set)) (tier<? (step-tier (search-graph-step graph (wt-tree/min step-set))) defer-tier))) (define (current-search-tier) (if (wt-tree/empty? pending) minimum-tier (step-tier (search-graph-step graph (wt-tree/min pending))))) (define (start-search) (log/info "Starting a new search.") (let* ((broken-size (wt-tree/size initial-broken)) (root-score (+ (* broken-size score/broken) (if (= 0 broken-size) score/full-solution 0))) (root (search-graph-add-root-step! graph root-score))) (set-step-promotion-queue-location! root promotion-queue-tail) (wt-tree/for-each (lambda (dependency true) (add-unresolved-dep root dependency)) initial-broken) (log/debug "Inserting the root at step " (step-num root) " with tier " (dsp-tier (step-tier root))) (wt-tree/add! pending (step-num root) #t))) (define (process-step step-num) (loop continue ((with step-num step-num)) (let ((step (search-graph-step graph step-num))) (log/info "Examining step " step-num " " (dsp-step step)) (when (tier>=? (step-tier step) defer-tier) (internal-error "the tier of step " step-num " is an unprocessed tier, so why is it a candidate?")) (check-for-new-promotions step-num) (sanity-check-promotions step) (cond ((already-seen? step-num) (log/debug "Dropping already visited search node in step " step-num)) ((irrelevant? step) (log/debug "Dropping irrelevant step " step-num)) ((tier>=? (step-tier step) defer-tier) (log/debug "Skipping newly deferred step " step-num) (wt-tree/add! pending step-num #t)) (else (log/trace "Processing step " step-num) (hashtable-set! closed step step-num) (cond ((step-solution? step) (log/info " --- Found solution at step " step-num ": " (dsp-step step)) (add-promotion step-num (make-promotion (generalize-choice-set (step-actions step)) already-generated-tier)) (set-step-blessed-solution?! step #t) (wt-tree/add! pending-future-solutions step-num #t)) (else (generate-successors step-num) (and-let* ((child-num (step-first-child step)) (child (search-graph-step graph child-num)) ((step-last-child? child)) ((tier<? (step-tier child) defer-tier))) (log/trace "Following forced dependency resolution from step " step-num " to step " child-num) (wt-tree/delete! pending child-num) (continue (=> step-num child-num)))))))))) (define (generate-successors step-num) (log/trace "Generating successors for step " step-num) (let ((parent (search-graph-step graph step-num))) (receive (best-dep best-solvers) (step-unresolved-deps-min parent) (let ((num-solvers (solver-tracker-size best-solvers))) (unless (> num-solvers 0) (internal-error "A step containing a dependency with no solvers" " was not promoted to the conflict tier.")) (log/trace "Generating successors for step " step-num " for the dependency " (dsp-solver-tracker best-solvers) " with " num-solvers " solvers: " (dsp-solver-tracker-solvers best-solvers))) (solver-tracker-fold (lambda (solver info first?) (check-for-new-promotions step-num) (unless first? (set-step-last-child?! (search-graph-last-step graph) #f)) (generate-single-successor parent solver (max-compare tier-compare (solver-info-tier info) (step-tier parent))) #f) #t best-solvers)))) (define (generate-single-successor parent original-choice tier) (let* ((reason (choice-with-id original-choice (choice-set-size (step-actions parent)))) (step (search-graph-add-step! graph parent tier reason (build-is-deferred-listener reason)))) (set-step-promotion-queue-location! step promotion-queue-tail) (log/trace "Generating a successor to step " (step-num parent) " for the action " (dsp-choice reason) " with tier " (dsp-tier tier) " and outputting to step " (step-num step)) (unless (choice-dep reason) (internal-error "No dependency attached to the choice " (dsp-choice reason) " used to generate step " (step-num step))) includes steps 1 and 2 steps 3 , 4 step 5 step 6 (extend-score-to-new-step step reason) (log/trace "Generated step " (step-num step) " (" (choice-set-size (step-actions step)) " actions): " (dsp-choice-set (step-actions step)) ";T" (dsp-tier (step-tier step)) "S" (step-score step)) (when (and (tier>=? (step-tier step) defer-tier) (tier<? (step-tier step) already-generated-tier)) (set! num-deferred (+ num-deferred 1))) (wt-tree/add! pending (step-num step) #t))) (define (extend-score-to-new-step step choice) (step-increase-action-score! step score/step) (let* ((version (choice-version choice)) (old-version (version-of (version-package version) initial-state)) (new-score (vector-ref version-scores (version-id version))) (old-score (vector-ref version-scores (version-id old-version)))) (log/trace "Modifying the score of step " (step-num step) " by " (num/sign (- new-score old-score)) " to account for the replacement of " (dsp-version old-version) " (score " old-score ") by " (dsp-version version) " (score " new-score ")") (step-increase-action-score! step (- new-score old-score)) (joint-score-set-visit joint-scores choice (lambda (choices score) (when (choice-set-subset? choices (step-actions step)) (log/trace "Adjusting the score of " (step-num step) " by " (num/sign score) " for a joint score constraint on " (dsp-choice-set choices)) (step-increase-action-score! step score) ))) (let ((num-unresolved-deps (step-num-unresolved-deps step))) (set-step-score! step (+ (step-action-score step) (* score/broken num-unresolved-deps))) (when (= 0 num-unresolved-deps) (log/trace "Modifying the score of step " (step-num step) " by " (num/sign score/full-solution) " because it is a full solution.") (step-increase-score! step score/full-solution))) (log/trace "Updated the score of step " (step-num step) " to " (step-score step)))) (define (find-new-incipient-promotions step choice) (let ((triggered-promotions (find-highest-incipient-promotions-containing promotions (step-actions step) choice (step-deps-solved-by-choice step) (make-blessed-discarder step)))) (loop ((for choice promotion (in-hashtable triggered-promotions))) (increase-solver-tier step promotion choice)))) (define (add-new-unresolved-deps step choice) (let ((test-installation (extend-installation initial-state (step-actions step)))) (define (add-broken-deps! deps) (loop ((for dep (in-list deps))) (when (broken-under? test-installation dep) (add-unresolved-dep step dep)))) (let ((new-version (choice-version choice)) (old-version (version-of (version-package (choice-version choice)) initial-state))) (log/trace "Finding new unresolved dependencies in step " (step-num step) " caused by replacing " (dsp-version old-version) " with " (dsp-version new-version) ".") (add-broken-deps! (version-reverse-dependencies old-version)) (add-broken-deps! (version-reverse-dependencies new-version)) (add-broken-deps! (version-dependencies new-version))))) (define (add-unresolved-dep step dep) (define (collect-infos+reasons versions choice-constructor) (loop ((for version (in-list versions)) (let-values (solver info reason) (solver-info-and-reason step dep (choice-constructor version dep #f))) (for infos (listing (cons solver info) (if info))) (for reasons (listing reason (if reason)))) => (values infos reasons) (when info (log/trace "Adding the solver " (dsp-choice solver) " with initial tier " (dsp-tier (solver-info-tier info))) (step-add-dep-solved-by-choice! step solver dep) (search-graph-bind-choice! graph solver (step-num step) dep)))) (cond ((step-unresolved-deps-ref step dep) (log/trace "The dependency " (dsp-dependency dep) " is already unresolved in step " (step-num step) ", not adding it again")) (else (log/trace "Marking the dependency " (dsp-dependency dep) " as unresolved in step " (step-num step)) (let-values (((target-infos target-reasons) (collect-infos+reasons (dependency-targets dep) make-install-choice)) ((source-infos source-reasons) (collect-infos+reasons (filter (lambda (version) (not (version=? version (dependency-source dep)))) (package-versions (version-package (dependency-source dep)))) make-install-from-dep-source-choice))) (let ((solvers (make-solver-tracker (append target-infos source-infos) (append target-reasons source-reasons)))) (log/trace "Marked the dependency " (dsp-dependency dep) " as unresolved in step " (step-num step) " with solver list " (dsp-solver-tracker solvers)) (step-add-unresolved-dep! step dep solvers) (find-promotions-for-dep-solvers step dep) (check-solvers-tier step solvers)))))) (define (solver-info-and-reason step dep solver) (assert (choice-dep solver)) (assert (dependency=? (choice-dep solver) dep)) (let* ((version (choice-version solver)) (package (version-package version))) (cond ((choice-set-version-of (step-actions step) package) => (lambda (selected) (when (version=? selected version) (internal-error "The solver " (dsp-choice solver) " of a supposedly unresolved dependency " " is already installed in step " (step-num step))) (log/trace "Not adding " (dsp-choice solver) ": monotonicity violation due to " (dsp-version selected)) (values solver #f (make-install-choice selected #f)))) ((version=? (version-of (version-package version) initial-state) version) (log/trace "Not adding " (dsp-choice solver) ": it is the current version of the package " (dsp-package package)) (values solver #f #f)) ((wt-tree/lookup (step-forbidden-versions step) version #f) => (lambda (forbidden) (log/trace "Not adding " (dsp-choice solver) ": it is forbidden due to the action " (dsp-choice forbidden)) (values solver #f forbidden))) (else (values solver (solver-info solver) #f))))) (define (solver-info choice) (let ((is-deferred (build-is-deferred-listener choice))) (if (expression/value is-deferred) (make-solver-info defer-tier (make-choice-set) (expression/child is-deferred) is-deferred) (make-solver-info (vector-ref version-tiers (version-id (choice-version choice))) (make-choice-set) #f is-deferred)))) (define (find-promotions-for-dep-solvers step dep) (cond ((step-unresolved-deps-ref step dep) => (lambda (tracker) (solver-tracker-for-each (lambda (solver info) (find-promotions-for-solver step solver)) tracker))))) (define (find-promotions-for-solver step solver) (let ((output-domain (make-choice-table)) (discarder (make-blessed-discarder step))) (choice-table-set! output-domain solver #t) (let ((triggered-promotions (find-highest-incipient-promotions-containing promotions (step-actions step) solver output-domain discarder))) (when (< 1 (hashtable-size triggered-promotions)) (internal-error "Found " (hashtable-size triggered-promotions) " (choice -> promotion) mappings for a single choice.")) (loop ((for choice promotion (in-hashtable triggered-promotions))) (increase-solver-tier step promotion choice))))) (define (strike-structurally-forbidden step choice) (let ((reason (singleton-choice-set (choice-with-from-dep-source? choice #f)))) (loop ((for version (in-list (package-versions (version-package (choice-version choice)))))) (unless (version=? version (choice-version choice)) (log/trace "Discarding " (dsp-version version) ": monotonicity violation") (strike-choice step (make-install-choice version #f) reason)))) (when (choice-from-dep-source? choice) (let ((version (choice-version choice)) (reason (singleton-choice-set choice))) (loop ((for target (in-list (dependency-targets (choice-dep choice))))) (unless (version=? target version) (log/trace "Discarding " (dsp-version target) ": forbidden by the resolution of " (dsp-dependency (choice-dep choice))) (strike-choice step (make-install-choice target #f) reason) (step-add-forbidden-version! step target choice)))))) (define (add-promotion step-num promotion) (define p (dsp-promotion promotion)) (cond ((= 0 (choice-set-size (promotion-choices promotion))) (log/debug "Ignoring the empty promotion " p)) ((promotion-set-insert! promotions promotion) (log/debug "Added the promotion " p " to the global promotion set.") (promotion-queue-push! promotion-queue-tail promotion) (let ((new-tail (promotion-queue-next promotion-queue-tail))) (set! promotion-queue-tail new-tail) (log/debug "The promotion queue now contains " (promotion-queue-index new-tail) " promotions with " (promotion-queue-action-sum new-tail) " total actions."))) (else (log/debug "Did not add " p " to the global promotion set: it was redundant" " with an existing promotion."))) (search-graph-schedule-promotion-propagation! graph step-num promotion)) (define (check-for-new-promotions step-num) (let* ((step (search-graph-step graph step-num)) (current-tail promotion-queue-tail) (step-location (step-promotion-queue-location step)) (tail-action-sum (promotion-queue-action-sum current-tail)) (step-action-sum (promotion-queue-action-sum step-location)) (action-delta (- tail-action-sum step-action-sum))) (log/trace (let ((tail-index (promotion-queue-index current-tail)) (step-index (promotion-queue-index step-location))) (cat "The current promotion tail has index " tail-index " and action sum " tail-action-sum "; step " step-num " points to a promotion cell with index " step-index " and action sum " step-action-sum ", for a difference of " (- tail-index step-index) " steps and " action-delta " actions."))) (cond ((<= action-delta (+ (choice-set-size (step-actions step)) (choice-table-size (step-deps-solved-by-choice step)))) (log/trace "Applying each new promotion to step " step-num ".") (loop ((for entry (in-promotion-queue step-location))) (apply-promotion step (promotion-queue-promotion entry))) (set-step-promotion-queue-location! step promotion-queue-tail)) (else (receive (incipient-promotions non-incipient-promotion) (find-highest-incipient-promotions promotions (step-actions step) (step-deps-solved-by-choice step)) (when non-incipient-promotion (log/trace "Found a new promotion in the action set of step " step-num ": " (dsp-promotion non-incipient-promotion)) (increase-step-tier step non-incipient-promotion)) (set-step-promotion-queue-location! step promotion-queue-tail) (loop ((for choice promotion (in-hashtable incipient-promotions))) (increase-solver-tier step promotion choice))))))) (define (apply-promotion step promotion) (define p (dsp-promotion promotion)) (let ((choices (promotion-choices promotion)) (step-num (step-num step))) (cond ((not (tier<? (step-tier step) (promotion-tier promotion))) (log/trace "Not applying " p " to step " step-num ": the step tier " (dsp-tier (step-tier step)) " is not below the promotion tier.")) (else (log/trace "Testing the promotion " p " against step " step-num) (let-values (((action-hits mismatch) (count-action-hits step choices)) ((p-size) (choice-set-size choices))) (cond ((not action-hits) (log/trace "Too many mismatches against " p ", not applying it.")) ((= action-hits p-size) (log/trace "Step " step-num " contains " p " as an active promotion.") (assign-step-tier step-num (step-tier step))) ((< (+ action-hits 1) p-size) (log/trace "Step " step-num " does not contain " p ".")) ((not mismatch) (internal-error "Found an incipient promotion with no mismatches!")) ((not (choice-table-contains? (step-deps-solved-by-choice step) mismatch)) (log/trace "Step " step-num " almost contains " p " as an incipient promotion, but the choice " (dsp-choice mismatch) " is not a solver.")) (else (log/trace "Step " step-num " contains " p " as an incipient promotion for the choice " (dsp-choice mismatch) ".") (increase-solver-tier step promotion mismatch)))))))) (define (increase-solver-tier step promotion solver) (define p (dsp-promotion promotion)) (log/trace "Applying the promotion " p " to the solver " (dsp-choice solver) " in the step " (step-num step)) (let ((new-tier (promotion-tier promotion))) (cond ((or (tier>=? new-tier conflict-tier) (tier>=? new-tier already-generated-tier)) (strike-choice step solver (promotion-choices promotion))) (else (let ((new-choices (choice-set-remove-overlaps (promotion-choices promotion) solver))) (log/trace "Increasing the tier of " (dsp-choice solver) " to " (dsp-tier new-tier) " in all solver lists in step " (step-num step) " with the reason set " (dsp-choice-set new-choices)) (choice-table-visit (step-deps-solved-by-choice step) solver (lambda (solver solved) (do-increase-tier solver solved step new-tier new-choices (promotion-valid-condition promotion)) #f))))))) (define (do-increase-tier solver solved step new-tier new-choices valid-condition) (loop ((for dep (in-list solved))) (let* ((solver-with-dep (choice-with-dep solver dep)) (current-solvers (step-unresolved-deps-ref step dep)) (info (solver-tracker-lookup current-solvers solver-with-dep))) (unless info (internal-error "In step " (step-num step) ", the solver " (dsp-choice solver) "is claimed to be a solver of " (dsp-dependency dep) " but does not appear in its solvers list.")) (when (tier<? (solver-info-tier info) new-tier) (let* ((new-info (make-solver-info new-tier new-choices valid-condition (solver-info-is-deferred-listener info))) (new-solvers (solver-tracker-update current-solvers solver-with-dep new-info))) (step-add-unresolved-dep! step dep new-solvers) (check-solvers-tier step new-solvers) (log/trace "Increased the tier of " (dsp-choice solver-with-dep) "to " (dsp-tier new-tier) " in the solvers list of " (dsp-dependency dep) " in step " (step-num step) " with the reason set " (dsp-choice-set new-choices) " and validity condition " (expression/dsp valid-condition) " ; new solvers list: " (dsp-solver-tracker new-solvers))))))) (define (check-solvers-tier step solvers) (let ((tier (calculate-tier solvers))) (when (tier<? (current-search-tier) tier) (let ((promotion (build-promotion solvers tier))) (log/trace "Emitting a new promotion " (dsp-promotion promotion) " at step " (step-num step)) (add-promotion (step-num step) promotion))) (when (tier<? (step-tier step) tier) (assign-step-tier (step-num step) tier)))) (define (assign-step-tier step-num tier) (let ((step (search-graph-step graph step-num))) (cond ((tier=? (step-tier step) tier) (values)) ((and (step-blessed-solution? step) (tier>=? tier already-generated-tier)) (log/trace "Step " step-num "is a blessed solution" "; ignoring the attempt to promote it to tier" (dsp-tier tier))) (else (log/trace "Setting the tier of step " step-num " to " (dsp-tier tier)) (let* ((was-in-pending? (wt-tree/member? step-num pending)) (was-in-pending-future-solutions? (wt-tree/member? step-num pending-future-solutions)) (step-pending-count (+ (if was-in-pending? 1 0) (if was-in-pending-future-solutions? 1 0)))) (when (step-in-defer-tier? step) (set! num-deferred (- num-deferred step-pending-count))) (set-step-tier! step tier) (when was-in-pending? (wt-tree/add! pending step-num #t)) (when was-in-pending-future-solutions? (wt-tree/add! pending-future-solutions step-num #t)) (cond ((step-in-defer-tier? step) (set! num-deferred step-pending-count)) ((tier<? (step-tier step) defer-tier) (when finished? (set! finished? (> step-pending-count 0)))))))))) (define (strike-choice step victim reasons) the choice set by removing the solver that 's being (let ((generalized-reasons (choice-set-remove-overlaps reasons victim))) (log/trace "Striking " (dsp-choice victim) " from all solver lists in step " (step-num step) " with the reason set " (dsp-choice-set generalized-reasons)) (choice-table-visit (step-deps-solved-by-choice step) victim (lambda (victim solved-by-victim) (log/trace "Removing the choice " (dsp-choice victim) " from the solver lists of [" (fmt-join dsp-dependency solved-by-victim " ") "] in step " (step-num step)) (loop ((for dep (in-list solved-by-victim))) (let ((victim-with-dep (choice-with-dep victim dep))) (define (solvers-modifier current-solvers) (let ((new-solvers (solver-tracker-remove current-solvers victim-with-dep reasons))) (log/trace "Removing the choice " (dsp-choice victim-with-dep) " from the solver set of " (dsp-dependency dep) " in step " (step-num step) ", new solvers: " (dsp-solver-tracker-solvers new-solvers)) new-solvers)) (search-graph-remove-choice! graph victim-with-dep (step-num step) dep) (cond ((step-modify-unresolved-dep! step dep solvers-modifier) => (lambda (new-solvers) Rescan the solvers , maybe updating the step 's tier . (check-solvers-tier step new-solvers))) (else (log/trace "The dependency " (dsp-dependency dep) " has no solver set, assuming it was already solved."))) (log/trace "Removing all solved-by links for " (dsp-choice victim) " in step " (step-num step)) (choice-table-delete! (step-deps-solved-by-choice step) victim) )))))) (define (increase-step-tier step promotion) (let ((p-tier (promotion-tier promotion))) (if (tier<? (step-tier step) p-tier) (assign-step-tier (step-num step) p-tier)))) (define (already-seen? step-num) (and-let* ((closed-step-num (hashtable-ref closed (search-graph-step graph step-num) #f))) (cond ((= closed-step-num step-num) #f) (else (log/trace "Step " step-num " is irrelevant: it was already encountered" " in this search.") (search-graph-add-clone! graph closed-step-num step-num) #t)))) (define (irrelevant? step) (let ((tier (step-tier step))) (cond ((or (tier>=? tier conflict-tier) (tier>=? tier already-generated-tier) (< (step-score step) minimum-score)) #t) (else (sanity-check-not-deferred step) #f)))) (define (build-is-deferred-listener choice) (make-expression-wrapper #f)) (define (sanity-check-promotions step) 'FIXME) (define (sanity-check-not-deferred step) 'FIXME) (really-make-solver find-next))) (define (find-next-solution! solver max-steps) ((solver-find-next solver) max-steps)) (define-record-type* solution (make-solution choices score tier) ()) (define (dsp-solution solution) (let ((choices (choice-set->list (solution-choices solution)))) (cat "<" (fmt-join dsp-choice choices ", ") ">;T" (dsp-tier (solution-tier solution)) "S" (solution-score solution)))) (define-condition-type &out-of-time-condition &condition make-out-of-time-condition out-of-time-condition?) (define (make-empty-installation) (lambda (package) (package-current-version package))) (define (version-of package installation) (installation package)) (define (extend-installation installation choices) (lambda (package) (or (choice-set-version-of choices package) (version-of package installation)))) (define (broken-under? installation dependency) (let ((source (dependency-source dependency))) (cond ((not (version=? (version-of (version-package source) installation) source)) #f) ((or-map (lambda (target) (version=? (version-of (version-package target) installation) target)) (dependency-targets dependency)) #f) (else #t)))) (define-record-type* joint-score (make-joint-score choices score) ()) (define (choice-by-action-compare c1 c2) (version-compare (choice-version c1) (choice-version c2))) (define choice-by-action<? (<? choice-by-action-compare)) (define choice-by-action-wt-type (make-wt-tree-type choice-by-action<?)) (define (make-joint-score-set initial-state versions.score-list) (define (versions->choice-set versions) (loop continue ((for version (in-list versions)) (with choices (make-choice-set) (choice-set-insert-or-narrow choices (make-install-choice version #f)))) => choices (if (version=? version (version-of (version-package version) initial-state)) #f (continue)))) (define (add-versions-score joint-scores versions score) (cond ((versions->choice-set versions) => (lambda (choices) (let ((joint-score (make-joint-score choices score))) (choice-set-fold (lambda (choice joint-scores) (wt-tree/update joint-scores choice (lambda (joint-scores) (cons joint-score joint-scores)) '())) joint-scores choices)))) (else joint-scores))) (loop ((for versions.score (in-list versions.score-list)) (with joint-scores (make-wt-tree choice-by-action-wt-type) (add-versions-score joint-scores (car versions.score) (cdr versions.score)))) => joint-scores)) (define (joint-score-set-visit joint-scores choice proc) (and=> (wt-tree/lookup joint-scores choice #f) (lambda (joint-scores) (loop continue ((for joint-score (in-list joint-scores))) (cond ((proc (joint-score-choices joint-score) (joint-score-score joint-score)) => values) (else (continue))))))) (define (make-version-scores universe version.score-list) (let ((version-scores (make-vector (universe-version-count universe) 0))) (loop ((for version.score (in-list version.score-list))) => version-scores (vector-set! version-scores (version-id (car version.score)) (cdr version.score))))) (define option-ref (let ((default-options `((step-score . 10) (broken-score . 10) (infinity . 10000) (goal-score . 10) (full-solution-score . 10) (future-horizon . 50) (initial-choices . ,(make-choice-set)) (remove-stupid? . #t) (joint-scores . ()) (version-scores . ())))) (lambda (options name) (cond ((or (assq name options) (assq name default-options)) => cdr) (else (assertion-violation 'option-ref "invalid solver option" name)))))) (define (universe-broken-dependency-set universe installation) (let ((set (make-wt-tree dependency-wt-type))) (loop ((for dependency (in-stream (universe-dependency-stream universe)))) => set (when (broken-under? installation dependency) (wt-tree/add! set dependency #t))))) (define (step-goodness-compare step1 step2) (refine-compare (tier-compare (step-tier step1) (step-tier step2)) (number-compare (step-score step2) (step-score step1)) (choice-set-compare (step-actions step2) (step-actions step1)))) (define (search-graph->wt-tree-type graph) (make-wt-tree-type (lambda (step-num1 step-num2) (let ((step1 (search-graph-step graph step-num1)) (step2 (search-graph-step graph step-num2))) (< (step-goodness-compare step1 step2) 0)))))) These two procedure replace aptitude 's step_contents structure (define (step-contents=? s1 s2) (and (= (step-score s1) (step-score s2)) (= (step-action-score s1) (step-action-score s2)) (choice-set=? (step-actions s1) (step-actions s2)))) (define (step-contents-hash step) (hash-combine (step-score step) (hash-combine (step-action-score step) (choice-set-hash (step-actions step))))) (define (calculate-tier solvers) (loop continue ((for solver info (in-solver-tracker solvers)) (with tier maximum-tier)) => tier (if (tier<? (solver-info-tier info) tier) (continue (=> tier (solver-info-tier info))) (continue)))) (define (build-promotion solvers tier) (loop ((for solver (in-solver-tracker solvers)) (with reasons (make-choice-set) (choice-set-merge reasons (solver-info-reasons solver))) (for valid-conditions (listing (solver-info-tier-valid solver) => values))) => (make-promotion (choice-set-adjoin reasons (solver-tracker-structural-reasons solvers)) tier (cond ((null? valid-conditions) #f) ((null? (cdr valid-conditions)) (car valid-conditions)) (else (make-and-expression valid-conditions)))))) (define (count-action-hits step choices) (let ((actions (step-actions step))) (loop continue ((for choice (in-choice-set choices)) (with hits 0) (with mismatch #f)) => (values hits mismatch) (cond ((choice-set-has-contained-choice? actions choice) (continue (=> hits (+ 1 hits)))) ((not mismatch) (continue (=> mismatch choice))) (else (values #f #f)))))) (define (make-blessed-discarder step) (if (step-blessed-solution? step) (lambda (promotion) (tier<? (promotion-tier promotion) already-generated-tier)) (lambda (promotion) #t))) (define (step-in-defer-tier? step) (and (tier>=? (step-tier step) defer-tier) (tier<? (step-tier step) already-generated-tier))) (define (num/sign n) (num n 10 #f #t)) )
c5514c5170e58c8d8eaa1d3740d1a381c35290cc9a8da448d3b0ca498a4af115
tezos/tezos-mirror
publisher_worker_types.mli
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2023 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) module Request : sig (** Type of requests accepted by the publisher worker. *) type ('a, 'b) t = | Publish : (unit, error trace) t * Request to publish new commitments in L1 . | Cement : (unit, error trace) t * Request to cement commitments in L1 . type view = View : _ t -> view include Worker_intf.REQUEST with type ('a, 'request_error) t := ('a, 'request_error) t and type view := view end module Name : Worker_intf.NAME with type t = unit
null
https://raw.githubusercontent.com/tezos/tezos-mirror/1b26ce0f9c2a9c508a65c45641a0a146d9b52fc7/src/proto_alpha/lib_sc_rollup_node/publisher_worker_types.mli
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Type of requests accepted by the publisher worker.
Copyright ( c ) 2023 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING module Request : sig type ('a, 'b) t = | Publish : (unit, error trace) t * Request to publish new commitments in L1 . | Cement : (unit, error trace) t * Request to cement commitments in L1 . type view = View : _ t -> view include Worker_intf.REQUEST with type ('a, 'request_error) t := ('a, 'request_error) t and type view := view end module Name : Worker_intf.NAME with type t = unit
695cbde39d1fdb5ac80ad3c279c706bde5a9f3f227254fef7ba491e58ba20e11
jamesmartin/datomic-tutorial
core.clj
(ns datomic-tutorial.core (:gen-class)) (defn -main "I don't do a whole lot ... yet." [& args] (println "Hello, World!"))
null
https://raw.githubusercontent.com/jamesmartin/datomic-tutorial/ca381b9be10e10df5a4c9417cacc512f086ff785/src/datomic_tutorial/core.clj
clojure
(ns datomic-tutorial.core (:gen-class)) (defn -main "I don't do a whole lot ... yet." [& args] (println "Hello, World!"))
8308d61838b681aea165c820401104d03910874f597b70becb46ead7799e3f2f
haskell-streaming/streaming
ByteString.hs
# LANGUAGE LambdaCase , RankNTypes , ScopedTypeVariables # module Stream.Folding.ByteString where import Stream.Types import Stream.Folding.Prelude hiding (fromHandle) import Control.Monad hiding (filterM, mapM) import Data.Functor.Identity import Control.Monad.Trans import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.ByteString.Lazy.Internal (foldrChunks, defaultChunkSize) import Data.ByteString (ByteString) import qualified System.IO as IO import Prelude hiding (map, filter, drop, take, sum , iterate, repeat, replicate, splitAt , takeWhile, enumFrom, enumFromTo) import Foreign.C.Error (Errno(Errno), ePIPE) import qualified GHC.IO.Exception as G import Control.Exception (throwIO, try) import Data.Word fromLazy bs = Folding (\construct wrap done -> foldrChunks (kurry construct) (done ()) bs) stdinLn :: Folding (Of ByteString) IO () stdinLn = fromHandleLn IO.stdin # INLINABLE stdinLn # fromHandleLn :: IO.Handle -> Folding (Of ByteString) IO () fromHandleLn h = Folding $ \construct wrap done -> wrap $ let go = do eof <- IO.hIsEOF h if eof then return (done ()) else do bs <- B.hGetLine h return (construct (bs :> wrap go)) in go {-# INLINABLE fromHandleLn #-} stdin :: Folding (Of ByteString) IO () stdin = fromHandle IO.stdin fromHandle :: IO.Handle -> Folding (Of ByteString) IO () fromHandle = hGetSome defaultChunkSize # INLINABLE fromHandle # hGetSome :: Int -> IO.Handle -> Folding (Of ByteString) IO () hGetSome size h = Folding $ \construct wrap done -> let go = do bs <- B.hGetSome h size if B.null bs then return (done ()) else liftM (construct . (bs :>)) go in wrap go # INLINABLE hGetSome # hGet :: Int -> IO.Handle -> Folding (Of ByteString) IO () hGet size h = Folding $ \construct wrap done -> let go = do bs <- B.hGet h size if B.null bs then return (done ()) else liftM (construct . (bs :>)) go in wrap go {-# INLINABLE hGet #-} stdout :: MonadIO m => Folding (Of ByteString) m () -> m () stdout (Folding phi) = phi (\(bs :> rest) -> do x <- liftIO (try (B.putStr bs)) case x of Left (G.IOError { G.ioe_type = G.ResourceVanished , G.ioe_errno = Just ioe }) | Errno ioe == ePIPE -> return () Left e -> liftIO (throwIO e) Right () -> rest) join (\_ -> return ()) # INLINABLE stdout # toHandle :: MonadIO m => IO.Handle -> Folding (Of ByteString) m () -> m () toHandle h (Folding phi) = phi (\(bs :> rest) -> liftIO (B.hPut h bs) >> rest) join (\_ -> return ()) # INLINE toHandle # -- span -- :: Monad m -- => (Word8 -> Bool) - > Lens ' ( Producer ByteString m x ) ( Producer ByteString m ( Producer ByteString m x ) ) span _ : : -- => Folding_ (Of ByteString) m r -- -> (Word8 -> Bool) -- -- span_ :: Folding_ (Of ByteString) m r -- -- -> (Word8 -> Bool) - > ( Of ByteString r ' - > r ' ) -- -> (m r' -> r') -- -> (Folding (Of ByteString) m r -> r') -- -> r' -- span _ : : -- => Folding (Of ByteString) m r -- -> (Word8 -> Bool) -> Folding (Of ByteString) m (Folding (Of ByteString) m r) -- ------------------------ span _ ( Folding phi ) p = Folding $ \construct wrap done - > ( phi -- (\(bs :> rest) -> undefined) -- (\mf -> undefined) -- (\r c w d -> getFolding r c w d)) -- construct wrap done -- ------------------------ ( \(bs :> Folding rest ) - > Folding $ \c w d - > let ( prefix , suffix ) = B.span p bs -- in if B.null suffix then ( rest c w d ) -- else c (prefix :> d rest) ( \mpsi - > Folding $ \c w d - > w $ mpsi > > = \(Folding psi ) - > return ( psi c w d ) ) ( \r - > Folding $ \c w d - > getFolding ( d r ) ) -- Folding $ \c w d - > wrap $ mpsi > > = \(Folding psi ) - > return ( psi c w d ) -- where -- go p = do -- x <- lift (next p) -- case x of -- Left r -> return (return r) Right ( bs , p ' ) - > do let ( prefix , suffix ) = BS.span predicate bs -- if (BS.null suffix) -- then do -- yield bs -- go p' -- else do -- yield prefix -- return (yield suffix >> p') # INLINABLE span # - } -- break predicate = span (not . predicate) -- nl : : Word8 nl = fromIntegral ( ord ' \n ' ) -- -- _lines : : = > Producer ByteString m x - > FreeT ( Producer ByteString m ) m x _ lines p0 = ( p0 ) -- where p = do -- x <- next p -- case x of -- Left r -> return (PG.Pure r) Right ( bs , p ' ) - > if ( BS.null bs ) -- then go0 p' else return $ PG.Free $ go1 ( yield bs > > p ' ) go1 p = do -- p' <- p^.line return $ PG.FreeT $ do -- x <- nextByte p' -- case x of -- Left r -> return (PG.Pure r) -- Right (_, p'') -> go0 p'' { - # INLINABLE _ lines # - } -- _ unlines : : = > FreeT ( Producer ByteString m ) m x - > Producer ByteString m x _ unlines = concats . -- where addNewline p = p < * yield ( BS.singleton nl ) -- {-# INLINABLE _unlines # -- -- splitAt :: (Monad m) => Int -> Folding (Of ByteString) m r -> Folding (Of ByteString) m (Folding (Of ByteString) m r) splitAt n0 (Folding phi) = phi (\(bs :> nfold) n -> let len = fromIntegral (B.length bs) rest = joinFold (nfold (n-len)) in if n > 0 then if n > len then Folding $ \construct wrap done -> construct $ bs :> getFolding (nfold (n-len)) construct wrap done else let (prefix, suffix) = B.splitAt (fromIntegral n) bs in Folding $ \construct wrap done -> construct $ if B.null suffix then prefix :> done rest else prefix :> done (cons suffix rest) else Folding $ \construct wrap done -> done $ bs `cons` rest ) (\m n -> Folding $ \construct wrap done -> wrap $ liftM (\f -> getFolding (f n) construct wrap done) m ) (\r n -> Folding $ \construct wrap done -> done $ Folding $ \c w d -> d r ) n0
null
https://raw.githubusercontent.com/haskell-streaming/streaming/eb3073e6ada51b2bae82c15a9ef3a21ffa5f5529/benchmarks/old/Stream/Folding/ByteString.hs
haskell
# INLINABLE fromHandleLn # # INLINABLE hGet # span :: Monad m => (Word8 -> Bool) => Folding_ (Of ByteString) m r -> (Word8 -> Bool) -- span_ :: Folding_ (Of ByteString) m r -- -> (Word8 -> Bool) -> (m r' -> r') -> (Folding (Of ByteString) m r -> r') -> r' => Folding (Of ByteString) m r -> (Word8 -> Bool) -> Folding (Of ByteString) m (Folding (Of ByteString) m r) ------------------------ (\(bs :> rest) -> undefined) (\mf -> undefined) (\r c w d -> getFolding r c w d)) construct wrap done ------------------------ in if B.null suffix else c (prefix :> d rest) where go p = do x <- lift (next p) case x of Left r -> return (return r) if (BS.null suffix) then do yield bs go p' else do yield prefix return (yield suffix >> p') break predicate = span (not . predicate) _lines where x <- next p case x of Left r -> return (PG.Pure r) then go0 p' p' <- p^.line x <- nextByte p' case x of Left r -> return (PG.Pure r) Right (_, p'') -> go0 p'' where {-# INLINABLE _unlines #
# LANGUAGE LambdaCase , RankNTypes , ScopedTypeVariables # module Stream.Folding.ByteString where import Stream.Types import Stream.Folding.Prelude hiding (fromHandle) import Control.Monad hiding (filterM, mapM) import Data.Functor.Identity import Control.Monad.Trans import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.ByteString.Lazy.Internal (foldrChunks, defaultChunkSize) import Data.ByteString (ByteString) import qualified System.IO as IO import Prelude hiding (map, filter, drop, take, sum , iterate, repeat, replicate, splitAt , takeWhile, enumFrom, enumFromTo) import Foreign.C.Error (Errno(Errno), ePIPE) import qualified GHC.IO.Exception as G import Control.Exception (throwIO, try) import Data.Word fromLazy bs = Folding (\construct wrap done -> foldrChunks (kurry construct) (done ()) bs) stdinLn :: Folding (Of ByteString) IO () stdinLn = fromHandleLn IO.stdin # INLINABLE stdinLn # fromHandleLn :: IO.Handle -> Folding (Of ByteString) IO () fromHandleLn h = Folding $ \construct wrap done -> wrap $ let go = do eof <- IO.hIsEOF h if eof then return (done ()) else do bs <- B.hGetLine h return (construct (bs :> wrap go)) in go stdin :: Folding (Of ByteString) IO () stdin = fromHandle IO.stdin fromHandle :: IO.Handle -> Folding (Of ByteString) IO () fromHandle = hGetSome defaultChunkSize # INLINABLE fromHandle # hGetSome :: Int -> IO.Handle -> Folding (Of ByteString) IO () hGetSome size h = Folding $ \construct wrap done -> let go = do bs <- B.hGetSome h size if B.null bs then return (done ()) else liftM (construct . (bs :>)) go in wrap go # INLINABLE hGetSome # hGet :: Int -> IO.Handle -> Folding (Of ByteString) IO () hGet size h = Folding $ \construct wrap done -> let go = do bs <- B.hGet h size if B.null bs then return (done ()) else liftM (construct . (bs :>)) go in wrap go stdout :: MonadIO m => Folding (Of ByteString) m () -> m () stdout (Folding phi) = phi (\(bs :> rest) -> do x <- liftIO (try (B.putStr bs)) case x of Left (G.IOError { G.ioe_type = G.ResourceVanished , G.ioe_errno = Just ioe }) | Errno ioe == ePIPE -> return () Left e -> liftIO (throwIO e) Right () -> rest) join (\_ -> return ()) # INLINABLE stdout # toHandle :: MonadIO m => IO.Handle -> Folding (Of ByteString) m () -> m () toHandle h (Folding phi) = phi (\(bs :> rest) -> liftIO (B.hPut h bs) >> rest) join (\_ -> return ()) # INLINE toHandle # - > Lens ' ( Producer ByteString m x ) ( Producer ByteString m ( Producer ByteString m x ) ) span _ : : - > ( Of ByteString r ' - > r ' ) span _ : : span _ ( Folding phi ) p = Folding $ \construct wrap done - > ( phi ( \(bs :> Folding rest ) - > Folding $ \c w d - > let ( prefix , suffix ) = B.span p bs then ( rest c w d ) ( \mpsi - > Folding $ \c w d - > w $ mpsi > > = \(Folding psi ) - > return ( psi c w d ) ) ( \r - > Folding $ \c w d - > getFolding ( d r ) ) Folding $ \c w d - > wrap $ mpsi > > = \(Folding psi ) - > return ( psi c w d ) Right ( bs , p ' ) - > do let ( prefix , suffix ) = BS.span predicate bs # INLINABLE span # - } nl : : Word8 nl = fromIntegral ( ord ' \n ' ) : : = > Producer ByteString m x - > FreeT ( Producer ByteString m ) m x _ lines p0 = ( p0 ) p = do Right ( bs , p ' ) - > if ( BS.null bs ) else return $ PG.Free $ go1 ( yield bs > > p ' ) go1 p = do return $ PG.FreeT $ do { - # INLINABLE _ lines # - } _ unlines : : = > FreeT ( Producer ByteString m ) m x - > Producer ByteString m x _ unlines = concats . addNewline p = p < * yield ( BS.singleton nl ) splitAt :: (Monad m) => Int -> Folding (Of ByteString) m r -> Folding (Of ByteString) m (Folding (Of ByteString) m r) splitAt n0 (Folding phi) = phi (\(bs :> nfold) n -> let len = fromIntegral (B.length bs) rest = joinFold (nfold (n-len)) in if n > 0 then if n > len then Folding $ \construct wrap done -> construct $ bs :> getFolding (nfold (n-len)) construct wrap done else let (prefix, suffix) = B.splitAt (fromIntegral n) bs in Folding $ \construct wrap done -> construct $ if B.null suffix then prefix :> done rest else prefix :> done (cons suffix rest) else Folding $ \construct wrap done -> done $ bs `cons` rest ) (\m n -> Folding $ \construct wrap done -> wrap $ liftM (\f -> getFolding (f n) construct wrap done) m ) (\r n -> Folding $ \construct wrap done -> done $ Folding $ \c w d -> d r ) n0
264fad01460446ec830bb103434e378295953dc5d9983dc7efe729c7a4ebcf4f
mbutterick/beautiful-racket
tokenize-only.rkt
#lang br/quicklang (require "parser.rkt" "tokenizer.rkt" brag/support) (define (read-syntax path port) (define tokens (apply-tokenizer-maker make-tokenizer port)) (strip-bindings #`(module basic-parser-mod basic-demo-3/parse-only '#,tokens))) (module+ reader (provide read-syntax)) (define-macro (mb PARSE-TREE) #'(#%module-begin 'PARSE-TREE)) (provide (rename-out [mb #%module-begin]))
null
https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/basic-demo-3/tokenize-only.rkt
racket
#lang br/quicklang (require "parser.rkt" "tokenizer.rkt" brag/support) (define (read-syntax path port) (define tokens (apply-tokenizer-maker make-tokenizer port)) (strip-bindings #`(module basic-parser-mod basic-demo-3/parse-only '#,tokens))) (module+ reader (provide read-syntax)) (define-macro (mb PARSE-TREE) #'(#%module-begin 'PARSE-TREE)) (provide (rename-out [mb #%module-begin]))
47034bb3302706a433c40cc8e0cdb604c3f5b1829e7984fb9c9b89f06afa05b6
luc-tielen/eclair-lang
Lower.hs
module Eclair.AST.Lower ( compileToRA ) where import Prelude hiding (swap, project) import qualified Data.Graph as G import qualified Data.Map as M import Eclair.AST.Codegen import Eclair.AST.IR hiding (Clause) import Eclair.Common.Id import Eclair.Common.Location (NodeId(..)) import qualified Eclair.RA.IR as RA import Eclair.Common.Extern type RA = RA.RA type Relation = RA.Relation compileToRA :: [Extern] -> AST -> RA compileToRA externs ast = RA.Module (NodeId 0) $ concatMap processDecls sortedDecls where sortedDecls = scc ast processDecls :: [AST] -> [RA] processDecls = \case [Atom _ name values] -> runCodegen externs $ let literals = map toTerm values in one <$> project name literals [Rule _ name args clauses] -> let terms = map toTerm args in runCodegen externs $ processSingleRule name terms clauses rules -> -- case for multiple mutually recursive rules runCodegen externs $ processMultipleRules rules scc :: AST -> [[AST]] scc = \case Module _ decls -> map G.flattenSCC sortedDecls' where relevantDecls = filter isRuleOrAtom decls sortedDecls' = G.stronglyConnComp $ zipWith (\i d -> (d, i, refersTo d)) [0..] relevantDecls declLineMapping = M.fromListWith (<>) $ zipWith (\i d -> (nameFor d, [i])) [0..] relevantDecls isRuleOrAtom = \case Atom {} -> True Rule {} -> True _ -> False refersTo :: AST -> [Int] refersTo = \case Rule _ _ _ clauses -> -- If no top level facts are defined, no entry exists in declLine mapping -> default to -1 concatMap (fromMaybe [-1] . flip M.lookup declLineMapping . nameFor) $ filter isRuleOrAtom clauses _ -> [] nameFor = \case Atom _ name _ -> name Rule _ name _ _ -> name Because of " " _ -> unreachable -- Because rejected by parser where unreachable = panic "Unreachable code in 'scc'" -- NOTE: These rules can all be evaluated in parallel inside the fixpoint loop processMultipleRules :: [AST] -> CodegenM [RA] processMultipleRules rules = sequence stmts where stmts = mergeStmts <> [loop (purgeStmts <> ruleStmts <> [exitStmt] <> endLoopStmts)] mergeStmts = map (\r -> merge r (deltaRelationOf r)) relations purgeStmts = map (purge . newRelationOf) relations ruleStmts = [parallel $ map f rulesInfo] exitStmt = exit $ map newRelationOf relations endLoopStmts = concatMap toMergeAndSwapStmts relations toMergeAndSwapStmts r = let newRelation = newRelationOf r deltaRelation = deltaRelationOf r in [merge newRelation r, swap newRelation deltaRelation] rulesInfo = mapMaybe extractRuleData rules relations = map (\(r, _, _) -> r) rulesInfo -- TODO: better func name f (r, map toTerm -> ts, clauses) = recursiveRuleToStmt r ts clauses processSingleRule :: Relation -> [CodegenM RA] -> [AST] -> CodegenM [RA] processSingleRule relation terms clauses | isRecursive relation clauses = let deltaRelation = deltaRelationOf relation newRelation = newRelationOf relation stmts = [ merge relation deltaRelation , loop [ purge newRelation , ruleToStmt relation terms clauses , exit [newRelation] , merge newRelation relation , swap newRelation deltaRelation ] ] in sequence stmts | otherwise = one <$> ruleToStmt relation terms clauses ruleToStmt :: Relation -> [CodegenM RA] -> [AST] -> CodegenM RA ruleToStmt relation terms clauses | isRecursive relation clauses = recursiveRuleToStmt relation terms clauses | otherwise = nestedSearchAndProject relation relation terms clauses id recursiveRuleToStmt :: Relation -> [CodegenM RA] -> [AST] -> CodegenM RA recursiveRuleToStmt relation terms clauses = let newRelation = newRelationOf relation extraClause = noElemOf relation terms in nestedSearchAndProject relation newRelation terms clauses extraClause nestedSearchAndProject :: Relation -> Relation -> [CodegenM RA] -> [AST] -> (CodegenM RA -> CodegenM RA) -> CodegenM RA nestedSearchAndProject relation intoRelation terms clauses wrapWithExtraClause = flip (foldr (processRuleClause relation)) clauses $ wrapWithExtraClause $ project intoRelation terms where processRuleClause ruleName clause inner = case clause of Atom _ clauseName args -> do externs <- asks envExterns let relation' = if clauseName `startsWithId` ruleName then prependToId deltaPrefix clauseName else clauseName isExtern = isJust $ find (\(Extern name _ _) -> relation' == name) externs if isExtern then do clause' <- toTerm clause zero <- toTerm (Lit (NodeId 0) $ LNumber 0) if' NotEquals clause' zero inner else search relation' args inner Not _ (Atom _ clauseName args) -> do -- No starts with check here, since cyclic negation is not allowed. let terms' = map toTerm args noElemOf clauseName terms' inner Constraint _ op lhs rhs -> do lhsTerm <- toTerm lhs rhsTerm <- toTerm rhs if' op lhsTerm rhsTerm inner _ -> panic "Unexpected rule clause in 'nestedSearchAndProject'!" isRecursive :: Relation -> [AST] -> Bool isRecursive ruleName clauses = let atomNames = flip mapMaybe clauses $ \case Atom _ name _ -> Just name _ -> Nothing in ruleName `elem` atomNames extractRuleData :: AST -> Maybe (Relation, [AST], [AST]) extractRuleData = \case Rule _ name args clauses -> Just (name, args, clauses) _ -> Nothing newRelationOf, deltaRelationOf :: Relation -> Relation deltaRelationOf = prependToId deltaPrefix newRelationOf = prependToId newPrefix
null
https://raw.githubusercontent.com/luc-tielen/eclair-lang/343db5e350ec8132cf0773b32a4cc112653bdab4/lib/Eclair/AST/Lower.hs
haskell
case for multiple mutually recursive rules If no top level facts are defined, no entry exists in declLine mapping -> default to -1 Because rejected by parser NOTE: These rules can all be evaluated in parallel inside the fixpoint loop TODO: better func name No starts with check here, since cyclic negation is not allowed.
module Eclair.AST.Lower ( compileToRA ) where import Prelude hiding (swap, project) import qualified Data.Graph as G import qualified Data.Map as M import Eclair.AST.Codegen import Eclair.AST.IR hiding (Clause) import Eclair.Common.Id import Eclair.Common.Location (NodeId(..)) import qualified Eclair.RA.IR as RA import Eclair.Common.Extern type RA = RA.RA type Relation = RA.Relation compileToRA :: [Extern] -> AST -> RA compileToRA externs ast = RA.Module (NodeId 0) $ concatMap processDecls sortedDecls where sortedDecls = scc ast processDecls :: [AST] -> [RA] processDecls = \case [Atom _ name values] -> runCodegen externs $ let literals = map toTerm values in one <$> project name literals [Rule _ name args clauses] -> let terms = map toTerm args in runCodegen externs $ processSingleRule name terms clauses runCodegen externs $ processMultipleRules rules scc :: AST -> [[AST]] scc = \case Module _ decls -> map G.flattenSCC sortedDecls' where relevantDecls = filter isRuleOrAtom decls sortedDecls' = G.stronglyConnComp $ zipWith (\i d -> (d, i, refersTo d)) [0..] relevantDecls declLineMapping = M.fromListWith (<>) $ zipWith (\i d -> (nameFor d, [i])) [0..] relevantDecls isRuleOrAtom = \case Atom {} -> True Rule {} -> True _ -> False refersTo :: AST -> [Int] refersTo = \case Rule _ _ _ clauses -> concatMap (fromMaybe [-1] . flip M.lookup declLineMapping . nameFor) $ filter isRuleOrAtom clauses _ -> [] nameFor = \case Atom _ name _ -> name Rule _ name _ _ -> name Because of " " where unreachable = panic "Unreachable code in 'scc'" processMultipleRules :: [AST] -> CodegenM [RA] processMultipleRules rules = sequence stmts where stmts = mergeStmts <> [loop (purgeStmts <> ruleStmts <> [exitStmt] <> endLoopStmts)] mergeStmts = map (\r -> merge r (deltaRelationOf r)) relations purgeStmts = map (purge . newRelationOf) relations ruleStmts = [parallel $ map f rulesInfo] exitStmt = exit $ map newRelationOf relations endLoopStmts = concatMap toMergeAndSwapStmts relations toMergeAndSwapStmts r = let newRelation = newRelationOf r deltaRelation = deltaRelationOf r in [merge newRelation r, swap newRelation deltaRelation] rulesInfo = mapMaybe extractRuleData rules relations = map (\(r, _, _) -> r) rulesInfo f (r, map toTerm -> ts, clauses) = recursiveRuleToStmt r ts clauses processSingleRule :: Relation -> [CodegenM RA] -> [AST] -> CodegenM [RA] processSingleRule relation terms clauses | isRecursive relation clauses = let deltaRelation = deltaRelationOf relation newRelation = newRelationOf relation stmts = [ merge relation deltaRelation , loop [ purge newRelation , ruleToStmt relation terms clauses , exit [newRelation] , merge newRelation relation , swap newRelation deltaRelation ] ] in sequence stmts | otherwise = one <$> ruleToStmt relation terms clauses ruleToStmt :: Relation -> [CodegenM RA] -> [AST] -> CodegenM RA ruleToStmt relation terms clauses | isRecursive relation clauses = recursiveRuleToStmt relation terms clauses | otherwise = nestedSearchAndProject relation relation terms clauses id recursiveRuleToStmt :: Relation -> [CodegenM RA] -> [AST] -> CodegenM RA recursiveRuleToStmt relation terms clauses = let newRelation = newRelationOf relation extraClause = noElemOf relation terms in nestedSearchAndProject relation newRelation terms clauses extraClause nestedSearchAndProject :: Relation -> Relation -> [CodegenM RA] -> [AST] -> (CodegenM RA -> CodegenM RA) -> CodegenM RA nestedSearchAndProject relation intoRelation terms clauses wrapWithExtraClause = flip (foldr (processRuleClause relation)) clauses $ wrapWithExtraClause $ project intoRelation terms where processRuleClause ruleName clause inner = case clause of Atom _ clauseName args -> do externs <- asks envExterns let relation' = if clauseName `startsWithId` ruleName then prependToId deltaPrefix clauseName else clauseName isExtern = isJust $ find (\(Extern name _ _) -> relation' == name) externs if isExtern then do clause' <- toTerm clause zero <- toTerm (Lit (NodeId 0) $ LNumber 0) if' NotEquals clause' zero inner else search relation' args inner Not _ (Atom _ clauseName args) -> do let terms' = map toTerm args noElemOf clauseName terms' inner Constraint _ op lhs rhs -> do lhsTerm <- toTerm lhs rhsTerm <- toTerm rhs if' op lhsTerm rhsTerm inner _ -> panic "Unexpected rule clause in 'nestedSearchAndProject'!" isRecursive :: Relation -> [AST] -> Bool isRecursive ruleName clauses = let atomNames = flip mapMaybe clauses $ \case Atom _ name _ -> Just name _ -> Nothing in ruleName `elem` atomNames extractRuleData :: AST -> Maybe (Relation, [AST], [AST]) extractRuleData = \case Rule _ name args clauses -> Just (name, args, clauses) _ -> Nothing newRelationOf, deltaRelationOf :: Relation -> Relation deltaRelationOf = prependToId deltaPrefix newRelationOf = prependToId newPrefix
ed2609a688d60f016902eeca4ee6ac68e1299aa93249d517ec98d7b841d8be62
untangled-web/untangled
locales.cljs
(ns app.i18n.locales (:require goog.module goog.module.ModuleLoader [goog.module.ModuleManager :as module-manager] [untangled.i18n.core :as i18n] app.i18n.en-US app.i18n.es-MX) (:import goog.module.ModuleManager)) (defonce manager (module-manager/getInstance)) (defonce modules #js {"en-US" "/en-US.js", "es-MX" "/es-MX.js"}) (defonce module-info #js {"en-US" [], "es-MX" []}) (defonce ^:export loader (let [loader (goog.module.ModuleLoader.)] (.setLoader manager loader) (.setAllModuleInfo manager module-info) (.setModuleUris manager modules) loader)) (defn set-locale [l] (js/console.log (str "LOADING ALTERNATE LOCALE: " l)) (if (exists? js/i18nDevMode) (do (js/console.log (str "LOADED ALTERNATE LOCALE in dev mode: " l)) (reset! i18n/*current-locale* l)) (.execOnLoad manager l (fn after-locale-load [] (js/console.log (str "LOADED ALTERNATE LOCALE: " l)) (reset! i18n/*current-locale* l)))))
null
https://raw.githubusercontent.com/untangled-web/untangled/705220539ff00b1e487ae387def11daad8638206/src/client/app/i18n/locales.cljs
clojure
(ns app.i18n.locales (:require goog.module goog.module.ModuleLoader [goog.module.ModuleManager :as module-manager] [untangled.i18n.core :as i18n] app.i18n.en-US app.i18n.es-MX) (:import goog.module.ModuleManager)) (defonce manager (module-manager/getInstance)) (defonce modules #js {"en-US" "/en-US.js", "es-MX" "/es-MX.js"}) (defonce module-info #js {"en-US" [], "es-MX" []}) (defonce ^:export loader (let [loader (goog.module.ModuleLoader.)] (.setLoader manager loader) (.setAllModuleInfo manager module-info) (.setModuleUris manager modules) loader)) (defn set-locale [l] (js/console.log (str "LOADING ALTERNATE LOCALE: " l)) (if (exists? js/i18nDevMode) (do (js/console.log (str "LOADED ALTERNATE LOCALE in dev mode: " l)) (reset! i18n/*current-locale* l)) (.execOnLoad manager l (fn after-locale-load [] (js/console.log (str "LOADED ALTERNATE LOCALE: " l)) (reset! i18n/*current-locale* l)))))
67a03b3a1b97e953f40ff934a20b74e63ff7de9b1dfaaa9298758575f055f2a5
Simre1/hero
Render.hs
# LANGUAGE TypeFamilies # module Hero.SDL2.Render ( runGraphics, Graphics (..), GraphicsConfig (..), SDL.WindowConfig (..), defaultGraphics, Render (..), render, Sprite (..), TextureSprite(..), SDL.Texture, loadTexture, Shape (..), Fill (..), fillBorder, fillColor, Camera (..), defaultCamera, ) where import Control.Category (Category (id, (.)), (>>>)) import Control.Monad.IO.Class (MonadIO) import Data.Coerce (coerce) import Data.Maybe (Maybe (..), fromMaybe, maybe) import Data.Text (Text, pack) import Data.Vector.Storable qualified as Vector import Data.Word (Word8) import GHC.Generics (Generic) import Hero ( Arrow (arr, first, second, (&&&)), BoxedSparseSet, Component (Store), Global, Position2D (..), Rectangle (Rectangle), Rotation2D (..), System, addGlobal, cmapM, getGlobal, liftSystem, once, withSetup, ) import Linear.V2 (V2 (..)) import Linear.V4 (V4 (..)) import Optics.Core ((^.)) import SDL qualified import SDL.Image qualified as Image import SDL.Primitive qualified as GFX import SDL.Video qualified as SDL import SDL.Video.Renderer qualified as SDL import Prelude hiding (id, (.)) -- | The graphics context containing the window and the renderer. -- It can be accessed globally since its stored in a `Global` store. data Graphics = Graphics { renderer :: {-# UNPACK #-} !SDL.Renderer, window :: {-# UNPACK #-} !SDL.Window } deriving (Generic) -- | All entities with a Render component get rendered. -- Rendering position is its Position2D + offset -- Rotation is its Rotation2D + rotation data Render = Render { rotation :: {-# UNPACK #-} !Float, offset :: {-# UNPACK #-} !(V2 Float), sprite :: {-# UNPACK #-} !Sprite } deriving (Generic) -- | Default render with no rotation, no offset and a blue circle as a sprite. render :: Render render = Render 0 (V2 0 0) (Shape (SCircle 25) $ Fill (Just $ V4 100 140 200 255) Nothing) -- | Fill colors used to draw shapes data Fill = Fill { color :: {-# UNPACK #-} !(Maybe (V4 Word8)), border :: {-# UNPACK #-} !(Maybe (V4 Word8)) } deriving (Generic) -- | Fill with color but no border fillColor :: V4 Word8 -> Fill fillColor c = Fill {color = Just c, border = Nothing} -- | Fill with border but no inner color fillBorder :: V4 Word8 -> Fill fillBorder c = Fill {color = Nothing, border = Just c} -- | The supported shapes data Shape = SRectangle {size :: (V2 Float)} | SCircle {radius :: Float} deriving (Generic) -- A sprite can either be a shape or a texture data Sprite = Shape {shape :: Shape, fill :: Fill} | Texture TextureSprite deriving (Generic) -- | A texture sprite defines a section of the texture which will be rendered data TextureSprite = TextureSprite { size :: V2 Float, source :: Maybe (Rectangle Float), texture :: SDL.Texture } deriving (Generic) instance Component Render where type Store Render = BoxedSparseSet instance Component Graphics where type Store Graphics = Global -- | The Camera defines which portion of the world should be rendered. It is in a `Global` store. data Camera = Camera { position :: V2 Float, size :: V2 Float } deriving (Generic, Show) instance Component Camera where type Store Camera = Global createWindow :: GraphicsConfig -> IO Graphics createWindow graphicsConfig = do SDL.initialize [SDL.InitVideo] window <- SDL.createWindow (graphicsConfig ^. #windowName) (graphicsConfig ^. #windowConfig) renderer <- SDL.createRenderer window (-1) $ SDL.RendererConfig (if graphicsConfig ^. #vsync then SDL.AcceleratedVSyncRenderer else SDL.AcceleratedRenderer) False pure $ Graphics renderer window data GraphicsConfig = GraphicsConfig { windowName :: Text, windowConfig :: SDL.WindowConfig, vsync :: Bool } deriving (Generic) defaultGraphics :: GraphicsConfig defaultGraphics = GraphicsConfig { windowName = pack "Hero App", windowConfig = SDL.defaultWindow, vsync = True } defaultCamera :: Camera defaultCamera = Camera { position = V2 0 0, size = V2 800 600 } -- | Initializes SDL2 graphics and runs the render functions after the given system. -- Use `runGraphics` to wrap your game logic systems to ensure that the render system runs after your game logic. runGraphics :: forall i o. GraphicsConfig -> System i o -> System i o runGraphics graphicsConfig system = setup >>> second system >>> first graphics >>> arr snd where setup :: System i (Graphics, i) setup = withSetup (\_ -> createWindow graphicsConfig) (\graphics -> addGlobal graphics *> addGlobal defaultCamera *> pure graphics) &&& id graphics :: System Graphics () graphics = let render = (id &&& getGlobal @Camera) >>> liftSystem ( \(graphics@(Graphics renderer window), camera) -> do windowSize@(V2 windowLength windowHeight) <- fmap (fmap fromIntegral) $ SDL.get $ SDL.windowSize window let scale = windowSize / (camera ^. #size) pure (graphics, scale, adjustPosition camera windowSize) ) >>> cmapM renderEntities present = liftSystem (\g@(Graphics renderer _) -> SDL.present renderer) clear = liftSystem (\g@(Graphics renderer _) -> SDL.rendererDrawColor renderer SDL.$= (V4 0 0 0 255) >> SDL.clear renderer *> pure g) in clear >>> id &&& render >>> arr fst >>> present # INLINE runGraphics # adjustPosition :: Camera -> V2 Float -> V2 Float -> V2 Float adjustPosition (camera@(Camera (V2 cX cY) cameraSize)) windowSize@(V2 windowLength windowHeight) (V2 x y) = let (V2 wX wY) = ((V2 x y) - (V2 cX cY)) * scale in 0.5 * windowSize + V2 wX (-wY) where scale = windowSize / cameraSize rotatePoint :: Float -> V2 Float -> V2 Float rotatePoint radian (V2 x y) = V2 (x * cos radian - y * sin radian) (x * sin radian + y * cos radian) renderEntities :: MonadIO m => (Graphics, V2 Float, V2 Float -> V2 Float) -> (Maybe Position2D, Maybe Rotation2D, Render) -> m () renderEntities (Graphics renderer window, scale, adjustPosition) (maybePosition, maybeRotation, render :: Render) = do let Position2D x y = fromMaybe (Position2D 0 0) maybePosition worldPosition = V2 x y + render ^. #offset windowPosition = adjustPosition worldPosition rotationRadian = fromMaybe 0 (coerce maybeRotation) + render ^. #rotation case render ^. #sprite of Texture (TextureSprite size source texture) -> do let scaledSize@(V2 sX sY) = size * scale sourceRect = (\(Rectangle pos src) -> round <$> SDL.Rectangle (SDL.P pos) src) <$> source destRect = round <$> SDL.Rectangle (SDL.P $ windowPosition - 0.5 * scaledSize) scaledSize rotationDegrees = realToFrac $ rotationRadian * (180 / pi) SDL.copyEx renderer texture sourceRect (Just destRect) rotationDegrees Nothing (V2 False False) Shape shape fill -> do let fillColor = fill ^. #color borderColor = fill ^. #border case shape of SRectangle size -> let half@(V2 hx hy) = scale * size / 2 in if abs rotationRadian < 0.01 then do let topLeft = windowPosition - half bottomRight = windowPosition + half maybe (pure ()) (GFX.fillRectangle renderer (round <$> topLeft) (round <$> bottomRight)) fillColor maybe (pure ()) (GFX.rectangle renderer (round <$> topLeft) (round <$> bottomRight)) borderColor else do let points = (+ windowPosition) . rotatePoint rotationRadian <$> [V2 (-hx) (-hy), V2 (hx) (-hy), V2 (hx) (hy), V2 (-hx) (hy)] let xs = Vector.fromList $ round . (\(V2 x _) -> x) <$> points let ys = Vector.fromList $ round . (\(V2 _ y) -> y) <$> points maybe (pure ()) (GFX.fillPolygon renderer xs ys) fillColor maybe (pure ()) (GFX.polygon renderer xs ys) borderColor SCircle radius -> do let r = round radius pos = round <$> windowPosition maybe (pure ()) (GFX.fillCircle renderer pos r) fillColor maybe (pure ()) (GFX.circle renderer pos r) borderColor | Loads a texture in the compilation step of a System and outputs it permanently . The Texture will stay alive for the whole -- program duration, so it is only suitable for small-scale applications. loadTexture :: FilePath -> System i SDL.Texture loadTexture filepath = getGlobal @Graphics >>> once (liftSystem $ \graphics -> Image.loadTexture (graphics ^. #renderer) filepath) {-# INLINE loadTexture #-}
null
https://raw.githubusercontent.com/Simre1/hero/99399835a983cc175870550f88665f50872d8be8/hero-sdl2/src/Hero/SDL2/Render.hs
haskell
| The graphics context containing the window and the renderer. It can be accessed globally since its stored in a `Global` store. # UNPACK # # UNPACK # | All entities with a Render component get rendered. Rendering position is its Position2D + offset Rotation is its Rotation2D + rotation # UNPACK # # UNPACK # # UNPACK # | Default render with no rotation, no offset and a blue circle as a sprite. | Fill colors used to draw shapes # UNPACK # # UNPACK # | Fill with color but no border | Fill with border but no inner color | The supported shapes A sprite can either be a shape or a texture | A texture sprite defines a section of the texture which will be rendered | The Camera defines which portion of the world should be rendered. It is in a `Global` store. | Initializes SDL2 graphics and runs the render functions after the given system. Use `runGraphics` to wrap your game logic systems to ensure that the render system runs after your game logic. program duration, so it is only suitable for small-scale applications. # INLINE loadTexture #
# LANGUAGE TypeFamilies # module Hero.SDL2.Render ( runGraphics, Graphics (..), GraphicsConfig (..), SDL.WindowConfig (..), defaultGraphics, Render (..), render, Sprite (..), TextureSprite(..), SDL.Texture, loadTexture, Shape (..), Fill (..), fillBorder, fillColor, Camera (..), defaultCamera, ) where import Control.Category (Category (id, (.)), (>>>)) import Control.Monad.IO.Class (MonadIO) import Data.Coerce (coerce) import Data.Maybe (Maybe (..), fromMaybe, maybe) import Data.Text (Text, pack) import Data.Vector.Storable qualified as Vector import Data.Word (Word8) import GHC.Generics (Generic) import Hero ( Arrow (arr, first, second, (&&&)), BoxedSparseSet, Component (Store), Global, Position2D (..), Rectangle (Rectangle), Rotation2D (..), System, addGlobal, cmapM, getGlobal, liftSystem, once, withSetup, ) import Linear.V2 (V2 (..)) import Linear.V4 (V4 (..)) import Optics.Core ((^.)) import SDL qualified import SDL.Image qualified as Image import SDL.Primitive qualified as GFX import SDL.Video qualified as SDL import SDL.Video.Renderer qualified as SDL import Prelude hiding (id, (.)) data Graphics = Graphics } deriving (Generic) data Render = Render } deriving (Generic) render :: Render render = Render 0 (V2 0 0) (Shape (SCircle 25) $ Fill (Just $ V4 100 140 200 255) Nothing) data Fill = Fill } deriving (Generic) fillColor :: V4 Word8 -> Fill fillColor c = Fill {color = Just c, border = Nothing} fillBorder :: V4 Word8 -> Fill fillBorder c = Fill {color = Nothing, border = Just c} data Shape = SRectangle {size :: (V2 Float)} | SCircle {radius :: Float} deriving (Generic) data Sprite = Shape {shape :: Shape, fill :: Fill} | Texture TextureSprite deriving (Generic) data TextureSprite = TextureSprite { size :: V2 Float, source :: Maybe (Rectangle Float), texture :: SDL.Texture } deriving (Generic) instance Component Render where type Store Render = BoxedSparseSet instance Component Graphics where type Store Graphics = Global data Camera = Camera { position :: V2 Float, size :: V2 Float } deriving (Generic, Show) instance Component Camera where type Store Camera = Global createWindow :: GraphicsConfig -> IO Graphics createWindow graphicsConfig = do SDL.initialize [SDL.InitVideo] window <- SDL.createWindow (graphicsConfig ^. #windowName) (graphicsConfig ^. #windowConfig) renderer <- SDL.createRenderer window (-1) $ SDL.RendererConfig (if graphicsConfig ^. #vsync then SDL.AcceleratedVSyncRenderer else SDL.AcceleratedRenderer) False pure $ Graphics renderer window data GraphicsConfig = GraphicsConfig { windowName :: Text, windowConfig :: SDL.WindowConfig, vsync :: Bool } deriving (Generic) defaultGraphics :: GraphicsConfig defaultGraphics = GraphicsConfig { windowName = pack "Hero App", windowConfig = SDL.defaultWindow, vsync = True } defaultCamera :: Camera defaultCamera = Camera { position = V2 0 0, size = V2 800 600 } runGraphics :: forall i o. GraphicsConfig -> System i o -> System i o runGraphics graphicsConfig system = setup >>> second system >>> first graphics >>> arr snd where setup :: System i (Graphics, i) setup = withSetup (\_ -> createWindow graphicsConfig) (\graphics -> addGlobal graphics *> addGlobal defaultCamera *> pure graphics) &&& id graphics :: System Graphics () graphics = let render = (id &&& getGlobal @Camera) >>> liftSystem ( \(graphics@(Graphics renderer window), camera) -> do windowSize@(V2 windowLength windowHeight) <- fmap (fmap fromIntegral) $ SDL.get $ SDL.windowSize window let scale = windowSize / (camera ^. #size) pure (graphics, scale, adjustPosition camera windowSize) ) >>> cmapM renderEntities present = liftSystem (\g@(Graphics renderer _) -> SDL.present renderer) clear = liftSystem (\g@(Graphics renderer _) -> SDL.rendererDrawColor renderer SDL.$= (V4 0 0 0 255) >> SDL.clear renderer *> pure g) in clear >>> id &&& render >>> arr fst >>> present # INLINE runGraphics # adjustPosition :: Camera -> V2 Float -> V2 Float -> V2 Float adjustPosition (camera@(Camera (V2 cX cY) cameraSize)) windowSize@(V2 windowLength windowHeight) (V2 x y) = let (V2 wX wY) = ((V2 x y) - (V2 cX cY)) * scale in 0.5 * windowSize + V2 wX (-wY) where scale = windowSize / cameraSize rotatePoint :: Float -> V2 Float -> V2 Float rotatePoint radian (V2 x y) = V2 (x * cos radian - y * sin radian) (x * sin radian + y * cos radian) renderEntities :: MonadIO m => (Graphics, V2 Float, V2 Float -> V2 Float) -> (Maybe Position2D, Maybe Rotation2D, Render) -> m () renderEntities (Graphics renderer window, scale, adjustPosition) (maybePosition, maybeRotation, render :: Render) = do let Position2D x y = fromMaybe (Position2D 0 0) maybePosition worldPosition = V2 x y + render ^. #offset windowPosition = adjustPosition worldPosition rotationRadian = fromMaybe 0 (coerce maybeRotation) + render ^. #rotation case render ^. #sprite of Texture (TextureSprite size source texture) -> do let scaledSize@(V2 sX sY) = size * scale sourceRect = (\(Rectangle pos src) -> round <$> SDL.Rectangle (SDL.P pos) src) <$> source destRect = round <$> SDL.Rectangle (SDL.P $ windowPosition - 0.5 * scaledSize) scaledSize rotationDegrees = realToFrac $ rotationRadian * (180 / pi) SDL.copyEx renderer texture sourceRect (Just destRect) rotationDegrees Nothing (V2 False False) Shape shape fill -> do let fillColor = fill ^. #color borderColor = fill ^. #border case shape of SRectangle size -> let half@(V2 hx hy) = scale * size / 2 in if abs rotationRadian < 0.01 then do let topLeft = windowPosition - half bottomRight = windowPosition + half maybe (pure ()) (GFX.fillRectangle renderer (round <$> topLeft) (round <$> bottomRight)) fillColor maybe (pure ()) (GFX.rectangle renderer (round <$> topLeft) (round <$> bottomRight)) borderColor else do let points = (+ windowPosition) . rotatePoint rotationRadian <$> [V2 (-hx) (-hy), V2 (hx) (-hy), V2 (hx) (hy), V2 (-hx) (hy)] let xs = Vector.fromList $ round . (\(V2 x _) -> x) <$> points let ys = Vector.fromList $ round . (\(V2 _ y) -> y) <$> points maybe (pure ()) (GFX.fillPolygon renderer xs ys) fillColor maybe (pure ()) (GFX.polygon renderer xs ys) borderColor SCircle radius -> do let r = round radius pos = round <$> windowPosition maybe (pure ()) (GFX.fillCircle renderer pos r) fillColor maybe (pure ()) (GFX.circle renderer pos r) borderColor | Loads a texture in the compilation step of a System and outputs it permanently . The Texture will stay alive for the whole loadTexture :: FilePath -> System i SDL.Texture loadTexture filepath = getGlobal @Graphics >>> once (liftSystem $ \graphics -> Image.loadTexture (graphics ^. #renderer) filepath)
b065a76ed6f962fd27283feac4fccab972be803e67ad4088e40262e1bf784bc6
elastic/eui-cljs
timeline_item_icon.cljs
(ns eui.timeline-item-icon (:require ["@elastic/eui/lib/components/timeline/timeline_item_icon.js" :as eui])) (def EuiTimelineItemIcon eui/EuiTimelineItemIcon)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/timeline_item_icon.cljs
clojure
(ns eui.timeline-item-icon (:require ["@elastic/eui/lib/components/timeline/timeline_item_icon.js" :as eui])) (def EuiTimelineItemIcon eui/EuiTimelineItemIcon)
fc661497b529dc1549f49d9f4e3c6df0930fc3c8c2add37e24da913b6a2d2eb5
startalkIM/ejabberd
iconv.erl
%%%---------------------------------------------------------------------- %%% File : iconv.erl Author : < > Purpose : Interface to Created : 16 Feb 2003 by < > %%% %%% Copyright ( C ) 2002 - 2016 ProcessOne , SARL . All Rights Reserved . %%% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% -2.0 %%% %%% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%---------------------------------------------------------------------- -module(iconv). -author(''). -export([load_nif/0, load_nif/1, convert/3]). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. %%%=================================================================== %%% API functions %%%=================================================================== load_nif() -> NifFile = p1_nif_utils:get_so_path(?MODULE, [iconv], "iconv"), case erlang:load_nif(NifFile, 0) of ok -> ok; {error, {Reason, Txt}} -> error_logger:error_msg("failed to load NIF ~s: ~s", [NifFile, Txt]), {error, Reason} end. load_nif(_LibDir) -> load_nif(). -spec convert(iodata(), iodata(), iodata()) -> binary(). convert(_From, _To, _String) -> erlang:nif_error(nif_not_loaded). %%%=================================================================== %%% Unit tests %%%=================================================================== -ifdef(TEST). load_nif_test() -> ?assertEqual(ok, load_nif(filename:join(["..", "priv", "lib"]))). utf8_to_koi8r_test() -> ?assertEqual( <<212,197,211,212>>, iconv:convert("utf-8", "koi8-r", <<209,130,208,181,209,129,209,130>>)). koi8r_to_cp1251_test() -> ?assertEqual( <<242,229,241,242>>, iconv:convert("koi8-r", "cp1251", <<212,197,211,212>>)). wrong_encoding_test() -> ?assertEqual( <<1,2,3,4,5>>, iconv:convert("wrong_encoding_from", "wrong_encoding_to", <<1,2,3,4,5>>)). -endif.
null
https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/deps/iconv/src/iconv.erl
erlang
---------------------------------------------------------------------- File : iconv.erl 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. ---------------------------------------------------------------------- =================================================================== API functions =================================================================== =================================================================== Unit tests ===================================================================
Author : < > Purpose : Interface to Created : 16 Feb 2003 by < > Copyright ( C ) 2002 - 2016 ProcessOne , SARL . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(iconv). -author(''). -export([load_nif/0, load_nif/1, convert/3]). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. load_nif() -> NifFile = p1_nif_utils:get_so_path(?MODULE, [iconv], "iconv"), case erlang:load_nif(NifFile, 0) of ok -> ok; {error, {Reason, Txt}} -> error_logger:error_msg("failed to load NIF ~s: ~s", [NifFile, Txt]), {error, Reason} end. load_nif(_LibDir) -> load_nif(). -spec convert(iodata(), iodata(), iodata()) -> binary(). convert(_From, _To, _String) -> erlang:nif_error(nif_not_loaded). -ifdef(TEST). load_nif_test() -> ?assertEqual(ok, load_nif(filename:join(["..", "priv", "lib"]))). utf8_to_koi8r_test() -> ?assertEqual( <<212,197,211,212>>, iconv:convert("utf-8", "koi8-r", <<209,130,208,181,209,129,209,130>>)). koi8r_to_cp1251_test() -> ?assertEqual( <<242,229,241,242>>, iconv:convert("koi8-r", "cp1251", <<212,197,211,212>>)). wrong_encoding_test() -> ?assertEqual( <<1,2,3,4,5>>, iconv:convert("wrong_encoding_from", "wrong_encoding_to", <<1,2,3,4,5>>)). -endif.
85f4c420f2b6e39fe7705bd20ad2beff8840bdc04cfdebb1b92d3baf5e57320b
adamgundry/uom-plugin
Internal.hs
# LANGUAGE DataKinds # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RoleAnnotations # # LANGUAGE StandaloneDeriving # # LANGUAGE StandaloneKindSignatures # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # -- | This module defines the core types used in the @uom-plugin@ -- library. Note that importing this module may allow you to violate -- invariants, so you should generally work with the safe interface in -- "Data.UnitsOfMeasure" instead. module Data.UnitsOfMeasure.Internal ( -- * Type-level units of measure Unit , type One , type Base , type (*:) , type (/:) , type (^:) -- * Values indexed by their units , Quantity(..) , unQuantity , zero , mk * Unit - safe ' ' operations , (+:) , (*:) , (-:) , negate' , abs' , signum' , fromInteger' -- * Unit-safe 'Fractional' operations , (/:) , recip' , fromRational' -- * Unit-safe 'Real' operations , toRational' -- * Unit-safe 'Floating' operations , sqrt' -- * Syntactic representation of units , UnitSyntax(..) , Unpack , Pack , Prod -- * Internal , type (~~) , MkUnit ) where import Control.DeepSeq import Foreign.Storable import GHC.Exts (Constraint) import GHC.TypeLits (Symbol, Nat, type (-)) -- | (Kind) Units of measure data Unit | Dimensionless unit ( identity element ) type family One :: Unit where -- | Base unit type Base :: Symbol -> Unit type family Base b where -- | Multiplication for units of measure type (*:) :: Unit -> Unit -> Unit type family u *: v where -- | Division for units of measure type (/:) :: Unit -> Unit -> Unit type family u /: v where -- | Exponentiation (to a positive power) for units of measure; negative exponents are not yet supported ( they require an Integer kind ) type (^:) :: Unit -> Nat -> Unit type family u ^: n where u ^: 0 = One u ^: 1 = u u ^: n = u *: (u ^: (n-1)) infixl 6 +:, -: infixl 7 *:, /: infixr 8 ^: -- | A @Quantity a u@ is represented identically to a value of -- underlying numeric type @a@, but with units @u@. newtype Quantity a (u :: Unit) = MkQuantity a ^ Warning : the ' MkQuantity ' constructor allows module invariants -- to be violated, so use it with caution! type role Quantity representational nominal -- These classes work uniformly on the underlying representation, -- regardless of the units deriving instance Bounded a => Bounded (Quantity a u) deriving instance Eq a => Eq (Quantity a u) deriving instance Ord a => Ord (Quantity a u) -- These classes are not unit-polymorphic, so we have to restrict the -- unit index to be dimensionless deriving instance (Enum a, u ~ One) => Enum (Quantity a u) deriving instance (Floating a, u ~ One) => Floating (Quantity a u) deriving instance (Fractional a, u ~ One) => Fractional (Quantity a u) deriving instance (Integral a, u ~ One) => Integral (Quantity a u) deriving instance (Num a, u ~ One) => Num (Quantity a u) deriving instance (Real a, u ~ One) => Real (Quantity a u) deriving instance (RealFloat a, u ~ One) => RealFloat (Quantity a u) deriving instance (RealFrac a, u ~ One) => RealFrac (Quantity a u) To enable marshalling into FFI code . deriving instance Storable a => Storable (Quantity a u) To enable deriving NFData for data types containing Quantity fields . deriving instance NFData a => NFData (Quantity a u) -- | Extract the underlying value of a quantity unQuantity :: Quantity a u -> a unQuantity (MkQuantity x) = x -- | Zero is polymorphic in its units: this is required because the ' ' instance constrains the quantity to be dimensionless , so -- @0 :: Quantity a u@ is not well typed. zero :: Num a => Quantity a u zero = MkQuantity 0 -- | Construct a 'Quantity' from a dimensionless value. Note that for -- numeric literals, the 'Num' and 'Fractional' instances allow them -- to be treated as quantities directly. mk :: a -> Quantity a One mk = MkQuantity -- | Addition ('+') of quantities requires the units to match. (+:) :: Num a => Quantity a u -> Quantity a u -> Quantity a u MkQuantity x +: MkQuantity y = MkQuantity (x + y) {-# INLINE (+:) #-} -- | Multiplication ('*') of quantities multiplies the units. (*:) :: (Num a, w ~~ u *: v) => Quantity a u -> Quantity a v -> Quantity a w MkQuantity x *: MkQuantity y = MkQuantity (x * y) {-# INLINE (*:) #-} -- | Subtraction ('-') of quantities requires the units to match. (-:) :: Num a => Quantity a u -> Quantity a u -> Quantity a u MkQuantity x -: MkQuantity y = MkQuantity (x - y) {-# INLINE (-:) #-} -- | Negation ('negate') of quantities is polymorphic in the units. negate' :: Num a => Quantity a u -> Quantity a u negate' (MkQuantity x) = MkQuantity (negate x) {-# INLINE negate' #-} -- | Absolute value ('abs') of quantities is polymorphic in the units. abs' :: Num a => Quantity a u -> Quantity a u abs' (MkQuantity x) = MkQuantity (abs x) {-# INLINE abs' #-} -- | The sign ('signum') of a quantity gives a dimensionless result. signum' :: Num a => Quantity a u -> Quantity a One signum' (MkQuantity x) = MkQuantity (signum x) # INLINE signum ' # | Convert an ' Integer ' quantity into any ' Integral ' type ( ' fromInteger ' ) . fromInteger' :: Integral a => Quantity Integer u -> Quantity a u fromInteger' (MkQuantity x) = MkQuantity (fromInteger x) # INLINE fromInteger ' # -- | Division ('/') of quantities divides the units. (/:) :: (Fractional a, w ~~ u /: v) => Quantity a u -> Quantity a v -> Quantity a w MkQuantity x /: MkQuantity y = MkQuantity (x / y) {-# INLINE (/:) #-} -- | Reciprocal ('recip') of quantities reciprocates the units. recip' :: (Fractional a, w ~~ One /: u) => Quantity a u -> Quantity a w recip' (MkQuantity x) = MkQuantity (recip x) {-# INLINE recip' #-} -- | Convert a 'Rational' quantity into any 'Fractional' type ('fromRational'). fromRational' :: Fractional a => Quantity Rational u -> Quantity a u fromRational' (MkQuantity x) = MkQuantity (fromRational x) # INLINE fromRational ' # -- | Convert any 'Real' quantity into a 'Rational' type ('toRational'). toRational' :: Real a => Quantity a u -> Quantity Rational u toRational' (MkQuantity x) = MkQuantity (toRational x) # INLINE toRational ' # -- | Taking the square root ('sqrt') of a quantity requires its units -- to be a square. Fractional units are not currently supported. sqrt' :: (Floating a, w ~~ u ^: 2) => Quantity a w -> Quantity a u sqrt' (MkQuantity x) = MkQuantity (sqrt x) {-# INLINE sqrt' #-} -- | Syntactic representation of a unit as a pair of lists of base -- units, for example 'One' is represented as @[] ':/' []@ and @'Base ' " m " ' / : ' ' Base ' " s " ^ : 2@ is represented as @["m " ] ' :/ ' [ " s","s"]@. data UnitSyntax s = [s] :/ [s] deriving (Eq, Show) -- | Pack up a syntactic representation of a unit as a unit. For example: -- -- @ 'Pack' ([] ':/' []) = 'One' @ -- @ ' Pack ' ( [ " m " ] ' :/ ' [ " s","s " ] ) = ' Base ' " m " ' / : ' ' Base ' " s " ^ : 2 @ -- -- This is a perfectly ordinary closed type family. 'Pack' is a left inverse of ' Unpack ' up to the equational theory of units , but it is -- not a right inverse (because there are multiple list -- representations of the same unit). type Pack :: UnitSyntax Symbol -> Unit type family Pack u where Pack (xs :/ ys) = Prod xs /: Prod ys -- | Take the product of a list of base units. type Prod :: [Symbol] -> Unit type family Prod xs where Prod '[] = One Prod (x ': xs) = Base x *: Prod xs -- | Unpack a unit as a syntactic representation, where the order of -- units is deterministic. For example: -- -- @ 'Unpack' 'One' = [] ':/' [] @ -- -- @ 'Unpack' ('Base' "s" '*:' 'Base' "m") = ["m","s"] ':/' [] @ -- -- This does not break type soundness because ' Unpack ' will reduce only when the unit is entirely constant , and -- it does not allow the structure of the unit to be observed. The -- reduction behaviour is implemented by the plugin, because we cannot -- define it otherwise. type Unpack :: Unit -> UnitSyntax Symbol type family Unpack u where -- | This is a bit of a hack, honestly, but a good hack. Constraints -- @u ~~ v@ are just like equalities @u ~ v@, except solving them will -- be delayed until the plugin. This may lead to better inferred types. type (~~) :: Unit -> Unit -> Constraint type family u ~~ v where infix 4 ~~ -- | This type family is used for translating unit names (as -- type-level strings) into units. It will be 'Base' for base units -- or expand the definition for derived units. -- The instances displayed by are available only if " Data . UnitsOfMeasure . " is imported . type MkUnit :: Symbol -> Unit type family MkUnit s
null
https://raw.githubusercontent.com/adamgundry/uom-plugin/067a926042a6279cd13efc50c75112e53c95cb27/uom-plugin/src/Data/UnitsOfMeasure/Internal.hs
haskell
| This module defines the core types used in the @uom-plugin@ library. Note that importing this module may allow you to violate invariants, so you should generally work with the safe interface in "Data.UnitsOfMeasure" instead. * Type-level units of measure * Values indexed by their units * Unit-safe 'Fractional' operations * Unit-safe 'Real' operations * Unit-safe 'Floating' operations * Syntactic representation of units * Internal | (Kind) Units of measure | Base unit | Multiplication for units of measure | Division for units of measure | Exponentiation (to a positive power) for units of measure; | A @Quantity a u@ is represented identically to a value of underlying numeric type @a@, but with units @u@. to be violated, so use it with caution! These classes work uniformly on the underlying representation, regardless of the units These classes are not unit-polymorphic, so we have to restrict the unit index to be dimensionless | Extract the underlying value of a quantity | Zero is polymorphic in its units: this is required because the @0 :: Quantity a u@ is not well typed. | Construct a 'Quantity' from a dimensionless value. Note that for numeric literals, the 'Num' and 'Fractional' instances allow them to be treated as quantities directly. | Addition ('+') of quantities requires the units to match. # INLINE (+:) # | Multiplication ('*') of quantities multiplies the units. # INLINE (*:) # | Subtraction ('-') of quantities requires the units to match. # INLINE (-:) # | Negation ('negate') of quantities is polymorphic in the units. # INLINE negate' # | Absolute value ('abs') of quantities is polymorphic in the units. # INLINE abs' # | The sign ('signum') of a quantity gives a dimensionless result. | Division ('/') of quantities divides the units. # INLINE (/:) # | Reciprocal ('recip') of quantities reciprocates the units. # INLINE recip' # | Convert a 'Rational' quantity into any 'Fractional' type ('fromRational'). | Convert any 'Real' quantity into a 'Rational' type ('toRational'). | Taking the square root ('sqrt') of a quantity requires its units to be a square. Fractional units are not currently supported. # INLINE sqrt' # | Syntactic representation of a unit as a pair of lists of base units, for example 'One' is represented as @[] ':/' []@ and | Pack up a syntactic representation of a unit as a unit. For example: @ 'Pack' ([] ':/' []) = 'One' @ This is a perfectly ordinary closed type family. 'Pack' is a left not a right inverse (because there are multiple list representations of the same unit). | Take the product of a list of base units. | Unpack a unit as a syntactic representation, where the order of units is deterministic. For example: @ 'Unpack' 'One' = [] ':/' [] @ @ 'Unpack' ('Base' "s" '*:' 'Base' "m") = ["m","s"] ':/' [] @ This does not break type soundness because it does not allow the structure of the unit to be observed. The reduction behaviour is implemented by the plugin, because we cannot define it otherwise. | This is a bit of a hack, honestly, but a good hack. Constraints @u ~~ v@ are just like equalities @u ~ v@, except solving them will be delayed until the plugin. This may lead to better inferred types. | This type family is used for translating unit names (as type-level strings) into units. It will be 'Base' for base units or expand the definition for derived units.
# LANGUAGE DataKinds # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RoleAnnotations # # LANGUAGE StandaloneDeriving # # LANGUAGE StandaloneKindSignatures # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Data.UnitsOfMeasure.Internal Unit , type One , type Base , type (*:) , type (/:) , type (^:) , Quantity(..) , unQuantity , zero , mk * Unit - safe ' ' operations , (+:) , (*:) , (-:) , negate' , abs' , signum' , fromInteger' , (/:) , recip' , fromRational' , toRational' , sqrt' , UnitSyntax(..) , Unpack , Pack , Prod , type (~~) , MkUnit ) where import Control.DeepSeq import Foreign.Storable import GHC.Exts (Constraint) import GHC.TypeLits (Symbol, Nat, type (-)) data Unit | Dimensionless unit ( identity element ) type family One :: Unit where type Base :: Symbol -> Unit type family Base b where type (*:) :: Unit -> Unit -> Unit type family u *: v where type (/:) :: Unit -> Unit -> Unit type family u /: v where negative exponents are not yet supported ( they require an Integer kind ) type (^:) :: Unit -> Nat -> Unit type family u ^: n where u ^: 0 = One u ^: 1 = u u ^: n = u *: (u ^: (n-1)) infixl 6 +:, -: infixl 7 *:, /: infixr 8 ^: newtype Quantity a (u :: Unit) = MkQuantity a ^ Warning : the ' MkQuantity ' constructor allows module invariants type role Quantity representational nominal deriving instance Bounded a => Bounded (Quantity a u) deriving instance Eq a => Eq (Quantity a u) deriving instance Ord a => Ord (Quantity a u) deriving instance (Enum a, u ~ One) => Enum (Quantity a u) deriving instance (Floating a, u ~ One) => Floating (Quantity a u) deriving instance (Fractional a, u ~ One) => Fractional (Quantity a u) deriving instance (Integral a, u ~ One) => Integral (Quantity a u) deriving instance (Num a, u ~ One) => Num (Quantity a u) deriving instance (Real a, u ~ One) => Real (Quantity a u) deriving instance (RealFloat a, u ~ One) => RealFloat (Quantity a u) deriving instance (RealFrac a, u ~ One) => RealFrac (Quantity a u) To enable marshalling into FFI code . deriving instance Storable a => Storable (Quantity a u) To enable deriving NFData for data types containing Quantity fields . deriving instance NFData a => NFData (Quantity a u) unQuantity :: Quantity a u -> a unQuantity (MkQuantity x) = x ' ' instance constrains the quantity to be dimensionless , so zero :: Num a => Quantity a u zero = MkQuantity 0 mk :: a -> Quantity a One mk = MkQuantity (+:) :: Num a => Quantity a u -> Quantity a u -> Quantity a u MkQuantity x +: MkQuantity y = MkQuantity (x + y) (*:) :: (Num a, w ~~ u *: v) => Quantity a u -> Quantity a v -> Quantity a w MkQuantity x *: MkQuantity y = MkQuantity (x * y) (-:) :: Num a => Quantity a u -> Quantity a u -> Quantity a u MkQuantity x -: MkQuantity y = MkQuantity (x - y) negate' :: Num a => Quantity a u -> Quantity a u negate' (MkQuantity x) = MkQuantity (negate x) abs' :: Num a => Quantity a u -> Quantity a u abs' (MkQuantity x) = MkQuantity (abs x) signum' :: Num a => Quantity a u -> Quantity a One signum' (MkQuantity x) = MkQuantity (signum x) # INLINE signum ' # | Convert an ' Integer ' quantity into any ' Integral ' type ( ' fromInteger ' ) . fromInteger' :: Integral a => Quantity Integer u -> Quantity a u fromInteger' (MkQuantity x) = MkQuantity (fromInteger x) # INLINE fromInteger ' # (/:) :: (Fractional a, w ~~ u /: v) => Quantity a u -> Quantity a v -> Quantity a w MkQuantity x /: MkQuantity y = MkQuantity (x / y) recip' :: (Fractional a, w ~~ One /: u) => Quantity a u -> Quantity a w recip' (MkQuantity x) = MkQuantity (recip x) fromRational' :: Fractional a => Quantity Rational u -> Quantity a u fromRational' (MkQuantity x) = MkQuantity (fromRational x) # INLINE fromRational ' # toRational' :: Real a => Quantity a u -> Quantity Rational u toRational' (MkQuantity x) = MkQuantity (toRational x) # INLINE toRational ' # sqrt' :: (Floating a, w ~~ u ^: 2) => Quantity a w -> Quantity a u sqrt' (MkQuantity x) = MkQuantity (sqrt x) @'Base ' " m " ' / : ' ' Base ' " s " ^ : 2@ is represented as @["m " ] ' :/ ' [ " s","s"]@. data UnitSyntax s = [s] :/ [s] deriving (Eq, Show) @ ' Pack ' ( [ " m " ] ' :/ ' [ " s","s " ] ) = ' Base ' " m " ' / : ' ' Base ' " s " ^ : 2 @ inverse of ' Unpack ' up to the equational theory of units , but it is type Pack :: UnitSyntax Symbol -> Unit type family Pack u where Pack (xs :/ ys) = Prod xs /: Prod ys type Prod :: [Symbol] -> Unit type family Prod xs where Prod '[] = One Prod (x ': xs) = Base x *: Prod xs ' Unpack ' will reduce only when the unit is entirely constant , and type Unpack :: Unit -> UnitSyntax Symbol type family Unpack u where type (~~) :: Unit -> Unit -> Constraint type family u ~~ v where infix 4 ~~ The instances displayed by are available only if " Data . UnitsOfMeasure . " is imported . type MkUnit :: Symbol -> Unit type family MkUnit s
a6bf6fbac8213bae57ddb14421ccf6c07271efb5419b3d656dd0c5f54ac290dc
RedPRL/algaeff
TestUniqueID.mli
(* This file is intentionally blank to detect unused declarations. *)
null
https://raw.githubusercontent.com/RedPRL/algaeff/0a9742860a98d2ad0297ffed4760670baf91d041/test/TestUniqueID.mli
ocaml
This file is intentionally blank to detect unused declarations.
108871f454535948703e299817ed590e01390fa48e74c90fd455c41dda348440
jeroanan/rkt-coreutils
id.rkt
#lang s-exp "util/frontend-program.rkt" (require "repl/id.rkt") (id)
null
https://raw.githubusercontent.com/jeroanan/rkt-coreutils/571629d1e2562c557ba258b31ce454add2e93dd9/src/id.rkt
racket
#lang s-exp "util/frontend-program.rkt" (require "repl/id.rkt") (id)
8de73bc91e5a5776b13410709932cbac2710df8f9240a618c6c59be2eea78d1a
elaforge/karya
Swam_test.hs
Copyright 2019 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt module User.Elaforge.Instrument.Swam_test where import qualified Derive.Controls as Controls import qualified Derive.DeriveTest as DeriveTest import qualified Derive.Score as Score import qualified Ui.UiTest as UiTest import qualified User.Elaforge.Instrument.Swam as Swam import Util.Test test_bow :: Test test_bow = do let run title = DeriveTest.extract extract . DeriveTest.derive_tracks_setup setup ("inst=i | %dyn=.75" <> title) . UiTest.note_track1 extract e = (Score.event_start e, DeriveTest.e_initial_control Controls.dynamic e) equal (run "" ["4c"]) ([(0, Just 0.75)], []) equal (run "" ["bow down | -- 4c"]) ([(0, Just (-0.75))], []) equal (run "" ["bow up | -- 4c"]) ([(0, Just 0.75)], []) equal (run "| bow" ["4c", "4d"]) ([(0, Just (-0.75)), (1, Just 0.75)], []) equal (run "| bow" ["+ -- 4c", "4d", "4e"]) ([(0, Just (-0.75)), (1, Just (-0.75)), (2, Just 0.75)], []) equal (run "| `downbow`" ["4c", "4d"]) ([(0, Just (-0.75)), (1, Just (-0.75))], []) setup :: DeriveTest.Setup setup = DeriveTest.with_synths_simple allocs [Swam.synth] allocs :: DeriveTest.SimpleAllocations allocs = [("i", "swam/violin")]
null
https://raw.githubusercontent.com/elaforge/karya/8ea15e6a5fb57e2f15f8c19836751e315f9c09f2/User/Elaforge/Instrument/Swam_test.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt
Copyright 2019 module User.Elaforge.Instrument.Swam_test where import qualified Derive.Controls as Controls import qualified Derive.DeriveTest as DeriveTest import qualified Derive.Score as Score import qualified Ui.UiTest as UiTest import qualified User.Elaforge.Instrument.Swam as Swam import Util.Test test_bow :: Test test_bow = do let run title = DeriveTest.extract extract . DeriveTest.derive_tracks_setup setup ("inst=i | %dyn=.75" <> title) . UiTest.note_track1 extract e = (Score.event_start e, DeriveTest.e_initial_control Controls.dynamic e) equal (run "" ["4c"]) ([(0, Just 0.75)], []) equal (run "" ["bow down | -- 4c"]) ([(0, Just (-0.75))], []) equal (run "" ["bow up | -- 4c"]) ([(0, Just 0.75)], []) equal (run "| bow" ["4c", "4d"]) ([(0, Just (-0.75)), (1, Just 0.75)], []) equal (run "| bow" ["+ -- 4c", "4d", "4e"]) ([(0, Just (-0.75)), (1, Just (-0.75)), (2, Just 0.75)], []) equal (run "| `downbow`" ["4c", "4d"]) ([(0, Just (-0.75)), (1, Just (-0.75))], []) setup :: DeriveTest.Setup setup = DeriveTest.with_synths_simple allocs [Swam.synth] allocs :: DeriveTest.SimpleAllocations allocs = [("i", "swam/violin")]
b8ddb36ecc2aa5d36e61b3ab29765eafb5e9301ad4cab1e9e2a32de11a099e1d
RedPRL/stagedtt
Unfold.mli
open Core module D := Domain module I := Inner val unfold : stage:int -> size:int -> D.t -> D.t val unfold_top : stage:int -> D.t -> D.t val unfold_inner : I.t -> I.t
null
https://raw.githubusercontent.com/RedPRL/stagedtt/f88538036b51cebb83ebb0b418ec9b089550275d/lib/unfold/Unfold.mli
ocaml
open Core module D := Domain module I := Inner val unfold : stage:int -> size:int -> D.t -> D.t val unfold_top : stage:int -> D.t -> D.t val unfold_inner : I.t -> I.t
1513de02b6ab26b14d837aaf91c7ff9adfb5eba6753b99014dc61e8f4120eb51
eugmes/imp
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import IMP.Parser import IMP.Codegen.Error import IMP.Emit import IMP.AST (Program) import qualified Data.Text.IO as TIO import qualified Text.Megaparsec as P import LLVM import LLVM.Context import LLVM.PassManager as PM import LLVM.Analysis import LLVM.Exception import LLVM.Target import qualified LLVM.Relocation as Reloc import qualified LLVM.CodeModel as CodeModel import qualified LLVM.CodeGenOpt as CodeGenOpt import qualified Data.ByteString.Char8 as C import LLVM.CommandLine import Options.Applicative as Opt import System.Exit import Control.Exception import Control.Monad import Data.String import qualified Data.Map as Map import System.Environment (getProgName, lookupEnv) import System.IO.Temp (withSystemTempDirectory) import System.FilePath import System.Process import Data.Maybe import Paths_imp (getDataFileName) getStdLibrarySource :: IO FilePath getStdLibrarySource = getDataFileName $ "stdlib" </> "impstd.c" getDefaultCCompiler :: IO FilePath getDefaultCCompiler = fromMaybe "cc" <$> lookupEnv "CC" data Stage = ParseStage | AssemblyStage | ObjectStage | LinkStage deriving Show data OutputKind = NativeOutput | LLVMOutput deriving Show data Options = Options { inputFile :: FilePath , lastStage :: Stage , outputKind :: OutputKind , outputFile :: Maybe FilePath , optimizationLevel :: Maybe Word , triple :: Maybe String , cpu :: Maybe String , llvmOptions :: [String] , cc :: Maybe FilePath } deriving Show getDefaultOutputExt :: Options -> String getDefaultOutputExt o = case (lastStage o, outputKind o) of (ParseStage, _) -> "tree" (AssemblyStage, NativeOutput) -> "s" (AssemblyStage, LLVMOutput) -> "ll" (ObjectStage, NativeOutput) -> "o" (ObjectStage, LLVMOutput) -> "bc" (LinkStage, _) -> "" makeOutputFileName :: Options -> Maybe FilePath makeOutputFileName o = case outputFile o of Just "-" -> Nothing Just name -> Just name Nothing -> Just $ takeBaseName (inputFile o) <.> getDefaultOutputExt o options :: Opt.Parser Options options = Options <$> strArgument (metavar "FILE" <> help "Source file name") <*> ( flag' ParseStage (long "parse-only" <> help "Stop after parsing and dump the parse tree") <|> flag' AssemblyStage (short 'S' <> help "Emit assembly") <|> flag' ObjectStage (short 'c' <> help "Emit object code/bitcode") <|> pure LinkStage ) <*> ( flag' LLVMOutput (long "emit-llvm" <> help "Emit LLVM assembly code/bitcode") <|> pure NativeOutput ) <*> optional (option str (short 'o' <> metavar "FILE" <> help "Redirect output to FILE")) <*> optional (option auto (short 'O' <> metavar "LEVEL" <> help "Set optimization level")) <*> optional (option str (long "triple" <> metavar "TRIPLE" <> help "Target triple for code generation")) <*> optional (option str (long "cpu" <> metavar "CPU" <> help "Target a specific CPU type")) <*> many (option str (long "llvm" <> metavar "OPTION" <> help "Additional options to pass to LLVM")) <*> optional (option str (long "cc" <> metavar "PATH" <> help "Use specified C compiler for linking")) withTargetFromOptions :: Options -> (TargetMachine -> IO a) -> IO a withTargetFromOptions o f = do initializeAllTargets triple <- case triple o of Nothing -> getDefaultTargetTriple Just t -> return $ fromString t (target, tname) <- lookupTarget Nothing triple let cpuName = maybe "" fromString $ cpu o features = Map.empty withTargetOptions $ \options -> withTargetMachine target tname cpuName features options Reloc.Default CodeModel.Default CodeGenOpt.Default f setLLVMCommandLineOptions :: [String] -> IO () setLLVMCommandLineOptions [] = return () setLLVMCommandLineOptions opts = do prog <- getProgName let args = map fromString $ prog : opts parseCommandLineOptions args Nothing -- TODO: Use some type class for this showingErrorsBy :: Either e a -> (e -> String) -> IO a showingErrorsBy v handler = case v of Left err -> do putStrLn $ handler err exitFailure Right r -> return r genCode :: Options -> FilePath -> Program -> IO () genCode o name pgm = do setLLVMCommandLineOptions $ llvmOptions o withContext $ \context -> withTargetFromOptions o $ \target -> do dataLayout <- getTargetMachineDataLayout target targetTriple <- getTargetMachineTriple target let opts = CodegenOptions name dataLayout targetTriple ast <- compileProgram opts pgm `showingErrorsBy` locatedErrorPretty withModuleFromAST context ast $ \m -> do verify m let passes = defaultCuratedPassSetSpec { PM.optLevel = optimizationLevel o , PM.dataLayout = Just dataLayout , PM.targetMachine = Just target } withPassManager passes $ \pm -> do void $ runPassManager pm m llstr <- case (lastStage o, outputKind o) of (AssemblyStage, NativeOutput) -> moduleTargetAssembly target m (AssemblyStage, LLVMOutput) -> moduleLLVMAssembly m (ObjectStage, NativeOutput) -> moduleObject target m (ObjectStage, LLVMOutput) -> moduleBitcode m _ -> error "Unexpected stage" emitOutput llstr where emitOutput = maybe C.putStr C.writeFile $ makeOutputFileName o outputTree :: Options -> Program -> IO () outputTree o tree = writeOutput $ show tree <> "\n" where writeOutput = maybe putStr writeFile $ makeOutputFileName o linkProgram :: Options -> FilePath -> FilePath -> IO () linkProgram o objectFileName outputFileName = do stdLibFile <- getStdLibrarySource cc <- maybe getDefaultCCompiler pure $ cc o let optOption = "-O" <> maybe "2" show (optimizationLevel o) compilerArgs = [ "-o", outputFileName , objectFileName, stdLibFile , optOption Needed when using GCC in some environments callProcess cc compilerArgs run :: Options -> IO () run o = do let fileName = inputFile o text <- TIO.readFile fileName tree <- P.runParser parser fileName text `showingErrorsBy` P.errorBundlePretty let runGenCode opts = genCode opts fileName tree `catch` \(VerifyException msg) -> do putStrLn "Verification exception:" putStrLn msg exitFailure case lastStage o of ParseStage -> outputTree o tree LinkStage -> case makeOutputFileName o of Nothing -> do putStrLn "Refusing to produce executable on standard output." exitFailure Just outputFileName -> withSystemTempDirectory "imp" $ \dir -> do let tmpExt = getDefaultOutputExt $ o { lastStage = ObjectStage } tmpFileName = dir </> takeBaseName fileName <.> tmpExt opts = o { lastStage = ObjectStage, outputFile = Just tmpFileName } runGenCode opts linkProgram o tmpFileName outputFileName _ -> runGenCode o main :: IO () main = execParser opts >>= run where opts = info (options <**> helper) ( progDesc "Compiles IMP programs" )
null
https://raw.githubusercontent.com/eugmes/imp/7bee4dcff146e041b0242b9e7054dfec4c04c84f/src/Main.hs
haskell
# LANGUAGE OverloadedStrings # TODO: Use some type class for this
module Main (main) where import IMP.Parser import IMP.Codegen.Error import IMP.Emit import IMP.AST (Program) import qualified Data.Text.IO as TIO import qualified Text.Megaparsec as P import LLVM import LLVM.Context import LLVM.PassManager as PM import LLVM.Analysis import LLVM.Exception import LLVM.Target import qualified LLVM.Relocation as Reloc import qualified LLVM.CodeModel as CodeModel import qualified LLVM.CodeGenOpt as CodeGenOpt import qualified Data.ByteString.Char8 as C import LLVM.CommandLine import Options.Applicative as Opt import System.Exit import Control.Exception import Control.Monad import Data.String import qualified Data.Map as Map import System.Environment (getProgName, lookupEnv) import System.IO.Temp (withSystemTempDirectory) import System.FilePath import System.Process import Data.Maybe import Paths_imp (getDataFileName) getStdLibrarySource :: IO FilePath getStdLibrarySource = getDataFileName $ "stdlib" </> "impstd.c" getDefaultCCompiler :: IO FilePath getDefaultCCompiler = fromMaybe "cc" <$> lookupEnv "CC" data Stage = ParseStage | AssemblyStage | ObjectStage | LinkStage deriving Show data OutputKind = NativeOutput | LLVMOutput deriving Show data Options = Options { inputFile :: FilePath , lastStage :: Stage , outputKind :: OutputKind , outputFile :: Maybe FilePath , optimizationLevel :: Maybe Word , triple :: Maybe String , cpu :: Maybe String , llvmOptions :: [String] , cc :: Maybe FilePath } deriving Show getDefaultOutputExt :: Options -> String getDefaultOutputExt o = case (lastStage o, outputKind o) of (ParseStage, _) -> "tree" (AssemblyStage, NativeOutput) -> "s" (AssemblyStage, LLVMOutput) -> "ll" (ObjectStage, NativeOutput) -> "o" (ObjectStage, LLVMOutput) -> "bc" (LinkStage, _) -> "" makeOutputFileName :: Options -> Maybe FilePath makeOutputFileName o = case outputFile o of Just "-" -> Nothing Just name -> Just name Nothing -> Just $ takeBaseName (inputFile o) <.> getDefaultOutputExt o options :: Opt.Parser Options options = Options <$> strArgument (metavar "FILE" <> help "Source file name") <*> ( flag' ParseStage (long "parse-only" <> help "Stop after parsing and dump the parse tree") <|> flag' AssemblyStage (short 'S' <> help "Emit assembly") <|> flag' ObjectStage (short 'c' <> help "Emit object code/bitcode") <|> pure LinkStage ) <*> ( flag' LLVMOutput (long "emit-llvm" <> help "Emit LLVM assembly code/bitcode") <|> pure NativeOutput ) <*> optional (option str (short 'o' <> metavar "FILE" <> help "Redirect output to FILE")) <*> optional (option auto (short 'O' <> metavar "LEVEL" <> help "Set optimization level")) <*> optional (option str (long "triple" <> metavar "TRIPLE" <> help "Target triple for code generation")) <*> optional (option str (long "cpu" <> metavar "CPU" <> help "Target a specific CPU type")) <*> many (option str (long "llvm" <> metavar "OPTION" <> help "Additional options to pass to LLVM")) <*> optional (option str (long "cc" <> metavar "PATH" <> help "Use specified C compiler for linking")) withTargetFromOptions :: Options -> (TargetMachine -> IO a) -> IO a withTargetFromOptions o f = do initializeAllTargets triple <- case triple o of Nothing -> getDefaultTargetTriple Just t -> return $ fromString t (target, tname) <- lookupTarget Nothing triple let cpuName = maybe "" fromString $ cpu o features = Map.empty withTargetOptions $ \options -> withTargetMachine target tname cpuName features options Reloc.Default CodeModel.Default CodeGenOpt.Default f setLLVMCommandLineOptions :: [String] -> IO () setLLVMCommandLineOptions [] = return () setLLVMCommandLineOptions opts = do prog <- getProgName let args = map fromString $ prog : opts parseCommandLineOptions args Nothing showingErrorsBy :: Either e a -> (e -> String) -> IO a showingErrorsBy v handler = case v of Left err -> do putStrLn $ handler err exitFailure Right r -> return r genCode :: Options -> FilePath -> Program -> IO () genCode o name pgm = do setLLVMCommandLineOptions $ llvmOptions o withContext $ \context -> withTargetFromOptions o $ \target -> do dataLayout <- getTargetMachineDataLayout target targetTriple <- getTargetMachineTriple target let opts = CodegenOptions name dataLayout targetTriple ast <- compileProgram opts pgm `showingErrorsBy` locatedErrorPretty withModuleFromAST context ast $ \m -> do verify m let passes = defaultCuratedPassSetSpec { PM.optLevel = optimizationLevel o , PM.dataLayout = Just dataLayout , PM.targetMachine = Just target } withPassManager passes $ \pm -> do void $ runPassManager pm m llstr <- case (lastStage o, outputKind o) of (AssemblyStage, NativeOutput) -> moduleTargetAssembly target m (AssemblyStage, LLVMOutput) -> moduleLLVMAssembly m (ObjectStage, NativeOutput) -> moduleObject target m (ObjectStage, LLVMOutput) -> moduleBitcode m _ -> error "Unexpected stage" emitOutput llstr where emitOutput = maybe C.putStr C.writeFile $ makeOutputFileName o outputTree :: Options -> Program -> IO () outputTree o tree = writeOutput $ show tree <> "\n" where writeOutput = maybe putStr writeFile $ makeOutputFileName o linkProgram :: Options -> FilePath -> FilePath -> IO () linkProgram o objectFileName outputFileName = do stdLibFile <- getStdLibrarySource cc <- maybe getDefaultCCompiler pure $ cc o let optOption = "-O" <> maybe "2" show (optimizationLevel o) compilerArgs = [ "-o", outputFileName , objectFileName, stdLibFile , optOption Needed when using GCC in some environments callProcess cc compilerArgs run :: Options -> IO () run o = do let fileName = inputFile o text <- TIO.readFile fileName tree <- P.runParser parser fileName text `showingErrorsBy` P.errorBundlePretty let runGenCode opts = genCode opts fileName tree `catch` \(VerifyException msg) -> do putStrLn "Verification exception:" putStrLn msg exitFailure case lastStage o of ParseStage -> outputTree o tree LinkStage -> case makeOutputFileName o of Nothing -> do putStrLn "Refusing to produce executable on standard output." exitFailure Just outputFileName -> withSystemTempDirectory "imp" $ \dir -> do let tmpExt = getDefaultOutputExt $ o { lastStage = ObjectStage } tmpFileName = dir </> takeBaseName fileName <.> tmpExt opts = o { lastStage = ObjectStage, outputFile = Just tmpFileName } runGenCode opts linkProgram o tmpFileName outputFileName _ -> runGenCode o main :: IO () main = execParser opts >>= run where opts = info (options <**> helper) ( progDesc "Compiles IMP programs" )
728bc0499843d056f21e7554fb5072cb71a3dfdc75cad9ef16856d8c503eec72
wireless-net/erlang-nommu
dtls_record.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2013 - 2014 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %%---------------------------------------------------------------------- Purpose : Handle DTLS record protocol . ( Parts that are not shared with SSL / TLS ) %%---------------------------------------------------------------------- -module(dtls_record). -include("dtls_record.hrl"). -include("ssl_internal.hrl"). -include("ssl_alert.hrl"). -include("dtls_handshake.hrl"). -include("ssl_cipher.hrl"). %% Handling of incoming data -export([get_dtls_records/2]). %% Decoding -export([decode_cipher_text/2]). %% Encoding -export([encode_plain_text/4, encode_handshake/3, encode_change_cipher_spec/2]). Protocol version handling -export([protocol_version/1, lowest_protocol_version/2, highest_protocol_version/1, supported_protocol_versions/0, is_acceptable_version/2]). DTLS Epoch handling -export([init_connection_state_seq/2, current_connection_state_epoch/2, set_connection_state_by_epoch/3, connection_state_by_epoch/3]). -export_type([dtls_version/0, dtls_atom_version/0]). -type dtls_version() :: ssl_record:ssl_version(). -type dtls_atom_version() :: dtlsv1 | 'dtlsv1.2'. -compile(inline). %%==================================================================== Internal application API %%==================================================================== %%-------------------------------------------------------------------- -spec get_dtls_records(binary(), binary()) -> {[binary()], binary()} | #alert{}. %% Description : Given old buffer and new data from UDP / SCTP , packs up a records %% and returns it as a list of tls_compressed binaries also returns leftover %% data %%-------------------------------------------------------------------- get_dtls_records(Data, <<>>) -> get_dtls_records_aux(Data, []); get_dtls_records(Data, Buffer) -> get_dtls_records_aux(list_to_binary([Buffer, Data]), []). get_dtls_records_aux(<<?BYTE(?APPLICATION_DATA),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(SequenceNumber), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_dtls_records_aux(Rest, [#ssl_tls{type = ?APPLICATION_DATA, version = {MajVer, MinVer}, epoch = Epoch, sequence_number = SequenceNumber, fragment = Data} | Acc]); get_dtls_records_aux(<<?BYTE(?HANDSHAKE),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(SequenceNumber), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) when MajVer >= 128 -> get_dtls_records_aux(Rest, [#ssl_tls{type = ?HANDSHAKE, version = {MajVer, MinVer}, epoch = Epoch, sequence_number = SequenceNumber, fragment = Data} | Acc]); get_dtls_records_aux(<<?BYTE(?ALERT),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(SequenceNumber), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_dtls_records_aux(Rest, [#ssl_tls{type = ?ALERT, version = {MajVer, MinVer}, epoch = Epoch, sequence_number = SequenceNumber, fragment = Data} | Acc]); get_dtls_records_aux(<<?BYTE(?CHANGE_CIPHER_SPEC),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(SequenceNumber), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_dtls_records_aux(Rest, [#ssl_tls{type = ?CHANGE_CIPHER_SPEC, version = {MajVer, MinVer}, epoch = Epoch, sequence_number = SequenceNumber, fragment = Data} | Acc]); get_dtls_records_aux(<<0:1, _CT:7, ?BYTE(_MajVer), ?BYTE(_MinVer), ?UINT16(Length), _/binary>>, _Acc) when Length > ?MAX_CIPHER_TEXT_LENGTH -> ?ALERT_REC(?FATAL, ?RECORD_OVERFLOW); get_dtls_records_aux(<<1:1, Length0:15, _/binary>>,_Acc) when Length0 > ?MAX_CIPHER_TEXT_LENGTH -> ?ALERT_REC(?FATAL, ?RECORD_OVERFLOW); get_dtls_records_aux(Data, Acc) -> case size(Data) =< ?MAX_CIPHER_TEXT_LENGTH + ?INITIAL_BYTES of true -> {lists:reverse(Acc), Data}; false -> ?ALERT_REC(?FATAL, ?UNEXPECTED_MESSAGE) end. encode_plain_text(Type, Version, Data, #connection_states{current_write=#connection_state{ epoch = Epoch, sequence_number = Seq, compression_state=CompS0, security_parameters= #security_parameters{compression_algorithm=CompAlg} }= WriteState0} = ConnectionStates) -> {Comp, CompS1} = ssl_record:compress(CompAlg, Data, CompS0), WriteState1 = WriteState0#connection_state{compression_state = CompS1}, MacHash = calc_mac_hash(WriteState1, Type, Version, Epoch, Seq, Comp), {CipherFragment, WriteState} = ssl_record:cipher(dtls_v1:corresponding_tls_version(Version), Comp, WriteState1, MacHash), CipherText = encode_tls_cipher_text(Type, Version, Epoch, Seq, CipherFragment), {CipherText, ConnectionStates#connection_states{current_write = WriteState#connection_state{sequence_number = Seq +1}}}. decode_cipher_text(#ssl_tls{type = Type, version = Version, epoch = Epoch, sequence_number = Seq, fragment = CipherFragment} = CipherText, #connection_states{current_read = #connection_state{compression_state = CompressionS0, security_parameters = SecParams} = ReadState0} = ConnnectionStates0) -> CompressAlg = SecParams#security_parameters.compression_algorithm, {PlainFragment, Mac, ReadState1} = ssl_record:decipher(dtls_v1:corresponding_tls_version(Version), CipherFragment, ReadState0), MacHash = calc_mac_hash(ReadState1, Type, Version, Epoch, Seq, PlainFragment), case ssl_record:is_correct_mac(Mac, MacHash) of true -> {Plain, CompressionS1} = ssl_record:uncompress(CompressAlg, PlainFragment, CompressionS0), ConnnectionStates = ConnnectionStates0#connection_states{ current_read = ReadState1#connection_state{ compression_state = CompressionS1}}, {CipherText#ssl_tls{fragment = Plain}, ConnnectionStates}; false -> ?ALERT_REC(?FATAL, ?BAD_RECORD_MAC) end. %%-------------------------------------------------------------------- -spec encode_handshake(iolist(), dtls_version(), #connection_states{}) -> {iolist(), #connection_states{}}. %% %% Description: Encodes a handshake message to send on the ssl-socket. %%-------------------------------------------------------------------- encode_handshake(Frag, Version, ConnectionStates) -> encode_plain_text(?HANDSHAKE, Version, Frag, ConnectionStates). %%-------------------------------------------------------------------- -spec encode_change_cipher_spec(dtls_version(), #connection_states{}) -> {iolist(), #connection_states{}}. %% %% Description: Encodes a change_cipher_spec-message to send on the ssl socket. %%-------------------------------------------------------------------- encode_change_cipher_spec(Version, ConnectionStates) -> encode_plain_text(?CHANGE_CIPHER_SPEC, Version, <<1:8>>, ConnectionStates). %%-------------------------------------------------------------------- -spec protocol_version(dtls_atom_version() | dtls_version()) -> dtls_version() | dtls_atom_version(). %% %% Description: Creates a protocol version record from a version atom %% or vice versa. %%-------------------------------------------------------------------- protocol_version('dtlsv1.2') -> {254, 253}; protocol_version(dtlsv1) -> {254, 255}; protocol_version({254, 253}) -> 'dtlsv1.2'; protocol_version({254, 255}) -> dtlsv1. %%-------------------------------------------------------------------- -spec lowest_protocol_version(dtls_version(), dtls_version()) -> dtls_version(). %% Description : Lowes protocol version of two given versions %%-------------------------------------------------------------------- lowest_protocol_version(Version = {M, N}, {M, O}) when N > O -> Version; lowest_protocol_version({M, _}, Version = {M, _}) -> Version; lowest_protocol_version(Version = {M,_}, {N, _}) when M > N -> Version; lowest_protocol_version(_,Version) -> Version. %%-------------------------------------------------------------------- -spec highest_protocol_version([dtls_version()]) -> dtls_version(). %% %% Description: Highest protocol version present in a list %%-------------------------------------------------------------------- highest_protocol_version([Ver | Vers]) -> highest_protocol_version(Ver, Vers). highest_protocol_version(Version, []) -> Version; highest_protocol_version(Version = {N, M}, [{N, O} | Rest]) when M < O -> highest_protocol_version(Version, Rest); highest_protocol_version({M, _}, [Version = {M, _} | Rest]) -> highest_protocol_version(Version, Rest); highest_protocol_version(Version = {M,_}, [{N,_} | Rest]) when M < N -> highest_protocol_version(Version, Rest); highest_protocol_version(_, [Version | Rest]) -> highest_protocol_version(Version, Rest). %%-------------------------------------------------------------------- -spec supported_protocol_versions() -> [dtls_version()]. %% %% Description: Protocol versions supported %%-------------------------------------------------------------------- supported_protocol_versions() -> Fun = fun(Version) -> protocol_version(Version) end, case application:get_env(ssl, dtls_protocol_version) of undefined -> lists:map(Fun, supported_protocol_versions([])); {ok, []} -> lists:map(Fun, supported_protocol_versions([])); {ok, Vsns} when is_list(Vsns) -> supported_protocol_versions(Vsns); {ok, Vsn} -> supported_protocol_versions([Vsn]) end. supported_protocol_versions([]) -> Vsns = supported_connection_protocol_versions([]), application:set_env(ssl, dtls_protocol_version, Vsns), Vsns; supported_protocol_versions([_|_] = Vsns) -> Vsns. supported_connection_protocol_versions([]) -> ?ALL_DATAGRAM_SUPPORTED_VERSIONS. %%-------------------------------------------------------------------- -spec is_acceptable_version(dtls_version(), Supported :: [dtls_version()]) -> boolean(). %% Description : ssl version 2 is not acceptable security risks are too big . %% %%-------------------------------------------------------------------- is_acceptable_version(Version, Versions) -> lists:member(Version, Versions). %%-------------------------------------------------------------------- -spec init_connection_state_seq(dtls_version(), #connection_states{}) -> #connection_state{}. %% %% Description: Copy the read sequence number to the write sequence number This is only valid for DTLS in the first client_hello %%-------------------------------------------------------------------- init_connection_state_seq({254, _}, #connection_states{ current_read = Read = #connection_state{epoch = 0}, current_write = Write = #connection_state{epoch = 0}} = CS0) -> CS0#connection_states{current_write = Write#connection_state{ sequence_number = Read#connection_state.sequence_number}}; init_connection_state_seq(_, CS) -> CS. %%-------------------------------------------------------- -spec current_connection_state_epoch(#connection_states{}, read | write) -> integer(). %% %% Description: Returns the epoch the connection_state record %% that is currently defined as the current conection state. %%-------------------------------------------------------------------- current_connection_state_epoch(#connection_states{current_read = Current}, read) -> Current#connection_state.epoch; current_connection_state_epoch(#connection_states{current_write = Current}, write) -> Current#connection_state.epoch. %%-------------------------------------------------------------------- -spec connection_state_by_epoch(#connection_states{}, integer(), read | write) -> #connection_state{}. %% %% Description: Returns the instance of the connection_state record %% that is defined by the Epoch. %%-------------------------------------------------------------------- connection_state_by_epoch(#connection_states{current_read = CS}, Epoch, read) when CS#connection_state.epoch == Epoch -> CS; connection_state_by_epoch(#connection_states{pending_read = CS}, Epoch, read) when CS#connection_state.epoch == Epoch -> CS; connection_state_by_epoch(#connection_states{current_write = CS}, Epoch, write) when CS#connection_state.epoch == Epoch -> CS; connection_state_by_epoch(#connection_states{pending_write = CS}, Epoch, write) when CS#connection_state.epoch == Epoch -> CS. %%-------------------------------------------------------------------- -spec set_connection_state_by_epoch(#connection_states{}, #connection_state{}, read | write) -> #connection_states{}. %% %% Description: Returns the instance of the connection_state record %% that is defined by the Epoch. %%-------------------------------------------------------------------- set_connection_state_by_epoch(ConnectionStates0 = #connection_states{current_read = CS}, NewCS = #connection_state{epoch = Epoch}, read) when CS#connection_state.epoch == Epoch -> ConnectionStates0#connection_states{current_read = NewCS}; set_connection_state_by_epoch(ConnectionStates0 = #connection_states{pending_read = CS}, NewCS = #connection_state{epoch = Epoch}, read) when CS#connection_state.epoch == Epoch -> ConnectionStates0#connection_states{pending_read = NewCS}; set_connection_state_by_epoch(ConnectionStates0 = #connection_states{current_write = CS}, NewCS = #connection_state{epoch = Epoch}, write) when CS#connection_state.epoch == Epoch -> ConnectionStates0#connection_states{current_write = NewCS}; set_connection_state_by_epoch(ConnectionStates0 = #connection_states{pending_write = CS}, NewCS = #connection_state{epoch = Epoch}, write) when CS#connection_state.epoch == Epoch -> ConnectionStates0#connection_states{pending_write = NewCS}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- encode_tls_cipher_text(Type, {MajVer, MinVer}, Epoch, Seq, Fragment) -> Length = erlang:iolist_size(Fragment), [<<?BYTE(Type), ?BYTE(MajVer), ?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(Seq), ?UINT16(Length)>>, Fragment]. calc_mac_hash(#connection_state{mac_secret = MacSecret, security_parameters = #security_parameters{mac_algorithm = MacAlg}}, Type, Version, Epoch, SeqNo, Fragment) -> Length = erlang:iolist_size(Fragment), NewSeq = (Epoch bsl 48) + SeqNo, mac_hash(Version, MacAlg, MacSecret, NewSeq, Type, Length, Fragment). mac_hash(Version, MacAlg, MacSecret, SeqNo, Type, Length, Fragment) -> dtls_v1:mac_hash(Version, MacAlg, MacSecret, SeqNo, Type, Length, Fragment).
null
https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/ssl/src/dtls_record.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% ---------------------------------------------------------------------- ---------------------------------------------------------------------- Handling of incoming data Decoding Encoding ==================================================================== ==================================================================== -------------------------------------------------------------------- and returns it as a list of tls_compressed binaries also returns leftover data -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Encodes a handshake message to send on the ssl-socket. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Encodes a change_cipher_spec-message to send on the ssl socket. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Creates a protocol version record from a version atom or vice versa. -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Highest protocol version present in a list -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Protocol versions supported -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Copy the read sequence number to the write sequence number -------------------------------------------------------------------- -------------------------------------------------------- Description: Returns the epoch the connection_state record that is currently defined as the current conection state. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Returns the instance of the connection_state record that is defined by the Epoch. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Returns the instance of the connection_state record that is defined by the Epoch. -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright Ericsson AB 2013 - 2014 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " Purpose : Handle DTLS record protocol . ( Parts that are not shared with SSL / TLS ) -module(dtls_record). -include("dtls_record.hrl"). -include("ssl_internal.hrl"). -include("ssl_alert.hrl"). -include("dtls_handshake.hrl"). -include("ssl_cipher.hrl"). -export([get_dtls_records/2]). -export([decode_cipher_text/2]). -export([encode_plain_text/4, encode_handshake/3, encode_change_cipher_spec/2]). Protocol version handling -export([protocol_version/1, lowest_protocol_version/2, highest_protocol_version/1, supported_protocol_versions/0, is_acceptable_version/2]). DTLS Epoch handling -export([init_connection_state_seq/2, current_connection_state_epoch/2, set_connection_state_by_epoch/3, connection_state_by_epoch/3]). -export_type([dtls_version/0, dtls_atom_version/0]). -type dtls_version() :: ssl_record:ssl_version(). -type dtls_atom_version() :: dtlsv1 | 'dtlsv1.2'. -compile(inline). Internal application API -spec get_dtls_records(binary(), binary()) -> {[binary()], binary()} | #alert{}. Description : Given old buffer and new data from UDP / SCTP , packs up a records get_dtls_records(Data, <<>>) -> get_dtls_records_aux(Data, []); get_dtls_records(Data, Buffer) -> get_dtls_records_aux(list_to_binary([Buffer, Data]), []). get_dtls_records_aux(<<?BYTE(?APPLICATION_DATA),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(SequenceNumber), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_dtls_records_aux(Rest, [#ssl_tls{type = ?APPLICATION_DATA, version = {MajVer, MinVer}, epoch = Epoch, sequence_number = SequenceNumber, fragment = Data} | Acc]); get_dtls_records_aux(<<?BYTE(?HANDSHAKE),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(SequenceNumber), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) when MajVer >= 128 -> get_dtls_records_aux(Rest, [#ssl_tls{type = ?HANDSHAKE, version = {MajVer, MinVer}, epoch = Epoch, sequence_number = SequenceNumber, fragment = Data} | Acc]); get_dtls_records_aux(<<?BYTE(?ALERT),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(SequenceNumber), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_dtls_records_aux(Rest, [#ssl_tls{type = ?ALERT, version = {MajVer, MinVer}, epoch = Epoch, sequence_number = SequenceNumber, fragment = Data} | Acc]); get_dtls_records_aux(<<?BYTE(?CHANGE_CIPHER_SPEC),?BYTE(MajVer),?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(SequenceNumber), ?UINT16(Length), Data:Length/binary, Rest/binary>>, Acc) -> get_dtls_records_aux(Rest, [#ssl_tls{type = ?CHANGE_CIPHER_SPEC, version = {MajVer, MinVer}, epoch = Epoch, sequence_number = SequenceNumber, fragment = Data} | Acc]); get_dtls_records_aux(<<0:1, _CT:7, ?BYTE(_MajVer), ?BYTE(_MinVer), ?UINT16(Length), _/binary>>, _Acc) when Length > ?MAX_CIPHER_TEXT_LENGTH -> ?ALERT_REC(?FATAL, ?RECORD_OVERFLOW); get_dtls_records_aux(<<1:1, Length0:15, _/binary>>,_Acc) when Length0 > ?MAX_CIPHER_TEXT_LENGTH -> ?ALERT_REC(?FATAL, ?RECORD_OVERFLOW); get_dtls_records_aux(Data, Acc) -> case size(Data) =< ?MAX_CIPHER_TEXT_LENGTH + ?INITIAL_BYTES of true -> {lists:reverse(Acc), Data}; false -> ?ALERT_REC(?FATAL, ?UNEXPECTED_MESSAGE) end. encode_plain_text(Type, Version, Data, #connection_states{current_write=#connection_state{ epoch = Epoch, sequence_number = Seq, compression_state=CompS0, security_parameters= #security_parameters{compression_algorithm=CompAlg} }= WriteState0} = ConnectionStates) -> {Comp, CompS1} = ssl_record:compress(CompAlg, Data, CompS0), WriteState1 = WriteState0#connection_state{compression_state = CompS1}, MacHash = calc_mac_hash(WriteState1, Type, Version, Epoch, Seq, Comp), {CipherFragment, WriteState} = ssl_record:cipher(dtls_v1:corresponding_tls_version(Version), Comp, WriteState1, MacHash), CipherText = encode_tls_cipher_text(Type, Version, Epoch, Seq, CipherFragment), {CipherText, ConnectionStates#connection_states{current_write = WriteState#connection_state{sequence_number = Seq +1}}}. decode_cipher_text(#ssl_tls{type = Type, version = Version, epoch = Epoch, sequence_number = Seq, fragment = CipherFragment} = CipherText, #connection_states{current_read = #connection_state{compression_state = CompressionS0, security_parameters = SecParams} = ReadState0} = ConnnectionStates0) -> CompressAlg = SecParams#security_parameters.compression_algorithm, {PlainFragment, Mac, ReadState1} = ssl_record:decipher(dtls_v1:corresponding_tls_version(Version), CipherFragment, ReadState0), MacHash = calc_mac_hash(ReadState1, Type, Version, Epoch, Seq, PlainFragment), case ssl_record:is_correct_mac(Mac, MacHash) of true -> {Plain, CompressionS1} = ssl_record:uncompress(CompressAlg, PlainFragment, CompressionS0), ConnnectionStates = ConnnectionStates0#connection_states{ current_read = ReadState1#connection_state{ compression_state = CompressionS1}}, {CipherText#ssl_tls{fragment = Plain}, ConnnectionStates}; false -> ?ALERT_REC(?FATAL, ?BAD_RECORD_MAC) end. -spec encode_handshake(iolist(), dtls_version(), #connection_states{}) -> {iolist(), #connection_states{}}. encode_handshake(Frag, Version, ConnectionStates) -> encode_plain_text(?HANDSHAKE, Version, Frag, ConnectionStates). -spec encode_change_cipher_spec(dtls_version(), #connection_states{}) -> {iolist(), #connection_states{}}. encode_change_cipher_spec(Version, ConnectionStates) -> encode_plain_text(?CHANGE_CIPHER_SPEC, Version, <<1:8>>, ConnectionStates). -spec protocol_version(dtls_atom_version() | dtls_version()) -> dtls_version() | dtls_atom_version(). protocol_version('dtlsv1.2') -> {254, 253}; protocol_version(dtlsv1) -> {254, 255}; protocol_version({254, 253}) -> 'dtlsv1.2'; protocol_version({254, 255}) -> dtlsv1. -spec lowest_protocol_version(dtls_version(), dtls_version()) -> dtls_version(). Description : Lowes protocol version of two given versions lowest_protocol_version(Version = {M, N}, {M, O}) when N > O -> Version; lowest_protocol_version({M, _}, Version = {M, _}) -> Version; lowest_protocol_version(Version = {M,_}, {N, _}) when M > N -> Version; lowest_protocol_version(_,Version) -> Version. -spec highest_protocol_version([dtls_version()]) -> dtls_version(). highest_protocol_version([Ver | Vers]) -> highest_protocol_version(Ver, Vers). highest_protocol_version(Version, []) -> Version; highest_protocol_version(Version = {N, M}, [{N, O} | Rest]) when M < O -> highest_protocol_version(Version, Rest); highest_protocol_version({M, _}, [Version = {M, _} | Rest]) -> highest_protocol_version(Version, Rest); highest_protocol_version(Version = {M,_}, [{N,_} | Rest]) when M < N -> highest_protocol_version(Version, Rest); highest_protocol_version(_, [Version | Rest]) -> highest_protocol_version(Version, Rest). -spec supported_protocol_versions() -> [dtls_version()]. supported_protocol_versions() -> Fun = fun(Version) -> protocol_version(Version) end, case application:get_env(ssl, dtls_protocol_version) of undefined -> lists:map(Fun, supported_protocol_versions([])); {ok, []} -> lists:map(Fun, supported_protocol_versions([])); {ok, Vsns} when is_list(Vsns) -> supported_protocol_versions(Vsns); {ok, Vsn} -> supported_protocol_versions([Vsn]) end. supported_protocol_versions([]) -> Vsns = supported_connection_protocol_versions([]), application:set_env(ssl, dtls_protocol_version, Vsns), Vsns; supported_protocol_versions([_|_] = Vsns) -> Vsns. supported_connection_protocol_versions([]) -> ?ALL_DATAGRAM_SUPPORTED_VERSIONS. -spec is_acceptable_version(dtls_version(), Supported :: [dtls_version()]) -> boolean(). Description : ssl version 2 is not acceptable security risks are too big . is_acceptable_version(Version, Versions) -> lists:member(Version, Versions). -spec init_connection_state_seq(dtls_version(), #connection_states{}) -> #connection_state{}. This is only valid for DTLS in the first client_hello init_connection_state_seq({254, _}, #connection_states{ current_read = Read = #connection_state{epoch = 0}, current_write = Write = #connection_state{epoch = 0}} = CS0) -> CS0#connection_states{current_write = Write#connection_state{ sequence_number = Read#connection_state.sequence_number}}; init_connection_state_seq(_, CS) -> CS. -spec current_connection_state_epoch(#connection_states{}, read | write) -> integer(). current_connection_state_epoch(#connection_states{current_read = Current}, read) -> Current#connection_state.epoch; current_connection_state_epoch(#connection_states{current_write = Current}, write) -> Current#connection_state.epoch. -spec connection_state_by_epoch(#connection_states{}, integer(), read | write) -> #connection_state{}. connection_state_by_epoch(#connection_states{current_read = CS}, Epoch, read) when CS#connection_state.epoch == Epoch -> CS; connection_state_by_epoch(#connection_states{pending_read = CS}, Epoch, read) when CS#connection_state.epoch == Epoch -> CS; connection_state_by_epoch(#connection_states{current_write = CS}, Epoch, write) when CS#connection_state.epoch == Epoch -> CS; connection_state_by_epoch(#connection_states{pending_write = CS}, Epoch, write) when CS#connection_state.epoch == Epoch -> CS. -spec set_connection_state_by_epoch(#connection_states{}, #connection_state{}, read | write) -> #connection_states{}. set_connection_state_by_epoch(ConnectionStates0 = #connection_states{current_read = CS}, NewCS = #connection_state{epoch = Epoch}, read) when CS#connection_state.epoch == Epoch -> ConnectionStates0#connection_states{current_read = NewCS}; set_connection_state_by_epoch(ConnectionStates0 = #connection_states{pending_read = CS}, NewCS = #connection_state{epoch = Epoch}, read) when CS#connection_state.epoch == Epoch -> ConnectionStates0#connection_states{pending_read = NewCS}; set_connection_state_by_epoch(ConnectionStates0 = #connection_states{current_write = CS}, NewCS = #connection_state{epoch = Epoch}, write) when CS#connection_state.epoch == Epoch -> ConnectionStates0#connection_states{current_write = NewCS}; set_connection_state_by_epoch(ConnectionStates0 = #connection_states{pending_write = CS}, NewCS = #connection_state{epoch = Epoch}, write) when CS#connection_state.epoch == Epoch -> ConnectionStates0#connection_states{pending_write = NewCS}. Internal functions encode_tls_cipher_text(Type, {MajVer, MinVer}, Epoch, Seq, Fragment) -> Length = erlang:iolist_size(Fragment), [<<?BYTE(Type), ?BYTE(MajVer), ?BYTE(MinVer), ?UINT16(Epoch), ?UINT48(Seq), ?UINT16(Length)>>, Fragment]. calc_mac_hash(#connection_state{mac_secret = MacSecret, security_parameters = #security_parameters{mac_algorithm = MacAlg}}, Type, Version, Epoch, SeqNo, Fragment) -> Length = erlang:iolist_size(Fragment), NewSeq = (Epoch bsl 48) + SeqNo, mac_hash(Version, MacAlg, MacSecret, NewSeq, Type, Length, Fragment). mac_hash(Version, MacAlg, MacSecret, SeqNo, Type, Length, Fragment) -> dtls_v1:mac_hash(Version, MacAlg, MacSecret, SeqNo, Type, Length, Fragment).
e7c65c9947d9f36a4c5151e349d972aae89af2a27a763e0e571670834d9ee485
vernemq/vmq_mzbench
vmq_parser.erl
-module(vmq_parser). -include("vmq_types.hrl"). -export([parse/1, parse/2, serialise/1]). -dialyzer({no_match, utf8/1}). -export([gen_connect/2, gen_connack/0, gen_connack/1, gen_connack/2, gen_publish/4, gen_puback/1, gen_pubrec/1, gen_pubrel/1, gen_pubcomp/1, gen_subscribe/2, gen_subscribe/3, gen_suback/2, gen_unsubscribe/2, gen_unsuback/1, gen_pingreq/0, gen_pingresp/0, gen_disconnect/0]). %% frame types -define(CONNECT, 1). -define(CONNACK, 2). -define(PUBLISH, 3). -define(PUBACK, 4). -define(PUBREC, 5). -define(PUBREL, 6). -define(PUBCOMP, 7). -define(SUBSCRIBE, 8). -define(SUBACK, 9). -define(UNSUBSCRIBE, 10). -define(UNSUBACK, 11). -define(PINGREQ, 12). -define(PINGRESP, 13). -define(DISCONNECT, 14). -define(RESERVED, 0). -define(PROTOCOL_MAGIC_31, <<"MQIsdp">>). -define(PROTOCOL_MAGIC_311, <<"MQTT">>). -define(MAX_LEN, 16#fffffff). -define(HIGHBIT, 2#10000000). -define(LOWBITS, 2#01111111). -define(MAX_PACKET_SIZE, 268435455). -spec parse(binary()) -> {mqtt_frame(), binary()} | {error, atom()} | {{error, atom()}, any()} |more. parse(Data) -> parse(Data, ?MAX_PACKET_SIZE). -spec parse(binary(), non_neg_integer()) -> {mqtt_frame(), binary()} | {error, atom()} | more. parse(<<Fixed:1/binary, 0:1, DataSize:7, Data/binary>>, MaxSize)-> parse(DataSize, MaxSize, Fixed, Data); parse(<<Fixed:1/binary, 1:1, L1:7, 0:1, L2:7, Data/binary>>, MaxSize) -> parse(L1 + (L2 bsl 7), MaxSize, Fixed, Data); parse(<<Fixed:1/binary, 1:1, L1:7, 1:1, L2:7, 0:1, L3:7, Data/binary>>, MaxSize) -> parse(L1 + (L2 bsl 7) + (L3 bsl 14), MaxSize, Fixed, Data); parse(<<Fixed:1/binary, 1:1, L1:7, 1:1, L2:7, 1:1, L3:7, 0:1, L4:7, Data/binary>>, MaxSize) -> parse(L1 + (L2 bsl 7) + (L3 bsl 14) + (L4 bsl 21), MaxSize, Fixed, Data); parse(<<_:8/binary, _/binary>>, _) -> {error, cant_parse_fixed_header}; parse(_, _) -> more. parse(DataSize, 0, Fixed, Data) when byte_size(Data) >= DataSize -> %% no max size limit <<Var:DataSize/binary, Rest/binary>> = Data, {variable(Fixed, Var), Rest}; parse(DataSize, 0, _Fixed, Data) when byte_size(Data) < DataSize -> more; parse(DataSize, MaxSize, Fixed, Data) when byte_size(Data) >= DataSize, byte_size(Data) =< MaxSize -> <<Var:DataSize/binary, Rest/binary>> = Data, {variable(Fixed, Var), Rest}; parse(DataSize, MaxSize, _, _) when DataSize > MaxSize -> {error, packet_exceeds_max_size}; parse(_, _, _, _) -> more. -spec variable(binary(), binary()) -> mqtt_frame() | {error, atom()}. variable(<<?PUBLISH:4, Dup:1, 0:2, Retain:1>>, <<TopicLen:16/big, Topic:TopicLen/binary, Payload/binary>>) -> case vmq_topic:validate_topic(publish, Topic) of {ok, ParsedTopic} -> #mqtt_publish{dup=Dup, retain=Retain, topic=ParsedTopic, qos=0, payload=Payload}; {error, Reason} -> {error, Reason} end; variable(<<?PUBLISH:4, Dup:1, QoS:2, Retain:1>>, <<TopicLen:16/big, Topic:TopicLen/binary, MessageId:16/big, Payload/binary>>) when QoS < 3 -> case vmq_topic:validate_topic(publish, Topic) of {ok, ParsedTopic} -> #mqtt_publish{dup=Dup, retain=Retain, topic=ParsedTopic, qos=QoS, message_id=MessageId, payload=Payload}; {error, Reason} -> {error, Reason} end; variable(<<?PUBACK:4, 0:4>>, <<MessageId:16/big>>) -> #mqtt_puback{message_id=MessageId}; variable(<<?PUBREC:4, 0:4>>, <<MessageId:16/big>>) -> #mqtt_pubrec{message_id=MessageId}; variable(<<?PUBREL:4, 0:2, 1:1, 0:1>>, <<MessageId:16/big>>) -> #mqtt_pubrel{message_id=MessageId}; variable(<<?PUBCOMP:4, 0:4>>, <<MessageId:16/big>>) -> #mqtt_pubcomp{message_id=MessageId}; variable(<<?SUBSCRIBE:4, 0:2, 1:1, 0:1>>, <<MessageId:16/big, Topics/binary>>) -> case parse_topics(Topics, ?SUBSCRIBE, []) of {ok, ParsedTopics} -> #mqtt_subscribe{topics=ParsedTopics, message_id=MessageId}; E -> E end; variable(<<?UNSUBSCRIBE:4, 0:2, 1:1, 0:1>>, <<MessageId:16/big, Topics/binary>>) -> case parse_topics(Topics, ?UNSUBSCRIBE, []) of {ok, ParsedTopics} -> #mqtt_unsubscribe{topics=ParsedTopics, message_id=MessageId}; E -> E end; variable(<<?SUBACK:4, 0:4>>, <<MessageId:16/big, Acks/binary>>) -> #mqtt_suback{qos_table=parse_acks(Acks, []), message_id=MessageId}; variable(<<?UNSUBACK:4, 0:4>>, <<MessageId:16/big>>) -> #mqtt_unsuback{message_id=MessageId}; variable(<<?CONNECT:4, 0:4>>, <<L:16/big, PMagic:L/binary, _/binary>>) when not ((PMagic == ?PROTOCOL_MAGIC_311) or (PMagic == ?PROTOCOL_MAGIC_31)) -> {error, unknown_protocol_magic}; variable(<<?CONNECT:4, 0:4>>, <<L:16/big, _:L/binary, ProtoVersion:8, UserNameFlag:1, PasswordFlag:1, WillRetain:1, WillQos:2, WillFlag:1, CleanSession:1, 0:1, % reserved KeepAlive: 16/big, ClientIdLen:16/big, ClientId:ClientIdLen/binary, Rest0/binary>>) -> Conn0 = #mqtt_connect{proto_ver=ProtoVersion, clean_session=CleanSession, keep_alive=KeepAlive, client_id=ClientId}, case parse_last_will_topic(Rest0, WillFlag, WillRetain, WillQos, Conn0) of {ok, Rest1, Conn1} -> case parse_username(Rest1, UserNameFlag, Conn1) of {ok, Rest2, Conn2} -> case parse_password(Rest2, UserNameFlag, PasswordFlag, Conn2) of {ok, <<>>, Conn3} -> Conn3; {ok, _, _} -> {error, invalid_rest_of_binary}; E -> E end; E -> E end; E -> E end; variable(<<?CONNACK:4, 0:4>>, <<0:7, SP:1, ReturnCode:8/big>>) -> #mqtt_connack{session_present=SP, return_code=ReturnCode}; variable(<<?PINGREQ:4, 0:4>>, <<>>) -> #mqtt_pingreq{}; variable(<<?PINGRESP:4, 0:4>>, <<>>) -> #mqtt_pingresp{}; variable(<<?DISCONNECT:4, 0:4>>, <<>>) -> #mqtt_disconnect{}; variable(_, _) -> {error, cant_parse_variable_header}. parse_last_will_topic(Rest, 0, 0, 0, Conn) -> {ok, Rest, Conn}; parse_last_will_topic(<<WillTopicLen:16/big, WillTopic:WillTopicLen/binary, WillMsgLen:16/big, WillMsg:WillMsgLen/binary, Rest/binary>>, 1, Retain, QoS, Conn) -> case vmq_topic:validate_topic(publish, WillTopic) of {ok, ParsedTopic} -> {ok, Rest, Conn#mqtt_connect{will_msg=WillMsg, will_topic=ParsedTopic, will_retain=Retain, will_qos=QoS}}; _ -> {error, cant_validate_last_will_topic} end; parse_last_will_topic(_, _, _, _,_) -> {error, cant_parse_last_will}. parse_username(Rest, 0, Conn) -> {ok, Rest, Conn}; parse_username(<<Len:16/big, UserName:Len/binary, Rest/binary>>, 1, Conn) -> {ok, Rest, Conn#mqtt_connect{username=UserName}}; parse_username(_, 1, _) -> {error, cant_parse_username}. parse_password(Rest, _, 0, Conn) -> {ok, Rest, Conn}; parse_password(<<Len:16/big, Password:Len/binary, Rest/binary>>, 1, 1, Conn) -> {ok, Rest, Conn#mqtt_connect{password=Password}}; parse_password(_, 0, 1, _) -> {error, username_flag_not_set}; parse_password(_, _, 1, _) -> {error, cant_parse_password}. parse_topics(<<>>, _, []) -> {error, no_topic_provided}; parse_topics(<<>>, _, Topics) -> {ok, Topics}; parse_topics(<<L:16/big, Topic:L/binary, 0:6, QoS:2, Rest/binary>>, ?SUBSCRIBE = Sub, Acc) when (QoS >= 0) and (QoS < 3) -> case vmq_topic:validate_topic(subscribe, Topic) of {ok, ParsedTopic} -> parse_topics(Rest, Sub, [{ParsedTopic, QoS}|Acc]); E -> E end; parse_topics(<<L:16/big, Topic:L/binary, Rest/binary>>, ?UNSUBSCRIBE = Sub, Acc) -> case vmq_topic:validate_topic(subscribe, Topic) of {ok, ParsedTopic} -> parse_topics(Rest, Sub, [ParsedTopic|Acc]); E -> E end; parse_topics(_, _, _) -> {error, cant_parse_topics}. parse_acks(<<>>, Acks) -> Acks; parse_acks(<<128:8, Rest/binary>>, Acks) -> parse_acks(Rest, [not_allowed | Acks]); parse_acks(<<_:6, QoS:2, Rest/binary>>, Acks) when is_integer(QoS) and ((QoS >= 0) and (QoS =< 2)) -> parse_acks(Rest, [QoS | Acks]). -spec serialise(mqtt_frame()) -> binary() | iolist(). serialise(#mqtt_publish{qos=0, topic=Topic, retain=Retain, dup=Dup, payload=Payload}) -> Var = [utf8(vmq_topic:unword(Topic)), Payload], LenBytes = serialise_len(iolist_size(Var)), [<<?PUBLISH:4, (flag(Dup)):1/integer, 0:2/integer, (flag(Retain)):1/integer>>, LenBytes, Var]; serialise(#mqtt_publish{message_id=MessageId, topic=Topic, qos=QoS, retain=Retain, dup=Dup, payload=Payload}) -> Var = [utf8(vmq_topic:unword(Topic)), msg_id(MessageId), Payload], LenBytes = serialise_len(iolist_size(Var)), [<<?PUBLISH:4, (flag(Dup)):1/integer, (default(QoS, 0)):2/integer, (flag(Retain)):1/integer>>, LenBytes, Var]; serialise(#mqtt_puback{message_id=MessageId}) -> <<?PUBACK:4, 0:4, 2, MessageId:16/big>>; serialise(#mqtt_pubrel{message_id=MessageId}) -> <<?PUBREL:4, 0:2, 1:1, 0:1, 2, MessageId:16/big>>; serialise(#mqtt_pubrec{message_id=MessageId}) -> <<?PUBREC:4, 0:4, 2, MessageId:16/big>>; serialise(#mqtt_pubcomp{message_id=MessageId}) -> <<?PUBCOMP:4, 0:4, 2, MessageId:16/big>>; serialise(#mqtt_connect{proto_ver=ProtoVersion, username=UserName, password=Password, will_retain=WillRetain, will_qos=WillQos, clean_session=CleanSession, keep_alive=KeepAlive, client_id=ClientId, will_topic=WillTopic, will_msg=WillMsg}) -> {PMagicL, PMagic} = proto(ProtoVersion), Var = [<<PMagicL:16/big-unsigned-integer, PMagic/binary, ProtoVersion:8/unsigned-integer, (flag(UserName)):1/integer, (flag(Password)):1/integer, (flag(WillRetain)):1/integer, (default(WillQos, 0)):2/integer, (flag(WillTopic)):1/integer, (flag(CleanSession)):1/integer, 0:1, % reserved (default(KeepAlive, 0)):16/big-unsigned-integer>>, utf8(ClientId), utf8(vmq_topic:unword(WillTopic)), utf8(WillMsg), utf8(UserName), utf8(Password)], LenBytes = serialise_len(iolist_size(Var)), [<<?CONNECT:4, 0:4>>, LenBytes, Var]; serialise(#mqtt_connack{session_present=SP, return_code=RC}) -> [<<?CONNACK:4, 0:4>>, serialise_len(2), <<0:7, (flag(SP)):1/integer>>, <<RC:8/big>>]; serialise(#mqtt_subscribe{message_id=MessageId, topics=Topics}) -> SerialisedTopics = serialise_topics(?SUBSCRIBE, Topics, []), LenBytes = serialise_len(iolist_size(SerialisedTopics) + 2), [<<?SUBSCRIBE:4, 0:2, 1:1, 0:1>>, LenBytes, <<MessageId:16/big>>, SerialisedTopics]; serialise(#mqtt_suback{message_id=MessageId, qos_table=QosTable}) -> SerialisedAcks = serialise_acks(QosTable, []), LenBytes = serialise_len(iolist_size(SerialisedAcks) + 2), [<<?SUBACK:4, 0:4>>, LenBytes, <<MessageId:16/big>>, SerialisedAcks]; serialise(#mqtt_unsubscribe{message_id=MessageId, topics=Topics}) -> SerialisedTopics = serialise_topics(?UNSUBSCRIBE, Topics, []), LenBytes = serialise_len(iolist_size(SerialisedTopics) + 2), [<<?UNSUBSCRIBE:4, 0:2, 1:1, 0:1>>, LenBytes, <<MessageId:16/big>>, SerialisedTopics]; serialise(#mqtt_unsuback{message_id=MessageId}) -> <<?UNSUBACK:4, 0:4, 2, MessageId:16/big>>; serialise(#mqtt_pingreq{}) -> <<?PINGREQ:4, 0:4, 0>>; serialise(#mqtt_pingresp{}) -> <<?PINGRESP:4, 0:4, 0>>; serialise(#mqtt_disconnect{}) -> <<?DISCONNECT:4, 0:4, 0>>. serialise_len(N) when N =< ?LOWBITS -> <<0:1, N:7>>; serialise_len(N) -> <<1:1, (N rem ?HIGHBIT):7, (serialise_len(N div ?HIGHBIT))/binary>>. serialise_topics(?SUBSCRIBE = Sub, [{Topic, QoS}|Rest], Acc) -> serialise_topics(Sub, Rest, [utf8(vmq_topic:unword(Topic)), <<0:6, QoS:2>>|Acc]); serialise_topics(?UNSUBSCRIBE = Sub, [Topic|Rest], Acc) -> serialise_topics(Sub, Rest, [utf8(vmq_topic:unword(Topic))|Acc]); serialise_topics(_, [], Topics) -> Topics. serialise_acks([QoS|Rest], Acks) when is_integer(QoS) and ((QoS >= 0) and (QoS =< 2)) -> serialise_acks(Rest, [<<0:6, QoS:2>>|Acks]); serialise_acks([_|Rest], Acks) -> use 0x80 failure code for everything else serialise_acks(Rest, [<<128:8>>|Acks]); serialise_acks([], Acks) -> Acks. proto(4) -> {4, ?PROTOCOL_MAGIC_311}; proto(3) -> {6, ?PROTOCOL_MAGIC_31}; proto(131) -> {6, ?PROTOCOL_MAGIC_31}; proto(132) -> {4, ?PROTOCOL_MAGIC_311}. flag(<<>>) -> 0; flag(undefined) -> 0; flag(0) -> 0; flag(1) -> 1; flag(false) -> 0; flag(true) -> 1; flag(V) when is_binary(V) orelse is_list(V) -> 1; flag(empty) -> 1; %% for test purposes flag(_) -> 0. msg_id(undefined) -> <<>>; msg_id(MsgId) -> <<MsgId:16/big>>. default(undefined, Default) -> Default; default(Val, _) -> Val. utf8(<<>>) -> <<>>; utf8(undefined) -> <<>>; utf8(empty) -> <<0:16/big>>; %% for test purposes, useful if you want to encode an empty string.. utf8(IoList) when is_list(IoList) -> [<<(iolist_size(IoList)):16/big>>, IoList]; utf8(Bin) when is_binary(Bin) -> <<(byte_size(Bin)):16/big, Bin/binary>>. ensure_binary(L) when is_list(L) -> list_to_binary(L); ensure_binary(B) when is_binary(B) -> B; ensure_binary(undefined) -> undefined; ensure_binary(empty) -> empty. % for test purposes %%%%%%% packet generator functions (useful for testing) gen_connect(ClientId, Opts) -> Frame = #mqtt_connect{ client_id = ensure_binary(ClientId), clean_session = proplists:get_value(clean_session, Opts, true), keep_alive = proplists:get_value(keepalive, Opts, 60), username = ensure_binary(proplists:get_value(username, Opts)), password = ensure_binary(proplists:get_value(password, Opts)), proto_ver = proplists:get_value(proto_ver, Opts, 3), will_topic = ensure_binary(proplists:get_value(will_topic, Opts)), will_qos = proplists:get_value(will_qos, Opts, 0), will_retain = proplists:get_value(will_retain, Opts, false), will_msg = ensure_binary(proplists:get_value(will_msg, Opts)) }, iolist_to_binary(serialise(Frame)). gen_connack() -> gen_connack(?CONNACK_ACCEPT). gen_connack(RC) -> gen_connack(0, RC). gen_connack(SP, RC) -> iolist_to_binary(serialise(#mqtt_connack{session_present=flag(SP), return_code=RC})). gen_publish(Topic, Qos, Payload, Opts) -> Frame = #mqtt_publish{ dup = proplists:get_value(dup, Opts, false), qos = Qos, retain = proplists:get_value(retain, Opts, false), topic = ensure_binary(Topic), message_id = proplists:get_value(mid, Opts, 0), payload = ensure_binary(Payload) }, iolist_to_binary(serialise(Frame)). gen_puback(MId) -> iolist_to_binary(serialise(#mqtt_puback{message_id=MId})). gen_pubrec(MId) -> iolist_to_binary(serialise(#mqtt_pubrec{message_id=MId})). gen_pubrel(MId) -> iolist_to_binary(serialise(#mqtt_pubrel{message_id=MId})). gen_pubcomp(MId) -> iolist_to_binary(serialise(#mqtt_pubcomp{message_id=MId})). gen_subscribe(MId, [{_, _}|_] = Topics) -> BinTopics = [{ensure_binary(Topic), QoS} || {Topic, QoS} <- Topics], iolist_to_binary(serialise(#mqtt_subscribe{topics=BinTopics, message_id=MId})). gen_subscribe(MId, Topic, QoS) -> gen_subscribe(MId, [{Topic, QoS}]). gen_suback(MId, QoSs) when is_list(QoSs) -> iolist_to_binary(serialise(#mqtt_suback{qos_table=QoSs, message_id=MId})); gen_suback(MId, QoS) -> gen_suback(MId, [QoS]). gen_unsubscribe(MId, Topic) -> iolist_to_binary(serialise(#mqtt_unsubscribe{topics=[ensure_binary(Topic)], message_id=MId})). gen_unsuback(MId) -> iolist_to_binary(serialise(#mqtt_unsuback{message_id=MId})). gen_pingreq() -> iolist_to_binary(serialise(#mqtt_pingreq{})). gen_pingresp() -> iolist_to_binary(serialise(#mqtt_pingresp{})). gen_disconnect() -> iolist_to_binary(serialise(#mqtt_disconnect{})).
null
https://raw.githubusercontent.com/vernemq/vmq_mzbench/640a6eb73b2ea35f874b798c8480ca91abff59d8/src/vmq_parser.erl
erlang
frame types no max size limit reserved reserved for test purposes for test purposes, useful if you want to encode an empty string.. for test purposes packet generator functions (useful for testing)
-module(vmq_parser). -include("vmq_types.hrl"). -export([parse/1, parse/2, serialise/1]). -dialyzer({no_match, utf8/1}). -export([gen_connect/2, gen_connack/0, gen_connack/1, gen_connack/2, gen_publish/4, gen_puback/1, gen_pubrec/1, gen_pubrel/1, gen_pubcomp/1, gen_subscribe/2, gen_subscribe/3, gen_suback/2, gen_unsubscribe/2, gen_unsuback/1, gen_pingreq/0, gen_pingresp/0, gen_disconnect/0]). -define(CONNECT, 1). -define(CONNACK, 2). -define(PUBLISH, 3). -define(PUBACK, 4). -define(PUBREC, 5). -define(PUBREL, 6). -define(PUBCOMP, 7). -define(SUBSCRIBE, 8). -define(SUBACK, 9). -define(UNSUBSCRIBE, 10). -define(UNSUBACK, 11). -define(PINGREQ, 12). -define(PINGRESP, 13). -define(DISCONNECT, 14). -define(RESERVED, 0). -define(PROTOCOL_MAGIC_31, <<"MQIsdp">>). -define(PROTOCOL_MAGIC_311, <<"MQTT">>). -define(MAX_LEN, 16#fffffff). -define(HIGHBIT, 2#10000000). -define(LOWBITS, 2#01111111). -define(MAX_PACKET_SIZE, 268435455). -spec parse(binary()) -> {mqtt_frame(), binary()} | {error, atom()} | {{error, atom()}, any()} |more. parse(Data) -> parse(Data, ?MAX_PACKET_SIZE). -spec parse(binary(), non_neg_integer()) -> {mqtt_frame(), binary()} | {error, atom()} | more. parse(<<Fixed:1/binary, 0:1, DataSize:7, Data/binary>>, MaxSize)-> parse(DataSize, MaxSize, Fixed, Data); parse(<<Fixed:1/binary, 1:1, L1:7, 0:1, L2:7, Data/binary>>, MaxSize) -> parse(L1 + (L2 bsl 7), MaxSize, Fixed, Data); parse(<<Fixed:1/binary, 1:1, L1:7, 1:1, L2:7, 0:1, L3:7, Data/binary>>, MaxSize) -> parse(L1 + (L2 bsl 7) + (L3 bsl 14), MaxSize, Fixed, Data); parse(<<Fixed:1/binary, 1:1, L1:7, 1:1, L2:7, 1:1, L3:7, 0:1, L4:7, Data/binary>>, MaxSize) -> parse(L1 + (L2 bsl 7) + (L3 bsl 14) + (L4 bsl 21), MaxSize, Fixed, Data); parse(<<_:8/binary, _/binary>>, _) -> {error, cant_parse_fixed_header}; parse(_, _) -> more. parse(DataSize, 0, Fixed, Data) when byte_size(Data) >= DataSize -> <<Var:DataSize/binary, Rest/binary>> = Data, {variable(Fixed, Var), Rest}; parse(DataSize, 0, _Fixed, Data) when byte_size(Data) < DataSize -> more; parse(DataSize, MaxSize, Fixed, Data) when byte_size(Data) >= DataSize, byte_size(Data) =< MaxSize -> <<Var:DataSize/binary, Rest/binary>> = Data, {variable(Fixed, Var), Rest}; parse(DataSize, MaxSize, _, _) when DataSize > MaxSize -> {error, packet_exceeds_max_size}; parse(_, _, _, _) -> more. -spec variable(binary(), binary()) -> mqtt_frame() | {error, atom()}. variable(<<?PUBLISH:4, Dup:1, 0:2, Retain:1>>, <<TopicLen:16/big, Topic:TopicLen/binary, Payload/binary>>) -> case vmq_topic:validate_topic(publish, Topic) of {ok, ParsedTopic} -> #mqtt_publish{dup=Dup, retain=Retain, topic=ParsedTopic, qos=0, payload=Payload}; {error, Reason} -> {error, Reason} end; variable(<<?PUBLISH:4, Dup:1, QoS:2, Retain:1>>, <<TopicLen:16/big, Topic:TopicLen/binary, MessageId:16/big, Payload/binary>>) when QoS < 3 -> case vmq_topic:validate_topic(publish, Topic) of {ok, ParsedTopic} -> #mqtt_publish{dup=Dup, retain=Retain, topic=ParsedTopic, qos=QoS, message_id=MessageId, payload=Payload}; {error, Reason} -> {error, Reason} end; variable(<<?PUBACK:4, 0:4>>, <<MessageId:16/big>>) -> #mqtt_puback{message_id=MessageId}; variable(<<?PUBREC:4, 0:4>>, <<MessageId:16/big>>) -> #mqtt_pubrec{message_id=MessageId}; variable(<<?PUBREL:4, 0:2, 1:1, 0:1>>, <<MessageId:16/big>>) -> #mqtt_pubrel{message_id=MessageId}; variable(<<?PUBCOMP:4, 0:4>>, <<MessageId:16/big>>) -> #mqtt_pubcomp{message_id=MessageId}; variable(<<?SUBSCRIBE:4, 0:2, 1:1, 0:1>>, <<MessageId:16/big, Topics/binary>>) -> case parse_topics(Topics, ?SUBSCRIBE, []) of {ok, ParsedTopics} -> #mqtt_subscribe{topics=ParsedTopics, message_id=MessageId}; E -> E end; variable(<<?UNSUBSCRIBE:4, 0:2, 1:1, 0:1>>, <<MessageId:16/big, Topics/binary>>) -> case parse_topics(Topics, ?UNSUBSCRIBE, []) of {ok, ParsedTopics} -> #mqtt_unsubscribe{topics=ParsedTopics, message_id=MessageId}; E -> E end; variable(<<?SUBACK:4, 0:4>>, <<MessageId:16/big, Acks/binary>>) -> #mqtt_suback{qos_table=parse_acks(Acks, []), message_id=MessageId}; variable(<<?UNSUBACK:4, 0:4>>, <<MessageId:16/big>>) -> #mqtt_unsuback{message_id=MessageId}; variable(<<?CONNECT:4, 0:4>>, <<L:16/big, PMagic:L/binary, _/binary>>) when not ((PMagic == ?PROTOCOL_MAGIC_311) or (PMagic == ?PROTOCOL_MAGIC_31)) -> {error, unknown_protocol_magic}; variable(<<?CONNECT:4, 0:4>>, <<L:16/big, _:L/binary, ProtoVersion:8, UserNameFlag:1, PasswordFlag:1, WillRetain:1, WillQos:2, WillFlag:1, CleanSession:1, KeepAlive: 16/big, ClientIdLen:16/big, ClientId:ClientIdLen/binary, Rest0/binary>>) -> Conn0 = #mqtt_connect{proto_ver=ProtoVersion, clean_session=CleanSession, keep_alive=KeepAlive, client_id=ClientId}, case parse_last_will_topic(Rest0, WillFlag, WillRetain, WillQos, Conn0) of {ok, Rest1, Conn1} -> case parse_username(Rest1, UserNameFlag, Conn1) of {ok, Rest2, Conn2} -> case parse_password(Rest2, UserNameFlag, PasswordFlag, Conn2) of {ok, <<>>, Conn3} -> Conn3; {ok, _, _} -> {error, invalid_rest_of_binary}; E -> E end; E -> E end; E -> E end; variable(<<?CONNACK:4, 0:4>>, <<0:7, SP:1, ReturnCode:8/big>>) -> #mqtt_connack{session_present=SP, return_code=ReturnCode}; variable(<<?PINGREQ:4, 0:4>>, <<>>) -> #mqtt_pingreq{}; variable(<<?PINGRESP:4, 0:4>>, <<>>) -> #mqtt_pingresp{}; variable(<<?DISCONNECT:4, 0:4>>, <<>>) -> #mqtt_disconnect{}; variable(_, _) -> {error, cant_parse_variable_header}. parse_last_will_topic(Rest, 0, 0, 0, Conn) -> {ok, Rest, Conn}; parse_last_will_topic(<<WillTopicLen:16/big, WillTopic:WillTopicLen/binary, WillMsgLen:16/big, WillMsg:WillMsgLen/binary, Rest/binary>>, 1, Retain, QoS, Conn) -> case vmq_topic:validate_topic(publish, WillTopic) of {ok, ParsedTopic} -> {ok, Rest, Conn#mqtt_connect{will_msg=WillMsg, will_topic=ParsedTopic, will_retain=Retain, will_qos=QoS}}; _ -> {error, cant_validate_last_will_topic} end; parse_last_will_topic(_, _, _, _,_) -> {error, cant_parse_last_will}. parse_username(Rest, 0, Conn) -> {ok, Rest, Conn}; parse_username(<<Len:16/big, UserName:Len/binary, Rest/binary>>, 1, Conn) -> {ok, Rest, Conn#mqtt_connect{username=UserName}}; parse_username(_, 1, _) -> {error, cant_parse_username}. parse_password(Rest, _, 0, Conn) -> {ok, Rest, Conn}; parse_password(<<Len:16/big, Password:Len/binary, Rest/binary>>, 1, 1, Conn) -> {ok, Rest, Conn#mqtt_connect{password=Password}}; parse_password(_, 0, 1, _) -> {error, username_flag_not_set}; parse_password(_, _, 1, _) -> {error, cant_parse_password}. parse_topics(<<>>, _, []) -> {error, no_topic_provided}; parse_topics(<<>>, _, Topics) -> {ok, Topics}; parse_topics(<<L:16/big, Topic:L/binary, 0:6, QoS:2, Rest/binary>>, ?SUBSCRIBE = Sub, Acc) when (QoS >= 0) and (QoS < 3) -> case vmq_topic:validate_topic(subscribe, Topic) of {ok, ParsedTopic} -> parse_topics(Rest, Sub, [{ParsedTopic, QoS}|Acc]); E -> E end; parse_topics(<<L:16/big, Topic:L/binary, Rest/binary>>, ?UNSUBSCRIBE = Sub, Acc) -> case vmq_topic:validate_topic(subscribe, Topic) of {ok, ParsedTopic} -> parse_topics(Rest, Sub, [ParsedTopic|Acc]); E -> E end; parse_topics(_, _, _) -> {error, cant_parse_topics}. parse_acks(<<>>, Acks) -> Acks; parse_acks(<<128:8, Rest/binary>>, Acks) -> parse_acks(Rest, [not_allowed | Acks]); parse_acks(<<_:6, QoS:2, Rest/binary>>, Acks) when is_integer(QoS) and ((QoS >= 0) and (QoS =< 2)) -> parse_acks(Rest, [QoS | Acks]). -spec serialise(mqtt_frame()) -> binary() | iolist(). serialise(#mqtt_publish{qos=0, topic=Topic, retain=Retain, dup=Dup, payload=Payload}) -> Var = [utf8(vmq_topic:unword(Topic)), Payload], LenBytes = serialise_len(iolist_size(Var)), [<<?PUBLISH:4, (flag(Dup)):1/integer, 0:2/integer, (flag(Retain)):1/integer>>, LenBytes, Var]; serialise(#mqtt_publish{message_id=MessageId, topic=Topic, qos=QoS, retain=Retain, dup=Dup, payload=Payload}) -> Var = [utf8(vmq_topic:unword(Topic)), msg_id(MessageId), Payload], LenBytes = serialise_len(iolist_size(Var)), [<<?PUBLISH:4, (flag(Dup)):1/integer, (default(QoS, 0)):2/integer, (flag(Retain)):1/integer>>, LenBytes, Var]; serialise(#mqtt_puback{message_id=MessageId}) -> <<?PUBACK:4, 0:4, 2, MessageId:16/big>>; serialise(#mqtt_pubrel{message_id=MessageId}) -> <<?PUBREL:4, 0:2, 1:1, 0:1, 2, MessageId:16/big>>; serialise(#mqtt_pubrec{message_id=MessageId}) -> <<?PUBREC:4, 0:4, 2, MessageId:16/big>>; serialise(#mqtt_pubcomp{message_id=MessageId}) -> <<?PUBCOMP:4, 0:4, 2, MessageId:16/big>>; serialise(#mqtt_connect{proto_ver=ProtoVersion, username=UserName, password=Password, will_retain=WillRetain, will_qos=WillQos, clean_session=CleanSession, keep_alive=KeepAlive, client_id=ClientId, will_topic=WillTopic, will_msg=WillMsg}) -> {PMagicL, PMagic} = proto(ProtoVersion), Var = [<<PMagicL:16/big-unsigned-integer, PMagic/binary, ProtoVersion:8/unsigned-integer, (flag(UserName)):1/integer, (flag(Password)):1/integer, (flag(WillRetain)):1/integer, (default(WillQos, 0)):2/integer, (flag(WillTopic)):1/integer, (flag(CleanSession)):1/integer, (default(KeepAlive, 0)):16/big-unsigned-integer>>, utf8(ClientId), utf8(vmq_topic:unword(WillTopic)), utf8(WillMsg), utf8(UserName), utf8(Password)], LenBytes = serialise_len(iolist_size(Var)), [<<?CONNECT:4, 0:4>>, LenBytes, Var]; serialise(#mqtt_connack{session_present=SP, return_code=RC}) -> [<<?CONNACK:4, 0:4>>, serialise_len(2), <<0:7, (flag(SP)):1/integer>>, <<RC:8/big>>]; serialise(#mqtt_subscribe{message_id=MessageId, topics=Topics}) -> SerialisedTopics = serialise_topics(?SUBSCRIBE, Topics, []), LenBytes = serialise_len(iolist_size(SerialisedTopics) + 2), [<<?SUBSCRIBE:4, 0:2, 1:1, 0:1>>, LenBytes, <<MessageId:16/big>>, SerialisedTopics]; serialise(#mqtt_suback{message_id=MessageId, qos_table=QosTable}) -> SerialisedAcks = serialise_acks(QosTable, []), LenBytes = serialise_len(iolist_size(SerialisedAcks) + 2), [<<?SUBACK:4, 0:4>>, LenBytes, <<MessageId:16/big>>, SerialisedAcks]; serialise(#mqtt_unsubscribe{message_id=MessageId, topics=Topics}) -> SerialisedTopics = serialise_topics(?UNSUBSCRIBE, Topics, []), LenBytes = serialise_len(iolist_size(SerialisedTopics) + 2), [<<?UNSUBSCRIBE:4, 0:2, 1:1, 0:1>>, LenBytes, <<MessageId:16/big>>, SerialisedTopics]; serialise(#mqtt_unsuback{message_id=MessageId}) -> <<?UNSUBACK:4, 0:4, 2, MessageId:16/big>>; serialise(#mqtt_pingreq{}) -> <<?PINGREQ:4, 0:4, 0>>; serialise(#mqtt_pingresp{}) -> <<?PINGRESP:4, 0:4, 0>>; serialise(#mqtt_disconnect{}) -> <<?DISCONNECT:4, 0:4, 0>>. serialise_len(N) when N =< ?LOWBITS -> <<0:1, N:7>>; serialise_len(N) -> <<1:1, (N rem ?HIGHBIT):7, (serialise_len(N div ?HIGHBIT))/binary>>. serialise_topics(?SUBSCRIBE = Sub, [{Topic, QoS}|Rest], Acc) -> serialise_topics(Sub, Rest, [utf8(vmq_topic:unword(Topic)), <<0:6, QoS:2>>|Acc]); serialise_topics(?UNSUBSCRIBE = Sub, [Topic|Rest], Acc) -> serialise_topics(Sub, Rest, [utf8(vmq_topic:unword(Topic))|Acc]); serialise_topics(_, [], Topics) -> Topics. serialise_acks([QoS|Rest], Acks) when is_integer(QoS) and ((QoS >= 0) and (QoS =< 2)) -> serialise_acks(Rest, [<<0:6, QoS:2>>|Acks]); serialise_acks([_|Rest], Acks) -> use 0x80 failure code for everything else serialise_acks(Rest, [<<128:8>>|Acks]); serialise_acks([], Acks) -> Acks. proto(4) -> {4, ?PROTOCOL_MAGIC_311}; proto(3) -> {6, ?PROTOCOL_MAGIC_31}; proto(131) -> {6, ?PROTOCOL_MAGIC_31}; proto(132) -> {4, ?PROTOCOL_MAGIC_311}. flag(<<>>) -> 0; flag(undefined) -> 0; flag(0) -> 0; flag(1) -> 1; flag(false) -> 0; flag(true) -> 1; flag(V) when is_binary(V) orelse is_list(V) -> 1; flag(_) -> 0. msg_id(undefined) -> <<>>; msg_id(MsgId) -> <<MsgId:16/big>>. default(undefined, Default) -> Default; default(Val, _) -> Val. utf8(<<>>) -> <<>>; utf8(undefined) -> <<>>; utf8(IoList) when is_list(IoList) -> [<<(iolist_size(IoList)):16/big>>, IoList]; utf8(Bin) when is_binary(Bin) -> <<(byte_size(Bin)):16/big, Bin/binary>>. ensure_binary(L) when is_list(L) -> list_to_binary(L); ensure_binary(B) when is_binary(B) -> B; ensure_binary(undefined) -> undefined; gen_connect(ClientId, Opts) -> Frame = #mqtt_connect{ client_id = ensure_binary(ClientId), clean_session = proplists:get_value(clean_session, Opts, true), keep_alive = proplists:get_value(keepalive, Opts, 60), username = ensure_binary(proplists:get_value(username, Opts)), password = ensure_binary(proplists:get_value(password, Opts)), proto_ver = proplists:get_value(proto_ver, Opts, 3), will_topic = ensure_binary(proplists:get_value(will_topic, Opts)), will_qos = proplists:get_value(will_qos, Opts, 0), will_retain = proplists:get_value(will_retain, Opts, false), will_msg = ensure_binary(proplists:get_value(will_msg, Opts)) }, iolist_to_binary(serialise(Frame)). gen_connack() -> gen_connack(?CONNACK_ACCEPT). gen_connack(RC) -> gen_connack(0, RC). gen_connack(SP, RC) -> iolist_to_binary(serialise(#mqtt_connack{session_present=flag(SP), return_code=RC})). gen_publish(Topic, Qos, Payload, Opts) -> Frame = #mqtt_publish{ dup = proplists:get_value(dup, Opts, false), qos = Qos, retain = proplists:get_value(retain, Opts, false), topic = ensure_binary(Topic), message_id = proplists:get_value(mid, Opts, 0), payload = ensure_binary(Payload) }, iolist_to_binary(serialise(Frame)). gen_puback(MId) -> iolist_to_binary(serialise(#mqtt_puback{message_id=MId})). gen_pubrec(MId) -> iolist_to_binary(serialise(#mqtt_pubrec{message_id=MId})). gen_pubrel(MId) -> iolist_to_binary(serialise(#mqtt_pubrel{message_id=MId})). gen_pubcomp(MId) -> iolist_to_binary(serialise(#mqtt_pubcomp{message_id=MId})). gen_subscribe(MId, [{_, _}|_] = Topics) -> BinTopics = [{ensure_binary(Topic), QoS} || {Topic, QoS} <- Topics], iolist_to_binary(serialise(#mqtt_subscribe{topics=BinTopics, message_id=MId})). gen_subscribe(MId, Topic, QoS) -> gen_subscribe(MId, [{Topic, QoS}]). gen_suback(MId, QoSs) when is_list(QoSs) -> iolist_to_binary(serialise(#mqtt_suback{qos_table=QoSs, message_id=MId})); gen_suback(MId, QoS) -> gen_suback(MId, [QoS]). gen_unsubscribe(MId, Topic) -> iolist_to_binary(serialise(#mqtt_unsubscribe{topics=[ensure_binary(Topic)], message_id=MId})). gen_unsuback(MId) -> iolist_to_binary(serialise(#mqtt_unsuback{message_id=MId})). gen_pingreq() -> iolist_to_binary(serialise(#mqtt_pingreq{})). gen_pingresp() -> iolist_to_binary(serialise(#mqtt_pingresp{})). gen_disconnect() -> iolist_to_binary(serialise(#mqtt_disconnect{})).
e10f54207a5d0a9625f19ba02e7e612e2f2aab42e4fdb1328913501b6cb5952f
hpdeifel/hledger-iadd
DateParserSpec.hs
{-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -fno - warn - orphans # module DateParserSpec (spec) where import Test.Hspec import Test.QuickCheck import Control.Monad import Data.Either import Data.Text (Text) import qualified Data.Text as T import Data.Time import Data.Time.Calendar.WeekDate import DateParser spec :: Spec spec = do dateFormatTests dateTests dateCompletionTests printTests dateFormatTests :: Spec dateFormatTests = describe "date format parser" $ it "parses the german format correctly" $ parseDateFormat "%d[.[%m[.[%y]]]]" `shouldBe` Right german dateTests :: Spec dateTests = describe "date parser" $ do it "actually requires non-optional fields" $ shouldFail "%d-%m-%y" "05" describe "weekDay" $ do it "actually returns the right week day" $ property weekDayProp it "is always smaller than the current date" $ property weekDaySmallerProp dateCompletionTests :: Spec dateCompletionTests = describe "date completion" $ do it "today" $ parseGerman 2004 7 31 "31.7.2004" `shouldBe` Right (fromGregorian 2004 7 31) it "today is a leap day" $ parseGerman 2012 2 29 "29.2.2012" `shouldBe` Right (fromGregorian 2012 2 29) it "skips to previous month" $ parseGerman 2016 9 20 "21" `shouldBe` Right (fromGregorian 2016 08 21) it "stays in month if possible" $ parseGerman 2016 8 30 "21" `shouldBe` Right (fromGregorian 2016 08 21) it "skips to previous month to reach the 31st" $ parseGerman 2016 8 30 "31" `shouldBe` Right (fromGregorian 2016 07 31) it "skips to an earlier month to reach the 31st" $ parseGerman 2016 7 30 "31" `shouldBe` Right (fromGregorian 2016 05 31) it "skips to the previous year if necessary" $ parseGerman 2016 9 30 "2.12." `shouldBe` Right (fromGregorian 2015 12 2) it "skips to the previous years if after a leap year" $ parseGerman 2017 3 10 "29.2" `shouldBe` Right (fromGregorian 2016 02 29) it "even might skip to a leap year 8 years ago" $ parseGerman 2104 2 27 "29.2" `shouldBe` Right (fromGregorian 2096 02 29) it "some date in the near future" $ parseGerman 2016 2 20 "30.11.2016" `shouldBe` Right (fromGregorian 2016 11 30) it "some date in the far future" $ parseGerman 2016 2 20 "30.11.3348" `shouldBe` Right (fromGregorian 3348 11 30) it "last october" $ (do monthOnly <- parseDateFormat "%m" parseDate (fromGregorian 2016 9 15) monthOnly "10" ) `shouldBe` Right (fromGregorian 2015 10 31) it "last november" $ (do monthOnly <- parseDateFormat "%m" parseDate (fromGregorian 2016 9 15) monthOnly "11" ) `shouldBe` Right (fromGregorian 2015 11 30) it "next november" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2016.11" ) `shouldBe` Right (fromGregorian 2016 11 1) it "next january" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2017.1" ) `shouldBe` Right (fromGregorian 2017 1 1) it "last january" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2016.1" ) `shouldBe` Right (fromGregorian 2016 1 31) it "literally yesterday" $ do parseGerman 2018 10 18 "yesterday" `shouldBe` Right (fromGregorian 2018 10 17) parseGerman 2018 10 18 "yest" `shouldBe` Right (fromGregorian 2018 10 17) it "literally today" $ do parseGerman 2018 10 18 "today" `shouldBe` Right (fromGregorian 2018 10 18) it "literally tomorrow" $ do parseGerman 2018 10 18 "tomorrow" `shouldBe` Right (fromGregorian 2018 10 19) it "literally monday" $ do parseGerman 2018 10 18 "monday" `shouldBe` Right (fromGregorian 2018 10 15) parseGerman 2018 10 18 "mon" `shouldBe` Right (fromGregorian 2018 10 15) it "literally tuesday" $ do parseGerman 2018 10 18 "tuesday" `shouldBe` Right (fromGregorian 2018 10 16) parseGerman 2018 10 18 "tues" `shouldBe` Right (fromGregorian 2018 10 16) parseGerman 2018 10 18 "tue" `shouldBe` Right (fromGregorian 2018 10 16) it "literally wednesday" $ do parseGerman 2018 10 18 "wednesday" `shouldBe` Right (fromGregorian 2018 10 17) parseGerman 2018 10 18 "wed" `shouldBe` Right (fromGregorian 2018 10 17) it "literally thursday" $ do parseGerman 2018 10 18 "thursday" `shouldBe` Right (fromGregorian 2018 10 18) parseGerman 2018 10 18 "thur" `shouldBe` Right (fromGregorian 2018 10 18) it "literally friday" $ do parseGerman 2018 10 18 "friday" `shouldBe` Right (fromGregorian 2018 10 12) parseGerman 2018 10 18 "fri" `shouldBe` Right (fromGregorian 2018 10 12) it "literally saturday" $ do parseGerman 2018 10 18 "saturday" `shouldBe` Right (fromGregorian 2018 10 13) parseGerman 2018 10 18 "sat" `shouldBe` Right (fromGregorian 2018 10 13) it "literally sunday" $ do parseGerman 2018 10 18 "sunday" `shouldBe` Right (fromGregorian 2018 10 14) parseGerman 2018 10 18 "sun" `shouldBe` Right (fromGregorian 2018 10 14) it "literally satan" $ do parseGerman 2018 10 18 "satan" `shouldSatisfy` isLeft where parseGerman :: Integer -> Int -> Int -> String -> Either Text Day parseGerman y m d str = parseDate (fromGregorian y m d) german (T.pack str) printTests :: Spec printTests = describe "date printer" $ do it "is inverse to reading" $ property $ printReadProp german it "handles short years correctly" $ do withDateFormat ("%d-[%m-[%y]]") $ \format -> printDate format (fromGregorian 2015 2 1) `shouldBe` "01-02-15" withDateFormat ("%d-[%m-[%y]]") $ \format -> printDate format (fromGregorian 1999 2 1) `shouldBe` "01-02-1999" it "handles long years correctly" $ withDateFormat ("%d-[%m-[%Y]]") $ \format -> printDate format (fromGregorian 2015 2 1) `shouldBe` "01-02-2015" withDateFormat :: Text -> (DateFormat -> Expectation) -> Expectation withDateFormat date action = case parseDateFormat date of Left err -> expectationFailure (show err) Right format -> action format shouldFail :: Text -> Text -> Expectation shouldFail format date = withDateFormat format $ \format' -> do res <- parseDateWithToday format' date unless (isLeft res) $ expectationFailure ("Should fail but parses: " ++ (T.unpack format) ++ " / " ++ (T.unpack date) ++ " as " ++ show res) weekDayProp :: Property weekDayProp = forAll (ModifiedJulianDay <$> (arbitrary `suchThat` (>= 7))) $ \current -> forAll (choose (1, 7)) $ \wday -> wday === getWDay (weekDay wday current) where getWDay :: Day -> Int getWDay d = let (_, _, w) = toWeekDate d in w weekDaySmallerProp :: Property weekDaySmallerProp = forAll (ModifiedJulianDay <$> (arbitrary `suchThat` (>= 7))) $ \current -> forAll (choose (1, 7)) $ \wday -> current >= weekDay wday current printReadProp :: DateFormat -> Day -> Property printReadProp format day = case parseDate day format (printDate format day) of Left err -> counterexample (T.unpack err) False Right res -> res === day instance Arbitrary Day where arbitrary = ModifiedJulianDay <$> arbitrary
null
https://raw.githubusercontent.com/hpdeifel/hledger-iadd/782239929d411bce4714e65dd5c7bb97b2ba4e75/tests/DateParserSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# OPTIONS_GHC -fno - warn - orphans # module DateParserSpec (spec) where import Test.Hspec import Test.QuickCheck import Control.Monad import Data.Either import Data.Text (Text) import qualified Data.Text as T import Data.Time import Data.Time.Calendar.WeekDate import DateParser spec :: Spec spec = do dateFormatTests dateTests dateCompletionTests printTests dateFormatTests :: Spec dateFormatTests = describe "date format parser" $ it "parses the german format correctly" $ parseDateFormat "%d[.[%m[.[%y]]]]" `shouldBe` Right german dateTests :: Spec dateTests = describe "date parser" $ do it "actually requires non-optional fields" $ shouldFail "%d-%m-%y" "05" describe "weekDay" $ do it "actually returns the right week day" $ property weekDayProp it "is always smaller than the current date" $ property weekDaySmallerProp dateCompletionTests :: Spec dateCompletionTests = describe "date completion" $ do it "today" $ parseGerman 2004 7 31 "31.7.2004" `shouldBe` Right (fromGregorian 2004 7 31) it "today is a leap day" $ parseGerman 2012 2 29 "29.2.2012" `shouldBe` Right (fromGregorian 2012 2 29) it "skips to previous month" $ parseGerman 2016 9 20 "21" `shouldBe` Right (fromGregorian 2016 08 21) it "stays in month if possible" $ parseGerman 2016 8 30 "21" `shouldBe` Right (fromGregorian 2016 08 21) it "skips to previous month to reach the 31st" $ parseGerman 2016 8 30 "31" `shouldBe` Right (fromGregorian 2016 07 31) it "skips to an earlier month to reach the 31st" $ parseGerman 2016 7 30 "31" `shouldBe` Right (fromGregorian 2016 05 31) it "skips to the previous year if necessary" $ parseGerman 2016 9 30 "2.12." `shouldBe` Right (fromGregorian 2015 12 2) it "skips to the previous years if after a leap year" $ parseGerman 2017 3 10 "29.2" `shouldBe` Right (fromGregorian 2016 02 29) it "even might skip to a leap year 8 years ago" $ parseGerman 2104 2 27 "29.2" `shouldBe` Right (fromGregorian 2096 02 29) it "some date in the near future" $ parseGerman 2016 2 20 "30.11.2016" `shouldBe` Right (fromGregorian 2016 11 30) it "some date in the far future" $ parseGerman 2016 2 20 "30.11.3348" `shouldBe` Right (fromGregorian 3348 11 30) it "last october" $ (do monthOnly <- parseDateFormat "%m" parseDate (fromGregorian 2016 9 15) monthOnly "10" ) `shouldBe` Right (fromGregorian 2015 10 31) it "last november" $ (do monthOnly <- parseDateFormat "%m" parseDate (fromGregorian 2016 9 15) monthOnly "11" ) `shouldBe` Right (fromGregorian 2015 11 30) it "next november" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2016.11" ) `shouldBe` Right (fromGregorian 2016 11 1) it "next january" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2017.1" ) `shouldBe` Right (fromGregorian 2017 1 1) it "last january" $ (do yearMonth <- parseDateFormat "%y.%m" parseDate (fromGregorian 2016 9 15) yearMonth "2016.1" ) `shouldBe` Right (fromGregorian 2016 1 31) it "literally yesterday" $ do parseGerman 2018 10 18 "yesterday" `shouldBe` Right (fromGregorian 2018 10 17) parseGerman 2018 10 18 "yest" `shouldBe` Right (fromGregorian 2018 10 17) it "literally today" $ do parseGerman 2018 10 18 "today" `shouldBe` Right (fromGregorian 2018 10 18) it "literally tomorrow" $ do parseGerman 2018 10 18 "tomorrow" `shouldBe` Right (fromGregorian 2018 10 19) it "literally monday" $ do parseGerman 2018 10 18 "monday" `shouldBe` Right (fromGregorian 2018 10 15) parseGerman 2018 10 18 "mon" `shouldBe` Right (fromGregorian 2018 10 15) it "literally tuesday" $ do parseGerman 2018 10 18 "tuesday" `shouldBe` Right (fromGregorian 2018 10 16) parseGerman 2018 10 18 "tues" `shouldBe` Right (fromGregorian 2018 10 16) parseGerman 2018 10 18 "tue" `shouldBe` Right (fromGregorian 2018 10 16) it "literally wednesday" $ do parseGerman 2018 10 18 "wednesday" `shouldBe` Right (fromGregorian 2018 10 17) parseGerman 2018 10 18 "wed" `shouldBe` Right (fromGregorian 2018 10 17) it "literally thursday" $ do parseGerman 2018 10 18 "thursday" `shouldBe` Right (fromGregorian 2018 10 18) parseGerman 2018 10 18 "thur" `shouldBe` Right (fromGregorian 2018 10 18) it "literally friday" $ do parseGerman 2018 10 18 "friday" `shouldBe` Right (fromGregorian 2018 10 12) parseGerman 2018 10 18 "fri" `shouldBe` Right (fromGregorian 2018 10 12) it "literally saturday" $ do parseGerman 2018 10 18 "saturday" `shouldBe` Right (fromGregorian 2018 10 13) parseGerman 2018 10 18 "sat" `shouldBe` Right (fromGregorian 2018 10 13) it "literally sunday" $ do parseGerman 2018 10 18 "sunday" `shouldBe` Right (fromGregorian 2018 10 14) parseGerman 2018 10 18 "sun" `shouldBe` Right (fromGregorian 2018 10 14) it "literally satan" $ do parseGerman 2018 10 18 "satan" `shouldSatisfy` isLeft where parseGerman :: Integer -> Int -> Int -> String -> Either Text Day parseGerman y m d str = parseDate (fromGregorian y m d) german (T.pack str) printTests :: Spec printTests = describe "date printer" $ do it "is inverse to reading" $ property $ printReadProp german it "handles short years correctly" $ do withDateFormat ("%d-[%m-[%y]]") $ \format -> printDate format (fromGregorian 2015 2 1) `shouldBe` "01-02-15" withDateFormat ("%d-[%m-[%y]]") $ \format -> printDate format (fromGregorian 1999 2 1) `shouldBe` "01-02-1999" it "handles long years correctly" $ withDateFormat ("%d-[%m-[%Y]]") $ \format -> printDate format (fromGregorian 2015 2 1) `shouldBe` "01-02-2015" withDateFormat :: Text -> (DateFormat -> Expectation) -> Expectation withDateFormat date action = case parseDateFormat date of Left err -> expectationFailure (show err) Right format -> action format shouldFail :: Text -> Text -> Expectation shouldFail format date = withDateFormat format $ \format' -> do res <- parseDateWithToday format' date unless (isLeft res) $ expectationFailure ("Should fail but parses: " ++ (T.unpack format) ++ " / " ++ (T.unpack date) ++ " as " ++ show res) weekDayProp :: Property weekDayProp = forAll (ModifiedJulianDay <$> (arbitrary `suchThat` (>= 7))) $ \current -> forAll (choose (1, 7)) $ \wday -> wday === getWDay (weekDay wday current) where getWDay :: Day -> Int getWDay d = let (_, _, w) = toWeekDate d in w weekDaySmallerProp :: Property weekDaySmallerProp = forAll (ModifiedJulianDay <$> (arbitrary `suchThat` (>= 7))) $ \current -> forAll (choose (1, 7)) $ \wday -> current >= weekDay wday current printReadProp :: DateFormat -> Day -> Property printReadProp format day = case parseDate day format (printDate format day) of Left err -> counterexample (T.unpack err) False Right res -> res === day instance Arbitrary Day where arbitrary = ModifiedJulianDay <$> arbitrary
f571fcd967d68de623011304ecfa7b1f2e65bf57b32a4851e842028072cb34fb
TrustInSoft/tis-kernel
ival.ml
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Abstract_interp module F_Set = Set.Make(Fval.F) (* Uses F's total compare function *) (* Make sure all this is synchronized with the default value of -ilevel *) let small_cardinal = ref 8 let small_cardinal_Int = ref (Int.of_int !small_cardinal) let small_cardinal_log = ref 3 let debug_cardinal = false let set_small_cardinal i = assert (2 <= i && i <= 1024); let rec log j p = if i <= p then j else log (j+1) (2*p) in small_cardinal := i; small_cardinal_Int := Int.of_int i; small_cardinal_log := log 1 2 let get_small_cardinal () = !small_cardinal let emitter = Lattice_messages.register "Ival";; let log_imprecision s = Lattice_messages.emit_imprecision emitter s ;; module Widen_Arithmetic_Value_Set = struct include Datatype.Integer.Set let pretty fmt s = if is_empty s then Format.fprintf fmt "{}" else Pretty_utils.pp_iter ~pre:"@[<hov 1>{" ~suf:"}@]" ~sep:";@ " iter Int.pretty fmt s let of_list l = match l with | [] -> empty | [e] -> singleton e | e :: q -> List.fold_left (fun acc x -> add x acc) (singleton e) q let default_widen_hints = of_list (List.map Int.of_int [-1;0;1]) end exception Infinity let opt2 f m1 m2 = match m1, m2 with None, _ | _, None -> raise Infinity | Some m1, Some m2 -> f m1 m2 let opt1 f m = match m with None -> None | Some m -> Some (f m) exception Error_Top exception Error_Bottom module O = FCSet.Make(Integer) type pre_set = Pre_set of O.t * int | Pre_top of Int.t * Int.t * Int.t type t = | Set of Int.t array | Float of Fval.t | Top of Int.t option * Int.t option * Int.t * Int.t Binary abstract operations do not model precisely float / integer operations . It is the responsability of the callers to have two operands of the same implicit type . The only exception is for [ singleton_zero ] , which is the correct representation of [ 0 . ] It is the responsability of the callers to have two operands of the same implicit type. The only exception is for [singleton_zero], which is the correct representation of [0.] *) module Widen_Hints = Widen_Arithmetic_Value_Set type size_widen_hint = Integer.t type generic_widen_hint = Widen_Hints.t type widen_hint = size_widen_hint * generic_widen_hint let some_zero = Some Int.zero let bottom = Set (Array.make 0 Int.zero) let top = Top(None, None, Int.zero, Int.one) let hash_v_option v = match v with None -> 97 | Some v -> Int.hash v let hash v = match v with Set s -> Array.fold_left (fun acc v -> 1031 * acc + (Int.hash v)) 17 s | Top(mn,mx,r,m) -> hash_v_option mn + 5501 * (hash_v_option mx) + 59 * (Int.hash r) + 13031 * (Int.hash m) | Float(f) -> 3 + 17 * Fval.hash f let bound_compare x y = match x,y with None, None -> 0 | None, Some _ -> 1 | Some _, None -> -1 | Some x, Some y -> Int.compare x y exception Unequal of int let compare e1 e2 = if e1==e2 then 0 else match e1,e2 with | Set e1,Set e2 -> let l1 = Array.length e1 in let l2 = Array.length e2 in if l1 <> l2 then l1 - l2 (* no overflow here *) else (try for i=0 to l1 -1 do let r = Int.compare e1.(i) e2.(i) in if r <> 0 then raise (Unequal r) done; 0 with Unequal v -> v ) | _, Set _ -> 1 | Set _, _ -> -1 | Top(mn,mx,r,m), Top(mn',mx',r',m') -> let r1 = bound_compare mn mn' in if r1 <> 0 then r1 else let r2 = bound_compare mx mx' in if r2 <> 0 then r2 else let r3 = Int.compare r r' in if r3 <> 0 then r3 else Int.compare m m' | _, Top _ -> 1 | Top _, _ -> -1 | Float(f1), Float(f2) -> Fval.compare f1 f2 | _ , Float _ - > 1 | Float _ , _ - > -1 | Float _, _ -> -1 *) let equal e1 e2 = compare e1 e2 = 0 let pretty fmt t = match t with | Top(mn,mx,r,m) -> let print_bound fmt = function None -> Format.fprintf fmt "--" | Some v -> Int.pretty fmt v in Format.fprintf fmt "[%a..%a]%t" print_bound mn print_bound mx (fun fmt -> if Int.is_zero r && Int.is_one m then Format.fprintf fmt "" else Format.fprintf fmt ",%a%%%a" Int.pretty r Int.pretty m) | Float (f) -> Fval.pretty fmt f | Set s -> if Array.length s = 0 then Format.fprintf fmt "BottomMod" else begin Pretty_utils.pp_iter ~pre:"@[<hov 1>{" ~suf:"}@]" ~sep:";@ " Array.iter Int.pretty fmt s end let min_le_elt min elt = match min with | None -> true | Some m -> Int.le m elt let max_ge_elt max elt = match max with | None -> true | Some m -> Int.ge m elt let all_positives min = match min with | None -> false | Some m -> Int.ge m Int.zero let all_negatives max = match max with | None -> false | Some m -> Int.le m Int.zero let fail min max r modu = let bound fmt = function | None -> Format.fprintf fmt "--" | Some(x) -> Int.pretty fmt x in Kernel.fatal "Ival: broken Top, min=%a max=%a r=%a modu=%a" bound min bound max Int.pretty r Int.pretty modu let is_safe_modulo r modu = (Int.ge r Int.zero ) && (Int.ge modu Int.one) && (Int.lt r modu) let check_modulo min max r modu = if not (is_safe_modulo r modu) then fail min max r modu let is_safe_bound bound r modu = match bound with | None -> true | Some m -> Int.equal (Int.pos_rem m modu) r (* Sanity check for Top's arguments *) let check min max r modu = if not (is_safe_modulo r modu && is_safe_bound min r modu && is_safe_bound max r modu) then fail min max r modu let cardinal_zero_or_one v = match v with | Top _ -> false | Set s -> Array.length s <= 1 | Float f -> Fval.is_singleton f let is_singleton_int v = match v with | Float _ | Top _ -> false | Set s -> Array.length s = 1 let is_bottom x = x == bottom let o_zero = O.singleton Int.zero let o_one = O.singleton Int.one let o_zero_or_one = O.union o_zero o_one let small_nums = Array.map (fun i -> Set [| i |]) Int.small_nums let zero = small_nums.(0) let one = small_nums.(1) let minus_one = Set [| Int.minus_one |] let zero_or_one = Set [| Int.zero ; Int.one |] let float_zeros = Float Fval.zeros let positive_integers = Top(Some Int.zero, None, Int.zero, Int.one) let negative_integers = Top(None, Some Int.zero, Int.zero, Int.one) let strictly_negative_integers = Top(None, Some Int.minus_one, Int.zero, Int.one) let is_zero x = x == zero let inject_singleton e = if Int.le Int.zero e && Int.le e Int.thirtytwo then small_nums.(Int.to_int e) else Set [| e |] let share_set o s = if s = 0 then bottom else if s = 1 then begin let e = O.min_elt o in inject_singleton e end else if O.equal o o_zero_or_one then zero_or_one else let a = Array.make s Int.zero in let i = ref 0 in O.iter (fun e -> a.(!i) <- e; incr i) o; assert (!i = s); Set a let share_array a s = if s = 0 then bottom else let e = a.(0) in if s = 1 && Int.le Int.zero e && Int.le e Int.thirtytwo then small_nums.(Int.to_int e) else if s = 2 && Int.is_zero e && Int.is_one a.(1) then zero_or_one else Set a let inject_float f = if Fval.is_zero f then zero else Float f let inject_float_interval flow fup = let flow = Fval.F.of_float flow in let fup = Fval.F.of_float fup in if Fval.F.equal Fval.F.zero flow && Fval.F.equal Fval.F.zero fup then zero else Float (Fval.inject flow fup) let subdiv_float_interval ~size v = match v with | Float f -> let f1, f2 = Fval.subdiv_float_interval ~size f in inject_float f1, inject_float f2 | Top _ | Set _ -> assert (is_zero v); raise Can_not_subdiv (* let minus_zero = Float (Fval.minus_zero, Fval.minus_zero) *) let is_one = equal one exception Nan_or_infinite let project_float v = if is_zero v then Fval.zero else match v with | Float f -> f | Top _ | Set _ -> raise Nan_or_infinite (* Also catches bottom. TODO *) let in_interval x min max r modu = Int.equal (Int.pos_rem x modu) r && min_le_elt min x && max_ge_elt max x let array_mem v a = let l = Array.length a in let rec c i = if i = l then (-1) else let ae = a.(i) in if Int.equal ae v then i else if Int.gt ae v then (-1) else c (succ i) in c 0 let contains_zero s = match s with | Top(mn,mx,r,m) -> in_interval Int.zero mn mx r m | Set s -> (array_mem Int.zero s)>=0 | Float f -> Fval.contains_zero f exception Not_Singleton_Int let project_int v = match v with | Set [| e |] -> e | _ -> raise Not_Singleton_Int let cardinal v = match v with | Top (None,_,_,_) | Top (_,None,_,_) -> None | Top (Some mn, Some mx,_,m) -> Some (Int.succ ((Int.native_div (Int.sub mx mn) m))) | Set s -> Some (Int.of_int (Array.length s)) | Float f -> if Fval.is_singleton f then Some Int.one else None let cardinal_estimate v size = match v with | Set s -> Int.of_int (Array.length s) | Top (mn,mx,_,d) -> (* Note: we clip the interval to get a finite cardinal. *) let mn = match mn with | None -> Integer.neg (Integer.two_power (Integer.pred size)) | Some(mn) -> mn in let mx = match mx with | None -> Integer.pred (Integer.two_power size) | Some(mx) -> mx in Int.(div (sub mx mn) d) | Float f -> if Fval.is_singleton f then Int.one TODO : Get exponent of min and , and multiply by two_power the size of mantissa . the size of mantissa. *) else Int.two_power size let cardinal_less_than v n = let c = match v with | Top (None,_,_,_) | Top (_,None,_,_) -> raise Not_less_than | Top (Some mn, Some mx,_,m) -> Int.succ ((Int.native_div (Int.sub mx mn) m)) | Set s -> Int.of_int (Array.length s) | Float f -> if Fval.is_singleton f then Int.one else raise Not_less_than in if Int.le c (Int.of_int n) then Int.to_int c (* This is smaller than the original [n] *) else raise Not_less_than let cardinal_is_less_than v n = match cardinal v with | None -> false | Some c -> Int.le c (Int.of_int n) let share_top min max r modu = let r = Top (min, max, r, modu) in if equal r top then top else r let make ~min ~max ~rem ~modu = match min, max with | Some mn, Some mx -> if Int.gt mx mn then let l = Int.succ (Int.div (Int.sub mx mn) modu) in if Int.le l !small_cardinal_Int then let l = Int.to_int l in let s = Array.make l Int.zero in let v = ref mn in let i = ref 0 in while (!i < l) do s.(!i) <- !v; v := Int.add modu !v; incr i done; assert (Int.equal !v (Int.add modu mx)); share_array s l else Top (min, max, rem, modu) else if Int.equal mx mn then inject_singleton mn else bottom | _ -> share_top min max rem modu let inject_top min max rem modu = check min max rem modu; make ~min ~max ~rem ~modu let inject_interval ~min ~max ~rem:r ~modu = check_modulo min max r modu; let min = Extlib.opt_map (fun min -> Int.round_up_to_r ~min ~r ~modu) min and max = Extlib.opt_map (fun max -> Int.round_down_to_r ~max ~r ~modu) max in make ~min ~max ~rem:r ~modu let subdiv_int v = match v with | Float _ -> raise Can_not_subdiv | Set arr -> let len = Array.length arr in assert (len > 0 ); if len <= 1 then raise Can_not_subdiv; let m = len lsr 1 in let lenhi = len - m in let lo = Array.sub arr 0 m in let hi = Array.sub arr m lenhi in share_array lo m, share_array hi lenhi | Top (Some lo, Some hi, r, modu) -> let mean = Int.native_div (Int.add lo hi) Abstract_interp.Int.two in let succmean = Abstract_interp.Int.succ mean in let hilo = Integer.round_down_to_r ~max:mean ~r ~modu in let lohi = Integer.round_up_to_r ~min:succmean ~r ~modu in inject_top (Some lo) (Some hilo) r modu, inject_top (Some lohi) (Some hi) r modu | Top _ -> raise Can_not_subdiv let inject_range min max = inject_top min max Int.zero Int.one let top_float = Float Fval.top let top_single_precision_float = Float Fval.top_single_precision_float let unsafe_make_top_from_set_4 s = if debug_cardinal then assert (O.cardinal s >= 2); let m = O.min_elt s in let modu = O.fold (fun x acc -> if Int.equal x m then acc else Int.pgcd (Int.sub x m) acc) s Int.zero in let r = Int.pos_rem m modu in let max = O.max_elt s in let min = m in (min,max,r,modu) let unsafe_make_top_from_array_4 s = let l = Array.length s in assert (l >= 2); let m = s.(0) in let modu = Array.fold_left (fun acc x -> if Int.equal x m then acc else Int.pgcd (Int.sub x m) acc) Int.zero s in let r = Int.pos_rem m modu in let max = Some s.(pred l) in let min = Some m in check min max r modu; (min,max,r,modu) let unsafe_make_top_from_array s = let min, max, r, modu = unsafe_make_top_from_array_4 s in share_top min max r modu let empty_ps = Pre_set (O.empty, 0) let add_ps ps x = match ps with | Pre_set(o,s) -> if debug_cardinal then assert (O.cardinal o = s); if (O.mem x o) (* TODO: improve *) then ps else let no = O.add x o in if s < !small_cardinal then begin if debug_cardinal then assert (O.cardinal no = succ s); Pre_set (no, succ s) end else let min, max, _r, modu = unsafe_make_top_from_set_4 no in Pre_top (min, max, modu) | Pre_top (min, max, modu) -> let new_modu = if Int.equal x min then modu else Int.pgcd (Int.sub x min) modu in let new_min = Int.min min x in let new_max = Int.max max x in Pre_top (new_min, new_max, new_modu) let inject_ps ps = match ps with Pre_set(o, s) -> share_set o s | Pre_top (min, max, modu) -> Top(Some min, Some max, Int.pos_rem min modu, modu) let min_max_r_mod t = match t with | Set s -> assert (Array.length s >= 2); unsafe_make_top_from_array_4 s | Top (a,b,c,d) -> a,b,c,d | Float _ -> None, None, Int.zero, Int.one let min_and_max t = match t with | Set s -> let l = Array.length s in assert (l >= 1); Some s.(0), Some s.(pred l) | Top (a,b,_,_) -> a, b | Float _ -> None, None let min_and_max_float t = match t with Set _ when is_zero t -> Fval.F.zero, Fval.F.zero | Float f -> Fval.min_and_max f | _ -> assert false let compare_min_int t1 t2 = let m1, _ = min_and_max t1 in let m2, _ = min_and_max t2 in match m1, m2 with None, None -> 0 | None, Some _ -> -1 | Some _, None -> 1 | Some m1, Some m2 -> Int.compare m1 m2 let compare_max_int t1 t2 = let _, m1 = min_and_max t1 in let _, m2 = min_and_max t2 in match m1, m2 with None, None -> 0 | None, Some _ -> -1 | Some _, None -> 1 | Some m1, Some m2 -> Int.compare m2 m1 let compare_min_float t1 t2 = let f1 = project_float t1 in let f2 = project_float t2 in Fval.compare_min f1 f2 let compare_max_float t1 t2 = let f1 = project_float t1 in let f2 = project_float t2 in Fval.compare_max f1 f2 let widen (bitsize,wh) t1 t2 = if equal t1 t2 || cardinal_zero_or_one t1 then t2 else match t2 with | Float f2 -> ( try let f1 = project_float t1 in if not (Fval.is_included f1 f2) then assert false; Float (Fval.widen f1 f2) with Nan_or_infinite (* raised by project_float *) -> assert false) | Top _ | Set _ -> (* Add possible interval limits deducted from the bitsize *) let wh = if Integer.is_zero bitsize then wh else let limits = [ Integer.neg (Integer.two_power (Integer.pred bitsize)); Integer.pred (Integer.two_power (Integer.pred bitsize)); Integer.pred (Integer.two_power bitsize); ] in let module ISet = Datatype.Integer.Set in ISet.union wh (ISet.of_list limits) in let (mn2,mx2,r2,m2) = min_max_r_mod t2 in let (mn1,mx1,r1,m1) = min_max_r_mod t1 in let new_mod = Int.pgcd (Int.pgcd m1 m2) (Int.abs (Int.sub r1 r2)) in let new_rem = Int.rem r1 new_mod in let new_min = if bound_compare mn1 mn2 = 0 then mn2 else match mn2 with | None -> None | Some mn2 -> try let v = Widen_Hints.nearest_elt_le mn2 wh in Some (Int.round_up_to_r ~r:new_rem ~modu:new_mod ~min:v) with Not_found -> None in let new_max = if bound_compare mx1 mx2 = 0 then mx2 else match mx2 with None -> None | Some mx2 -> try let v = Widen_Hints.nearest_elt_ge mx2 wh in Some (Int.round_down_to_r ~r:new_rem ~modu:new_mod ~max:v) with Not_found -> None in let result = inject_top new_min new_max new_rem new_mod in Format.printf " % a -- % a -- > % a ( thx to % a)@. " pretty t1 pretty t2 pretty result Widen_Hints.pretty wh ; pretty t1 pretty t2 pretty result Widen_Hints.pretty wh; *) result let compute_first_common mn1 mn2 r modu = if mn1 = None && mn2 = None then None else let m = match (mn1, mn2) with | Some m, None | None, Some m -> m | Some m1, Some m2 -> Int.max m1 m2 | None, None -> assert false (* already tested above *) in Some (Int.round_up_to_r ~min:m ~r ~modu) let compute_last_common mx1 mx2 r modu = if mx1 = None && mx2 = None then None else let m = match (mx1, mx2) with | Some m, None | None, Some m -> m | Some m1, Some m2 -> Int.min m1 m2 | None, None -> assert false (* already tested above *) in Some (Int.round_down_to_r ~max:m ~r ~modu) let min_min x y = match x,y with | None,_ | _,None -> None | Some x, Some y -> Some (Int.min x y) let max_max x y = match x,y with | None,_ | _,None -> None | Some x, Some y -> Some (Int.max x y) (* [extended_euclidian_algorithm a b] returns x,y,gcd such that a*x+b*y=gcd(x,y). *) let extended_euclidian_algorithm a b = assert (Int.gt a Int.zero); assert (Int.gt b Int.zero); let a = ref a and b = ref b in let x = ref Int.zero and lastx = ref Int.one in let y = ref Int.one and lasty = ref Int.zero in while not (Int.is_zero !b) do let (q,r) = Int.div_rem !a !b in a := !b; b := r; let tmpx = !x in (x:= Int.sub !lastx (Int.mul q !x); lastx := tmpx); let tmpy = !y in (y:= Int.sub !lasty (Int.mul q !y); lasty := tmpy); done; (!lastx,!lasty,!a) [ JS 2013/05/23 ] unused right now [ modular_inverse a m ] returns [ x ] such that a*x is congruent to 1 mod m. [modular_inverse a m] returns [x] such that a*x is congruent to 1 mod m. *) let _modular_inverse a m = let (x,_,gcd) = extended_euclidian_algorithm a m in assert (Int.equal Int.one gcd); x This function provides solutions to the chinese remainder theorem , i.e. it finds the solutions x such that : x = = r1 mod m1 & & x = = r2 mod m2 . If no such solution exists , it raises Error_Bottom ; else it returns ( r , m ) such that all solutions x are such that x = = r i.e. it finds the solutions x such that: x == r1 mod m1 && x == r2 mod m2. If no such solution exists, it raises Error_Bottom; else it returns (r,m) such that all solutions x are such that x == r mod m. *) let compute_r_common r1 m1 r2 m2 = ( E1 ) x = = r1 mod m1 & & x = = r2 mod m2 < = > \E k1,k2 : x = r1 + k1*m1 & & x = r2 + k2*m2 < = > \E k1,k2 : x = r1 + k1*m1 & & k1*m1 - k2*m2 = r2 - r1 Let c = r2 - r1 . The equation ( E2 ): k1*m1 - k2*m2 = c is diophantine ; there are solutions x to ( E1 ) iff there are solutions ( k1,k2 ) to ( E2 ) . Let d = pgcd(m1,m2 ) . There are solutions to ( E2 ) only if d divides c ( because d divides k1*m1 - k2*m2 ) . Else we raise [ Error_Bottom ] . <=> \E k1,k2: x = r1 + k1*m1 && x = r2 + k2*m2 <=> \E k1,k2: x = r1 + k1*m1 && k1*m1 - k2*m2 = r2 - r1 Let c = r2 - r1. The equation (E2): k1*m1 - k2*m2 = c is diophantine; there are solutions x to (E1) iff there are solutions (k1,k2) to (E2). Let d = pgcd(m1,m2). There are solutions to (E2) only if d divides c (because d divides k1*m1 - k2*m2). Else we raise [Error_Bottom]. *) let (x1,_,pgcd) = extended_euclidian_algorithm m1 m2 in let c = Int.sub r2 r1 in let (c_div_d,c_rem) = Int.div_rem c pgcd in if not (Int.equal c_rem Int.zero) then raise Error_Bottom The extended euclidian algorithm has provided solutions to the Bezout identity x1*m1 + x2*m2 = d. x1*m1 + x2*m2 = d = = > x1*(c / d)*m1 + x2*(c / d)*m2 = d*(c / d ) . Thus , k1 = x1*(c / d ) , k2=-x2*(c / d ) are solutions to ( E2 ) Thus , x = r1 + x1*(c / d)*m1 is a particular solution to ( E1 ) . the Bezout identity x1*m1 + x2*m2 = d. x1*m1 + x2*m2 = d ==> x1*(c/d)*m1 + x2*(c/d)*m2 = d*(c/d). Thus, k1 = x1*(c/d), k2=-x2*(c/d) are solutions to (E2) Thus, x = r1 + x1*(c/d)*m1 is a particular solution to (E1). *) else let k1 = Int.mul x1 c_div_d in let x = Int.add r1 (Int.mul k1 m1) in If two solutions x and y exist , they are equal modulo ppcm(m1,m2 ) . We have x = = r1 mod m1 & & y = = r1 mod m1 = = > \E k1 : x - y = k1*m1 x = = r2 mod m2 & & y = = r2 mod m2 = = > \E k2 : x - y = k2*m2 Thus k1*m1 = k2*m2 is a multiple of m1 and , i.e. is a multiple of ppcm(m1,m2 ) . Thus x = y mod ppcm(m1,m2 ) . We have x == r1 mod m1 && y == r1 mod m1 ==> \E k1: x - y = k1*m1 x == r2 mod m2 && y == r2 mod m2 ==> \E k2: x - y = k2*m2 Thus k1*m1 = k2*m2 is a multiple of m1 and m2, i.e. is a multiple of ppcm(m1,m2). Thus x = y mod ppcm(m1,m2). *) let ppcm = Int.divexact (Int.mul m1 m2) pgcd in x may be bigger than the ppcm , we normalize it . (Int.rem x ppcm, ppcm) ;; let array_truncate r i = if i = 0 then bottom else if i = 1 then inject_singleton r.(0) else begin (Obj.truncate (Obj.repr r) i); assert (Array.length r = i); Set r end let array_inter a1 a2 = let l1 = Array.length a1 in let l2 = Array.length a2 in let lr_max = min l1 l2 in let r = Array.make lr_max Int.zero in let rec c i i1 i2 = if i1 = l1 || i2 = l2 then array_truncate r i else let e1 = a1.(i1) in let e2 = a2.(i2) in if Int.equal e1 e2 then begin r.(i) <- e1; c (succ i) (succ i1) (succ i2) end else if Int.lt e1 e2 then c i (succ i1) i2 else c i i1 (succ i2) in c 0 0 0 Do the two arrays have an integer in common let arrays_intersect a1 a2 = let l1 = Array.length a1 in let l2 = Array.length a2 in let rec aux i1 i2 = if i1 = l1 || i2 = l2 then false else let e1 = a1.(i1) in let e2 = a2.(i2) in if Int.equal e1 e2 then true else if Int.lt e1 e2 then aux (succ i1) i2 else aux i1 (succ i2) in aux 0 0 let meet v1 v2 = if v1 == v2 then v1 else let result = match v1,v2 with | Top(min1,max1,r1,modu1), Top(min2,max2,r2,modu2) -> begin try let r,modu = compute_r_common r1 modu1 r2 modu2 in inject_top (compute_first_common min1 min2 r modu) (compute_last_common max1 max2 r modu) r modu with Error_Bottom -> " meet to bottom : % a /\\ % a@\n " pretty v1 pretty v2 ; pretty v1 pretty v2;*) bottom end | Set s1 , Set s2 -> array_inter s1 s2 | Set s, Top(min, max, rm, modu) | Top(min, max, rm, modu), Set s -> let l = Array.length s in let r = Array.make l Int.zero in let rec c i j = if i = l then array_truncate r j else let si = succ i in let x = s.(i) in if in_interval x min max rm modu then begin r.(j) <- x; c si (succ j) end else c si j in c 0 0 | Float(f1), Float(f2) -> begin match Fval.meet f1 f2 with | `Value f -> inject_float f | `Bottom -> bottom end | (Float f) as ff, other | other, ((Float f) as ff) -> if equal top other then ff else if (Fval.contains_zero f) && contains_zero other then zero else bottom in (* Format.printf "meet: %a /\\ %a -> %a@\n" pretty v1 pretty v2 pretty result;*) result let intersects v1 v2 = v1 == v2 || match v1, v2 with YYY : slightly inefficient | Set s1 , Set s2 -> arrays_intersect s1 s2 | Set s, Top (min, max, rm, modu) | Top (min, max, rm, modu), Set s -> Extlib.array_exists (fun x -> in_interval x min max rm modu) s | Float f1, Float f2 -> begin match Fval.forward_comp Comp.Eq f1 f2 with | Comp.False -> false | Comp.True | Comp.Unknown -> true end | Float f, other | other, Float f -> equal top other || (Fval.contains_zero f && contains_zero other) let narrow v1 v2 = match v1, v2 with | _, Set [||] | Set [||], _ -> bottom | Float _, Float _ | (Top _| Set _), (Top _ | Set _) -> meet v1 v2 (* meet is exact *) | v, (Top _ as t) when equal t top -> v | (Top _ as t), v when equal t top -> v | Float f, (Set _ as s) | (Set _ as s), Float f when is_zero s -> begin match Fval.meet f Fval.zero with | `Value f -> inject_float f | `Bottom -> bottom end | Float _, (Set _ | Top _) | (Set _ | Top _), Float _ -> (* ill-typed case. It is better to keep the operation symmetric *) top (* Given a set of elements that is an under-approximation, returns an ival (while maintaining the ival invariants that the "Set" constructor is used only for small sets of elements. *) let set_to_ival_under set = let card = Int.Set.cardinal set in if card <= !small_cardinal then (let a = Array.make card Int.zero in ignore(Int.Set.fold (fun elt i -> Array.set a i elt; i + 1) set 0); share_array a card) else (* If by chance the set is contiguous. *) if (Int.equal (Int.sub (Int.Set.max_elt set) (Int.Set.min_elt set)) (Int.of_int (card - 1))) then Top( Some(Int.Set.min_elt set), Some(Int.Set.max_elt set), Int.one, Int.zero) (* Else: arbitrarily drop some elements of the under approximation. *) else let a = Array.make !small_cardinal Int.zero in log_imprecision "Ival.set_to_ival_under"; try ignore(Int.Set.fold (fun elt i -> if i = !small_cardinal then raise Exit; Array.set a i elt; i + 1) set 0); assert false with Exit -> Set a ;; let link v1 v2 = match v1, v2 with | Set a1, Set a2 -> let s1 = Array.fold_right Int.Set.add a1 Int.Set.empty in let s2 = Array.fold_right Int.Set.add a2 s1 in set_to_ival_under s2 | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> if Int.equal r1 r2 && Int.equal m1 m2 then let min = match mn1,mn2 with | Some(a), Some(b) -> Some(Int.min a b) | _ -> None in let max = match mx1,mx2 with | Some(a), Some(b) -> Some(Int.max a b) | _ -> None in inject_top min max r1 m1 else v1 (* No best abstraction anyway. *) | Top(mn,mx,r,m), Set s | Set s, Top(mn,mx,r,m) -> let max = match mx with | None -> None | Some(max) -> let curmax = ref max in for i = 0 to (Array.length s) - 1 do let elt = s.(i) in if Int.equal elt (Int.add !curmax m) then curmax := elt done; Some(!curmax) in let min = match mn with | None -> None | Some(min) -> let curmin = ref min in for i = (Array.length s) - 1 downto 0 do let elt = s.(i) in if Int.equal elt (Int.sub !curmin m) then curmin := elt done; Some(!curmin) in inject_top min max r m | _ -> bottom ;; let join v1 v2 = let result = if v1 == v2 then v1 else match v1,v2 with | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> check mn1 mx1 r1 m1; check mn2 mx2 r2 m2; let modu = Int.pgcd (Int.pgcd m1 m2) (Int.abs(Int.sub r1 r2)) in let r = Int.rem r1 modu in let min = min_min mn1 mn2 in let max = max_max mx1 mx2 in let r = inject_top min max r modu in r | Set s, (Top(min, max, r, modu) as t) | (Top(min, max, r, modu) as t), Set s -> let l = Array.length s in if l = 0 then t else let f modu elt = Int.pgcd modu (Int.abs(Int.sub r elt)) in let new_modu = Array.fold_left f modu s in let new_r = Int.rem r new_modu in let new_min = match min with None -> None | Some m -> Some (Int.min m s.(0)) in let new_max = match max with None -> None | Some m -> Some (Int.max m s.(pred l)) in check new_min new_max new_r new_modu; share_top new_min new_max new_r new_modu | Set s1 , Set s2 -> let l1 = Array.length s1 in if l1 = 0 then v2 else let l2 = Array.length s2 in if l2 = 0 then v1 else second pass : make a set or make a top let second uniq = if uniq <= !small_cardinal then let r = Array.make uniq Int.zero in let rec c i i1 i2 = if i1 = l1 then begin Array.blit s2 i2 r i (l2 - i2); share_array r uniq end else if i2 = l2 then begin Array.blit s1 i1 r i (l1 - i1); share_array r uniq end else let si = succ i in let e1 = s1.(i1) in let e2 = s2.(i2) in if Int.lt e2 e1 then begin r.(i) <- e2; c si i1 (succ i2) end else begin r.(i) <- e1; let si1 = succ i1 in if Int.equal e1 e2 then begin c si si1 (succ i2) end else begin c si si1 i2 end end in c 0 0 0 else begin let m = Int.min s1.(0) s2.(0) in let accum acc x = if Int.equal x m then acc else Int.pgcd (Int.sub x m) acc in let modu = ref Int.zero in for j = 0 to pred l1 do modu := accum !modu s1.(j) done; for j = 0 to pred l2 do modu := accum !modu s2.(j) done; inject_ps (Pre_top (m, Int.max s1.(pred l1) s2.(pred l2), !modu)) end in first pass : count unique elements and detect inclusions let rec first i1 i2 uniq inc1 inc2 = let finished1 = i1 = l1 in if finished1 then begin if inc2 then v2 else second (uniq + l2 - i2) end else let finished2 = i2 = l2 in if finished2 then begin if inc1 then v1 else second (uniq + l1 - i1) end else let e1 = s1.(i1) in let e2 = s2.(i2) in if Int.lt e2 e1 then begin first i1 (succ i2) (succ uniq) false inc2 end else if Int.gt e2 e1 then begin first (succ i1) i2 (succ uniq) inc1 false end else first (succ i1) (succ i2) (succ uniq) inc1 inc2 in first 0 0 0 true true | Float(f1), Float(f2) -> inject_float (Fval.join f1 f2) | Float (f) as ff, other | other, (Float (f) as ff) -> if is_zero other then inject_float (Fval.join Fval.zero f) else if is_bottom other then ff else top in " % a % a - > % a@. " pretty v1 pretty v2 pretty result ; pretty v1 pretty v2 pretty result; *) result let fold_int f v acc = match v with Top(None,_,_,_) | Top(_,None,_,_) | Float _ -> raise Error_Top | Top(Some inf, Some sup, _, step) -> Int.fold f ~inf ~sup ~step acc | Set s -> Array.fold_left (fun acc x -> f x acc) acc s let fold_int_decrease f v acc = match v with Top(None,_,_,_) | Top(_,None,_,_) | Float _ -> raise Error_Top | Top(Some inf, Some sup, _, step) -> Int.fold f ~inf ~sup ~step:(Int.neg step) acc | Set s -> Array.fold_right (fun x acc -> f x acc) s acc let fold_enum f v acc = match v with | Float fl when Fval.is_singleton fl -> f v acc | Float _ -> raise Error_Top | Set _ | Top _ -> fold_int (fun x acc -> f (inject_singleton x) acc) v acc let fold_split ~split f v acc = match v with | Float (fl) when Fval.is_singleton fl -> f v acc | Float (fl) -> Fval.fold_split split (fun fl acc -> f (inject_float fl) acc) fl acc | Top(_,_,_,_) | Set _ -> fold_int (fun x acc -> f (inject_singleton x) acc) v acc (** [min_is_lower mn1 mn2] is true iff mn1 is a lower min than mn2 *) let min_is_lower mn1 mn2 = match mn1, mn2 with None, _ -> true | _, None -> false | Some m1, Some m2 -> Int.le m1 m2 * [ max_is_greater mx1 mx2 ] is true iff mx1 is a greater max than mx2 let max_is_greater mx1 mx2 = match mx1, mx2 with None, _ -> true | _, None -> false | Some m1, Some m2 -> Int.ge m1 m2 let rem_is_included r1 m1 r2 m2 = (Int.is_zero (Int.rem m1 m2)) && (Int.equal (Int.rem r1 m2) r2) let array_for_all f (a : Integer.t array) = let l = Array.length a in let rec c i = i = l || ((f a.(i)) && c (succ i)) in c 0 let array_subset a1 a2 = let l1 = Array.length a1 in let l2 = Array.length a2 in if l1 > l2 then false else let rec c i1 i2 = if i1 = l1 then true else if i2 = l2 then false else let e1 = a1.(i1) in let e2 = a2.(i2) in let si2 = succ i2 in if Int.equal e1 e2 then c (succ i1) si2 else if Int.lt e1 e2 then false else c i1 si2 (* TODO: improve by not reading a1.(i1) all the time *) in c 0 0 let is_included t1 t2 = (t1 == t2) || match t1,t2 with | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> (min_is_lower mn2 mn1) && (max_is_greater mx2 mx1) && rem_is_included r1 m1 r2 m2 | Top _, Set _ -> false (* Top _ represents more elements than can be represented by Set _ *) | Set [||], Top _ -> true | Set s, Top(min, max, r, modu) -> (* Inclusion of bounds is needed for the entire inclusion *) min_le_elt min s.(0) && max_ge_elt max s.(Array.length s-1) && (Int.equal Int.one modu || (*Top side contains all integers, we're done*) array_for_all (fun x -> Int.equal (Int.pos_rem x modu) r) s) | Set s1, Set s2 -> array_subset s1 s2 | Float(f1), Float(f2) -> Fval.is_included f1 f2 | Float _, _ -> equal t2 top | _, Float (f) -> is_zero t1 && (Fval.contains_zero f) let join_and_is_included a b = let ab = join a b in (ab, equal a b) let partially_overlaps ~size t1 t2 = match t1, t2 with Set s1, Set s2 -> not (array_for_all (fun e1 -> array_for_all (fun e2 -> Int.equal e1 e2 || Int.le e1 (Int.sub e2 size) || Int.ge e1 (Int.add e2 size)) s2) s1) | Set s, Top(mi, ma, r, modu) | Top(mi, ma, r, modu), Set s -> not (array_for_all (fun e -> let psize = Int.pred size in (not (min_le_elt mi (Int.add e psize))) || (not (max_ge_elt ma (Int.sub e psize))) || ( Int.ge modu size && let re = Int.pos_rem (Int.sub e r) modu in Int.is_zero re || (Int.ge re size && Int.le re (Int.sub modu size)) )) s) TODO let overlap ival size offset offset_size = let offset_itg = Integer.of_int offset in let offset_size_itg = Integer.of_int offset_size in let offset_max_bound = Integer.add offset_itg (Integer.sub offset_size_itg Integer.one) in let overlap_itv elt_min elt_max = let elt_max_bound = Integer.add elt_max (Integer.sub size Integer.one) in Integer.le elt_min offset_max_bound && Integer.le offset_itg elt_max_bound in match ival with | Set s -> Array.exists (fun elt -> overlap_itv elt elt) s | Top (min, max, rem, modulo) -> let psize = Integer.sub size Integer.one in let overlap = match min, max with | None, None -> true | Some min, None -> Integer.ge offset_max_bound min | None, Some max -> Integer.le offset_itg (Integer.add max psize) | Some min, Some max -> overlap_itv min max in let remain = Integer.pos_rem (Integer.sub offset_itg rem) modulo in overlap && (Integer.lt modulo offset_size_itg || Integer.is_zero remain || Int.lt remain offset_size_itg || Int.gt remain (Int.sub modulo offset_size_itg)) | _ -> assert false (* TODO: float ? *) let map_set_exnsafe_acc f acc (s : Integer.t array) = Array.fold_left (fun acc v -> add_ps acc (f v)) acc s let map_set_exnsafe f (s : Integer.t array) = inject_ps (map_set_exnsafe_acc f empty_ps s) let apply2_notzero f (s1 : Integer.t array) s2 = inject_ps (Array.fold_left (fun acc v1 -> Array.fold_left (fun acc v2 -> if Int.is_zero v2 then acc else add_ps acc (f v1 v2)) acc s2) empty_ps s1) let apply2_n f (s1 : Integer.t array) (s2 : Integer.t array) = let ps = ref empty_ps in let l1 = Array.length s1 in let l2 = Array.length s2 in for i1 = 0 to pred l1 do let e1 = s1.(i1) in for i2 = 0 to pred l2 do ps := add_ps !ps (f e1 s2.(i2)) done done; inject_ps !ps let apply2_v f s1 s2 = match s1, s2 with [| x1 |], [| x2 |] -> inject_singleton (f x1 x2) | _ -> apply2_n f s1 s2 let apply_set f v1 v2 = match v1,v2 with | Set s1, Set s2 -> apply2_n f s1 s2 | _ -> (*ignore (CilE.warn_once "unsupported case for binary operator '%s'" info);*) top let apply_set_unary _info f v = (* TODO: improve by allocating array*) match v with | Set s -> map_set_exnsafe f s | _ -> (*ignore (CilE.warn_once "unsupported case for unary operator '%s'" info);*) top let apply_bin_1_strict_incr f x (s : Integer.t array) = let l = Array.length s in let r = Array.make l Int.zero in let rec c i = if i = l then share_array r l else let v = f x s.(i) in r.(i) <- v; c (succ i) in c 0 let apply_bin_1_strict_decr f x (s : Integer.t array) = let l = Array.length s in let r = Array.make l Int.zero in let rec c i = if i = l then share_array r l else let v = f x s.(i) in r.(l - i - 1) <- v; c (succ i) in c 0 let map_set_strict_decr f (s : Integer.t array) = let l = Array.length s in let r = Array.make l Int.zero in let rec c i = if i = l then share_array r l else let v = f s.(i) in r.(l - i - 1) <- v; c (succ i) in c 0 let map_set_decr f (s : Integer.t array) = let l = Array.length s in if l = 0 then bottom else let r = Array.make l Int.zero in let rec c srcindex dstindex last = if srcindex < 0 then begin r.(dstindex) <- last; array_truncate r (succ dstindex) end else let v = f s.(srcindex) in if Int.equal v last then c (pred srcindex) dstindex last else begin r.(dstindex) <- last; c (pred srcindex) (succ dstindex) v end in c (l-2) 0 (f s.(pred l)) let map_set_incr f (s : Integer.t array) = let l = Array.length s in if l = 0 then bottom else let r = Array.make l Int.zero in let rec c srcindex dstindex last = if srcindex = l then begin r.(dstindex) <- last; array_truncate r (succ dstindex) end else let v = f s.(srcindex) in if Int.equal v last then c (succ srcindex) dstindex last else begin r.(dstindex) <- last; c (succ srcindex) (succ dstindex) v end in c 1 0 (f s.(0)) let add_singleton_int i v = match v with | Float _ -> assert false | Set s -> apply_bin_1_strict_incr Int.add i s | Top (mn, mx, r, m) -> let incr v = Int.add i v in let new_mn = opt1 incr mn in let new_mx = opt1 incr mx in let new_r = Int.pos_rem (incr r) m in share_top new_mn new_mx new_r m let rec add_int v1 v2 = match v1,v2 with | Float _, _ | _, Float _ -> assert false | Set [| x |], Set s | Set s, Set [| x |]-> apply_bin_1_strict_incr Int.add x s | Set s1, Set s2 -> apply2_n Int.add s1 s2 | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> let m = Int.pgcd m1 m2 in let r = Int.rem (Int.add r1 r2) m in let mn = try Some (Int.round_up_to_r ~min:(opt2 Int.add mn1 mn2) ~r ~modu:m) with Infinity -> None in let mx = try Some (Int.round_down_to_r ~max:(opt2 Int.add mx1 mx2) ~r ~modu:m) with Infinity -> None in inject_top mn mx r m | Set s, (Top _ as t) | (Top _ as t), Set s -> let l = Array.length s in if l = 0 then bottom else if l = 1 only one element add_singleton_int s.(0) t else add_int t (unsafe_make_top_from_array s) let add_int_under v1 v2 = match v1,v2 with | Float _, _ | _, Float _ -> assert false | Set [| x |], Set s | Set s, Set [| x |]-> apply_bin_1_strict_incr Int.add x s | Set s1, Set s2 -> let set = Array.fold_left (fun acc i1 -> Array.fold_left (fun acc i2 -> Int.Set.add (Int.add i1 i2) acc) acc s2) Int.Set.empty s1 in set_to_ival_under set | Top(min1,max1,r1,modu1) , Top(min2,max2,r2,modu2) when Int.equal modu1 modu2 -> Note : min1+min2 % modu = max1 + max2 % modu = r1 + r2 % modu ; no need to trim the bounds here . no need to trim the bounds here. *) let r = Int.rem (Int.add r1 r2) modu1 in let min = match min1, min2 with | Some min1, Some min2 -> Some (Int.add min1 min2) | _ -> None in let max = match max1, max2 with | Some max1, Some max2 -> Some (Int.add max1 max2) | _ -> None in inject_top min max r modu1 In many cases , there is no best abstraction ; for instance when divides modu2 , a part of the resulting interval is congruent to , and a larger part is congruent to modu2 . In general , one can take the intersection . In any case , this code should be rarely called . modu1 divides modu2, a part of the resulting interval is congruent to modu1, and a larger part is congruent to modu2. In general, one can take the intersection. In any case, this code should be rarely called. *) | Top _, Top _ -> bottom | Set s, (Top _ as t) | (Top _ as t), Set s -> let l = Array.length s in if l = 0 then bottom else if l = 1 only one element : precise . add_singleton_int s.(0) t else begin log_imprecision "Ival.add_int_under"; (* Not worse than another computation. *) add_singleton_int s.(0) t end ;; let neg_int v = match v with | Float _ -> assert false | Set s -> map_set_strict_decr Int.neg s | Top(mn,mx,r,m) -> share_top (opt1 Int.neg mx) (opt1 Int.neg mn) (Int.pos_rem (Int.neg r) m) m let sub_int v1 v2 = add_int v1 (neg_int v2) let sub_int_under v1 v2 = add_int_under v1 (neg_int v2) type ext_value = Ninf | Pinf | Val of Int.t let inject_min = function None -> Ninf | Some m -> Val m let inject_max = function None -> Pinf | Some m -> Val m let ext_neg = function Ninf -> Pinf | Pinf -> Ninf | Val v -> Val (Int.neg v) let ext_mul x y = match x, y with | Ninf, Ninf | Pinf, Pinf -> Pinf | Ninf, Pinf | Pinf, Ninf -> Ninf | Val v1, Val v2 -> Val (Int.mul v1 v2) | x, Val v when (Int.gt v Int.zero) -> x | Val v, x when (Int.gt v Int.zero) -> x | x, Val v when (Int.lt v Int.zero) -> ext_neg x | Val v, x when (Int.lt v Int.zero) -> ext_neg x | _ -> Val Int.zero let ext_min x y = match x,y with Ninf, _ | _, Ninf -> Ninf | Pinf, x | x, Pinf -> x | Val x, Val y -> Val(Int.min x y) let ext_max x y = match x,y with Pinf, _ | _, Pinf -> Pinf | Ninf, x | x, Ninf -> x | Val x, Val y -> Val(Int.max x y) let ext_proj = function Val x -> Some x | _ -> None let min_int s = match s with | Top (min,_,_,_) -> min | Set s -> if Array.length s = 0 then raise Error_Bottom else Some s.(0) | Float _ -> None let max_int s = match s with | Top (_,max,_,_) -> max | Set s -> let l = Array.length s in if l = 0 then raise Error_Bottom else Some s.(pred l) | Float _ -> None exception No_such_element let smallest_above min x = (* TODO: improve for Set *) match x with | Set s -> let r = ref None in Array.iter (fun e -> if Int.ge e min then match !r with | Some rr when Int.lt e rr -> r := Some e | None -> r := Some e | _ -> ()) s; begin match !r with None -> raise No_such_element | Some r -> r end | Top(mn,mx,r,modu) -> let some_min = Some min in if not (max_is_greater mx some_min) then raise No_such_element; if min_is_lower some_min mn then Extlib.the mn else Int.round_up_to_r ~min ~r ~modu | Float _ -> raise No_such_element let largest_below max x = (* TODO: improve for Set *) match x with | Float _ -> raise No_such_element | Set s -> let r = ref None in Array.iter (fun e -> if Int.le e max then match !r with | Some rr when Int.gt e rr -> r := Some e | None -> r := Some e | _ -> ()) s; begin match !r with None -> raise No_such_element | Some r -> r end | Top(mn,mx,r,modu) -> let some_max = Some max in if not (min_is_lower mn some_max) then raise No_such_element; if max_is_greater some_max mx then Extlib.the mx else Int.round_down_to_r ~max ~r ~modu Rounds up ( x+1 ) to the next power of two , then substracts one ; optimized . let next_pred_power_of_two x = Unroll the first iterations , and skip the tests . let x = Int.logor x (Int.shift_right x Int.one) in let x = Int.logor x (Int.shift_right x Int.two) in let x = Int.logor x (Int.shift_right x Int.four) in let x = Int.logor x (Int.shift_right x Int.eight) in let x = Int.logor x (Int.shift_right x Int.sixteen) in let shift = Int.thirtytwo in let rec loop old shift = let x = Int.logor old (Int.shift_right old shift) in if Int.equal old x then x else loop x (Int.shift_left shift Int.one) in loop x shift (* [different_bits min max] returns an overapproximation of the mask of the bits that can be different for different numbers in the interval [min]..[max] *) let different_bits min max = let x = Int.logxor min max in next_pred_power_of_two x [ pos_max_land min1 max1 min2 max2 ] computes an upper bound for [ x1 land x2 ] where [ x1 ] is in [ min1] .. [max1 ] and [ x2 ] is in [ min2] .. [max2 ] . Precondition : [ min1 ] , [ max1 ] , [ min2 ] , [ max2 ] must all have the same sign . Note : the algorithm below is optimal for the problem as stated . It is possible to compute this optimal solution faster but it does not seem worth the time necessary to think about it as long as integers are at most 64 - bit . [x1 land x2] where [x1] is in [min1]..[max1] and [x2] is in [min2]..[max2]. Precondition : [min1], [max1], [min2], [max2] must all have the same sign. Note: the algorithm below is optimal for the problem as stated. It is possible to compute this optimal solution faster but it does not seem worth the time necessary to think about it as long as integers are at most 64-bit. *) let pos_max_land min1 max1 min2 max2 = let x1 = different_bits min1 max1 in let x2 = different_bits min2 max2 in (* Format.printf "pos_max_land %a %a -> %a | %a %a -> %a@." Int.pretty min1 Int.pretty max1 Int.pretty x1 Int.pretty min2 Int.pretty max2 Int.pretty x2; *) let fold_maxs max1 p f acc = let rec aux p acc = let p = Int.shift_right p Int.one in if Int.is_zero p then f max1 acc else if Int.is_zero (Int.logand p max1) then aux p acc else let c = Int.logor (Int.sub max1 p) (Int.pred p) in aux p (f c acc) in aux p acc in let sx1 = Int.succ x1 in let n1 = fold_maxs max1 sx1 (fun _ y -> succ y) 0 in let maxs1 = Array.make n1 sx1 in let _ = fold_maxs max1 sx1 (fun x i -> Array.set maxs1 i x; succ i) 0 in fold_maxs max2 (Int.succ x2) (fun max2 acc -> Array.fold_left (fun acc max1 -> Int.max (Int.logand max1 max2) acc) acc maxs1) (Int.logand max1 max2) let bitwise_or v1 v2 = if is_bottom v1 || is_bottom v2 then bottom else match v1, v2 with | Float _, _ | _, Float _ -> top | Set s1, Set s2 -> apply2_v Int.logor s1 s2 | Set [|s|],(Top _ as v) | (Top _ as v),Set [|s|] when Int.is_zero s -> v | Top _, _ | _, Top _ -> ( match min_and_max v1 with Some mn1, Some mx1 when Int.ge mn1 Int.zero -> ( match min_and_max v2 with Some mn2, Some mx2 when Int.ge mn2 Int.zero -> let new_max = next_pred_power_of_two (Int.logor mx1 mx2) in let new_min = Int.max mn1 mn2 in (* Or can only add bits *) inject_range (Some new_min) (Some new_max) | _ -> top ) | _ -> top ) let bitwise_xor v1 v2 = if is_bottom v1 || is_bottom v2 then bottom else match v1, v2 with | Float _, _ | _, Float _ -> top | Set s1, Set s2 -> apply2_v Int.logxor s1 s2 | Top _, _ | _, Top _ -> (match min_and_max v1 with | Some mn1, Some mx1 when Int.ge mn1 Int.zero -> (match min_and_max v2 with | Some mn2, Some mx2 when Int.ge mn2 Int.zero -> let new_max = next_pred_power_of_two (Int.logor mx1 mx2) in let new_min = Int.zero in inject_range (Some new_min) (Some new_max) | _ -> top ) | _ -> top ) let contains_non_zero v = not (is_zero v || is_bottom v) TODO : rename this function to let scale f v = if Int.is_zero f then zero else match v with | Float _ -> top | Top(mn1,mx1,r1,m1) -> let incr = Int.mul f in if Int.gt f Int.zero then let modu = incr m1 in share_top (opt1 incr mn1) (opt1 incr mx1) (Int.pos_rem (incr r1) modu) modu else let modu = Int.neg (incr m1) in share_top (opt1 incr mx1) (opt1 incr mn1) (Int.pos_rem (incr r1) modu) modu | Set s -> if Int.ge f Int.zero then apply_bin_1_strict_incr Int.mul f s else apply_bin_1_strict_decr Int.mul f s let scale_div_common ~pos f v degenerate_ival degenerate_float = assert (not (Int.is_zero f)); let div_f = if pos then fun a -> Int.pos_div a f else fun a -> Int.c_div a f in match v with | Top(mn1,mx1,r1,m1) -> let r, modu = let negative = max_is_greater (some_zero) mx1 in if (negative (* all negative *) || pos (* good div *) || (min_is_lower (some_zero) mn1) (* all positive *) || (Int.is_zero (Int.rem r1 f)) (* exact *) ) && (Int.is_zero (Int.rem m1 f)) then let modu = Int.abs (div_f m1) in let r = if negative then Int.sub r1 m1 else r1 in (Int.pos_rem (div_f r) modu), modu else (* degeneration*) degenerate_ival r1 m1 in let divf_mn1 = opt1 div_f mn1 in let divf_mx1 = opt1 div_f mx1 in let mn, mx = if Int.gt f Int.zero then divf_mn1, divf_mx1 else divf_mx1, divf_mn1 in inject_top mn mx r modu | Set s -> if Int.lt f Int.zero then map_set_decr div_f s else map_set_incr div_f s | Float _ -> degenerate_float let scale_div ~pos f v = scale_div_common ~pos f v (fun _ _ -> Int.zero, Int.one) top ;; let scale_div_under ~pos f v = try TODO : a more precise result could be obtained by transforming Top(min , , r , m ) into Top(min , , r / f , m / gcd(m , f ) ) . But this is more complex to implement when pos or f is negative . Top(min,max,r,m) into Top(min,max,r/f,m/gcd(m,f)). But this is more complex to implement when pos or f is negative. *) scale_div_common ~pos f v (fun _r _m -> raise Exit) bottom with Exit -> bottom ;; let div_set x sy = Array.fold_left (fun acc elt -> if Int.is_zero elt then acc else join acc (scale_div ~pos:false elt x)) bottom sy ymin and ymax must be the same sign let div_range x ymn ymx = match min_and_max x with | Some xmn, Some xmx -> let c1 = Int.c_div xmn ymn in let c2 = Int.c_div xmx ymn in let c3 = Int.c_div xmn ymx in let c4 = Int.c_div xmx ymx in let min = Int.min (Int.min c1 c2) (Int.min c3 c4) in let max = Int.max (Int.max c1 c2) (Int.max c3 c4) in Format.printf " div : % a % a % a % a@. " Int.pretty mn Int.pretty mx Int.pretty xmn Int.pretty xmx ; Int.pretty mn Int.pretty mx Int.pretty xmn Int.pretty xmx; *) inject_range (Some min) (Some max) | _ -> log_imprecision "Ival.div_range"; top let div x y = if ( intersects y negative || intersects x negative ) then ignore ( CilE.warn_once " using ' round towards zero ' semantics for ' / ' , which only became specified in C99 . " ) ; (CilE.warn_once "using 'round towards zero' semantics for '/', which only became specified in C99."); *) match y with Set sy -> div_set x sy | Top (Some mn,Some mx, r, modu) -> let result_pos = if Int.gt mx Int.zero then let lpos = if Int.gt mn Int.zero then mn else Int.round_up_to_r ~min:Int.one ~r ~modu in div_range x lpos mx else bottom in let result_neg = if Int.lt mn Int.zero then let gneg = if Int.lt mx Int.zero then mx else Int.round_down_to_r ~max:Int.minus_one ~r ~modu in div_range x mn gneg else bottom in join result_neg result_pos | Float _ -> assert false | Top (None, _, _, _) | Top (_, None, _, _) -> log_imprecision "Ival.div"; top (* [scale_rem ~pos:false f v] is an over-approximation of the set of elements [x mod f] for [x] in [v]. [scale_rem ~pos:true f v] is an over-approximation of the set of elements [x pos_rem f] for [x] in [v]. *) let scale_rem ~pos f v = (* Format.printf "scale_rem %b %a %a@." pos Int.pretty f pretty v; *) if Int.is_zero f then bottom else let f = if Int.lt f Int.zero then Int.neg f else f in let rem_f a = if pos then Int.pos_rem a f else Int.c_rem a f in match v with | Top(mn,mx,r,m) -> let modu = Int.pgcd f m in let rr = Int.pos_rem r modu in let binf,bsup = if pos then (Int.round_up_to_r ~min:Int.zero ~r:rr ~modu), (Int.round_down_to_r ~max:(Int.pred f) ~r:rr ~modu) else let min = if all_positives mn then Int.zero else Int.neg (Int.pred f) in let max = if all_negatives mx then Int.zero else Int.pred f in (Int.round_up_to_r ~min ~r:rr ~modu, Int.round_down_to_r ~max ~r:rr ~modu) in let mn_rem,mx_rem = match mn,mx with | Some mn,Some mx -> let div_f a = if pos then Int.pos_div a f else Int.c_div a f in (* See if [mn..mx] is included in [k*f..(k+1)*f] for some [k]. In this case, [%] is monotonic and [mn%f .. mx%f] is a more precise result. *) if Int.equal (div_f mn) (div_f mx) then rem_f mn, rem_f mx else binf,bsup | _ -> binf,bsup in inject_top (Some mn_rem) (Some mx_rem) rr modu | Set s -> map_set_exnsafe rem_f s | Float _ -> top let c_rem x y = match y with | Top (None, _, _, _) | Top (_, None, _, _) | Float _ -> top | Top (Some mn, Some mx, _, _) -> if Int.equal mx Int.zero then bottom (* completely undefined. *) else Result is of the sign of x. Also , compute |x| to bound the result let neg, pos, max_x = match x with | Float _ -> true, true, None | Set set -> let s = Array.length set in if s = 0 then (* Bottom *) false, false, None else Int.le set.(0) Int.minus_one, Int.ge set.(s-1) Int.one, Some (Int.max (Int.abs set.(0)) (Int.abs set.(s-1))) | Top (mn, mx, _, _) -> min_le_elt mn Int.minus_one, max_ge_elt mx Int.one, (match mn, mx with | Some mn, Some mx -> Some (Int.max (Int.abs mn) (Int.abs mx)) | _ -> None) in Bound the result : no more than |x| , and no more than |y|-1 let pos_rem = Integer.max (Int.abs mn) (Int.abs mx) in let bound = Int.pred pos_rem in let bound = Extlib.may_map (Int.min bound) ~dft:bound max_x in (* Compute result bounds using sign information *) let mn = if neg then Some (Int.neg bound) else Some Int.zero in let mx = if pos then Some bound else Some Int.zero in inject_top mn mx Int.zero Int.one | Set yy -> ( match x with Set xx -> apply2_notzero Int.c_rem xx yy | Float _ -> top | Top _ -> let f acc y = join (scale_rem ~pos:false y x) acc in Array.fold_left f bottom yy) module AllValueHashtbl = Hashtbl.Make (struct type t = Int.t * bool * int let equal (a,b,c:t) (d,e,f:t) = b=e && c=f && Int.equal a d let hash (a,b,c:t) = 257 * (Hashtbl.hash b) + 17 * (Hashtbl.hash c) + Int.hash a end) let all_values_table = AllValueHashtbl.create 7 let create_all_values_modu ~modu ~signed ~size = let t = modu, signed, size in try AllValueHashtbl.find all_values_table t with Not_found -> let mn, mx = if signed then let b = Int.two_power_of_int (size-1) in (Int.round_up_to_r ~min:(Int.neg b) ~modu ~r:Int.zero, Int.round_down_to_r ~max:(Int.pred b) ~modu ~r:Int.zero) else let b = Int.two_power_of_int size in Int.zero, Int.round_down_to_r ~max:(Int.pred b) ~modu ~r:Int.zero in let r = inject_top (Some mn) (Some mx) Int.zero modu in AllValueHashtbl.add all_values_table t r; r let create_all_values ~signed ~size = if size <= !small_cardinal_log then (* We may need to create a set. Use slow path *) create_all_values_modu ~signed ~size ~modu:Int.one else if signed then let b = Int.two_power_of_int (size-1) in Top (Some (Int.neg b), Some (Int.pred b), Int.zero, Int.one) else let b = Int.two_power_of_int size in Top (Some Int.zero, Some (Int.pred b), Int.zero, Int.one) let big_int_64 = Int.of_int 64 let big_int_32 = Int.thirtytwo let cast ~size ~signed ~value = if equal top value then create_all_values ~size:(Int.to_int size) ~signed else let result = let factor = Int.two_power size in let mask = Int.two_power (Int.pred size) in let rem_f value = Int.cast ~size ~signed ~value in let not_p_factor = Int.neg factor in let best_effort r m = let modu = Int.pgcd factor m in let rr = Int.pos_rem r modu in let min_val = Some (if signed then Int.round_up_to_r ~min:(Int.neg mask) ~r:rr ~modu else Int.round_up_to_r ~min:Int.zero ~r:rr ~modu) in let max_val = Some (if signed then Int.round_down_to_r ~max:(Int.pred mask) ~r:rr ~modu else Int.round_down_to_r ~max:(Int.pred factor) ~r:rr ~modu) in inject_top min_val max_val rr modu in match value with | Top(Some mn,Some mx,r,m) -> let highbits_mn,highbits_mx = if signed then Int.logand (Int.add mn mask) not_p_factor, Int.logand (Int.add mx mask) not_p_factor else Int.logand mn not_p_factor, Int.logand mx not_p_factor in if Int.equal highbits_mn highbits_mx then if Int.is_zero highbits_mn then value else let new_min = rem_f mn in let new_r = Int.pos_rem new_min m in inject_top (Some new_min) (Some (rem_f mx)) new_r m else best_effort r m | Top (_,_,r,m) -> best_effort r m | Set s -> begin let all = create_all_values ~size:(Int.to_int size) ~signed in if is_included value all then value else map_set_exnsafe rem_f s end | Float f -> let low, high = if Int.equal size big_int_64 then let l, h = Fval.bits_of_float64 ~signed f in Some l, Some h else if Int.equal size big_int_32 then let l, h = Fval.bits_of_float32 ~signed f in Some l, Some h else None, None in inject_range low high in " Cast with size:%d signed:%b to % a@\n " size signed pretty result ; size signed pretty result; *) if equal result value then value else result let cast_float ~rounding_mode v = match v with | Float f -> ( try let b, f = Fval.round_to_single_precision_float ~rounding_mode f in b, inject_float f with Fval.Non_finite -> true, bottom) | Set _ when is_zero v -> false, zero | Set _ | Top _ -> true, top_single_precision_float let cast_double v = match v with | Float _ -> false, v | Set _ when is_zero v -> false, v | Set _ | Top _ -> true, top_float TODO rename to mul_int let rec mul v1 v2 = " . : ' % a ' ' % a'@\n " pretty v1 pretty v2 ; let result = if is_one v1 then v2 else if is_zero v2 || is_zero v1 then zero else if is_one v2 then v1 else match v1,v2 with | Float _, _ | _, Float _ -> top | Set s1, Set [| x |] | Set [| x |], Set s1 -> if Int.ge x Int.zero then apply_bin_1_strict_incr Int.mul x s1 else apply_bin_1_strict_decr Int.mul x s1 | Set s1, Set s2 -> apply2_n Int.mul s1 s2 | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> check mn1 mx1 r1 m1; check mn2 mx2 r2 m2; let mn1 = inject_min mn1 in let mx1 = inject_max mx1 in let mn2 = inject_min mn2 in let mx2 = inject_max mx2 in let a = ext_mul mn1 mn2 in let b = ext_mul mn1 mx2 in let c = ext_mul mx1 mn2 in let d = ext_mul mx1 mx2 in let min = ext_min (ext_min a b) (ext_min c d) in let max = ext_max (ext_max a b) (ext_max c d) in let multipl1 = Int.pgcd m1 r1 in let = Int.pgcd m2 r2 in let = Int.pgcd in let modu2 = in let modu = Int.ppcm in let multipl2 = Int.pgcd m2 r2 in let modu1 = Int.pgcd m1 m2 in let modu2 = Int.mul multipl1 multipl2 in let modu = Int.ppcm modu1 modu2 in *) let modu = Int.pgcd (Int.pgcd (Int.mul m1 m2) (Int.mul r1 m2)) (Int.mul r2 m1) in let r = Int.rem (Int.mul r1 r2) modu in let t = Top ( ext_proj min , ext_proj max , r , modu ) in " . Result : ' % a'@\n " pretty t ; Format.printf "mul. Result: '%a'@\n" pretty t; *) inject_top (ext_proj min) (ext_proj max) r modu | Set s, (Top(_,_,_,_) as t) | (Top(_,_,_,_) as t), Set s -> let l = Array.length s in if l = 0 then bottom else if l = 1 only one element scale s.(0) t else mul t (unsafe_make_top_from_array s) in Format.printf " . result : % a@\n " pretty result ; result * Computes [ x ( op ) ( { y > = 0 } * 2^n ) ] , as an auxiliary function for [ shift_left ] and [ shift_right ] . [ op ] and [ scale ] must verify [ scale a b = = op ( inject_singleton a ) b ] [shift_left] and [shift_right]. [op] and [scale] must verify [scale a b == op (inject_singleton a) b] *) let shift_aux scale op (x: t) (y: t) = let y = narrow (inject_range (Some Int.zero) None) y in try match y with | Set s -> Array.fold_left (fun acc n -> join acc (scale (Int.two_power n) x)) bottom s | _ -> let min_factor = Extlib.opt_map Int.two_power (min_int y) in let max_factor = Extlib.opt_map Int.two_power (max_int y) in let modu = match min_factor with None -> Int.one | Some m -> m in let factor = inject_top min_factor max_factor Int.zero modu in op x factor with Integer.Too_big -> Lattice_messages.emit_imprecision emitter "Ival.shift_aux"; (* We only preserve the sign of the result *) if is_included x positive_integers then positive_integers else if is_included x negative_integers then negative_integers else top let shift_right x y = shift_aux (scale_div ~pos:true) div x y let shift_left x y = shift_aux scale mul x y let interp_boolean ~contains_zero ~contains_non_zero = match contains_zero, contains_non_zero with | true, true -> zero_or_one | true, false -> zero | false, true -> one | false, false -> bottom let backward_le_int max v = match v with | Float _ -> v | Set _ | Top _ -> narrow v (Top(None,max,Int.zero,Int.one)) let backward_ge_int min v = match v with | Float _ -> v | Set _ | Top _ -> narrow v (Top(min,None,Int.zero,Int.one)) let backward_lt_int max v = backward_le_int (opt1 Int.pred max) v let backward_gt_int min v = backward_ge_int (opt1 Int.succ min) v let diff_if_one value rem = match rem, value with | Set [| v |], Set a -> let index = array_mem v a in if index >= 0 then let l = Array.length a in let pl = pred l in let r = Array.make pl Int.zero in Array.blit a 0 r 0 index; Array.blit a (succ index) r index (pl-index); share_array r pl else value | Set [| v |], Top (Some mn, mx, r, m) when Int.equal v mn -> inject_top (Some (Int.add mn m)) mx r m | Set [| v |], Top (mn, Some mx, r, m) when Int.equal v mx -> inject_top mn (Some (Int.sub mx m)) r m | Set [| v |], Top ((Some mn as min), (Some mx as max), r, m) when Int.equal (Int.sub mx mn) (Int.mul m !small_cardinal_Int) && in_interval v min max r m -> let r = ref mn in Set (Array.init !small_cardinal (fun _ -> let c = !r in let corrected_c = if Int.equal c v then Int.add c m else c in r := Int.add corrected_c m; corrected_c)) | _ -> value (* TODO: more cases: Float *) let diff value rem = log_imprecision "Ival.diff"; diff_if_one value rem let backward_comp_int_left op l r = let open Comp in try match op with | Le -> backward_le_int (max_int r) l | Ge -> backward_ge_int (min_int r) l | Lt -> backward_lt_int (max_int r) l | Gt -> backward_gt_int (min_int r) l | Eq -> narrow l r | Ne -> diff_if_one l r with Error_Bottom (* raised by max_int *) -> bottom let backward_comp_float_left op allmodes fkind f1 f2 = try let f1 = project_float f1 in let f2 = project_float f2 in begin match Fval.backward_comp_left op allmodes fkind f1 f2 with | `Value f -> inject_float f | `Bottom -> bottom end with | Nan_or_infinite (* raised by project_float *) -> f1 let rec extract_bits ~start ~stop ~size v = match v with | Set s -> inject_ps (Array.fold_left (fun acc elt -> add_ps acc (Int.extract_bits ~start ~stop elt)) empty_ps s) | Float f -> let l, u = if Int.equal size big_int_64 then Fval.bits_of_float64 ~signed:true f else Fval.bits_of_float32 ~signed:true f in extract_bits ~start ~stop ~size (inject_range (Some l) (Some u)) | Top(_,_,_,_) as d -> try let dived = scale_div ~pos:true (Int.two_power start) d in scale_rem ~pos:true (Int.two_power (Int.length start stop)) dived with Integer.Too_big -> Lattice_messages.emit_imprecision emitter "Ival.extract_bits"; top ;; let all_values ~size v = if Int.lt big_int_64 size then false (* values of this size cannot be enumerated anyway in C. They may occur while initializing large blocks of arrays. *) else match v with | Float _ -> false | Top (None,_,_,modu) | Top (_,None,_,modu) -> Int.is_one modu | Top (Some mn, Some mx,_,modu) -> Int.is_one modu && Int.le (Int.two_power size) (Int.length mn mx) | Set s -> let siz = Int.to_int size in Array.length s >= 1 lsl siz && equal (cast ~size ~signed:false ~value:v) (create_all_values ~size:siz ~signed:false) let compare_min_max min max = match min, max with | None,_ -> -1 | _,None -> -1 | Some min, Some max -> Int.compare min max let compare_max_min max min = match max, min with | None,_ -> 1 | _,None -> 1 | Some max, Some min -> Int.compare max min let forward_le_int i1 i2 = if compare_max_min (max_int i1) (min_int i2) <= 0 then Comp.True else if compare_min_max (min_int i1) (max_int i2) > 0 then Comp.False else Comp.Unknown let forward_lt_int i1 i2 = if compare_max_min (max_int i1) (min_int i2) < 0 then Comp.True else if compare_min_max (min_int i1) (max_int i2) >= 0 then Comp.False else Comp.Unknown let forward_eq_int i1 i2 = if cardinal_zero_or_one i1 && equal i1 i2 then Comp.True else if intersects i2 i2 then Comp.Unknown else Comp.False let forward_comp_int op i1 i2 = let open Abstract_interp.Comp in match op with | Le -> forward_le_int i1 i2 | Ge -> forward_le_int i2 i1 | Lt -> forward_lt_int i1 i2 | Gt -> forward_lt_int i2 i1 | Eq -> forward_eq_int i1 i2 | Ne -> inv_result (forward_eq_int i1 i2) include ( Datatype.Make_with_collections (struct type ival = t type t = ival let name = Int.name ^ " lattice_mod" open Structural_descr let structural_descr = let s_int = Descr.str Int.descr in t_sum [| [| pack (t_array s_int) |]; [| Fval.packed_descr |]; [| pack (t_option s_int); pack (t_option s_int); Int.packed_descr; Int.packed_descr |] |] let reprs = [ top ; bottom ] let equal = equal let compare = compare let hash = hash let pretty = pretty let rehash x = match x with | Set a -> share_array a (Array.length a) | _ -> x let internal_pretty_code = Datatype.pp_fail let mem_project = Datatype.never_any_project let copy = Datatype.undefined let varname = Datatype.undefined end): Datatype.S_with_collections with type t := t) let scale_int_base factor v = match factor with | Int_Base.Top -> top | Int_Base.Value f -> scale f v type overflow_float_to_int = | FtI_Ok of Int.t (* Value in range *) | FtI_Overflow of Floating_point.sign (* Overflow in the corresponding direction *) let cast_float_to_int ~signed ~size iv = let all = create_all_values ~size ~signed in let min_all = Extlib.the (min_int all) in let max_all = Extlib.the (max_int all) in try let min, max = Fval.min_and_max (project_float iv) in let conv f = try truncate_to_integer returns an integer that fits in a 64 bits integer , but might not fit in [ size , sized ] integer, but might not fit in [size, sized] *) let i = Floating_point.truncate_to_integer f in if Int.ge i min_all then if Int.le i max_all then FtI_Ok i else FtI_Overflow Floating_point.Pos else FtI_Overflow Floating_point.Neg with Floating_point.Float_Non_representable_as_Int64 sign -> FtI_Overflow sign in let min_int = conv (Fval.F.to_float min) in let max_int = conv (Fval.F.to_float max) in match min_int, max_int with | FtI_Ok min_int, FtI_Ok max_int -> (* no overflow *) false, (false, false), inject_range (Some min_int) (Some max_int) one overflow false, (true, false), inject_range (Some min_all) (Some max_int) one overflow false, (false, true), inject_range (Some min_int) (Some max_all) two overflows | FtI_Overflow Floating_point.Neg, FtI_Overflow Floating_point.Pos -> false, (true, true), inject_range (Some min_all) (Some max_all) (* Completely out of range *) | FtI_Overflow Floating_point.Pos, FtI_Overflow Floating_point.Pos -> false, (false, true), bottom | FtI_Overflow Floating_point.Neg, FtI_Overflow Floating_point.Neg -> false, (true, false), bottom | FtI_Overflow Floating_point.Pos, FtI_Overflow Floating_point.Neg | FtI_Overflow Floating_point.Pos, FtI_Ok _ | FtI_Ok _, FtI_Overflow Floating_point.Neg -> assert false (* impossible if min-max are correct *) with | Nan_or_infinite -> (* raised by project_float *) true, (true, true), all These are the bounds of the range of integers that can be represented exactly as 64 bits double values exactly as 64 bits double values *) let double_min_exact_integer = Int.neg (Int.two_power_of_int 53) let double_max_exact_integer = Int.two_power_of_int 53 same with 32 bits single values let single_min_exact_integer = Int.neg (Int.two_power_of_int 24) let single_max_exact_integer = Int.two_power_of_int 24 (* Same values expressed as double *) let double_min_exact_integer_d = -. (2. ** 53.) let double_max_exact_integer_d = 2. ** 53. let single_min_exact_integer_d = -. (2. ** 24.) let single_max_exact_integer_d = 2. ** 24. (* finds all floating-point values [f] such that casting [f] to an integer type returns [i]. *) let cast_float_to_int_inverse ~single_precision i = let exact_min, exact_max = if single_precision then single_min_exact_integer, single_max_exact_integer else double_min_exact_integer, double_max_exact_integer in match min_and_max i with | Some min, Some max when Int.lt exact_min min && Int.lt max exact_max -> let minf = if Int.le min Int.zero then min is negative . We want to return [ ( float)((real)(min-1)+epsilon ) ] , as converting this number to int will truncate all the fractional part ( C99 6.3.1.4 ) . Given [ exact_min ] and [ exact_max ] , 1ulp is at most 1 here , so adding will at most cancel the -1 . Hence , we can use [ next_float ] . as converting this number to int will truncate all the fractional part (C99 6.3.1.4). Given [exact_min] and [exact_max], 1ulp is at most 1 here, so adding 1ulp will at most cancel the -1. Hence, we can use [next_float]. *) (* This float is finite because min is small enough *) let r = Fval.F.next_float (Int.to_float (Int.pred min)) in if single_precision then begin (* Single precision: round towards 0 (hence up) to minimize the range of the value returned. *) Floating_point.set_round_upward (); let r = Floating_point.round_to_single_precision_float r in Floating_point.set_round_nearest_even (); r; end else r else (* min is positive. Since casting truncates towards 0, [(int)((real)min-epsilon)] would return [min-1]. Hence, we can simply return the float corresponding to [min] -- which can be represented precisely given [exact_min] and [exact_max]. *) Int.to_float min in (* All operations are dual w.r.t. the min bound. *) let maxf = if Int.le Int.zero max then This float is finite because is big enough let r = Fval.F.prev_float (Int.to_float (Int.succ max)) in if single_precision then begin Floating_point.set_round_downward (); let r = Floating_point.round_to_single_precision_float r in Floating_point.set_round_nearest_even (); r; end else r else Int.to_float max in Float (Fval.inject (Fval.F.of_float minf) (Fval.F.of_float maxf)) | _ -> if single_precision then top_single_precision_float else top_float let cast_int_to_float_inverse ~single_precision f = (* We restrict ourselves to f \in [exact_min, exact_max]. Outside of this range, the conversion int -> float is not exact, and the operation is more involved. *) let exact_min, exact_max = if single_precision then single_min_exact_integer_d, single_max_exact_integer_d else double_min_exact_integer_d, double_max_exact_integer_d in (* We find the integer range included in [f] *) let min, max = min_and_max_float f in let min = Fval.F.to_float min in let max = Fval.F.to_float max in if exact_min <= min && max <= exact_max then (* Round to integers in the proper direction: discard the non-floating-point values on each extremity. *) let min = ceil min in let max = floor max in let conv f = try Some (Integer.of_float f) with Integer.Too_big -> None in let r = inject_range (conv min) (conv max) in Kernel.result " Cast : % a - > % a@. " pretty f pretty r ; r else top (* Approximate *) let of_int i = inject_singleton (Int.of_int i) let of_int64 i = inject_singleton (Int.of_int64 i) This function always succeeds without alarms for C integers , because they always fit within a float32 . always fit within a float32. *) let cast_int_to_float rounding_mode v = match min_and_max v with | None, _ | _, None -> false (* not ok *), top_float | Some min, Some max -> Floating_point.set_round_nearest_even (); (* PC: Do not even ask *) let b = Int.to_float min in let e = Int.to_float max in Note that conversion from integer to float in modes other than round - to - nearest is unavailable when using Big_int and Linux because 1- Big_int implements the conversion to float with a conversion from the integer to a decimal representation ( ! ) followed by strtod ( ) 2- Linux does not honor the FPU direction flag in strtod ( ) , as it arguably should round-to-nearest is unavailable when using Big_int and Linux because 1- Big_int implements the conversion to float with a conversion from the integer to a decimal representation (!) followed by strtod() 2- Linux does not honor the FPU direction flag in strtod(), as it arguably should *) let b', e' = if rounding_mode = Fval.Nearest_Even || (Int.le double_min_exact_integer min && Int.le max double_max_exact_integer) then b, e else Fval.F.prev_float b, Fval.F.next_float e in let ok, f = Fval.inject_r (Fval.F.of_float b') (Fval.F.of_float e') in not ok, inject_float f exception Unforceable let force_float kind i = match i with | Float _ -> false, i | Set _ when is_zero i -> false, i | Set _ when is_bottom i -> true, i | Top _ | Set _ -> Convert a range of integers to a range of floats . Float are ordered this way : if [ min_i ] , [ max_i ] are the bounds of the signed integer type that has the same number of bits as the floating point type , and [ min_f ] [ max_f ] are the integer representation of the most negative and most positive finite float of the type , and < is signed integer comparison , we have : min_i < min_f+1 < -1 < 0 < max_f < max_f+1 < max_i | | | | | | | | --finite-- -not finite- -finite- -not finite- | | |<--------- > | | |<--------- > -0 . -max + inf NaNs +0 . max + inf NaNs The float are of the same sign as the integer they convert into . Furthermore , the conversion function is increasing on the positive interval , and decreasing on the negative one . way : if [min_i], [max_i] are the bounds of the signed integer type that has the same number of bits as the floating point type, and [min_f] [max_f] are the integer representation of the most negative and most positive finite float of the type, and < is signed integer comparison, we have: min_i < min_f < min_f+1 < -1 < 0 < max_f < max_f+1 < max_i | | | | | | | | --finite-- -not finite- -finite- -not finite- | | |<---------> | | |<---------> -0. -max +inf NaNs +0. max +inf NaNs The float are of the same sign as the integer they convert into. Furthermore, the conversion function is increasing on the positive interval, and decreasing on the negative one. *) let reinterpret size conv min_f max_f = let i = cast ~size:(Integer.of_int size) ~signed:true ~value:i in match min_and_max i with | Some mn, Some mx -> let range mn mx = let red, fa = Fval.inject_r mn mx in assert (not red); inject_float fa in if Int.le Int.zero mn && Int.le mx max_f then range (conv mn) (conv mx) else if Int.le mx min_f then range (conv mx) (conv mn) else begin match i with | Set a -> let s = ref F_Set.empty in for i = 0 to Array.length a - 1 do if (Int.le Int.zero a.(i) && Int.le a.(i) max_f) || Int.le a.(i) min_f then s := F_Set.add (conv a.(i)) !s (* Not NaN *) else raise Unforceable done; (* cannot fail, [i] is not bottom, hence [a] is not empty *) let mn, mx = F_Set.min_elt !s, F_Set.max_elt !s in range mn mx | _ -> raise Unforceable end | _, _ -> raise Unforceable in let open Floating_point in match kind with | Cil_types.FDouble -> begin let conv v = Fval.F.of_float (Int64.float_of_bits (Int.to_int64 v)) in try false, reinterpret 64 conv bits_of_most_negative_double bits_of_max_double with Unforceable -> true, top_float end | Cil_types.FFloat -> begin let conv v = Fval.F.of_float (Int32.float_of_bits (Int64.to_int32 (Int.to_int64 v))) in try false, reinterpret 32 conv bits_of_most_negative_float bits_of_max_float with Unforceable -> true, top_single_precision_float end | Cil_types.FLongDouble -> true, top_float let set_bits mn mx = match mn, mx with Some mn, Some mx -> Int.logand (Int.lognot (different_bits mn mx)) mn | _ -> Int.zero let sub_bits x = (* TODO: can be improved *) let popcnt = Int.popcount x in let rec aux cursor acc = if Int.gt cursor x then acc else let acc = if Int.is_zero (Int.logand cursor x) then acc else O.fold (fun e acc -> O.add (Int.logor cursor e) acc) acc acc in aux (Int.shift_left cursor Int.one) acc in let o = aux Int.one o_zero in let s = 1 lsl popcnt in (* assert (O.cardinal o = s); *) inject_ps (Pre_set (o, s)) let bitwise_and_intervals ~size ~signed v1 v2 = let max_int_v1, max_int_v2 as max_int_v1_v2 = max_int v1, max_int v2 in let min_int_v1, min_int_v2 as min_int_v1_v2 = min_int v1, min_int v2 in let half_range = Int.two_power_of_int (pred size) in let minint = Int.neg half_range in let vmax = match max_int_v1_v2 with | Some maxv1, Some maxv2 -> if Int.lt maxv1 Int.zero && Int.lt maxv2 Int.zero then begin Some (match min_int_v1_v2 with Some minv1, Some minv2 -> pos_max_land minv1 maxv1 minv2 maxv2 | _ -> assert false) end else improved min of and maxv2 try let bi1 = smallest_above Int.zero v1 in let bi2 = smallest_above Int.zero v2 in pos_max_land bi1 maxv1 bi2 maxv2 with No_such_element -> minint in improved min of and altmax2 try let altmax2 = Int.add half_range (largest_below Int.minus_one v2) in let bi1 = smallest_above Int.zero v1 in let bi2 = Int.add half_range (smallest_above minint v2) in pos_max_land bi1 maxv1 bi2 altmax2 with No_such_element -> minint in improved min of maxv2 and try let altmax1 = Int.add half_range (largest_below Int.minus_one v1) in let bi2 = smallest_above Int.zero v2 in let bi1 = Int.add half_range (smallest_above minint v1) in pos_max_land bi2 maxv2 bi1 altmax1 with No_such_element -> minint in Format.printf " bitwise_and v1 % a v2 % a % a maxv2 % a \ max1 max2 max3 % a % a % a@. " pretty v1 pretty v2 Int.pretty Int.pretty maxv2 Int.pretty max1 Int.pretty max2 Int.pretty max3 ; max1 max2 max3 %a %a %a@." pretty v1 pretty v2 Int.pretty maxv1 Int.pretty maxv2 Int.pretty max1 Int.pretty max2 Int.pretty max3; *) Some (Int.max max1 (Int.max max2 max3)) | _ -> None in let somenegativev1 = intersects v1 strictly_negative_integers in let somenegativev2 = intersects v2 strictly_negative_integers in let vmin = if somenegativev1 && somenegativev2 then Some minint else if somenegativev1 || somenegativev2 then some_zero else begin let bits1 = set_bits min_int_v1 max_int_v1 in let bits2 = set_bits min_int_v2 max_int_v2 in let min_a = Int.logand bits1 bits2 in let min_a = if not signed then let rec find_mask x bit acc = if Int.is_zero (Int.logand x bit) then acc else find_mask x (Int.shift_right bit Int.one) (Int.logor bit acc) in match min_int_v1_v2 with Some m1, Some m2 -> let mask1 = find_mask bits1 half_range Int.zero in let min_b = Int.logand mask1 m2 in let mask2 = find_mask bits2 half_range Int.zero in let min_c = Int.logand mask2 m1 in (* Format.printf "bitwise_and v1 %a v2 %a min_b %a min_c %a@." pretty v1 pretty v2 Int.pretty min_b Int.pretty min_c; *) Int.max (Int.max min_a min_b) min_c | _ -> assert false else min_a in Format.printf " bitwise_and v1 % a v2 % a bits1 % a bits2 % a@. " pretty v1 pretty v2 Int.pretty bits1 Int.pretty bits2 ; pretty v1 pretty v2 Int.pretty bits1 Int.pretty bits2; *) Some min_a end in vmin, vmax (* [common_low_bits v] returns the common pattern between the least-significant bits of all the elements of the Ival [v]. The pattern is in the form [lower_bits, mask] where [mask] indicates the consecutive least significant bits that are common between all elements, and [lower_bits] indicates their values. *) let common_low_bits ~size v = match v with | Float _ -> assert false | Top(_,_,r,m) -> if Int.is_zero (Int.logand m (Int.pred m)) m is a power of two r, Int.pred m TODO | Set [| v |] -> v, Int.pred (Int.two_power_of_int size) TODO let bitwise_and ~size ~signed v1 v2 = if is_bottom v1 || is_bottom v2 then bottom else let v1 = match v1 with | Float _ -> create_all_values ~size ~signed | _ -> v1 in let v2 = match v2 with | Float _ -> create_all_values ~size ~signed | _ -> v2 in match v1, v2 with | Float _, _ | _, Float _ -> assert false | Set s1, Set s2 -> apply2_v Int.logand s1 s2 | Top _, other | other, Top _ -> let min, max = bitwise_and_intervals ~signed ~size v1 v2 in let lower_bits1, mask1 = common_low_bits ~size v1 in let lower_bits2, mask2 = common_low_bits ~size v2 in let mask = Int.logand mask1 mask2 in let modu = Int.succ mask in let r = Int.logand lower_bits1 (Int.logand lower_bits2 mask) in let min = match min with | Some min -> Some (Int.round_up_to_r ~min ~r ~modu) | _ -> min in let max = match max with | Some max -> Some (Int.round_down_to_r ~max ~r ~modu) | _ -> max in let result = inject_top min max r modu in ( match other with Top _ | Float _ -> result | Set s -> if array_for_all (fun elt -> Int.ge elt Int.zero && Int.popcount elt <= !small_cardinal_log) s then let result2 = Array.fold_left (fun acc elt -> join (sub_bits elt) acc) bottom s in narrow result result2 else result) let pretty_debug = pretty let name = "ival" (* Local Variables: compile-command: "make -C ../../.." End: *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/kernel_services/abstract_interp/ival.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. ************************************************************************ Uses F's total compare function Make sure all this is synchronized with the default value of -ilevel no overflow here Sanity check for Top's arguments let minus_zero = Float (Fval.minus_zero, Fval.minus_zero) Also catches bottom. TODO Note: we clip the interval to get a finite cardinal. This is smaller than the original [n] TODO: improve raised by project_float Add possible interval limits deducted from the bitsize already tested above already tested above [extended_euclidian_algorithm a b] returns x,y,gcd such that a*x+b*y=gcd(x,y). Format.printf "meet: %a /\\ %a -> %a@\n" pretty v1 pretty v2 pretty result; meet is exact ill-typed case. It is better to keep the operation symmetric Given a set of elements that is an under-approximation, returns an ival (while maintaining the ival invariants that the "Set" constructor is used only for small sets of elements. If by chance the set is contiguous. Else: arbitrarily drop some elements of the under approximation. No best abstraction anyway. * [min_is_lower mn1 mn2] is true iff mn1 is a lower min than mn2 TODO: improve by not reading a1.(i1) all the time Top _ represents more elements than can be represented by Set _ Inclusion of bounds is needed for the entire inclusion Top side contains all integers, we're done TODO: float ? ignore (CilE.warn_once "unsupported case for binary operator '%s'" info); TODO: improve by allocating array ignore (CilE.warn_once "unsupported case for unary operator '%s'" info); Not worse than another computation. TODO: improve for Set TODO: improve for Set [different_bits min max] returns an overapproximation of the mask of the bits that can be different for different numbers in the interval [min]..[max] Format.printf "pos_max_land %a %a -> %a | %a %a -> %a@." Int.pretty min1 Int.pretty max1 Int.pretty x1 Int.pretty min2 Int.pretty max2 Int.pretty x2; Or can only add bits all negative good div all positive exact degeneration [scale_rem ~pos:false f v] is an over-approximation of the set of elements [x mod f] for [x] in [v]. [scale_rem ~pos:true f v] is an over-approximation of the set of elements [x pos_rem f] for [x] in [v]. Format.printf "scale_rem %b %a %a@." pos Int.pretty f pretty v; See if [mn..mx] is included in [k*f..(k+1)*f] for some [k]. In this case, [%] is monotonic and [mn%f .. mx%f] is a more precise result. completely undefined. Bottom Compute result bounds using sign information We may need to create a set. Use slow path We only preserve the sign of the result TODO: more cases: Float raised by max_int raised by project_float values of this size cannot be enumerated anyway in C. They may occur while initializing large blocks of arrays. Value in range Overflow in the corresponding direction no overflow Completely out of range impossible if min-max are correct raised by project_float Same values expressed as double finds all floating-point values [f] such that casting [f] to an integer type returns [i]. This float is finite because min is small enough Single precision: round towards 0 (hence up) to minimize the range of the value returned. min is positive. Since casting truncates towards 0, [(int)((real)min-epsilon)] would return [min-1]. Hence, we can simply return the float corresponding to [min] -- which can be represented precisely given [exact_min] and [exact_max]. All operations are dual w.r.t. the min bound. We restrict ourselves to f \in [exact_min, exact_max]. Outside of this range, the conversion int -> float is not exact, and the operation is more involved. We find the integer range included in [f] Round to integers in the proper direction: discard the non-floating-point values on each extremity. Approximate not ok PC: Do not even ask Not NaN cannot fail, [i] is not bottom, hence [a] is not empty TODO: can be improved assert (O.cardinal o = s); Format.printf "bitwise_and v1 %a v2 %a min_b %a min_c %a@." pretty v1 pretty v2 Int.pretty min_b Int.pretty min_c; [common_low_bits v] returns the common pattern between the least-significant bits of all the elements of the Ival [v]. The pattern is in the form [lower_bits, mask] where [mask] indicates the consecutive least significant bits that are common between all elements, and [lower_bits] indicates their values. Local Variables: compile-command: "make -C ../../.." End:
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Abstract_interp let small_cardinal = ref 8 let small_cardinal_Int = ref (Int.of_int !small_cardinal) let small_cardinal_log = ref 3 let debug_cardinal = false let set_small_cardinal i = assert (2 <= i && i <= 1024); let rec log j p = if i <= p then j else log (j+1) (2*p) in small_cardinal := i; small_cardinal_Int := Int.of_int i; small_cardinal_log := log 1 2 let get_small_cardinal () = !small_cardinal let emitter = Lattice_messages.register "Ival";; let log_imprecision s = Lattice_messages.emit_imprecision emitter s ;; module Widen_Arithmetic_Value_Set = struct include Datatype.Integer.Set let pretty fmt s = if is_empty s then Format.fprintf fmt "{}" else Pretty_utils.pp_iter ~pre:"@[<hov 1>{" ~suf:"}@]" ~sep:";@ " iter Int.pretty fmt s let of_list l = match l with | [] -> empty | [e] -> singleton e | e :: q -> List.fold_left (fun acc x -> add x acc) (singleton e) q let default_widen_hints = of_list (List.map Int.of_int [-1;0;1]) end exception Infinity let opt2 f m1 m2 = match m1, m2 with None, _ | _, None -> raise Infinity | Some m1, Some m2 -> f m1 m2 let opt1 f m = match m with None -> None | Some m -> Some (f m) exception Error_Top exception Error_Bottom module O = FCSet.Make(Integer) type pre_set = Pre_set of O.t * int | Pre_top of Int.t * Int.t * Int.t type t = | Set of Int.t array | Float of Fval.t | Top of Int.t option * Int.t option * Int.t * Int.t Binary abstract operations do not model precisely float / integer operations . It is the responsability of the callers to have two operands of the same implicit type . The only exception is for [ singleton_zero ] , which is the correct representation of [ 0 . ] It is the responsability of the callers to have two operands of the same implicit type. The only exception is for [singleton_zero], which is the correct representation of [0.] *) module Widen_Hints = Widen_Arithmetic_Value_Set type size_widen_hint = Integer.t type generic_widen_hint = Widen_Hints.t type widen_hint = size_widen_hint * generic_widen_hint let some_zero = Some Int.zero let bottom = Set (Array.make 0 Int.zero) let top = Top(None, None, Int.zero, Int.one) let hash_v_option v = match v with None -> 97 | Some v -> Int.hash v let hash v = match v with Set s -> Array.fold_left (fun acc v -> 1031 * acc + (Int.hash v)) 17 s | Top(mn,mx,r,m) -> hash_v_option mn + 5501 * (hash_v_option mx) + 59 * (Int.hash r) + 13031 * (Int.hash m) | Float(f) -> 3 + 17 * Fval.hash f let bound_compare x y = match x,y with None, None -> 0 | None, Some _ -> 1 | Some _, None -> -1 | Some x, Some y -> Int.compare x y exception Unequal of int let compare e1 e2 = if e1==e2 then 0 else match e1,e2 with | Set e1,Set e2 -> let l1 = Array.length e1 in let l2 = Array.length e2 in if l1 <> l2 else (try for i=0 to l1 -1 do let r = Int.compare e1.(i) e2.(i) in if r <> 0 then raise (Unequal r) done; 0 with Unequal v -> v ) | _, Set _ -> 1 | Set _, _ -> -1 | Top(mn,mx,r,m), Top(mn',mx',r',m') -> let r1 = bound_compare mn mn' in if r1 <> 0 then r1 else let r2 = bound_compare mx mx' in if r2 <> 0 then r2 else let r3 = Int.compare r r' in if r3 <> 0 then r3 else Int.compare m m' | _, Top _ -> 1 | Top _, _ -> -1 | Float(f1), Float(f2) -> Fval.compare f1 f2 | _ , Float _ - > 1 | Float _ , _ - > -1 | Float _, _ -> -1 *) let equal e1 e2 = compare e1 e2 = 0 let pretty fmt t = match t with | Top(mn,mx,r,m) -> let print_bound fmt = function None -> Format.fprintf fmt "--" | Some v -> Int.pretty fmt v in Format.fprintf fmt "[%a..%a]%t" print_bound mn print_bound mx (fun fmt -> if Int.is_zero r && Int.is_one m then Format.fprintf fmt "" else Format.fprintf fmt ",%a%%%a" Int.pretty r Int.pretty m) | Float (f) -> Fval.pretty fmt f | Set s -> if Array.length s = 0 then Format.fprintf fmt "BottomMod" else begin Pretty_utils.pp_iter ~pre:"@[<hov 1>{" ~suf:"}@]" ~sep:";@ " Array.iter Int.pretty fmt s end let min_le_elt min elt = match min with | None -> true | Some m -> Int.le m elt let max_ge_elt max elt = match max with | None -> true | Some m -> Int.ge m elt let all_positives min = match min with | None -> false | Some m -> Int.ge m Int.zero let all_negatives max = match max with | None -> false | Some m -> Int.le m Int.zero let fail min max r modu = let bound fmt = function | None -> Format.fprintf fmt "--" | Some(x) -> Int.pretty fmt x in Kernel.fatal "Ival: broken Top, min=%a max=%a r=%a modu=%a" bound min bound max Int.pretty r Int.pretty modu let is_safe_modulo r modu = (Int.ge r Int.zero ) && (Int.ge modu Int.one) && (Int.lt r modu) let check_modulo min max r modu = if not (is_safe_modulo r modu) then fail min max r modu let is_safe_bound bound r modu = match bound with | None -> true | Some m -> Int.equal (Int.pos_rem m modu) r let check min max r modu = if not (is_safe_modulo r modu && is_safe_bound min r modu && is_safe_bound max r modu) then fail min max r modu let cardinal_zero_or_one v = match v with | Top _ -> false | Set s -> Array.length s <= 1 | Float f -> Fval.is_singleton f let is_singleton_int v = match v with | Float _ | Top _ -> false | Set s -> Array.length s = 1 let is_bottom x = x == bottom let o_zero = O.singleton Int.zero let o_one = O.singleton Int.one let o_zero_or_one = O.union o_zero o_one let small_nums = Array.map (fun i -> Set [| i |]) Int.small_nums let zero = small_nums.(0) let one = small_nums.(1) let minus_one = Set [| Int.minus_one |] let zero_or_one = Set [| Int.zero ; Int.one |] let float_zeros = Float Fval.zeros let positive_integers = Top(Some Int.zero, None, Int.zero, Int.one) let negative_integers = Top(None, Some Int.zero, Int.zero, Int.one) let strictly_negative_integers = Top(None, Some Int.minus_one, Int.zero, Int.one) let is_zero x = x == zero let inject_singleton e = if Int.le Int.zero e && Int.le e Int.thirtytwo then small_nums.(Int.to_int e) else Set [| e |] let share_set o s = if s = 0 then bottom else if s = 1 then begin let e = O.min_elt o in inject_singleton e end else if O.equal o o_zero_or_one then zero_or_one else let a = Array.make s Int.zero in let i = ref 0 in O.iter (fun e -> a.(!i) <- e; incr i) o; assert (!i = s); Set a let share_array a s = if s = 0 then bottom else let e = a.(0) in if s = 1 && Int.le Int.zero e && Int.le e Int.thirtytwo then small_nums.(Int.to_int e) else if s = 2 && Int.is_zero e && Int.is_one a.(1) then zero_or_one else Set a let inject_float f = if Fval.is_zero f then zero else Float f let inject_float_interval flow fup = let flow = Fval.F.of_float flow in let fup = Fval.F.of_float fup in if Fval.F.equal Fval.F.zero flow && Fval.F.equal Fval.F.zero fup then zero else Float (Fval.inject flow fup) let subdiv_float_interval ~size v = match v with | Float f -> let f1, f2 = Fval.subdiv_float_interval ~size f in inject_float f1, inject_float f2 | Top _ | Set _ -> assert (is_zero v); raise Can_not_subdiv let is_one = equal one exception Nan_or_infinite let project_float v = if is_zero v then Fval.zero else match v with | Float f -> f let in_interval x min max r modu = Int.equal (Int.pos_rem x modu) r && min_le_elt min x && max_ge_elt max x let array_mem v a = let l = Array.length a in let rec c i = if i = l then (-1) else let ae = a.(i) in if Int.equal ae v then i else if Int.gt ae v then (-1) else c (succ i) in c 0 let contains_zero s = match s with | Top(mn,mx,r,m) -> in_interval Int.zero mn mx r m | Set s -> (array_mem Int.zero s)>=0 | Float f -> Fval.contains_zero f exception Not_Singleton_Int let project_int v = match v with | Set [| e |] -> e | _ -> raise Not_Singleton_Int let cardinal v = match v with | Top (None,_,_,_) | Top (_,None,_,_) -> None | Top (Some mn, Some mx,_,m) -> Some (Int.succ ((Int.native_div (Int.sub mx mn) m))) | Set s -> Some (Int.of_int (Array.length s)) | Float f -> if Fval.is_singleton f then Some Int.one else None let cardinal_estimate v size = match v with | Set s -> Int.of_int (Array.length s) | Top (mn,mx,_,d) -> let mn = match mn with | None -> Integer.neg (Integer.two_power (Integer.pred size)) | Some(mn) -> mn in let mx = match mx with | None -> Integer.pred (Integer.two_power size) | Some(mx) -> mx in Int.(div (sub mx mn) d) | Float f -> if Fval.is_singleton f then Int.one TODO : Get exponent of min and , and multiply by two_power the size of mantissa . the size of mantissa. *) else Int.two_power size let cardinal_less_than v n = let c = match v with | Top (None,_,_,_) | Top (_,None,_,_) -> raise Not_less_than | Top (Some mn, Some mx,_,m) -> Int.succ ((Int.native_div (Int.sub mx mn) m)) | Set s -> Int.of_int (Array.length s) | Float f -> if Fval.is_singleton f then Int.one else raise Not_less_than in if Int.le c (Int.of_int n) else raise Not_less_than let cardinal_is_less_than v n = match cardinal v with | None -> false | Some c -> Int.le c (Int.of_int n) let share_top min max r modu = let r = Top (min, max, r, modu) in if equal r top then top else r let make ~min ~max ~rem ~modu = match min, max with | Some mn, Some mx -> if Int.gt mx mn then let l = Int.succ (Int.div (Int.sub mx mn) modu) in if Int.le l !small_cardinal_Int then let l = Int.to_int l in let s = Array.make l Int.zero in let v = ref mn in let i = ref 0 in while (!i < l) do s.(!i) <- !v; v := Int.add modu !v; incr i done; assert (Int.equal !v (Int.add modu mx)); share_array s l else Top (min, max, rem, modu) else if Int.equal mx mn then inject_singleton mn else bottom | _ -> share_top min max rem modu let inject_top min max rem modu = check min max rem modu; make ~min ~max ~rem ~modu let inject_interval ~min ~max ~rem:r ~modu = check_modulo min max r modu; let min = Extlib.opt_map (fun min -> Int.round_up_to_r ~min ~r ~modu) min and max = Extlib.opt_map (fun max -> Int.round_down_to_r ~max ~r ~modu) max in make ~min ~max ~rem:r ~modu let subdiv_int v = match v with | Float _ -> raise Can_not_subdiv | Set arr -> let len = Array.length arr in assert (len > 0 ); if len <= 1 then raise Can_not_subdiv; let m = len lsr 1 in let lenhi = len - m in let lo = Array.sub arr 0 m in let hi = Array.sub arr m lenhi in share_array lo m, share_array hi lenhi | Top (Some lo, Some hi, r, modu) -> let mean = Int.native_div (Int.add lo hi) Abstract_interp.Int.two in let succmean = Abstract_interp.Int.succ mean in let hilo = Integer.round_down_to_r ~max:mean ~r ~modu in let lohi = Integer.round_up_to_r ~min:succmean ~r ~modu in inject_top (Some lo) (Some hilo) r modu, inject_top (Some lohi) (Some hi) r modu | Top _ -> raise Can_not_subdiv let inject_range min max = inject_top min max Int.zero Int.one let top_float = Float Fval.top let top_single_precision_float = Float Fval.top_single_precision_float let unsafe_make_top_from_set_4 s = if debug_cardinal then assert (O.cardinal s >= 2); let m = O.min_elt s in let modu = O.fold (fun x acc -> if Int.equal x m then acc else Int.pgcd (Int.sub x m) acc) s Int.zero in let r = Int.pos_rem m modu in let max = O.max_elt s in let min = m in (min,max,r,modu) let unsafe_make_top_from_array_4 s = let l = Array.length s in assert (l >= 2); let m = s.(0) in let modu = Array.fold_left (fun acc x -> if Int.equal x m then acc else Int.pgcd (Int.sub x m) acc) Int.zero s in let r = Int.pos_rem m modu in let max = Some s.(pred l) in let min = Some m in check min max r modu; (min,max,r,modu) let unsafe_make_top_from_array s = let min, max, r, modu = unsafe_make_top_from_array_4 s in share_top min max r modu let empty_ps = Pre_set (O.empty, 0) let add_ps ps x = match ps with | Pre_set(o,s) -> if debug_cardinal then assert (O.cardinal o = s); then ps else let no = O.add x o in if s < !small_cardinal then begin if debug_cardinal then assert (O.cardinal no = succ s); Pre_set (no, succ s) end else let min, max, _r, modu = unsafe_make_top_from_set_4 no in Pre_top (min, max, modu) | Pre_top (min, max, modu) -> let new_modu = if Int.equal x min then modu else Int.pgcd (Int.sub x min) modu in let new_min = Int.min min x in let new_max = Int.max max x in Pre_top (new_min, new_max, new_modu) let inject_ps ps = match ps with Pre_set(o, s) -> share_set o s | Pre_top (min, max, modu) -> Top(Some min, Some max, Int.pos_rem min modu, modu) let min_max_r_mod t = match t with | Set s -> assert (Array.length s >= 2); unsafe_make_top_from_array_4 s | Top (a,b,c,d) -> a,b,c,d | Float _ -> None, None, Int.zero, Int.one let min_and_max t = match t with | Set s -> let l = Array.length s in assert (l >= 1); Some s.(0), Some s.(pred l) | Top (a,b,_,_) -> a, b | Float _ -> None, None let min_and_max_float t = match t with Set _ when is_zero t -> Fval.F.zero, Fval.F.zero | Float f -> Fval.min_and_max f | _ -> assert false let compare_min_int t1 t2 = let m1, _ = min_and_max t1 in let m2, _ = min_and_max t2 in match m1, m2 with None, None -> 0 | None, Some _ -> -1 | Some _, None -> 1 | Some m1, Some m2 -> Int.compare m1 m2 let compare_max_int t1 t2 = let _, m1 = min_and_max t1 in let _, m2 = min_and_max t2 in match m1, m2 with None, None -> 0 | None, Some _ -> -1 | Some _, None -> 1 | Some m1, Some m2 -> Int.compare m2 m1 let compare_min_float t1 t2 = let f1 = project_float t1 in let f2 = project_float t2 in Fval.compare_min f1 f2 let compare_max_float t1 t2 = let f1 = project_float t1 in let f2 = project_float t2 in Fval.compare_max f1 f2 let widen (bitsize,wh) t1 t2 = if equal t1 t2 || cardinal_zero_or_one t1 then t2 else match t2 with | Float f2 -> ( try let f1 = project_float t1 in if not (Fval.is_included f1 f2) then assert false; Float (Fval.widen f1 f2) | Top _ | Set _ -> let wh = if Integer.is_zero bitsize then wh else let limits = [ Integer.neg (Integer.two_power (Integer.pred bitsize)); Integer.pred (Integer.two_power (Integer.pred bitsize)); Integer.pred (Integer.two_power bitsize); ] in let module ISet = Datatype.Integer.Set in ISet.union wh (ISet.of_list limits) in let (mn2,mx2,r2,m2) = min_max_r_mod t2 in let (mn1,mx1,r1,m1) = min_max_r_mod t1 in let new_mod = Int.pgcd (Int.pgcd m1 m2) (Int.abs (Int.sub r1 r2)) in let new_rem = Int.rem r1 new_mod in let new_min = if bound_compare mn1 mn2 = 0 then mn2 else match mn2 with | None -> None | Some mn2 -> try let v = Widen_Hints.nearest_elt_le mn2 wh in Some (Int.round_up_to_r ~r:new_rem ~modu:new_mod ~min:v) with Not_found -> None in let new_max = if bound_compare mx1 mx2 = 0 then mx2 else match mx2 with None -> None | Some mx2 -> try let v = Widen_Hints.nearest_elt_ge mx2 wh in Some (Int.round_down_to_r ~r:new_rem ~modu:new_mod ~max:v) with Not_found -> None in let result = inject_top new_min new_max new_rem new_mod in Format.printf " % a -- % a -- > % a ( thx to % a)@. " pretty t1 pretty t2 pretty result Widen_Hints.pretty wh ; pretty t1 pretty t2 pretty result Widen_Hints.pretty wh; *) result let compute_first_common mn1 mn2 r modu = if mn1 = None && mn2 = None then None else let m = match (mn1, mn2) with | Some m, None | None, Some m -> m | Some m1, Some m2 -> Int.max m1 m2 in Some (Int.round_up_to_r ~min:m ~r ~modu) let compute_last_common mx1 mx2 r modu = if mx1 = None && mx2 = None then None else let m = match (mx1, mx2) with | Some m, None | None, Some m -> m | Some m1, Some m2 -> Int.min m1 m2 in Some (Int.round_down_to_r ~max:m ~r ~modu) let min_min x y = match x,y with | None,_ | _,None -> None | Some x, Some y -> Some (Int.min x y) let max_max x y = match x,y with | None,_ | _,None -> None | Some x, Some y -> Some (Int.max x y) let extended_euclidian_algorithm a b = assert (Int.gt a Int.zero); assert (Int.gt b Int.zero); let a = ref a and b = ref b in let x = ref Int.zero and lastx = ref Int.one in let y = ref Int.one and lasty = ref Int.zero in while not (Int.is_zero !b) do let (q,r) = Int.div_rem !a !b in a := !b; b := r; let tmpx = !x in (x:= Int.sub !lastx (Int.mul q !x); lastx := tmpx); let tmpy = !y in (y:= Int.sub !lasty (Int.mul q !y); lasty := tmpy); done; (!lastx,!lasty,!a) [ JS 2013/05/23 ] unused right now [ modular_inverse a m ] returns [ x ] such that a*x is congruent to 1 mod m. [modular_inverse a m] returns [x] such that a*x is congruent to 1 mod m. *) let _modular_inverse a m = let (x,_,gcd) = extended_euclidian_algorithm a m in assert (Int.equal Int.one gcd); x This function provides solutions to the chinese remainder theorem , i.e. it finds the solutions x such that : x = = r1 mod m1 & & x = = r2 mod m2 . If no such solution exists , it raises Error_Bottom ; else it returns ( r , m ) such that all solutions x are such that x = = r i.e. it finds the solutions x such that: x == r1 mod m1 && x == r2 mod m2. If no such solution exists, it raises Error_Bottom; else it returns (r,m) such that all solutions x are such that x == r mod m. *) let compute_r_common r1 m1 r2 m2 = ( E1 ) x = = r1 mod m1 & & x = = r2 mod m2 < = > \E k1,k2 : x = r1 + k1*m1 & & x = r2 + k2*m2 < = > \E k1,k2 : x = r1 + k1*m1 & & k1*m1 - k2*m2 = r2 - r1 Let c = r2 - r1 . The equation ( E2 ): k1*m1 - k2*m2 = c is diophantine ; there are solutions x to ( E1 ) iff there are solutions ( k1,k2 ) to ( E2 ) . Let d = pgcd(m1,m2 ) . There are solutions to ( E2 ) only if d divides c ( because d divides k1*m1 - k2*m2 ) . Else we raise [ Error_Bottom ] . <=> \E k1,k2: x = r1 + k1*m1 && x = r2 + k2*m2 <=> \E k1,k2: x = r1 + k1*m1 && k1*m1 - k2*m2 = r2 - r1 Let c = r2 - r1. The equation (E2): k1*m1 - k2*m2 = c is diophantine; there are solutions x to (E1) iff there are solutions (k1,k2) to (E2). Let d = pgcd(m1,m2). There are solutions to (E2) only if d divides c (because d divides k1*m1 - k2*m2). Else we raise [Error_Bottom]. *) let (x1,_,pgcd) = extended_euclidian_algorithm m1 m2 in let c = Int.sub r2 r1 in let (c_div_d,c_rem) = Int.div_rem c pgcd in if not (Int.equal c_rem Int.zero) then raise Error_Bottom The extended euclidian algorithm has provided solutions to the Bezout identity x1*m1 + x2*m2 = d. x1*m1 + x2*m2 = d = = > x1*(c / d)*m1 + x2*(c / d)*m2 = d*(c / d ) . Thus , k1 = x1*(c / d ) , k2=-x2*(c / d ) are solutions to ( E2 ) Thus , x = r1 + x1*(c / d)*m1 is a particular solution to ( E1 ) . the Bezout identity x1*m1 + x2*m2 = d. x1*m1 + x2*m2 = d ==> x1*(c/d)*m1 + x2*(c/d)*m2 = d*(c/d). Thus, k1 = x1*(c/d), k2=-x2*(c/d) are solutions to (E2) Thus, x = r1 + x1*(c/d)*m1 is a particular solution to (E1). *) else let k1 = Int.mul x1 c_div_d in let x = Int.add r1 (Int.mul k1 m1) in If two solutions x and y exist , they are equal modulo ppcm(m1,m2 ) . We have x = = r1 mod m1 & & y = = r1 mod m1 = = > \E k1 : x - y = k1*m1 x = = r2 mod m2 & & y = = r2 mod m2 = = > \E k2 : x - y = k2*m2 Thus k1*m1 = k2*m2 is a multiple of m1 and , i.e. is a multiple of ppcm(m1,m2 ) . Thus x = y mod ppcm(m1,m2 ) . We have x == r1 mod m1 && y == r1 mod m1 ==> \E k1: x - y = k1*m1 x == r2 mod m2 && y == r2 mod m2 ==> \E k2: x - y = k2*m2 Thus k1*m1 = k2*m2 is a multiple of m1 and m2, i.e. is a multiple of ppcm(m1,m2). Thus x = y mod ppcm(m1,m2). *) let ppcm = Int.divexact (Int.mul m1 m2) pgcd in x may be bigger than the ppcm , we normalize it . (Int.rem x ppcm, ppcm) ;; let array_truncate r i = if i = 0 then bottom else if i = 1 then inject_singleton r.(0) else begin (Obj.truncate (Obj.repr r) i); assert (Array.length r = i); Set r end let array_inter a1 a2 = let l1 = Array.length a1 in let l2 = Array.length a2 in let lr_max = min l1 l2 in let r = Array.make lr_max Int.zero in let rec c i i1 i2 = if i1 = l1 || i2 = l2 then array_truncate r i else let e1 = a1.(i1) in let e2 = a2.(i2) in if Int.equal e1 e2 then begin r.(i) <- e1; c (succ i) (succ i1) (succ i2) end else if Int.lt e1 e2 then c i (succ i1) i2 else c i i1 (succ i2) in c 0 0 0 Do the two arrays have an integer in common let arrays_intersect a1 a2 = let l1 = Array.length a1 in let l2 = Array.length a2 in let rec aux i1 i2 = if i1 = l1 || i2 = l2 then false else let e1 = a1.(i1) in let e2 = a2.(i2) in if Int.equal e1 e2 then true else if Int.lt e1 e2 then aux (succ i1) i2 else aux i1 (succ i2) in aux 0 0 let meet v1 v2 = if v1 == v2 then v1 else let result = match v1,v2 with | Top(min1,max1,r1,modu1), Top(min2,max2,r2,modu2) -> begin try let r,modu = compute_r_common r1 modu1 r2 modu2 in inject_top (compute_first_common min1 min2 r modu) (compute_last_common max1 max2 r modu) r modu with Error_Bottom -> " meet to bottom : % a /\\ % a@\n " pretty v1 pretty v2 ; pretty v1 pretty v2;*) bottom end | Set s1 , Set s2 -> array_inter s1 s2 | Set s, Top(min, max, rm, modu) | Top(min, max, rm, modu), Set s -> let l = Array.length s in let r = Array.make l Int.zero in let rec c i j = if i = l then array_truncate r j else let si = succ i in let x = s.(i) in if in_interval x min max rm modu then begin r.(j) <- x; c si (succ j) end else c si j in c 0 0 | Float(f1), Float(f2) -> begin match Fval.meet f1 f2 with | `Value f -> inject_float f | `Bottom -> bottom end | (Float f) as ff, other | other, ((Float f) as ff) -> if equal top other then ff else if (Fval.contains_zero f) && contains_zero other then zero else bottom in result let intersects v1 v2 = v1 == v2 || match v1, v2 with YYY : slightly inefficient | Set s1 , Set s2 -> arrays_intersect s1 s2 | Set s, Top (min, max, rm, modu) | Top (min, max, rm, modu), Set s -> Extlib.array_exists (fun x -> in_interval x min max rm modu) s | Float f1, Float f2 -> begin match Fval.forward_comp Comp.Eq f1 f2 with | Comp.False -> false | Comp.True | Comp.Unknown -> true end | Float f, other | other, Float f -> equal top other || (Fval.contains_zero f && contains_zero other) let narrow v1 v2 = match v1, v2 with | _, Set [||] | Set [||], _ -> bottom | Float _, Float _ | (Top _| Set _), (Top _ | Set _) -> | v, (Top _ as t) when equal t top -> v | (Top _ as t), v when equal t top -> v | Float f, (Set _ as s) | (Set _ as s), Float f when is_zero s -> begin match Fval.meet f Fval.zero with | `Value f -> inject_float f | `Bottom -> bottom end | Float _, (Set _ | Top _) | (Set _ | Top _), Float _ -> top let set_to_ival_under set = let card = Int.Set.cardinal set in if card <= !small_cardinal then (let a = Array.make card Int.zero in ignore(Int.Set.fold (fun elt i -> Array.set a i elt; i + 1) set 0); share_array a card) else if (Int.equal (Int.sub (Int.Set.max_elt set) (Int.Set.min_elt set)) (Int.of_int (card - 1))) then Top( Some(Int.Set.min_elt set), Some(Int.Set.max_elt set), Int.one, Int.zero) else let a = Array.make !small_cardinal Int.zero in log_imprecision "Ival.set_to_ival_under"; try ignore(Int.Set.fold (fun elt i -> if i = !small_cardinal then raise Exit; Array.set a i elt; i + 1) set 0); assert false with Exit -> Set a ;; let link v1 v2 = match v1, v2 with | Set a1, Set a2 -> let s1 = Array.fold_right Int.Set.add a1 Int.Set.empty in let s2 = Array.fold_right Int.Set.add a2 s1 in set_to_ival_under s2 | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> if Int.equal r1 r2 && Int.equal m1 m2 then let min = match mn1,mn2 with | Some(a), Some(b) -> Some(Int.min a b) | _ -> None in let max = match mx1,mx2 with | Some(a), Some(b) -> Some(Int.max a b) | _ -> None in inject_top min max r1 m1 | Top(mn,mx,r,m), Set s | Set s, Top(mn,mx,r,m) -> let max = match mx with | None -> None | Some(max) -> let curmax = ref max in for i = 0 to (Array.length s) - 1 do let elt = s.(i) in if Int.equal elt (Int.add !curmax m) then curmax := elt done; Some(!curmax) in let min = match mn with | None -> None | Some(min) -> let curmin = ref min in for i = (Array.length s) - 1 downto 0 do let elt = s.(i) in if Int.equal elt (Int.sub !curmin m) then curmin := elt done; Some(!curmin) in inject_top min max r m | _ -> bottom ;; let join v1 v2 = let result = if v1 == v2 then v1 else match v1,v2 with | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> check mn1 mx1 r1 m1; check mn2 mx2 r2 m2; let modu = Int.pgcd (Int.pgcd m1 m2) (Int.abs(Int.sub r1 r2)) in let r = Int.rem r1 modu in let min = min_min mn1 mn2 in let max = max_max mx1 mx2 in let r = inject_top min max r modu in r | Set s, (Top(min, max, r, modu) as t) | (Top(min, max, r, modu) as t), Set s -> let l = Array.length s in if l = 0 then t else let f modu elt = Int.pgcd modu (Int.abs(Int.sub r elt)) in let new_modu = Array.fold_left f modu s in let new_r = Int.rem r new_modu in let new_min = match min with None -> None | Some m -> Some (Int.min m s.(0)) in let new_max = match max with None -> None | Some m -> Some (Int.max m s.(pred l)) in check new_min new_max new_r new_modu; share_top new_min new_max new_r new_modu | Set s1 , Set s2 -> let l1 = Array.length s1 in if l1 = 0 then v2 else let l2 = Array.length s2 in if l2 = 0 then v1 else second pass : make a set or make a top let second uniq = if uniq <= !small_cardinal then let r = Array.make uniq Int.zero in let rec c i i1 i2 = if i1 = l1 then begin Array.blit s2 i2 r i (l2 - i2); share_array r uniq end else if i2 = l2 then begin Array.blit s1 i1 r i (l1 - i1); share_array r uniq end else let si = succ i in let e1 = s1.(i1) in let e2 = s2.(i2) in if Int.lt e2 e1 then begin r.(i) <- e2; c si i1 (succ i2) end else begin r.(i) <- e1; let si1 = succ i1 in if Int.equal e1 e2 then begin c si si1 (succ i2) end else begin c si si1 i2 end end in c 0 0 0 else begin let m = Int.min s1.(0) s2.(0) in let accum acc x = if Int.equal x m then acc else Int.pgcd (Int.sub x m) acc in let modu = ref Int.zero in for j = 0 to pred l1 do modu := accum !modu s1.(j) done; for j = 0 to pred l2 do modu := accum !modu s2.(j) done; inject_ps (Pre_top (m, Int.max s1.(pred l1) s2.(pred l2), !modu)) end in first pass : count unique elements and detect inclusions let rec first i1 i2 uniq inc1 inc2 = let finished1 = i1 = l1 in if finished1 then begin if inc2 then v2 else second (uniq + l2 - i2) end else let finished2 = i2 = l2 in if finished2 then begin if inc1 then v1 else second (uniq + l1 - i1) end else let e1 = s1.(i1) in let e2 = s2.(i2) in if Int.lt e2 e1 then begin first i1 (succ i2) (succ uniq) false inc2 end else if Int.gt e2 e1 then begin first (succ i1) i2 (succ uniq) inc1 false end else first (succ i1) (succ i2) (succ uniq) inc1 inc2 in first 0 0 0 true true | Float(f1), Float(f2) -> inject_float (Fval.join f1 f2) | Float (f) as ff, other | other, (Float (f) as ff) -> if is_zero other then inject_float (Fval.join Fval.zero f) else if is_bottom other then ff else top in " % a % a - > % a@. " pretty v1 pretty v2 pretty result ; pretty v1 pretty v2 pretty result; *) result let fold_int f v acc = match v with Top(None,_,_,_) | Top(_,None,_,_) | Float _ -> raise Error_Top | Top(Some inf, Some sup, _, step) -> Int.fold f ~inf ~sup ~step acc | Set s -> Array.fold_left (fun acc x -> f x acc) acc s let fold_int_decrease f v acc = match v with Top(None,_,_,_) | Top(_,None,_,_) | Float _ -> raise Error_Top | Top(Some inf, Some sup, _, step) -> Int.fold f ~inf ~sup ~step:(Int.neg step) acc | Set s -> Array.fold_right (fun x acc -> f x acc) s acc let fold_enum f v acc = match v with | Float fl when Fval.is_singleton fl -> f v acc | Float _ -> raise Error_Top | Set _ | Top _ -> fold_int (fun x acc -> f (inject_singleton x) acc) v acc let fold_split ~split f v acc = match v with | Float (fl) when Fval.is_singleton fl -> f v acc | Float (fl) -> Fval.fold_split split (fun fl acc -> f (inject_float fl) acc) fl acc | Top(_,_,_,_) | Set _ -> fold_int (fun x acc -> f (inject_singleton x) acc) v acc let min_is_lower mn1 mn2 = match mn1, mn2 with None, _ -> true | _, None -> false | Some m1, Some m2 -> Int.le m1 m2 * [ max_is_greater mx1 mx2 ] is true iff mx1 is a greater max than mx2 let max_is_greater mx1 mx2 = match mx1, mx2 with None, _ -> true | _, None -> false | Some m1, Some m2 -> Int.ge m1 m2 let rem_is_included r1 m1 r2 m2 = (Int.is_zero (Int.rem m1 m2)) && (Int.equal (Int.rem r1 m2) r2) let array_for_all f (a : Integer.t array) = let l = Array.length a in let rec c i = i = l || ((f a.(i)) && c (succ i)) in c 0 let array_subset a1 a2 = let l1 = Array.length a1 in let l2 = Array.length a2 in if l1 > l2 then false else let rec c i1 i2 = if i1 = l1 then true else if i2 = l2 then false else let e1 = a1.(i1) in let e2 = a2.(i2) in let si2 = succ i2 in if Int.equal e1 e2 then c (succ i1) si2 else if Int.lt e1 e2 then false in c 0 0 let is_included t1 t2 = (t1 == t2) || match t1,t2 with | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> (min_is_lower mn2 mn1) && (max_is_greater mx2 mx1) && rem_is_included r1 m1 r2 m2 | Set [||], Top _ -> true | Set s, Top(min, max, r, modu) -> min_le_elt min s.(0) && max_ge_elt max s.(Array.length s-1) array_for_all (fun x -> Int.equal (Int.pos_rem x modu) r) s) | Set s1, Set s2 -> array_subset s1 s2 | Float(f1), Float(f2) -> Fval.is_included f1 f2 | Float _, _ -> equal t2 top | _, Float (f) -> is_zero t1 && (Fval.contains_zero f) let join_and_is_included a b = let ab = join a b in (ab, equal a b) let partially_overlaps ~size t1 t2 = match t1, t2 with Set s1, Set s2 -> not (array_for_all (fun e1 -> array_for_all (fun e2 -> Int.equal e1 e2 || Int.le e1 (Int.sub e2 size) || Int.ge e1 (Int.add e2 size)) s2) s1) | Set s, Top(mi, ma, r, modu) | Top(mi, ma, r, modu), Set s -> not (array_for_all (fun e -> let psize = Int.pred size in (not (min_le_elt mi (Int.add e psize))) || (not (max_ge_elt ma (Int.sub e psize))) || ( Int.ge modu size && let re = Int.pos_rem (Int.sub e r) modu in Int.is_zero re || (Int.ge re size && Int.le re (Int.sub modu size)) )) s) TODO let overlap ival size offset offset_size = let offset_itg = Integer.of_int offset in let offset_size_itg = Integer.of_int offset_size in let offset_max_bound = Integer.add offset_itg (Integer.sub offset_size_itg Integer.one) in let overlap_itv elt_min elt_max = let elt_max_bound = Integer.add elt_max (Integer.sub size Integer.one) in Integer.le elt_min offset_max_bound && Integer.le offset_itg elt_max_bound in match ival with | Set s -> Array.exists (fun elt -> overlap_itv elt elt) s | Top (min, max, rem, modulo) -> let psize = Integer.sub size Integer.one in let overlap = match min, max with | None, None -> true | Some min, None -> Integer.ge offset_max_bound min | None, Some max -> Integer.le offset_itg (Integer.add max psize) | Some min, Some max -> overlap_itv min max in let remain = Integer.pos_rem (Integer.sub offset_itg rem) modulo in overlap && (Integer.lt modulo offset_size_itg || Integer.is_zero remain || Int.lt remain offset_size_itg || Int.gt remain (Int.sub modulo offset_size_itg)) let map_set_exnsafe_acc f acc (s : Integer.t array) = Array.fold_left (fun acc v -> add_ps acc (f v)) acc s let map_set_exnsafe f (s : Integer.t array) = inject_ps (map_set_exnsafe_acc f empty_ps s) let apply2_notzero f (s1 : Integer.t array) s2 = inject_ps (Array.fold_left (fun acc v1 -> Array.fold_left (fun acc v2 -> if Int.is_zero v2 then acc else add_ps acc (f v1 v2)) acc s2) empty_ps s1) let apply2_n f (s1 : Integer.t array) (s2 : Integer.t array) = let ps = ref empty_ps in let l1 = Array.length s1 in let l2 = Array.length s2 in for i1 = 0 to pred l1 do let e1 = s1.(i1) in for i2 = 0 to pred l2 do ps := add_ps !ps (f e1 s2.(i2)) done done; inject_ps !ps let apply2_v f s1 s2 = match s1, s2 with [| x1 |], [| x2 |] -> inject_singleton (f x1 x2) | _ -> apply2_n f s1 s2 let apply_set f v1 v2 = match v1,v2 with | Set s1, Set s2 -> apply2_n f s1 s2 | _ -> top match v with | Set s -> map_set_exnsafe f s | _ -> top let apply_bin_1_strict_incr f x (s : Integer.t array) = let l = Array.length s in let r = Array.make l Int.zero in let rec c i = if i = l then share_array r l else let v = f x s.(i) in r.(i) <- v; c (succ i) in c 0 let apply_bin_1_strict_decr f x (s : Integer.t array) = let l = Array.length s in let r = Array.make l Int.zero in let rec c i = if i = l then share_array r l else let v = f x s.(i) in r.(l - i - 1) <- v; c (succ i) in c 0 let map_set_strict_decr f (s : Integer.t array) = let l = Array.length s in let r = Array.make l Int.zero in let rec c i = if i = l then share_array r l else let v = f s.(i) in r.(l - i - 1) <- v; c (succ i) in c 0 let map_set_decr f (s : Integer.t array) = let l = Array.length s in if l = 0 then bottom else let r = Array.make l Int.zero in let rec c srcindex dstindex last = if srcindex < 0 then begin r.(dstindex) <- last; array_truncate r (succ dstindex) end else let v = f s.(srcindex) in if Int.equal v last then c (pred srcindex) dstindex last else begin r.(dstindex) <- last; c (pred srcindex) (succ dstindex) v end in c (l-2) 0 (f s.(pred l)) let map_set_incr f (s : Integer.t array) = let l = Array.length s in if l = 0 then bottom else let r = Array.make l Int.zero in let rec c srcindex dstindex last = if srcindex = l then begin r.(dstindex) <- last; array_truncate r (succ dstindex) end else let v = f s.(srcindex) in if Int.equal v last then c (succ srcindex) dstindex last else begin r.(dstindex) <- last; c (succ srcindex) (succ dstindex) v end in c 1 0 (f s.(0)) let add_singleton_int i v = match v with | Float _ -> assert false | Set s -> apply_bin_1_strict_incr Int.add i s | Top (mn, mx, r, m) -> let incr v = Int.add i v in let new_mn = opt1 incr mn in let new_mx = opt1 incr mx in let new_r = Int.pos_rem (incr r) m in share_top new_mn new_mx new_r m let rec add_int v1 v2 = match v1,v2 with | Float _, _ | _, Float _ -> assert false | Set [| x |], Set s | Set s, Set [| x |]-> apply_bin_1_strict_incr Int.add x s | Set s1, Set s2 -> apply2_n Int.add s1 s2 | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> let m = Int.pgcd m1 m2 in let r = Int.rem (Int.add r1 r2) m in let mn = try Some (Int.round_up_to_r ~min:(opt2 Int.add mn1 mn2) ~r ~modu:m) with Infinity -> None in let mx = try Some (Int.round_down_to_r ~max:(opt2 Int.add mx1 mx2) ~r ~modu:m) with Infinity -> None in inject_top mn mx r m | Set s, (Top _ as t) | (Top _ as t), Set s -> let l = Array.length s in if l = 0 then bottom else if l = 1 only one element add_singleton_int s.(0) t else add_int t (unsafe_make_top_from_array s) let add_int_under v1 v2 = match v1,v2 with | Float _, _ | _, Float _ -> assert false | Set [| x |], Set s | Set s, Set [| x |]-> apply_bin_1_strict_incr Int.add x s | Set s1, Set s2 -> let set = Array.fold_left (fun acc i1 -> Array.fold_left (fun acc i2 -> Int.Set.add (Int.add i1 i2) acc) acc s2) Int.Set.empty s1 in set_to_ival_under set | Top(min1,max1,r1,modu1) , Top(min2,max2,r2,modu2) when Int.equal modu1 modu2 -> Note : min1+min2 % modu = max1 + max2 % modu = r1 + r2 % modu ; no need to trim the bounds here . no need to trim the bounds here. *) let r = Int.rem (Int.add r1 r2) modu1 in let min = match min1, min2 with | Some min1, Some min2 -> Some (Int.add min1 min2) | _ -> None in let max = match max1, max2 with | Some max1, Some max2 -> Some (Int.add max1 max2) | _ -> None in inject_top min max r modu1 In many cases , there is no best abstraction ; for instance when divides modu2 , a part of the resulting interval is congruent to , and a larger part is congruent to modu2 . In general , one can take the intersection . In any case , this code should be rarely called . modu1 divides modu2, a part of the resulting interval is congruent to modu1, and a larger part is congruent to modu2. In general, one can take the intersection. In any case, this code should be rarely called. *) | Top _, Top _ -> bottom | Set s, (Top _ as t) | (Top _ as t), Set s -> let l = Array.length s in if l = 0 then bottom else if l = 1 only one element : precise . add_singleton_int s.(0) t else begin log_imprecision "Ival.add_int_under"; add_singleton_int s.(0) t end ;; let neg_int v = match v with | Float _ -> assert false | Set s -> map_set_strict_decr Int.neg s | Top(mn,mx,r,m) -> share_top (opt1 Int.neg mx) (opt1 Int.neg mn) (Int.pos_rem (Int.neg r) m) m let sub_int v1 v2 = add_int v1 (neg_int v2) let sub_int_under v1 v2 = add_int_under v1 (neg_int v2) type ext_value = Ninf | Pinf | Val of Int.t let inject_min = function None -> Ninf | Some m -> Val m let inject_max = function None -> Pinf | Some m -> Val m let ext_neg = function Ninf -> Pinf | Pinf -> Ninf | Val v -> Val (Int.neg v) let ext_mul x y = match x, y with | Ninf, Ninf | Pinf, Pinf -> Pinf | Ninf, Pinf | Pinf, Ninf -> Ninf | Val v1, Val v2 -> Val (Int.mul v1 v2) | x, Val v when (Int.gt v Int.zero) -> x | Val v, x when (Int.gt v Int.zero) -> x | x, Val v when (Int.lt v Int.zero) -> ext_neg x | Val v, x when (Int.lt v Int.zero) -> ext_neg x | _ -> Val Int.zero let ext_min x y = match x,y with Ninf, _ | _, Ninf -> Ninf | Pinf, x | x, Pinf -> x | Val x, Val y -> Val(Int.min x y) let ext_max x y = match x,y with Pinf, _ | _, Pinf -> Pinf | Ninf, x | x, Ninf -> x | Val x, Val y -> Val(Int.max x y) let ext_proj = function Val x -> Some x | _ -> None let min_int s = match s with | Top (min,_,_,_) -> min | Set s -> if Array.length s = 0 then raise Error_Bottom else Some s.(0) | Float _ -> None let max_int s = match s with | Top (_,max,_,_) -> max | Set s -> let l = Array.length s in if l = 0 then raise Error_Bottom else Some s.(pred l) | Float _ -> None exception No_such_element match x with | Set s -> let r = ref None in Array.iter (fun e -> if Int.ge e min then match !r with | Some rr when Int.lt e rr -> r := Some e | None -> r := Some e | _ -> ()) s; begin match !r with None -> raise No_such_element | Some r -> r end | Top(mn,mx,r,modu) -> let some_min = Some min in if not (max_is_greater mx some_min) then raise No_such_element; if min_is_lower some_min mn then Extlib.the mn else Int.round_up_to_r ~min ~r ~modu | Float _ -> raise No_such_element match x with | Float _ -> raise No_such_element | Set s -> let r = ref None in Array.iter (fun e -> if Int.le e max then match !r with | Some rr when Int.gt e rr -> r := Some e | None -> r := Some e | _ -> ()) s; begin match !r with None -> raise No_such_element | Some r -> r end | Top(mn,mx,r,modu) -> let some_max = Some max in if not (min_is_lower mn some_max) then raise No_such_element; if max_is_greater some_max mx then Extlib.the mx else Int.round_down_to_r ~max ~r ~modu Rounds up ( x+1 ) to the next power of two , then substracts one ; optimized . let next_pred_power_of_two x = Unroll the first iterations , and skip the tests . let x = Int.logor x (Int.shift_right x Int.one) in let x = Int.logor x (Int.shift_right x Int.two) in let x = Int.logor x (Int.shift_right x Int.four) in let x = Int.logor x (Int.shift_right x Int.eight) in let x = Int.logor x (Int.shift_right x Int.sixteen) in let shift = Int.thirtytwo in let rec loop old shift = let x = Int.logor old (Int.shift_right old shift) in if Int.equal old x then x else loop x (Int.shift_left shift Int.one) in loop x shift let different_bits min max = let x = Int.logxor min max in next_pred_power_of_two x [ pos_max_land min1 max1 min2 max2 ] computes an upper bound for [ x1 land x2 ] where [ x1 ] is in [ min1] .. [max1 ] and [ x2 ] is in [ min2] .. [max2 ] . Precondition : [ min1 ] , [ max1 ] , [ min2 ] , [ max2 ] must all have the same sign . Note : the algorithm below is optimal for the problem as stated . It is possible to compute this optimal solution faster but it does not seem worth the time necessary to think about it as long as integers are at most 64 - bit . [x1 land x2] where [x1] is in [min1]..[max1] and [x2] is in [min2]..[max2]. Precondition : [min1], [max1], [min2], [max2] must all have the same sign. Note: the algorithm below is optimal for the problem as stated. It is possible to compute this optimal solution faster but it does not seem worth the time necessary to think about it as long as integers are at most 64-bit. *) let pos_max_land min1 max1 min2 max2 = let x1 = different_bits min1 max1 in let x2 = different_bits min2 max2 in let fold_maxs max1 p f acc = let rec aux p acc = let p = Int.shift_right p Int.one in if Int.is_zero p then f max1 acc else if Int.is_zero (Int.logand p max1) then aux p acc else let c = Int.logor (Int.sub max1 p) (Int.pred p) in aux p (f c acc) in aux p acc in let sx1 = Int.succ x1 in let n1 = fold_maxs max1 sx1 (fun _ y -> succ y) 0 in let maxs1 = Array.make n1 sx1 in let _ = fold_maxs max1 sx1 (fun x i -> Array.set maxs1 i x; succ i) 0 in fold_maxs max2 (Int.succ x2) (fun max2 acc -> Array.fold_left (fun acc max1 -> Int.max (Int.logand max1 max2) acc) acc maxs1) (Int.logand max1 max2) let bitwise_or v1 v2 = if is_bottom v1 || is_bottom v2 then bottom else match v1, v2 with | Float _, _ | _, Float _ -> top | Set s1, Set s2 -> apply2_v Int.logor s1 s2 | Set [|s|],(Top _ as v) | (Top _ as v),Set [|s|] when Int.is_zero s -> v | Top _, _ | _, Top _ -> ( match min_and_max v1 with Some mn1, Some mx1 when Int.ge mn1 Int.zero -> ( match min_and_max v2 with Some mn2, Some mx2 when Int.ge mn2 Int.zero -> let new_max = next_pred_power_of_two (Int.logor mx1 mx2) in inject_range (Some new_min) (Some new_max) | _ -> top ) | _ -> top ) let bitwise_xor v1 v2 = if is_bottom v1 || is_bottom v2 then bottom else match v1, v2 with | Float _, _ | _, Float _ -> top | Set s1, Set s2 -> apply2_v Int.logxor s1 s2 | Top _, _ | _, Top _ -> (match min_and_max v1 with | Some mn1, Some mx1 when Int.ge mn1 Int.zero -> (match min_and_max v2 with | Some mn2, Some mx2 when Int.ge mn2 Int.zero -> let new_max = next_pred_power_of_two (Int.logor mx1 mx2) in let new_min = Int.zero in inject_range (Some new_min) (Some new_max) | _ -> top ) | _ -> top ) let contains_non_zero v = not (is_zero v || is_bottom v) TODO : rename this function to let scale f v = if Int.is_zero f then zero else match v with | Float _ -> top | Top(mn1,mx1,r1,m1) -> let incr = Int.mul f in if Int.gt f Int.zero then let modu = incr m1 in share_top (opt1 incr mn1) (opt1 incr mx1) (Int.pos_rem (incr r1) modu) modu else let modu = Int.neg (incr m1) in share_top (opt1 incr mx1) (opt1 incr mn1) (Int.pos_rem (incr r1) modu) modu | Set s -> if Int.ge f Int.zero then apply_bin_1_strict_incr Int.mul f s else apply_bin_1_strict_decr Int.mul f s let scale_div_common ~pos f v degenerate_ival degenerate_float = assert (not (Int.is_zero f)); let div_f = if pos then fun a -> Int.pos_div a f else fun a -> Int.c_div a f in match v with | Top(mn1,mx1,r1,m1) -> let r, modu = let negative = max_is_greater (some_zero) mx1 in && (Int.is_zero (Int.rem m1 f)) then let modu = Int.abs (div_f m1) in let r = if negative then Int.sub r1 m1 else r1 in (Int.pos_rem (div_f r) modu), modu degenerate_ival r1 m1 in let divf_mn1 = opt1 div_f mn1 in let divf_mx1 = opt1 div_f mx1 in let mn, mx = if Int.gt f Int.zero then divf_mn1, divf_mx1 else divf_mx1, divf_mn1 in inject_top mn mx r modu | Set s -> if Int.lt f Int.zero then map_set_decr div_f s else map_set_incr div_f s | Float _ -> degenerate_float let scale_div ~pos f v = scale_div_common ~pos f v (fun _ _ -> Int.zero, Int.one) top ;; let scale_div_under ~pos f v = try TODO : a more precise result could be obtained by transforming Top(min , , r , m ) into Top(min , , r / f , m / gcd(m , f ) ) . But this is more complex to implement when pos or f is negative . Top(min,max,r,m) into Top(min,max,r/f,m/gcd(m,f)). But this is more complex to implement when pos or f is negative. *) scale_div_common ~pos f v (fun _r _m -> raise Exit) bottom with Exit -> bottom ;; let div_set x sy = Array.fold_left (fun acc elt -> if Int.is_zero elt then acc else join acc (scale_div ~pos:false elt x)) bottom sy ymin and ymax must be the same sign let div_range x ymn ymx = match min_and_max x with | Some xmn, Some xmx -> let c1 = Int.c_div xmn ymn in let c2 = Int.c_div xmx ymn in let c3 = Int.c_div xmn ymx in let c4 = Int.c_div xmx ymx in let min = Int.min (Int.min c1 c2) (Int.min c3 c4) in let max = Int.max (Int.max c1 c2) (Int.max c3 c4) in Format.printf " div : % a % a % a % a@. " Int.pretty mn Int.pretty mx Int.pretty xmn Int.pretty xmx ; Int.pretty mn Int.pretty mx Int.pretty xmn Int.pretty xmx; *) inject_range (Some min) (Some max) | _ -> log_imprecision "Ival.div_range"; top let div x y = if ( intersects y negative || intersects x negative ) then ignore ( CilE.warn_once " using ' round towards zero ' semantics for ' / ' , which only became specified in C99 . " ) ; (CilE.warn_once "using 'round towards zero' semantics for '/', which only became specified in C99."); *) match y with Set sy -> div_set x sy | Top (Some mn,Some mx, r, modu) -> let result_pos = if Int.gt mx Int.zero then let lpos = if Int.gt mn Int.zero then mn else Int.round_up_to_r ~min:Int.one ~r ~modu in div_range x lpos mx else bottom in let result_neg = if Int.lt mn Int.zero then let gneg = if Int.lt mx Int.zero then mx else Int.round_down_to_r ~max:Int.minus_one ~r ~modu in div_range x mn gneg else bottom in join result_neg result_pos | Float _ -> assert false | Top (None, _, _, _) | Top (_, None, _, _) -> log_imprecision "Ival.div"; top let scale_rem ~pos f v = if Int.is_zero f then bottom else let f = if Int.lt f Int.zero then Int.neg f else f in let rem_f a = if pos then Int.pos_rem a f else Int.c_rem a f in match v with | Top(mn,mx,r,m) -> let modu = Int.pgcd f m in let rr = Int.pos_rem r modu in let binf,bsup = if pos then (Int.round_up_to_r ~min:Int.zero ~r:rr ~modu), (Int.round_down_to_r ~max:(Int.pred f) ~r:rr ~modu) else let min = if all_positives mn then Int.zero else Int.neg (Int.pred f) in let max = if all_negatives mx then Int.zero else Int.pred f in (Int.round_up_to_r ~min ~r:rr ~modu, Int.round_down_to_r ~max ~r:rr ~modu) in let mn_rem,mx_rem = match mn,mx with | Some mn,Some mx -> let div_f a = if pos then Int.pos_div a f else Int.c_div a f in if Int.equal (div_f mn) (div_f mx) then rem_f mn, rem_f mx else binf,bsup | _ -> binf,bsup in inject_top (Some mn_rem) (Some mx_rem) rr modu | Set s -> map_set_exnsafe rem_f s | Float _ -> top let c_rem x y = match y with | Top (None, _, _, _) | Top (_, None, _, _) | Float _ -> top | Top (Some mn, Some mx, _, _) -> if Int.equal mx Int.zero then else Result is of the sign of x. Also , compute |x| to bound the result let neg, pos, max_x = match x with | Float _ -> true, true, None | Set set -> let s = Array.length set in else Int.le set.(0) Int.minus_one, Int.ge set.(s-1) Int.one, Some (Int.max (Int.abs set.(0)) (Int.abs set.(s-1))) | Top (mn, mx, _, _) -> min_le_elt mn Int.minus_one, max_ge_elt mx Int.one, (match mn, mx with | Some mn, Some mx -> Some (Int.max (Int.abs mn) (Int.abs mx)) | _ -> None) in Bound the result : no more than |x| , and no more than |y|-1 let pos_rem = Integer.max (Int.abs mn) (Int.abs mx) in let bound = Int.pred pos_rem in let bound = Extlib.may_map (Int.min bound) ~dft:bound max_x in let mn = if neg then Some (Int.neg bound) else Some Int.zero in let mx = if pos then Some bound else Some Int.zero in inject_top mn mx Int.zero Int.one | Set yy -> ( match x with Set xx -> apply2_notzero Int.c_rem xx yy | Float _ -> top | Top _ -> let f acc y = join (scale_rem ~pos:false y x) acc in Array.fold_left f bottom yy) module AllValueHashtbl = Hashtbl.Make (struct type t = Int.t * bool * int let equal (a,b,c:t) (d,e,f:t) = b=e && c=f && Int.equal a d let hash (a,b,c:t) = 257 * (Hashtbl.hash b) + 17 * (Hashtbl.hash c) + Int.hash a end) let all_values_table = AllValueHashtbl.create 7 let create_all_values_modu ~modu ~signed ~size = let t = modu, signed, size in try AllValueHashtbl.find all_values_table t with Not_found -> let mn, mx = if signed then let b = Int.two_power_of_int (size-1) in (Int.round_up_to_r ~min:(Int.neg b) ~modu ~r:Int.zero, Int.round_down_to_r ~max:(Int.pred b) ~modu ~r:Int.zero) else let b = Int.two_power_of_int size in Int.zero, Int.round_down_to_r ~max:(Int.pred b) ~modu ~r:Int.zero in let r = inject_top (Some mn) (Some mx) Int.zero modu in AllValueHashtbl.add all_values_table t r; r let create_all_values ~signed ~size = if size <= !small_cardinal_log then create_all_values_modu ~signed ~size ~modu:Int.one else if signed then let b = Int.two_power_of_int (size-1) in Top (Some (Int.neg b), Some (Int.pred b), Int.zero, Int.one) else let b = Int.two_power_of_int size in Top (Some Int.zero, Some (Int.pred b), Int.zero, Int.one) let big_int_64 = Int.of_int 64 let big_int_32 = Int.thirtytwo let cast ~size ~signed ~value = if equal top value then create_all_values ~size:(Int.to_int size) ~signed else let result = let factor = Int.two_power size in let mask = Int.two_power (Int.pred size) in let rem_f value = Int.cast ~size ~signed ~value in let not_p_factor = Int.neg factor in let best_effort r m = let modu = Int.pgcd factor m in let rr = Int.pos_rem r modu in let min_val = Some (if signed then Int.round_up_to_r ~min:(Int.neg mask) ~r:rr ~modu else Int.round_up_to_r ~min:Int.zero ~r:rr ~modu) in let max_val = Some (if signed then Int.round_down_to_r ~max:(Int.pred mask) ~r:rr ~modu else Int.round_down_to_r ~max:(Int.pred factor) ~r:rr ~modu) in inject_top min_val max_val rr modu in match value with | Top(Some mn,Some mx,r,m) -> let highbits_mn,highbits_mx = if signed then Int.logand (Int.add mn mask) not_p_factor, Int.logand (Int.add mx mask) not_p_factor else Int.logand mn not_p_factor, Int.logand mx not_p_factor in if Int.equal highbits_mn highbits_mx then if Int.is_zero highbits_mn then value else let new_min = rem_f mn in let new_r = Int.pos_rem new_min m in inject_top (Some new_min) (Some (rem_f mx)) new_r m else best_effort r m | Top (_,_,r,m) -> best_effort r m | Set s -> begin let all = create_all_values ~size:(Int.to_int size) ~signed in if is_included value all then value else map_set_exnsafe rem_f s end | Float f -> let low, high = if Int.equal size big_int_64 then let l, h = Fval.bits_of_float64 ~signed f in Some l, Some h else if Int.equal size big_int_32 then let l, h = Fval.bits_of_float32 ~signed f in Some l, Some h else None, None in inject_range low high in " Cast with size:%d signed:%b to % a@\n " size signed pretty result ; size signed pretty result; *) if equal result value then value else result let cast_float ~rounding_mode v = match v with | Float f -> ( try let b, f = Fval.round_to_single_precision_float ~rounding_mode f in b, inject_float f with Fval.Non_finite -> true, bottom) | Set _ when is_zero v -> false, zero | Set _ | Top _ -> true, top_single_precision_float let cast_double v = match v with | Float _ -> false, v | Set _ when is_zero v -> false, v | Set _ | Top _ -> true, top_float TODO rename to mul_int let rec mul v1 v2 = " . : ' % a ' ' % a'@\n " pretty v1 pretty v2 ; let result = if is_one v1 then v2 else if is_zero v2 || is_zero v1 then zero else if is_one v2 then v1 else match v1,v2 with | Float _, _ | _, Float _ -> top | Set s1, Set [| x |] | Set [| x |], Set s1 -> if Int.ge x Int.zero then apply_bin_1_strict_incr Int.mul x s1 else apply_bin_1_strict_decr Int.mul x s1 | Set s1, Set s2 -> apply2_n Int.mul s1 s2 | Top(mn1,mx1,r1,m1), Top(mn2,mx2,r2,m2) -> check mn1 mx1 r1 m1; check mn2 mx2 r2 m2; let mn1 = inject_min mn1 in let mx1 = inject_max mx1 in let mn2 = inject_min mn2 in let mx2 = inject_max mx2 in let a = ext_mul mn1 mn2 in let b = ext_mul mn1 mx2 in let c = ext_mul mx1 mn2 in let d = ext_mul mx1 mx2 in let min = ext_min (ext_min a b) (ext_min c d) in let max = ext_max (ext_max a b) (ext_max c d) in let multipl1 = Int.pgcd m1 r1 in let = Int.pgcd m2 r2 in let = Int.pgcd in let modu2 = in let modu = Int.ppcm in let multipl2 = Int.pgcd m2 r2 in let modu1 = Int.pgcd m1 m2 in let modu2 = Int.mul multipl1 multipl2 in let modu = Int.ppcm modu1 modu2 in *) let modu = Int.pgcd (Int.pgcd (Int.mul m1 m2) (Int.mul r1 m2)) (Int.mul r2 m1) in let r = Int.rem (Int.mul r1 r2) modu in let t = Top ( ext_proj min , ext_proj max , r , modu ) in " . Result : ' % a'@\n " pretty t ; Format.printf "mul. Result: '%a'@\n" pretty t; *) inject_top (ext_proj min) (ext_proj max) r modu | Set s, (Top(_,_,_,_) as t) | (Top(_,_,_,_) as t), Set s -> let l = Array.length s in if l = 0 then bottom else if l = 1 only one element scale s.(0) t else mul t (unsafe_make_top_from_array s) in Format.printf " . result : % a@\n " pretty result ; result * Computes [ x ( op ) ( { y > = 0 } * 2^n ) ] , as an auxiliary function for [ shift_left ] and [ shift_right ] . [ op ] and [ scale ] must verify [ scale a b = = op ( inject_singleton a ) b ] [shift_left] and [shift_right]. [op] and [scale] must verify [scale a b == op (inject_singleton a) b] *) let shift_aux scale op (x: t) (y: t) = let y = narrow (inject_range (Some Int.zero) None) y in try match y with | Set s -> Array.fold_left (fun acc n -> join acc (scale (Int.two_power n) x)) bottom s | _ -> let min_factor = Extlib.opt_map Int.two_power (min_int y) in let max_factor = Extlib.opt_map Int.two_power (max_int y) in let modu = match min_factor with None -> Int.one | Some m -> m in let factor = inject_top min_factor max_factor Int.zero modu in op x factor with Integer.Too_big -> Lattice_messages.emit_imprecision emitter "Ival.shift_aux"; if is_included x positive_integers then positive_integers else if is_included x negative_integers then negative_integers else top let shift_right x y = shift_aux (scale_div ~pos:true) div x y let shift_left x y = shift_aux scale mul x y let interp_boolean ~contains_zero ~contains_non_zero = match contains_zero, contains_non_zero with | true, true -> zero_or_one | true, false -> zero | false, true -> one | false, false -> bottom let backward_le_int max v = match v with | Float _ -> v | Set _ | Top _ -> narrow v (Top(None,max,Int.zero,Int.one)) let backward_ge_int min v = match v with | Float _ -> v | Set _ | Top _ -> narrow v (Top(min,None,Int.zero,Int.one)) let backward_lt_int max v = backward_le_int (opt1 Int.pred max) v let backward_gt_int min v = backward_ge_int (opt1 Int.succ min) v let diff_if_one value rem = match rem, value with | Set [| v |], Set a -> let index = array_mem v a in if index >= 0 then let l = Array.length a in let pl = pred l in let r = Array.make pl Int.zero in Array.blit a 0 r 0 index; Array.blit a (succ index) r index (pl-index); share_array r pl else value | Set [| v |], Top (Some mn, mx, r, m) when Int.equal v mn -> inject_top (Some (Int.add mn m)) mx r m | Set [| v |], Top (mn, Some mx, r, m) when Int.equal v mx -> inject_top mn (Some (Int.sub mx m)) r m | Set [| v |], Top ((Some mn as min), (Some mx as max), r, m) when Int.equal (Int.sub mx mn) (Int.mul m !small_cardinal_Int) && in_interval v min max r m -> let r = ref mn in Set (Array.init !small_cardinal (fun _ -> let c = !r in let corrected_c = if Int.equal c v then Int.add c m else c in r := Int.add corrected_c m; corrected_c)) let diff value rem = log_imprecision "Ival.diff"; diff_if_one value rem let backward_comp_int_left op l r = let open Comp in try match op with | Le -> backward_le_int (max_int r) l | Ge -> backward_ge_int (min_int r) l | Lt -> backward_lt_int (max_int r) l | Gt -> backward_gt_int (min_int r) l | Eq -> narrow l r | Ne -> diff_if_one l r let backward_comp_float_left op allmodes fkind f1 f2 = try let f1 = project_float f1 in let f2 = project_float f2 in begin match Fval.backward_comp_left op allmodes fkind f1 f2 with | `Value f -> inject_float f | `Bottom -> bottom end with let rec extract_bits ~start ~stop ~size v = match v with | Set s -> inject_ps (Array.fold_left (fun acc elt -> add_ps acc (Int.extract_bits ~start ~stop elt)) empty_ps s) | Float f -> let l, u = if Int.equal size big_int_64 then Fval.bits_of_float64 ~signed:true f else Fval.bits_of_float32 ~signed:true f in extract_bits ~start ~stop ~size (inject_range (Some l) (Some u)) | Top(_,_,_,_) as d -> try let dived = scale_div ~pos:true (Int.two_power start) d in scale_rem ~pos:true (Int.two_power (Int.length start stop)) dived with Integer.Too_big -> Lattice_messages.emit_imprecision emitter "Ival.extract_bits"; top ;; let all_values ~size v = if Int.lt big_int_64 size then false else match v with | Float _ -> false | Top (None,_,_,modu) | Top (_,None,_,modu) -> Int.is_one modu | Top (Some mn, Some mx,_,modu) -> Int.is_one modu && Int.le (Int.two_power size) (Int.length mn mx) | Set s -> let siz = Int.to_int size in Array.length s >= 1 lsl siz && equal (cast ~size ~signed:false ~value:v) (create_all_values ~size:siz ~signed:false) let compare_min_max min max = match min, max with | None,_ -> -1 | _,None -> -1 | Some min, Some max -> Int.compare min max let compare_max_min max min = match max, min with | None,_ -> 1 | _,None -> 1 | Some max, Some min -> Int.compare max min let forward_le_int i1 i2 = if compare_max_min (max_int i1) (min_int i2) <= 0 then Comp.True else if compare_min_max (min_int i1) (max_int i2) > 0 then Comp.False else Comp.Unknown let forward_lt_int i1 i2 = if compare_max_min (max_int i1) (min_int i2) < 0 then Comp.True else if compare_min_max (min_int i1) (max_int i2) >= 0 then Comp.False else Comp.Unknown let forward_eq_int i1 i2 = if cardinal_zero_or_one i1 && equal i1 i2 then Comp.True else if intersects i2 i2 then Comp.Unknown else Comp.False let forward_comp_int op i1 i2 = let open Abstract_interp.Comp in match op with | Le -> forward_le_int i1 i2 | Ge -> forward_le_int i2 i1 | Lt -> forward_lt_int i1 i2 | Gt -> forward_lt_int i2 i1 | Eq -> forward_eq_int i1 i2 | Ne -> inv_result (forward_eq_int i1 i2) include ( Datatype.Make_with_collections (struct type ival = t type t = ival let name = Int.name ^ " lattice_mod" open Structural_descr let structural_descr = let s_int = Descr.str Int.descr in t_sum [| [| pack (t_array s_int) |]; [| Fval.packed_descr |]; [| pack (t_option s_int); pack (t_option s_int); Int.packed_descr; Int.packed_descr |] |] let reprs = [ top ; bottom ] let equal = equal let compare = compare let hash = hash let pretty = pretty let rehash x = match x with | Set a -> share_array a (Array.length a) | _ -> x let internal_pretty_code = Datatype.pp_fail let mem_project = Datatype.never_any_project let copy = Datatype.undefined let varname = Datatype.undefined end): Datatype.S_with_collections with type t := t) let scale_int_base factor v = match factor with | Int_Base.Top -> top | Int_Base.Value f -> scale f v type overflow_float_to_int = let cast_float_to_int ~signed ~size iv = let all = create_all_values ~size ~signed in let min_all = Extlib.the (min_int all) in let max_all = Extlib.the (max_int all) in try let min, max = Fval.min_and_max (project_float iv) in let conv f = try truncate_to_integer returns an integer that fits in a 64 bits integer , but might not fit in [ size , sized ] integer, but might not fit in [size, sized] *) let i = Floating_point.truncate_to_integer f in if Int.ge i min_all then if Int.le i max_all then FtI_Ok i else FtI_Overflow Floating_point.Pos else FtI_Overflow Floating_point.Neg with Floating_point.Float_Non_representable_as_Int64 sign -> FtI_Overflow sign in let min_int = conv (Fval.F.to_float min) in let max_int = conv (Fval.F.to_float max) in match min_int, max_int with false, (false, false), inject_range (Some min_int) (Some max_int) one overflow false, (true, false), inject_range (Some min_all) (Some max_int) one overflow false, (false, true), inject_range (Some min_int) (Some max_all) two overflows | FtI_Overflow Floating_point.Neg, FtI_Overflow Floating_point.Pos -> false, (true, true), inject_range (Some min_all) (Some max_all) | FtI_Overflow Floating_point.Pos, FtI_Overflow Floating_point.Pos -> false, (false, true), bottom | FtI_Overflow Floating_point.Neg, FtI_Overflow Floating_point.Neg -> false, (true, false), bottom | FtI_Overflow Floating_point.Pos, FtI_Overflow Floating_point.Neg | FtI_Overflow Floating_point.Pos, FtI_Ok _ | FtI_Ok _, FtI_Overflow Floating_point.Neg -> with true, (true, true), all These are the bounds of the range of integers that can be represented exactly as 64 bits double values exactly as 64 bits double values *) let double_min_exact_integer = Int.neg (Int.two_power_of_int 53) let double_max_exact_integer = Int.two_power_of_int 53 same with 32 bits single values let single_min_exact_integer = Int.neg (Int.two_power_of_int 24) let single_max_exact_integer = Int.two_power_of_int 24 let double_min_exact_integer_d = -. (2. ** 53.) let double_max_exact_integer_d = 2. ** 53. let single_min_exact_integer_d = -. (2. ** 24.) let single_max_exact_integer_d = 2. ** 24. let cast_float_to_int_inverse ~single_precision i = let exact_min, exact_max = if single_precision then single_min_exact_integer, single_max_exact_integer else double_min_exact_integer, double_max_exact_integer in match min_and_max i with | Some min, Some max when Int.lt exact_min min && Int.lt max exact_max -> let minf = if Int.le min Int.zero then min is negative . We want to return [ ( float)((real)(min-1)+epsilon ) ] , as converting this number to int will truncate all the fractional part ( C99 6.3.1.4 ) . Given [ exact_min ] and [ exact_max ] , 1ulp is at most 1 here , so adding will at most cancel the -1 . Hence , we can use [ next_float ] . as converting this number to int will truncate all the fractional part (C99 6.3.1.4). Given [exact_min] and [exact_max], 1ulp is at most 1 here, so adding 1ulp will at most cancel the -1. Hence, we can use [next_float]. *) let r = Fval.F.next_float (Int.to_float (Int.pred min)) in if single_precision then begin Floating_point.set_round_upward (); let r = Floating_point.round_to_single_precision_float r in Floating_point.set_round_nearest_even (); r; end else r Int.to_float min in let maxf = if Int.le Int.zero max then This float is finite because is big enough let r = Fval.F.prev_float (Int.to_float (Int.succ max)) in if single_precision then begin Floating_point.set_round_downward (); let r = Floating_point.round_to_single_precision_float r in Floating_point.set_round_nearest_even (); r; end else r else Int.to_float max in Float (Fval.inject (Fval.F.of_float minf) (Fval.F.of_float maxf)) | _ -> if single_precision then top_single_precision_float else top_float let cast_int_to_float_inverse ~single_precision f = let exact_min, exact_max = if single_precision then single_min_exact_integer_d, single_max_exact_integer_d else double_min_exact_integer_d, double_max_exact_integer_d in let min, max = min_and_max_float f in let min = Fval.F.to_float min in let max = Fval.F.to_float max in if exact_min <= min && max <= exact_max then let min = ceil min in let max = floor max in let conv f = try Some (Integer.of_float f) with Integer.Too_big -> None in let r = inject_range (conv min) (conv max) in Kernel.result " Cast : % a - > % a@. " pretty f pretty r ; r let of_int i = inject_singleton (Int.of_int i) let of_int64 i = inject_singleton (Int.of_int64 i) This function always succeeds without alarms for C integers , because they always fit within a float32 . always fit within a float32. *) let cast_int_to_float rounding_mode v = match min_and_max v with | Some min, Some max -> let b = Int.to_float min in let e = Int.to_float max in Note that conversion from integer to float in modes other than round - to - nearest is unavailable when using Big_int and Linux because 1- Big_int implements the conversion to float with a conversion from the integer to a decimal representation ( ! ) followed by strtod ( ) 2- Linux does not honor the FPU direction flag in strtod ( ) , as it arguably should round-to-nearest is unavailable when using Big_int and Linux because 1- Big_int implements the conversion to float with a conversion from the integer to a decimal representation (!) followed by strtod() 2- Linux does not honor the FPU direction flag in strtod(), as it arguably should *) let b', e' = if rounding_mode = Fval.Nearest_Even || (Int.le double_min_exact_integer min && Int.le max double_max_exact_integer) then b, e else Fval.F.prev_float b, Fval.F.next_float e in let ok, f = Fval.inject_r (Fval.F.of_float b') (Fval.F.of_float e') in not ok, inject_float f exception Unforceable let force_float kind i = match i with | Float _ -> false, i | Set _ when is_zero i -> false, i | Set _ when is_bottom i -> true, i | Top _ | Set _ -> Convert a range of integers to a range of floats . Float are ordered this way : if [ min_i ] , [ max_i ] are the bounds of the signed integer type that has the same number of bits as the floating point type , and [ min_f ] [ max_f ] are the integer representation of the most negative and most positive finite float of the type , and < is signed integer comparison , we have : min_i < min_f+1 < -1 < 0 < max_f < max_f+1 < max_i | | | | | | | | --finite-- -not finite- -finite- -not finite- | | |<--------- > | | |<--------- > -0 . -max + inf NaNs +0 . max + inf NaNs The float are of the same sign as the integer they convert into . Furthermore , the conversion function is increasing on the positive interval , and decreasing on the negative one . way : if [min_i], [max_i] are the bounds of the signed integer type that has the same number of bits as the floating point type, and [min_f] [max_f] are the integer representation of the most negative and most positive finite float of the type, and < is signed integer comparison, we have: min_i < min_f < min_f+1 < -1 < 0 < max_f < max_f+1 < max_i | | | | | | | | --finite-- -not finite- -finite- -not finite- | | |<---------> | | |<---------> -0. -max +inf NaNs +0. max +inf NaNs The float are of the same sign as the integer they convert into. Furthermore, the conversion function is increasing on the positive interval, and decreasing on the negative one. *) let reinterpret size conv min_f max_f = let i = cast ~size:(Integer.of_int size) ~signed:true ~value:i in match min_and_max i with | Some mn, Some mx -> let range mn mx = let red, fa = Fval.inject_r mn mx in assert (not red); inject_float fa in if Int.le Int.zero mn && Int.le mx max_f then range (conv mn) (conv mx) else if Int.le mx min_f then range (conv mx) (conv mn) else begin match i with | Set a -> let s = ref F_Set.empty in for i = 0 to Array.length a - 1 do if (Int.le Int.zero a.(i) && Int.le a.(i) max_f) || Int.le a.(i) min_f else raise Unforceable done; let mn, mx = F_Set.min_elt !s, F_Set.max_elt !s in range mn mx | _ -> raise Unforceable end | _, _ -> raise Unforceable in let open Floating_point in match kind with | Cil_types.FDouble -> begin let conv v = Fval.F.of_float (Int64.float_of_bits (Int.to_int64 v)) in try false, reinterpret 64 conv bits_of_most_negative_double bits_of_max_double with Unforceable -> true, top_float end | Cil_types.FFloat -> begin let conv v = Fval.F.of_float (Int32.float_of_bits (Int64.to_int32 (Int.to_int64 v))) in try false, reinterpret 32 conv bits_of_most_negative_float bits_of_max_float with Unforceable -> true, top_single_precision_float end | Cil_types.FLongDouble -> true, top_float let set_bits mn mx = match mn, mx with Some mn, Some mx -> Int.logand (Int.lognot (different_bits mn mx)) mn | _ -> Int.zero let popcnt = Int.popcount x in let rec aux cursor acc = if Int.gt cursor x then acc else let acc = if Int.is_zero (Int.logand cursor x) then acc else O.fold (fun e acc -> O.add (Int.logor cursor e) acc) acc acc in aux (Int.shift_left cursor Int.one) acc in let o = aux Int.one o_zero in let s = 1 lsl popcnt in inject_ps (Pre_set (o, s)) let bitwise_and_intervals ~size ~signed v1 v2 = let max_int_v1, max_int_v2 as max_int_v1_v2 = max_int v1, max_int v2 in let min_int_v1, min_int_v2 as min_int_v1_v2 = min_int v1, min_int v2 in let half_range = Int.two_power_of_int (pred size) in let minint = Int.neg half_range in let vmax = match max_int_v1_v2 with | Some maxv1, Some maxv2 -> if Int.lt maxv1 Int.zero && Int.lt maxv2 Int.zero then begin Some (match min_int_v1_v2 with Some minv1, Some minv2 -> pos_max_land minv1 maxv1 minv2 maxv2 | _ -> assert false) end else improved min of and maxv2 try let bi1 = smallest_above Int.zero v1 in let bi2 = smallest_above Int.zero v2 in pos_max_land bi1 maxv1 bi2 maxv2 with No_such_element -> minint in improved min of and altmax2 try let altmax2 = Int.add half_range (largest_below Int.minus_one v2) in let bi1 = smallest_above Int.zero v1 in let bi2 = Int.add half_range (smallest_above minint v2) in pos_max_land bi1 maxv1 bi2 altmax2 with No_such_element -> minint in improved min of maxv2 and try let altmax1 = Int.add half_range (largest_below Int.minus_one v1) in let bi2 = smallest_above Int.zero v2 in let bi1 = Int.add half_range (smallest_above minint v1) in pos_max_land bi2 maxv2 bi1 altmax1 with No_such_element -> minint in Format.printf " bitwise_and v1 % a v2 % a % a maxv2 % a \ max1 max2 max3 % a % a % a@. " pretty v1 pretty v2 Int.pretty Int.pretty maxv2 Int.pretty max1 Int.pretty max2 Int.pretty max3 ; max1 max2 max3 %a %a %a@." pretty v1 pretty v2 Int.pretty maxv1 Int.pretty maxv2 Int.pretty max1 Int.pretty max2 Int.pretty max3; *) Some (Int.max max1 (Int.max max2 max3)) | _ -> None in let somenegativev1 = intersects v1 strictly_negative_integers in let somenegativev2 = intersects v2 strictly_negative_integers in let vmin = if somenegativev1 && somenegativev2 then Some minint else if somenegativev1 || somenegativev2 then some_zero else begin let bits1 = set_bits min_int_v1 max_int_v1 in let bits2 = set_bits min_int_v2 max_int_v2 in let min_a = Int.logand bits1 bits2 in let min_a = if not signed then let rec find_mask x bit acc = if Int.is_zero (Int.logand x bit) then acc else find_mask x (Int.shift_right bit Int.one) (Int.logor bit acc) in match min_int_v1_v2 with Some m1, Some m2 -> let mask1 = find_mask bits1 half_range Int.zero in let min_b = Int.logand mask1 m2 in let mask2 = find_mask bits2 half_range Int.zero in let min_c = Int.logand mask2 m1 in Int.max (Int.max min_a min_b) min_c | _ -> assert false else min_a in Format.printf " bitwise_and v1 % a v2 % a bits1 % a bits2 % a@. " pretty v1 pretty v2 Int.pretty bits1 Int.pretty bits2 ; pretty v1 pretty v2 Int.pretty bits1 Int.pretty bits2; *) Some min_a end in vmin, vmax let common_low_bits ~size v = match v with | Float _ -> assert false | Top(_,_,r,m) -> if Int.is_zero (Int.logand m (Int.pred m)) m is a power of two r, Int.pred m TODO | Set [| v |] -> v, Int.pred (Int.two_power_of_int size) TODO let bitwise_and ~size ~signed v1 v2 = if is_bottom v1 || is_bottom v2 then bottom else let v1 = match v1 with | Float _ -> create_all_values ~size ~signed | _ -> v1 in let v2 = match v2 with | Float _ -> create_all_values ~size ~signed | _ -> v2 in match v1, v2 with | Float _, _ | _, Float _ -> assert false | Set s1, Set s2 -> apply2_v Int.logand s1 s2 | Top _, other | other, Top _ -> let min, max = bitwise_and_intervals ~signed ~size v1 v2 in let lower_bits1, mask1 = common_low_bits ~size v1 in let lower_bits2, mask2 = common_low_bits ~size v2 in let mask = Int.logand mask1 mask2 in let modu = Int.succ mask in let r = Int.logand lower_bits1 (Int.logand lower_bits2 mask) in let min = match min with | Some min -> Some (Int.round_up_to_r ~min ~r ~modu) | _ -> min in let max = match max with | Some max -> Some (Int.round_down_to_r ~max ~r ~modu) | _ -> max in let result = inject_top min max r modu in ( match other with Top _ | Float _ -> result | Set s -> if array_for_all (fun elt -> Int.ge elt Int.zero && Int.popcount elt <= !small_cardinal_log) s then let result2 = Array.fold_left (fun acc elt -> join (sub_bits elt) acc) bottom s in narrow result result2 else result) let pretty_debug = pretty let name = "ival"
356a63269fe48a370c661df651af8dcfe0c60fe2642dd5524561ecfcfdd85960
typelead/eta
tc061.hs
module ShouldSucceed where class Eq1 a where deq :: a -> a -> Bool instance (Eq1 a) => Eq1 [a] where deq (a:as) (b:bs) = deq a b instance Eq1 Int where deq x y = True
null
https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/tc061.hs
haskell
module ShouldSucceed where class Eq1 a where deq :: a -> a -> Bool instance (Eq1 a) => Eq1 [a] where deq (a:as) (b:bs) = deq a b instance Eq1 Int where deq x y = True
bebcc086ee761a9f2e93a07936e8c20c8488f7e931b0d8f92049bc07f83602e1
lisp-mirror/cl-tar
extract.lisp
;;;; This is part of cl-tar. See README.md and LICENSE for more information. (in-package #:tar-extract) (defvar *deferred-links*) (defvar *deferred-directories*) #+tar-extract-use-openat (defvar *destination-dir-fd*) ;;; Directory permissions #+tar-extract-use-openat (defun handle-deferred-directory (entry pn &key touch no-same-owner numeric-uid mask) (with-fd (fd (fd (openat *destination-dir-fd* pn (logior nix:s-irusr nix:s-iwusr nix:s-ixusr)))) (unless touch (set-utimes entry :fd fd)) (set-permissions entry mask :fd fd) (unless no-same-owner (set-owner entry numeric-uid :fd fd)))) #-tar-extract-use-openat (defun handle-deferred-directory (entry pn &key touch no-same-owner numeric-uid mask) (set-permissions entry mask :pn pn)) ;;; Symbolic links (defun link-target-exists-p (pair) (let ((entry (first pair)) (pn (second pair)) (type (third pair))) (probe-file (merge-pathnames (tar:linkname entry) (if (eql type :hard) *default-pathname-defaults* (merge-pathnames pn)))))) (defun process-deferred-links-1 (deferred-links if-exists if-newer-exists) (let ((actionable-links (remove-if-not 'link-target-exists-p deferred-links))) (dolist (actionable-link actionable-links) (destructuring-bind (entry pn type) actionable-link (let ((pn (merge-pathnames pn))) (unless (null (probe-file pn)) (let ((file-write-date (file-write-date pn))) (when (and (not (null file-write-date)) (> file-write-date (local-time:timestamp-to-universal (tar:mtime entry)))) (setf if-exists if-newer-exists)))) (when (eql if-exists :keep) (setf if-exists nil)) (with-open-file (s pn :direction :output :element-type '(unsigned-byte 8) :if-exists if-exists) (unless (null s) (with-open-file (source (merge-pathnames (tar:linkname entry) (if (eql type :hard) *default-pathname-defaults* pn)) :element-type '(unsigned-byte 8)) (uiop:copy-stream-to-stream source s :element-type '(unsigned-byte 8)))))))) (set-difference deferred-links actionable-links))) (defun process-deferred-links (deferred-links if-exists if-newer-exists) (loop :for prev-links := deferred-links :then links :for links := (process-deferred-links-1 prev-links if-exists if-newer-exists) :while links :when (= (length links) (length prev-links)) :do (restart-case (error 'broken-or-circular-links-error) (continue () (return))))) ;;; Extracting entries (defgeneric extract-entry (entry pn &key mask numeric-uid no-same-owner touch keep-directory-metadata)) (defmethod extract-entry ((entry tar:file-entry) pn &key touch no-same-owner numeric-uid mask &allow-other-keys) #+windows (declare (ignore no-same-owner numeric-uid)) (with-open-stream (stream #+tar-extract-use-openat (openat *destination-dir-fd* pn (logior nix:s-irusr nix:s-iwusr)) #-tar-extract-use-openat (my-open pn (logior nix:s-irusr nix:s-iwusr))) (uiop:copy-stream-to-stream (tar:make-entry-stream entry) stream :element-type '(unsigned-byte 8)) (unless touch (set-utimes entry :fd (fd stream))) (set-permissions entry mask :fd (fd stream) :pn pn) #-windows (unless no-same-owner (set-owner entry numeric-uid :fd (fd stream))))) (defmethod extract-entry ((entry tar:directory-entry) pn &key keep-directory-metadata &allow-other-keys) #+tar-extract-use-openat (with-fd (dirfd (fd (openat *destination-dir-fd* pn (logior nix:s-irusr nix:s-iwusr nix:s-ixusr)))) (declare (ignore dirfd)) Enqueue this to later set its properties . (unless keep-directory-metadata (push (cons entry pn) *deferred-directories*))) #-tar-extract-use-openat (progn (ensure-directories-exist (merge-pathnames pn)) (unless keep-directory-metadata (push (cons entry pn) *deferred-directories*)))) (defmethod extract-entry ((entry tar:symbolic-link-entry) pn &key touch no-same-owner numeric-uid &allow-other-keys) #+windows (declare (ignore touch no-same-owner numeric-uid)) (restart-case (error 'extract-symbolic-link-entry-error) #-windows (extract-link () (let ((dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu)))) (with-fd (dir-fd) (nix:symlinkat (tar:linkname entry) dir-fd (file-namestring pn)) ;; There's no great portable to get a file descriptor for a symlink, ;; so we have to change utimes and owner by pathname. (unless touch (set-utimes entry :dirfd dir-fd :pn (file-namestring pn))) (unless no-same-owner (set-owner entry numeric-uid :dirfd dir-fd :pn (file-namestring pn)))))) (dereference-link () (push (list entry pn :symbolic) *deferred-links*)))) (defmethod extract-entry ((entry tar:hard-link-entry) pn &key &allow-other-keys) (restart-case (error 'extract-hard-link-entry-error) #-windows (extract-link () (let ((destination-pn (uiop:parse-unix-namestring (tar:linkname entry) :dot-dot :back))) (with-fd (dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu))) (with-fd (destination-dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname destination-pn) nix:s-irwxu))) (nix:linkat destination-dir-fd (file-namestring destination-pn) dir-fd (file-namestring pn) 0))))) (dereference-link () (push (list entry pn :hard) *deferred-links*)))) (defmethod extract-entry ((entry tar:fifo-entry) pn &key mask touch no-same-owner numeric-uid &allow-other-keys) #+windows (declare (ignore mask touch no-same-owner numeric-uid)) (restart-case (error 'extract-fifo-entry-error) #-windows (extract-fifo () (let ((dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu)))) (with-fd (dir-fd) #+tar-extract-use-mkfifoat (nix:mkfifoat dir-fd (file-namestring pn) (tar::permissions-to-mode (set-difference (tar:mode entry) mask))) #-tar-extract-use-mkfifoat (nix:mkfifo (merge-pathnames pn) (tar::permissions-to-mode (set-difference (tar:mode entry) mask))) (with-fd (fifo-fd (nix:openat dir-fd (file-namestring pn) (logior nix:o-rdonly nix:o-nofollow nix:o-nonblock))) (unless touch (set-utimes entry :fd fifo-fd)) (set-permissions entry mask :fd fifo-fd) (unless no-same-owner (set-owner entry numeric-uid :fd fifo-fd)))))))) (defmethod extract-entry ((entry tar:block-device-entry) pn &key touch no-same-owner numeric-uid mask &allow-other-keys) #+windows (declare (ignore touch no-same-owner numeric-uid mask)) (restart-case (error 'extract-block-device-entry-error :entry entry) #-windows (extract-device () (let ((dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu)))) (with-fd (dir-fd) (nix:mknodat dir-fd (file-namestring pn) (logior nix:s-ifblk (tar::permissions-to-mode (tar:mode entry))) (nix:makedev (tar:devmajor entry) (tar:devminor entry))) (with-fd (dev-fd (nix:openat dir-fd (file-namestring pn) (logior nix:o-rdonly nix:o-nofollow nix:o-nonblock))) (unless touch (set-utimes entry :fd dev-fd)) (set-permissions entry mask :fd dev-fd) (unless no-same-owner (set-owner entry numeric-uid :fd dev-fd)))))))) (defmethod extract-entry ((entry tar:character-device-entry) pn &key touch no-same-owner numeric-uid mask &allow-other-keys) #+windows (declare (ignore touch no-same-owner numeric-uid mask)) (restart-case (error 'extract-character-device-entry-error :entry entry) #-windows (extract-device () (let ((dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu)))) (with-fd (dir-fd) (nix:mknodat dir-fd (file-namestring pn) (logior nix:s-ifchr (tar::permissions-to-mode (tar:mode entry))) (nix:makedev (tar:devmajor entry) (tar:devminor entry))) (with-fd (dev-fd (nix:openat dir-fd (file-namestring pn) (logior nix:o-rdonly nix:o-nofollow nix:o-nonblock))) (unless touch (set-utimes entry :fd dev-fd)) (set-permissions entry mask :fd dev-fd) (unless no-same-owner (set-owner entry numeric-uid :fd dev-fd)))))))) ;;; Extract archive (defun extract-archive (archive &key (directory *default-pathname-defaults*) (absolute-pathnames :error) (device-pathnames :error) (dot-dot :error) (strip-components 0) (if-exists :error) (if-newer-exists :error) (if-symbolic-link-exists :error) (if-directory-symbolic-link-exists :error) keep-directory-metadata touch (no-same-owner #+:windows t #-windows (rootp)) numeric-uid mask (symbolic-links #-windows t #+windows :dereference) (hard-links #-windows t #+windows :dereference) (character-devices #-windows (if (rootp) t :error) #+windows :error) (block-devices #-windows (if (rootp) t :error) #+windows :error) (fifos #-windows t #+windows :error) (filter (constantly t))) "Extract all entries in ARCHIVE to DIRECTORY. DIRECTORY defaults to *DEFAULT-PATHNAME-DEFAULTS* and must be a directory pathname. The following options configure how the final pathname of each entry is computed: ABSOLUTE-PATHANMES controls what happens when an entry is discovered that has an absolute pathname. It defaults to :ERROR. The possible values are: + :ALLOW : Allow the pathname as is. + :SKIP : Silently skip the entry. + :RELATIVIZE : Strip the leading / and treat it as a relative pathname. + :ERROR : Signal an ENTRY-NAME-IS-ABSOLUTE-ERROR, with the restarts CONTINUE, SKIP-ENTRY, and RELATIVIZE-ENTRY-NAME active. DEVICE-PATHNAMES controls what happens when an entry is discovered that has a non-NIL device. It defaults to :ERROR. The possible values are: + :ALLOW : Allow the pathname as is. + :SKIP : Silently skip the entry. + :RELATIVIZE : Strip the device. + :ERROR : Signal an ENTRY-NAME-CONTAINS-DEVICE-ERROR, with the restarts CONTINUE, SKIP-ENTRY, and RELATIVIZE-ENTRY-NAME active. DOT-DOT controls what happens when an entry is discovered that has a name containing .. in a directory component. It defaults to :ERROR. The possible values are: + :BACK : Allow the pathname as is, treating .. as :BACK. + :SKIP : Silently skip the entry. + :ERROR : Signal an ENTRY-NAME-CONTAINS-..-ERROR, with the restarts TREAT-..-AS-BACK and SKIP-ENTRY active. STRIP-COMPONENTS is an integer specifying how many directory and file components to strip. Defaults to 0. The following options configure what happens to files that already exist on the filesystem. IF-DIRECTORY-SYMBOLIC-LINK-EXISTS controls what happens to existing directories that are symlinks. This includes any symlink on the destination path of the entry. Defaults to :ERROR. The possible values are: + :ERROR : Signal a EXTRACTION-THROUGH-SYMBOLIC-LINK-ERROR with the restarts FOLLOW-SYMBOLIC-LINK, REPLACE-SYMBOLIC-LINK, and SKIP-ENTRY active. + NIL, :SKIP : Skip the entry. + :SUPERSEDE : replace the symlink with a new, empty directory. + :FOLLOW : keep the existing symlink. IF-SYMBOLIC-LINK-EXISTS controls what happesn to existing files that are symlinks. Defaults to :ERROR. The possible values are: + :ERROR : Signal a EXTRACTION-THROUGH-SYMBOLIC-LINK-ERROR with the restarts FOLLOW-SYMBOLIC-LINK, REPLACE-SYMBOLIC-LINK, and SKIP-ENTRY active. + NIL, :SKIP : Skip the entry. + :FOLLOW : Follow the symlink and write the contents of the entry, respecting IF-NEWER-EXISTS and IF-EXISTS. + :SUPERSEDE : Replace the symlink. IF-NEWER-EXISTS controls what happens to files that already exist within DIRECTORY if extracting ARCHIVE would overwrite them and the existing file has a more recent mtime. It defaults to :ERROR. The possible values are: + :ERROR : A DESTINATION-EXISTS-ERROR is signaled, with the restarts SUPERSEDE-FILE, REMOVE-FILE, and SKIP-ENTRY active + NIL, :SKIP, :KEEP : existing files are skipped + :SUPERSEDE : Overwrite the file + :REPLACE : Delete file and replace it, atomically if possible. IF-EXISTS controls what happens to files that already exist within DIRECTORY. It defaults to :ERROR. The possible values are: + :ERROR : A DESTINATION-EXISTS-ERROR is signaled, with the restarts SUPERSEDE-FILE, REMOVE-FILE, and SKIP-ENTRY active + NIL, :SKIP, :KEEP : existing files are skipped + :SUPERSEDE : Overwrite the file + :REPLACE : Delete file and replace it, atomically if possible. The following options configure how metadata is extracted. If KEEP-DIRECTORY-METADATA is non-NIL, then metadata for existing directories is kept. If TOUCH is non-NIL, file mtimes will not be set on extraction. If NO-SAME-OWNER is non-NIL, then the owner and group of extracted entries will not be set. Defaults to T for non-root users and Windows. Must be T on Windows. If NUMERIC-UID is non-NIL, UIDs and GIDs are preferred over UNAMEs and GNAMEs. MASK is a list of permissions to remove from all entries. The following options configure how certain types of entries are extracted. SYMBOLIC-LINKS controls how symbolic links are extracted from ARCHIVE. It defaults to T on non-Windows platforms and :DEREFERENCE on Windows. The possible values are: + T : Extract the symlink as normal. + :DEREFERENCE : any symlink entries are instead written as normal files with the contents of the file they point to. + :SKIP : Skip the symlink. + :ERROR : Signal a EXTRACT-SYMBOLIC-LINK-ENTRY-ERROR with the restarts EXTRACT-LINK, DEREFERENCE-LINK and SKIP-ENTRY active. HARD-LINKS controls how hard links are extracted from ARCHIVE. It defaults to T on non-WINDOWS platforms and :DEREFERENCE on Windows. The possible values are: + T : Extract the hard link as normal. + :DEREFERENCE : any hard link entries are instead written as normal files with the contents of the file they point to. + :SKIP : Skip the hard link. + :ERROR : Signal a EXTRACT-HARD-LINK-ENTRY-ERROR with the restarts EXTRACT-LINK, DEREFERENCE-LINK and SKIP-ENTRY active. CHARACTER-DEVICES controls how character devices are extracted from ARCHIVE. It defaults to :ERROR on Windows or non-Windows and the current user is not root, T otherwise. The possible values are: + T : Extract the character device. + :SKIP : Skip the entry. + :ERROR : Signal a EXTRACT-CHARACTER-DEVICE-ENTRY-ERROR with the restarts EXTRACT-DEVICE and SKIP-ENTRY active. BLOCK-DEVICES controls how block devices are extracted from ARCHIVE. It defaults to :ERROR on Windows or non-Windows and the current user is not root, T otherwise. The possible values are: + T : Extract the block device. + :SKIP : Skip the entry. + :ERROR : Signal a EXTRACT-BLOCK-DEVICE-ENTRY-ERROR with the restarts EXTRACT-DEVICE and SKIP-ENTRY active. FIFOS controls how FIFOs are extracted from ARCHIVE. It defaults to T on non-Windows platforms and :ERROR on Windows. The possible values are: + T : Extract the FIFO. + :SKIP : Skip the entry. + :ERROR : Signal a EXTRACT-FIFO-ENTRY-ERROR with the restarts EXTRACT-FIFO and SKIP-ENTRY active. The following option controls what entries are extracted. FILTER defaults to (CONSTANTLY T). Must be a function designator that takes two arguments (the entry and the pathname were it will be extracted) and returns non-NIL if the entry should be extracted. If symbolic and hard links are dereferenced, there may be broken or circular links. If that is detected, a BROKEN-OR-CIRCULAR-LINKS-ERROR is signalled with the CONTINUE restart active." (assert (uiop:directory-pathname-p directory) (directory) "DIRECTORY must be a directory pathname") #+windows (assert no-same-owner (no-same-owner) "NO-SAME-OWNER must be non-NIL on Windows.") (let ((*default-pathname-defaults* (uiop:ensure-directory-pathname directory)) (*deferred-links* nil) (*deferred-directories* nil) #+tar-extract-use-openat *destination-dir-fd*) (ensure-directories-exist *default-pathname-defaults*) (#+tar-extract-use-openat with-fd #+tar-extract-use-openat (*destination-dir-fd* (nix:open *default-pathname-defaults* nix:o-rdonly)) #-tar-extract-use-openat progn (handler-bind ((entry-name-contains-device-error (lambda (c) (case device-pathnames (:allow (continue c)) (:skip (skip-entry c)) (:relativize (relativize-entry-name c))))) (entry-name-contains-..-error (lambda (c) (case dot-dot (:back (treat-..-as-back c)) (:skip (skip-entry c))))) (entry-name-is-absolute-error (lambda (c) (case absolute-pathnames (:allow (continue c)) (:skip (skip-entry c)) (:relativize (relativize-entry-name c))))) (extract-symbolic-link-entry-error (lambda (c) (case symbolic-links (:skip (skip-entry c)) (:dereference (dereference-link c)) ((t) (extract-link c))))) (extract-hard-link-entry-error (lambda (c) (case hard-links (:skip (skip-entry c)) (:dereference (dereference-link c)) ((t) (extract-link c))))) (extract-fifo-entry-error (lambda (c) (case fifos (:skip (skip-entry c)) ((t) (extract-fifo c))))) (extract-block-device-entry-error (lambda (c) (case block-devices (:skip (skip-entry c)) ((t) (extract-device c))))) (extract-character-device-entry-error (lambda (c) (case character-devices (:skip (skip-entry c)) ((t) (extract-device c))))) (extraction-through-symbolic-link-error (lambda (c) (if (uiop:directory-pathname-p (extraction-through-symbolic-link-error-pathname c)) (case if-directory-symbolic-link-exists ((nil :skip) (skip-entry c)) (:follow (follow-symbolic-link c)) (:supersede (replace-symbolic-link c))) (case if-symbolic-link-exists ((nil :skip) (skip-entry c)) (:follow (follow-symbolic-link c)) (:supersede (replace-symbolic-link c)))))) (destination-exists-error (lambda (c) (let ((entry-mtime (tar:mtime (extraction-entry-error-entry c))) (existing-mtime (destination-exists-error-mtime c))) (if (local-time:timestamp< entry-mtime existing-mtime) (case if-newer-exists ((nil :skip :keep) (skip-entry c)) (:supersede (invoke-restart 'supersede-file)) (:replace (invoke-restart 'remove-file))) (case if-exists ((nil :skip :keep) (skip-entry c)) (:supersede (invoke-restart 'supersede-file)) (:replace (invoke-restart 'remove-file)))))))) (tar:do-entries (entry archive) (let ((*current-entry* entry)) (restart-case (let ((pn (compute-extraction-pathname entry (tar:name entry) strip-components))) (when (and (not (null pn)) (funcall filter entry pn)) (tar:with-ignored-unsupported-properties () (extract-entry entry pn :mask mask :numeric-uid numeric-uid :no-same-owner no-same-owner :touch touch :keep-directory-metadata keep-directory-metadata)))) (skip-entry ())))) (process-deferred-links *deferred-links* if-exists if-newer-exists) (dolist (pair *deferred-directories*) (handle-deferred-directory (car pair) (cdr pair) :mask mask :numeric-uid numeric-uid :no-same-owner no-same-owner :touch touch)) (values)))))
null
https://raw.githubusercontent.com/lisp-mirror/cl-tar/8369f16b51dfe04dc68c2ebf146c769d4bc7d471/src/extract/extract.lisp
lisp
This is part of cl-tar. See README.md and LICENSE for more information. Directory permissions Symbolic links Extracting entries There's no great portable to get a file descriptor for a symlink, so we have to change utimes and owner by pathname. Extract archive
(in-package #:tar-extract) (defvar *deferred-links*) (defvar *deferred-directories*) #+tar-extract-use-openat (defvar *destination-dir-fd*) #+tar-extract-use-openat (defun handle-deferred-directory (entry pn &key touch no-same-owner numeric-uid mask) (with-fd (fd (fd (openat *destination-dir-fd* pn (logior nix:s-irusr nix:s-iwusr nix:s-ixusr)))) (unless touch (set-utimes entry :fd fd)) (set-permissions entry mask :fd fd) (unless no-same-owner (set-owner entry numeric-uid :fd fd)))) #-tar-extract-use-openat (defun handle-deferred-directory (entry pn &key touch no-same-owner numeric-uid mask) (set-permissions entry mask :pn pn)) (defun link-target-exists-p (pair) (let ((entry (first pair)) (pn (second pair)) (type (third pair))) (probe-file (merge-pathnames (tar:linkname entry) (if (eql type :hard) *default-pathname-defaults* (merge-pathnames pn)))))) (defun process-deferred-links-1 (deferred-links if-exists if-newer-exists) (let ((actionable-links (remove-if-not 'link-target-exists-p deferred-links))) (dolist (actionable-link actionable-links) (destructuring-bind (entry pn type) actionable-link (let ((pn (merge-pathnames pn))) (unless (null (probe-file pn)) (let ((file-write-date (file-write-date pn))) (when (and (not (null file-write-date)) (> file-write-date (local-time:timestamp-to-universal (tar:mtime entry)))) (setf if-exists if-newer-exists)))) (when (eql if-exists :keep) (setf if-exists nil)) (with-open-file (s pn :direction :output :element-type '(unsigned-byte 8) :if-exists if-exists) (unless (null s) (with-open-file (source (merge-pathnames (tar:linkname entry) (if (eql type :hard) *default-pathname-defaults* pn)) :element-type '(unsigned-byte 8)) (uiop:copy-stream-to-stream source s :element-type '(unsigned-byte 8)))))))) (set-difference deferred-links actionable-links))) (defun process-deferred-links (deferred-links if-exists if-newer-exists) (loop :for prev-links := deferred-links :then links :for links := (process-deferred-links-1 prev-links if-exists if-newer-exists) :while links :when (= (length links) (length prev-links)) :do (restart-case (error 'broken-or-circular-links-error) (continue () (return))))) (defgeneric extract-entry (entry pn &key mask numeric-uid no-same-owner touch keep-directory-metadata)) (defmethod extract-entry ((entry tar:file-entry) pn &key touch no-same-owner numeric-uid mask &allow-other-keys) #+windows (declare (ignore no-same-owner numeric-uid)) (with-open-stream (stream #+tar-extract-use-openat (openat *destination-dir-fd* pn (logior nix:s-irusr nix:s-iwusr)) #-tar-extract-use-openat (my-open pn (logior nix:s-irusr nix:s-iwusr))) (uiop:copy-stream-to-stream (tar:make-entry-stream entry) stream :element-type '(unsigned-byte 8)) (unless touch (set-utimes entry :fd (fd stream))) (set-permissions entry mask :fd (fd stream) :pn pn) #-windows (unless no-same-owner (set-owner entry numeric-uid :fd (fd stream))))) (defmethod extract-entry ((entry tar:directory-entry) pn &key keep-directory-metadata &allow-other-keys) #+tar-extract-use-openat (with-fd (dirfd (fd (openat *destination-dir-fd* pn (logior nix:s-irusr nix:s-iwusr nix:s-ixusr)))) (declare (ignore dirfd)) Enqueue this to later set its properties . (unless keep-directory-metadata (push (cons entry pn) *deferred-directories*))) #-tar-extract-use-openat (progn (ensure-directories-exist (merge-pathnames pn)) (unless keep-directory-metadata (push (cons entry pn) *deferred-directories*)))) (defmethod extract-entry ((entry tar:symbolic-link-entry) pn &key touch no-same-owner numeric-uid &allow-other-keys) #+windows (declare (ignore touch no-same-owner numeric-uid)) (restart-case (error 'extract-symbolic-link-entry-error) #-windows (extract-link () (let ((dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu)))) (with-fd (dir-fd) (nix:symlinkat (tar:linkname entry) dir-fd (file-namestring pn)) (unless touch (set-utimes entry :dirfd dir-fd :pn (file-namestring pn))) (unless no-same-owner (set-owner entry numeric-uid :dirfd dir-fd :pn (file-namestring pn)))))) (dereference-link () (push (list entry pn :symbolic) *deferred-links*)))) (defmethod extract-entry ((entry tar:hard-link-entry) pn &key &allow-other-keys) (restart-case (error 'extract-hard-link-entry-error) #-windows (extract-link () (let ((destination-pn (uiop:parse-unix-namestring (tar:linkname entry) :dot-dot :back))) (with-fd (dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu))) (with-fd (destination-dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname destination-pn) nix:s-irwxu))) (nix:linkat destination-dir-fd (file-namestring destination-pn) dir-fd (file-namestring pn) 0))))) (dereference-link () (push (list entry pn :hard) *deferred-links*)))) (defmethod extract-entry ((entry tar:fifo-entry) pn &key mask touch no-same-owner numeric-uid &allow-other-keys) #+windows (declare (ignore mask touch no-same-owner numeric-uid)) (restart-case (error 'extract-fifo-entry-error) #-windows (extract-fifo () (let ((dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu)))) (with-fd (dir-fd) #+tar-extract-use-mkfifoat (nix:mkfifoat dir-fd (file-namestring pn) (tar::permissions-to-mode (set-difference (tar:mode entry) mask))) #-tar-extract-use-mkfifoat (nix:mkfifo (merge-pathnames pn) (tar::permissions-to-mode (set-difference (tar:mode entry) mask))) (with-fd (fifo-fd (nix:openat dir-fd (file-namestring pn) (logior nix:o-rdonly nix:o-nofollow nix:o-nonblock))) (unless touch (set-utimes entry :fd fifo-fd)) (set-permissions entry mask :fd fifo-fd) (unless no-same-owner (set-owner entry numeric-uid :fd fifo-fd)))))))) (defmethod extract-entry ((entry tar:block-device-entry) pn &key touch no-same-owner numeric-uid mask &allow-other-keys) #+windows (declare (ignore touch no-same-owner numeric-uid mask)) (restart-case (error 'extract-block-device-entry-error :entry entry) #-windows (extract-device () (let ((dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu)))) (with-fd (dir-fd) (nix:mknodat dir-fd (file-namestring pn) (logior nix:s-ifblk (tar::permissions-to-mode (tar:mode entry))) (nix:makedev (tar:devmajor entry) (tar:devminor entry))) (with-fd (dev-fd (nix:openat dir-fd (file-namestring pn) (logior nix:o-rdonly nix:o-nofollow nix:o-nonblock))) (unless touch (set-utimes entry :fd dev-fd)) (set-permissions entry mask :fd dev-fd) (unless no-same-owner (set-owner entry numeric-uid :fd dev-fd)))))))) (defmethod extract-entry ((entry tar:character-device-entry) pn &key touch no-same-owner numeric-uid mask &allow-other-keys) #+windows (declare (ignore touch no-same-owner numeric-uid mask)) (restart-case (error 'extract-character-device-entry-error :entry entry) #-windows (extract-device () (let ((dir-fd (fd (openat *destination-dir-fd* (uiop:pathname-directory-pathname pn) nix:s-irwxu)))) (with-fd (dir-fd) (nix:mknodat dir-fd (file-namestring pn) (logior nix:s-ifchr (tar::permissions-to-mode (tar:mode entry))) (nix:makedev (tar:devmajor entry) (tar:devminor entry))) (with-fd (dev-fd (nix:openat dir-fd (file-namestring pn) (logior nix:o-rdonly nix:o-nofollow nix:o-nonblock))) (unless touch (set-utimes entry :fd dev-fd)) (set-permissions entry mask :fd dev-fd) (unless no-same-owner (set-owner entry numeric-uid :fd dev-fd)))))))) (defun extract-archive (archive &key (directory *default-pathname-defaults*) (absolute-pathnames :error) (device-pathnames :error) (dot-dot :error) (strip-components 0) (if-exists :error) (if-newer-exists :error) (if-symbolic-link-exists :error) (if-directory-symbolic-link-exists :error) keep-directory-metadata touch (no-same-owner #+:windows t #-windows (rootp)) numeric-uid mask (symbolic-links #-windows t #+windows :dereference) (hard-links #-windows t #+windows :dereference) (character-devices #-windows (if (rootp) t :error) #+windows :error) (block-devices #-windows (if (rootp) t :error) #+windows :error) (fifos #-windows t #+windows :error) (filter (constantly t))) "Extract all entries in ARCHIVE to DIRECTORY. DIRECTORY defaults to *DEFAULT-PATHNAME-DEFAULTS* and must be a directory pathname. The following options configure how the final pathname of each entry is computed: ABSOLUTE-PATHANMES controls what happens when an entry is discovered that has an absolute pathname. It defaults to :ERROR. The possible values are: + :ALLOW : Allow the pathname as is. + :SKIP : Silently skip the entry. + :RELATIVIZE : Strip the leading / and treat it as a relative pathname. + :ERROR : Signal an ENTRY-NAME-IS-ABSOLUTE-ERROR, with the restarts CONTINUE, SKIP-ENTRY, and RELATIVIZE-ENTRY-NAME active. DEVICE-PATHNAMES controls what happens when an entry is discovered that has a non-NIL device. It defaults to :ERROR. The possible values are: + :ALLOW : Allow the pathname as is. + :SKIP : Silently skip the entry. + :RELATIVIZE : Strip the device. + :ERROR : Signal an ENTRY-NAME-CONTAINS-DEVICE-ERROR, with the restarts CONTINUE, SKIP-ENTRY, and RELATIVIZE-ENTRY-NAME active. DOT-DOT controls what happens when an entry is discovered that has a name containing .. in a directory component. It defaults to :ERROR. The possible values are: + :BACK : Allow the pathname as is, treating .. as :BACK. + :SKIP : Silently skip the entry. + :ERROR : Signal an ENTRY-NAME-CONTAINS-..-ERROR, with the restarts TREAT-..-AS-BACK and SKIP-ENTRY active. STRIP-COMPONENTS is an integer specifying how many directory and file components to strip. Defaults to 0. The following options configure what happens to files that already exist on the filesystem. IF-DIRECTORY-SYMBOLIC-LINK-EXISTS controls what happens to existing directories that are symlinks. This includes any symlink on the destination path of the entry. Defaults to :ERROR. The possible values are: + :ERROR : Signal a EXTRACTION-THROUGH-SYMBOLIC-LINK-ERROR with the restarts FOLLOW-SYMBOLIC-LINK, REPLACE-SYMBOLIC-LINK, and SKIP-ENTRY active. + NIL, :SKIP : Skip the entry. + :SUPERSEDE : replace the symlink with a new, empty directory. + :FOLLOW : keep the existing symlink. IF-SYMBOLIC-LINK-EXISTS controls what happesn to existing files that are symlinks. Defaults to :ERROR. The possible values are: + :ERROR : Signal a EXTRACTION-THROUGH-SYMBOLIC-LINK-ERROR with the restarts FOLLOW-SYMBOLIC-LINK, REPLACE-SYMBOLIC-LINK, and SKIP-ENTRY active. + NIL, :SKIP : Skip the entry. + :FOLLOW : Follow the symlink and write the contents of the entry, respecting IF-NEWER-EXISTS and IF-EXISTS. + :SUPERSEDE : Replace the symlink. IF-NEWER-EXISTS controls what happens to files that already exist within DIRECTORY if extracting ARCHIVE would overwrite them and the existing file has a more recent mtime. It defaults to :ERROR. The possible values are: + :ERROR : A DESTINATION-EXISTS-ERROR is signaled, with the restarts SUPERSEDE-FILE, REMOVE-FILE, and SKIP-ENTRY active + NIL, :SKIP, :KEEP : existing files are skipped + :SUPERSEDE : Overwrite the file + :REPLACE : Delete file and replace it, atomically if possible. IF-EXISTS controls what happens to files that already exist within DIRECTORY. It defaults to :ERROR. The possible values are: + :ERROR : A DESTINATION-EXISTS-ERROR is signaled, with the restarts SUPERSEDE-FILE, REMOVE-FILE, and SKIP-ENTRY active + NIL, :SKIP, :KEEP : existing files are skipped + :SUPERSEDE : Overwrite the file + :REPLACE : Delete file and replace it, atomically if possible. The following options configure how metadata is extracted. If KEEP-DIRECTORY-METADATA is non-NIL, then metadata for existing directories is kept. If TOUCH is non-NIL, file mtimes will not be set on extraction. If NO-SAME-OWNER is non-NIL, then the owner and group of extracted entries will not be set. Defaults to T for non-root users and Windows. Must be T on Windows. If NUMERIC-UID is non-NIL, UIDs and GIDs are preferred over UNAMEs and GNAMEs. MASK is a list of permissions to remove from all entries. The following options configure how certain types of entries are extracted. SYMBOLIC-LINKS controls how symbolic links are extracted from ARCHIVE. It defaults to T on non-Windows platforms and :DEREFERENCE on Windows. The possible values are: + T : Extract the symlink as normal. + :DEREFERENCE : any symlink entries are instead written as normal files with the contents of the file they point to. + :SKIP : Skip the symlink. + :ERROR : Signal a EXTRACT-SYMBOLIC-LINK-ENTRY-ERROR with the restarts EXTRACT-LINK, DEREFERENCE-LINK and SKIP-ENTRY active. HARD-LINKS controls how hard links are extracted from ARCHIVE. It defaults to T on non-WINDOWS platforms and :DEREFERENCE on Windows. The possible values are: + T : Extract the hard link as normal. + :DEREFERENCE : any hard link entries are instead written as normal files with the contents of the file they point to. + :SKIP : Skip the hard link. + :ERROR : Signal a EXTRACT-HARD-LINK-ENTRY-ERROR with the restarts EXTRACT-LINK, DEREFERENCE-LINK and SKIP-ENTRY active. CHARACTER-DEVICES controls how character devices are extracted from ARCHIVE. It defaults to :ERROR on Windows or non-Windows and the current user is not root, T otherwise. The possible values are: + T : Extract the character device. + :SKIP : Skip the entry. + :ERROR : Signal a EXTRACT-CHARACTER-DEVICE-ENTRY-ERROR with the restarts EXTRACT-DEVICE and SKIP-ENTRY active. BLOCK-DEVICES controls how block devices are extracted from ARCHIVE. It defaults to :ERROR on Windows or non-Windows and the current user is not root, T otherwise. The possible values are: + T : Extract the block device. + :SKIP : Skip the entry. + :ERROR : Signal a EXTRACT-BLOCK-DEVICE-ENTRY-ERROR with the restarts EXTRACT-DEVICE and SKIP-ENTRY active. FIFOS controls how FIFOs are extracted from ARCHIVE. It defaults to T on non-Windows platforms and :ERROR on Windows. The possible values are: + T : Extract the FIFO. + :SKIP : Skip the entry. + :ERROR : Signal a EXTRACT-FIFO-ENTRY-ERROR with the restarts EXTRACT-FIFO and SKIP-ENTRY active. The following option controls what entries are extracted. FILTER defaults to (CONSTANTLY T). Must be a function designator that takes two arguments (the entry and the pathname were it will be extracted) and returns non-NIL if the entry should be extracted. If symbolic and hard links are dereferenced, there may be broken or circular links. If that is detected, a BROKEN-OR-CIRCULAR-LINKS-ERROR is signalled with the CONTINUE restart active." (assert (uiop:directory-pathname-p directory) (directory) "DIRECTORY must be a directory pathname") #+windows (assert no-same-owner (no-same-owner) "NO-SAME-OWNER must be non-NIL on Windows.") (let ((*default-pathname-defaults* (uiop:ensure-directory-pathname directory)) (*deferred-links* nil) (*deferred-directories* nil) #+tar-extract-use-openat *destination-dir-fd*) (ensure-directories-exist *default-pathname-defaults*) (#+tar-extract-use-openat with-fd #+tar-extract-use-openat (*destination-dir-fd* (nix:open *default-pathname-defaults* nix:o-rdonly)) #-tar-extract-use-openat progn (handler-bind ((entry-name-contains-device-error (lambda (c) (case device-pathnames (:allow (continue c)) (:skip (skip-entry c)) (:relativize (relativize-entry-name c))))) (entry-name-contains-..-error (lambda (c) (case dot-dot (:back (treat-..-as-back c)) (:skip (skip-entry c))))) (entry-name-is-absolute-error (lambda (c) (case absolute-pathnames (:allow (continue c)) (:skip (skip-entry c)) (:relativize (relativize-entry-name c))))) (extract-symbolic-link-entry-error (lambda (c) (case symbolic-links (:skip (skip-entry c)) (:dereference (dereference-link c)) ((t) (extract-link c))))) (extract-hard-link-entry-error (lambda (c) (case hard-links (:skip (skip-entry c)) (:dereference (dereference-link c)) ((t) (extract-link c))))) (extract-fifo-entry-error (lambda (c) (case fifos (:skip (skip-entry c)) ((t) (extract-fifo c))))) (extract-block-device-entry-error (lambda (c) (case block-devices (:skip (skip-entry c)) ((t) (extract-device c))))) (extract-character-device-entry-error (lambda (c) (case character-devices (:skip (skip-entry c)) ((t) (extract-device c))))) (extraction-through-symbolic-link-error (lambda (c) (if (uiop:directory-pathname-p (extraction-through-symbolic-link-error-pathname c)) (case if-directory-symbolic-link-exists ((nil :skip) (skip-entry c)) (:follow (follow-symbolic-link c)) (:supersede (replace-symbolic-link c))) (case if-symbolic-link-exists ((nil :skip) (skip-entry c)) (:follow (follow-symbolic-link c)) (:supersede (replace-symbolic-link c)))))) (destination-exists-error (lambda (c) (let ((entry-mtime (tar:mtime (extraction-entry-error-entry c))) (existing-mtime (destination-exists-error-mtime c))) (if (local-time:timestamp< entry-mtime existing-mtime) (case if-newer-exists ((nil :skip :keep) (skip-entry c)) (:supersede (invoke-restart 'supersede-file)) (:replace (invoke-restart 'remove-file))) (case if-exists ((nil :skip :keep) (skip-entry c)) (:supersede (invoke-restart 'supersede-file)) (:replace (invoke-restart 'remove-file)))))))) (tar:do-entries (entry archive) (let ((*current-entry* entry)) (restart-case (let ((pn (compute-extraction-pathname entry (tar:name entry) strip-components))) (when (and (not (null pn)) (funcall filter entry pn)) (tar:with-ignored-unsupported-properties () (extract-entry entry pn :mask mask :numeric-uid numeric-uid :no-same-owner no-same-owner :touch touch :keep-directory-metadata keep-directory-metadata)))) (skip-entry ())))) (process-deferred-links *deferred-links* if-exists if-newer-exists) (dolist (pair *deferred-directories*) (handle-deferred-directory (car pair) (cdr pair) :mask mask :numeric-uid numeric-uid :no-same-owner no-same-owner :touch touch)) (values)))))
44d577f341909e37904eda440d83277c5d627ec76aa77cddedb0a478a830f671
Innf107/cobble-compiler
Context.hs
# LANGUAGE TemplateHaskell # module Cobble.Util.Polysemy.Context where import Cobble.Prelude data Context c m a where GetContext :: Context c m (Seq c) WithContext :: c -> m a -> Context c m a ModifyContext :: (Seq c -> Seq c) -> m a -> Context c m a makeSem ''Context runContext :: Sem (Context c : r) a -> Sem r a runContext = runContextInitial [] runContextInitial :: Seq c -> Sem (Context c : r) a -> Sem r a runContextInitial i = interpretH \case GetContext -> pureT i WithContext c m -> do m' <- runT m raise $ runContextInitial (c <| i) m' ModifyContext f m -> do m' <- runT m raise $ runContextInitial (f i) m'
null
https://raw.githubusercontent.com/Innf107/cobble-compiler/d6b0b65dad0fd6f1d593f7f859b1cc832e01e21f/src/Cobble/Util/Polysemy/Context.hs
haskell
# LANGUAGE TemplateHaskell # module Cobble.Util.Polysemy.Context where import Cobble.Prelude data Context c m a where GetContext :: Context c m (Seq c) WithContext :: c -> m a -> Context c m a ModifyContext :: (Seq c -> Seq c) -> m a -> Context c m a makeSem ''Context runContext :: Sem (Context c : r) a -> Sem r a runContext = runContextInitial [] runContextInitial :: Seq c -> Sem (Context c : r) a -> Sem r a runContextInitial i = interpretH \case GetContext -> pureT i WithContext c m -> do m' <- runT m raise $ runContextInitial (c <| i) m' ModifyContext f m -> do m' <- runT m raise $ runContextInitial (f i) m'
45211ed5efd8f3e2612306df8f6590e742d28885a7b47d772cadfe834654b066
finnishtransportagency/harja
kuittaus_sampoon_sanoma.clj
(ns harja.palvelin.integraatiot.sampo.sanomat.kuittaus-sampoon-sanoma (:require [hiccup.core :refer [html]] [taoensso.timbre :as log] [harja.tyokalut.xml :as xml] [clojure.data.zip.xml :as z]) (:import (java.text SimpleDateFormat) (java.util Date))) (def +xsd-polku+ "xsd/sampo/inbound/") (defn formatoi-paivamaara [paivamaara] (.format (SimpleDateFormat. "yyyy-MM-dd'T'HH:mm:ss.S") paivamaara)) (defn tee-xml-sanoma [sisalto] (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" (html sisalto))) (defn muodosta-viesti [viesti-id viestityyppi virhekoodi virheviesti] [:Harja2SampoAck [:Ack {:ErrorCode virhekoodi, :ErrorMessage virheviesti, :MessageId viesti-id, :ObjectType viestityyppi, :Date (formatoi-paivamaara (new Date))}]]) (defn muodosta [viesti-id viestityyppi virhekoodi virheviesti] (let [sisalto (muodosta-viesti viesti-id viestityyppi virhekoodi virheviesti) xml (tee-xml-sanoma sisalto)] (if (xml/validi-xml? +xsd-polku+ "HarjaToSampoAcknowledgement.xsd" xml) xml (do (log/error (format "Kuittausta Sampoon ei voida lähettää viesti id:lle %s. Kuittaus XML ei ole validi." viesti-id)) nil)))) (defn muodosta-onnistunut-kuittaus [viesti-id viestityyppi] (muodosta viesti-id viestityyppi "NA" "")) (defn muodosta-muu-virhekuittaus [viesti-id viestityyppi virheviesti] (muodosta viesti-id viestityyppi "CUSTOM" virheviesti)) (defn muodosta-invalidi-xml-virhekuittaus [viesti-id viestityyppi virheviesti] (muodosta viesti-id viestityyppi "INVALID_XML" virheviesti)) (defn muodosta-puuttuva-suhde-virhekuittaus [viesti-id viestityyppi virheviesti] (muodosta viesti-id viestityyppi "MISSING_RELATION" virheviesti)) (defn onko-kuittaus-positiivinen? [kuittaus] (= "NA" (first (z/xml-> (xml/lue kuittaus) (fn [kuittaus] (z/xml1-> (z/xml1-> kuittaus) :Ack (z/attr :ErrorCode)))))))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/488b1e096f0611e175221d74ba4f2ffed6bea8f1/src/clj/harja/palvelin/integraatiot/sampo/sanomat/kuittaus_sampoon_sanoma.clj
clojure
(ns harja.palvelin.integraatiot.sampo.sanomat.kuittaus-sampoon-sanoma (:require [hiccup.core :refer [html]] [taoensso.timbre :as log] [harja.tyokalut.xml :as xml] [clojure.data.zip.xml :as z]) (:import (java.text SimpleDateFormat) (java.util Date))) (def +xsd-polku+ "xsd/sampo/inbound/") (defn formatoi-paivamaara [paivamaara] (.format (SimpleDateFormat. "yyyy-MM-dd'T'HH:mm:ss.S") paivamaara)) (defn tee-xml-sanoma [sisalto] (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" (html sisalto))) (defn muodosta-viesti [viesti-id viestityyppi virhekoodi virheviesti] [:Harja2SampoAck [:Ack {:ErrorCode virhekoodi, :ErrorMessage virheviesti, :MessageId viesti-id, :ObjectType viestityyppi, :Date (formatoi-paivamaara (new Date))}]]) (defn muodosta [viesti-id viestityyppi virhekoodi virheviesti] (let [sisalto (muodosta-viesti viesti-id viestityyppi virhekoodi virheviesti) xml (tee-xml-sanoma sisalto)] (if (xml/validi-xml? +xsd-polku+ "HarjaToSampoAcknowledgement.xsd" xml) xml (do (log/error (format "Kuittausta Sampoon ei voida lähettää viesti id:lle %s. Kuittaus XML ei ole validi." viesti-id)) nil)))) (defn muodosta-onnistunut-kuittaus [viesti-id viestityyppi] (muodosta viesti-id viestityyppi "NA" "")) (defn muodosta-muu-virhekuittaus [viesti-id viestityyppi virheviesti] (muodosta viesti-id viestityyppi "CUSTOM" virheviesti)) (defn muodosta-invalidi-xml-virhekuittaus [viesti-id viestityyppi virheviesti] (muodosta viesti-id viestityyppi "INVALID_XML" virheviesti)) (defn muodosta-puuttuva-suhde-virhekuittaus [viesti-id viestityyppi virheviesti] (muodosta viesti-id viestityyppi "MISSING_RELATION" virheviesti)) (defn onko-kuittaus-positiivinen? [kuittaus] (= "NA" (first (z/xml-> (xml/lue kuittaus) (fn [kuittaus] (z/xml1-> (z/xml1-> kuittaus) :Ack (z/attr :ErrorCode)))))))
85979b7c7b870b51e83d25a96fcf7dded40b455978eb101853e29234e2e1b27a
souenzzo/eql-as
eql_as.cljc
(ns br.com.souenzzo.eql-as)
null
https://raw.githubusercontent.com/souenzzo/eql-as/d33de8d1b4428d99c25e0d95b008fe4e3e842f24/src/main/br/com/souenzzo/eql_as.cljc
clojure
(ns br.com.souenzzo.eql-as)
e723f779b6e537d21429f4b9b9886930b63c6a5050c13747e8443ae5aadbbea0
Clozure/ccl-tests
write-sequence.lsp
;-*- Mode: Lisp -*- Author : Created : We d Jan 21 04:07:58 2004 ;;;; Contains: Tests of WRITE-SEQUENCE (in-package :cl-test) (defmacro def-write-sequence-test (name input args &rest expected) `(deftest ,name (let ((s ,input)) (with-output-to-string (os) (assert (eq (write-sequence s os ,@args) s)))) ,@expected)) ;;; on strings (def-write-sequence-test write-sequence.string.1 "abcde" () "abcde") (def-write-sequence-test write-sequence.string.2 "abcde" (:start 1) "bcde") (def-write-sequence-test write-sequence.string.3 "abcde" (:end 3) "abc") (def-write-sequence-test write-sequence.string.4 "abcde" (:start 1 :end 4) "bcd") (def-write-sequence-test write-sequence.string.5 "abcde" (:end nil) "abcde") (def-write-sequence-test write-sequence.string.6 "abcde" (:start 3 :end 3) "") (def-write-sequence-test write-sequence.string.7 "abcde" (:end nil :start 1) "bcde") (def-write-sequence-test write-sequence.string.8 "abcde" (:allow-other-keys nil) "abcde") (def-write-sequence-test write-sequence.string.9 "abcde" (:allow-other-keys t :foo nil) "abcde") (def-write-sequence-test write-sequence.string.10 "abcde" (:allow-other-keys t :allow-other-keys nil :foo nil) "abcde") (def-write-sequence-test write-sequence.string.11 "abcde" (:bar 'x :allow-other-keys t) "abcde") (def-write-sequence-test write-sequence.string.12 "abcde" (:start 1 :end 4 :start 2 :end 3) "bcd") (def-write-sequence-test write-sequence.string.13 "" () "") (defmacro def-write-sequence-special-test (name string args expected) `(deftest ,name (let ((str ,string) (expected ,expected)) (do-special-strings (s str nil) (let ((out (with-output-to-string (os) (assert (eq (write-sequence s os ,@args) s))))) (assert (equal out expected))))) nil)) (def-write-sequence-special-test write-sequence.string.14 "12345" () "12345") (def-write-sequence-special-test write-sequence.string.15 "12345" (:start 1 :end 3) "23") ;;; on lists (def-write-sequence-test write-sequence.list.1 (coerce "abcde" 'list) () "abcde") (def-write-sequence-test write-sequence.list.2 (coerce "abcde" 'list) (:start 1) "bcde") (def-write-sequence-test write-sequence.list.3 (coerce "abcde" 'list) (:end 3) "abc") (def-write-sequence-test write-sequence.list.4 (coerce "abcde" 'list) (:start 1 :end 4) "bcd") (def-write-sequence-test write-sequence.list.5 (coerce "abcde" 'list) (:end nil) "abcde") (def-write-sequence-test write-sequence.list.6 (coerce "abcde" 'list) (:start 3 :end 3) "") (def-write-sequence-test write-sequence.list.7 (coerce "abcde" 'list) (:end nil :start 1) "bcde") (def-write-sequence-test write-sequence.list.8 () () "") ;;; on vectors (def-write-sequence-test write-sequence.simple-vector.1 (coerce "abcde" 'simple-vector) () "abcde") (def-write-sequence-test write-sequence.simple-vector.2 (coerce "abcde" 'simple-vector) (:start 1) "bcde") (def-write-sequence-test write-sequence.simple-vector.3 (coerce "abcde" 'simple-vector) (:end 3) "abc") (def-write-sequence-test write-sequence.simple-vector.4 (coerce "abcde" 'simple-vector) (:start 1 :end 4) "bcd") (def-write-sequence-test write-sequence.simple-vector.5 (coerce "abcde" 'simple-vector) (:end nil) "abcde") (def-write-sequence-test write-sequence.simple-vector.6 (coerce "abcde" 'simple-vector) (:start 3 :end 3) "") (def-write-sequence-test write-sequence.simple-vector.7 (coerce "abcde" 'simple-vector) (:end nil :start 1) "bcde") (def-write-sequence-test write-sequence.simple-vector.8 #() () "") ;;; on vectors with fill pointers (def-write-sequence-test write-sequence.fill-vector.1 (make-array 10 :initial-contents "abcde " :fill-pointer 5) () "abcde") (def-write-sequence-test write-sequence.fill-vector.2 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:start 1) "bcde") (def-write-sequence-test write-sequence.fill-vector.3 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:end 3) "abc") (def-write-sequence-test write-sequence.fill-vector.4 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:start 1 :end 4) "bcd") (def-write-sequence-test write-sequence.fill-vector.5 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:end nil) "abcde") (def-write-sequence-test write-sequence.fill-vector.6 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:start 3 :end 3) "") (def-write-sequence-test write-sequence.fill-vector.7 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:end nil :start 1) "bcde") ;;; on bit vectors (defmacro def-write-sequence-bv-test (name input args expected) `(deftest ,name (let ((s ,input) (expected ,expected)) (with-open-file (os "tmp.dat" :direction :output :element-type '(unsigned-byte 8) :if-exists :supersede) (assert (eq (write-sequence s os ,@args) s))) (with-open-file (is "tmp.dat" :direction :input :element-type '(unsigned-byte 8)) (loop for i from 0 below (length expected) for e = (elt expected i) always (eql (read-byte is) e)))) t)) (def-write-sequence-bv-test write-sequence.bv.1 #*00111010 () #*00111010) (def-write-sequence-bv-test write-sequence.bv.2 #*00111010 (:start 1) #*0111010) (def-write-sequence-bv-test write-sequence.bv.3 #*00111010 (:end 5) #*00111) (def-write-sequence-bv-test write-sequence.bv.4 #*00111010 (:start 1 :end 6) #*01110) (def-write-sequence-bv-test write-sequence.bv.5 #*00111010 (:start 1 :end nil) #*0111010) (def-write-sequence-bv-test write-sequence.bv.6 #*00111010 (:start 1 :end nil :end 4) #*0111010) ;;; Error tests (deftest write-sequence.error.1 (signals-error (write-sequence) program-error) t) (deftest write-sequence.error.2 (signals-error (write-sequence "abcde") program-error) t) (deftest write-sequence.error.3 (signals-error (write-sequence '(#\a . #\b) *standard-output*) type-error) t) (deftest write-sequence.error.4 (signals-error (write-sequence #\a *standard-output*) type-error) t) (deftest write-sequence.error.5 (signals-error (write-sequence "ABC" *standard-output* :start -1) type-error) t) (deftest write-sequence.error.6 (signals-error (write-sequence "ABC" *standard-output* :start 'x) type-error) t) (deftest write-sequence.error.7 (signals-error (write-sequence "ABC" *standard-output* :start 0.0) type-error) t) (deftest write-sequence.error.8 (signals-error (write-sequence "ABC" *standard-output* :end -1) type-error) t) (deftest write-sequence.error.9 (signals-error (write-sequence "ABC" *standard-output* :end 'x) type-error) t) (deftest write-sequence.error.10 (signals-error (write-sequence "ABC" *standard-output* :end 2.0) type-error) t) (deftest write-sequence.error.11 (signals-error (write-sequence "abcde" *standard-output* :foo nil) program-error) t) (deftest write-sequence.error.12 (signals-error (write-sequence "abcde" *standard-output* :allow-other-keys nil :foo t) program-error) t) (deftest write-sequence.error.13 (signals-error (write-sequence "abcde" *standard-output* :start) program-error) t) (deftest write-sequence.error.14 (check-type-error #'(lambda (x) (write-sequence x *standard-output*)) #'sequencep) nil) (deftest write-sequence.error.15 (check-type-error #'(lambda (x) (write-sequence "abcde" *standard-output* :start x)) (typef 'unsigned-byte)) nil) (deftest write-sequence.error.16 (check-type-error #'(lambda (x) (write-sequence "abcde" *standard-output* :end x)) (typef '(or null unsigned-byte))) nil)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/write-sequence.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of WRITE-SEQUENCE on strings on lists on vectors on vectors with fill pointers on bit vectors Error tests
Author : Created : We d Jan 21 04:07:58 2004 (in-package :cl-test) (defmacro def-write-sequence-test (name input args &rest expected) `(deftest ,name (let ((s ,input)) (with-output-to-string (os) (assert (eq (write-sequence s os ,@args) s)))) ,@expected)) (def-write-sequence-test write-sequence.string.1 "abcde" () "abcde") (def-write-sequence-test write-sequence.string.2 "abcde" (:start 1) "bcde") (def-write-sequence-test write-sequence.string.3 "abcde" (:end 3) "abc") (def-write-sequence-test write-sequence.string.4 "abcde" (:start 1 :end 4) "bcd") (def-write-sequence-test write-sequence.string.5 "abcde" (:end nil) "abcde") (def-write-sequence-test write-sequence.string.6 "abcde" (:start 3 :end 3) "") (def-write-sequence-test write-sequence.string.7 "abcde" (:end nil :start 1) "bcde") (def-write-sequence-test write-sequence.string.8 "abcde" (:allow-other-keys nil) "abcde") (def-write-sequence-test write-sequence.string.9 "abcde" (:allow-other-keys t :foo nil) "abcde") (def-write-sequence-test write-sequence.string.10 "abcde" (:allow-other-keys t :allow-other-keys nil :foo nil) "abcde") (def-write-sequence-test write-sequence.string.11 "abcde" (:bar 'x :allow-other-keys t) "abcde") (def-write-sequence-test write-sequence.string.12 "abcde" (:start 1 :end 4 :start 2 :end 3) "bcd") (def-write-sequence-test write-sequence.string.13 "" () "") (defmacro def-write-sequence-special-test (name string args expected) `(deftest ,name (let ((str ,string) (expected ,expected)) (do-special-strings (s str nil) (let ((out (with-output-to-string (os) (assert (eq (write-sequence s os ,@args) s))))) (assert (equal out expected))))) nil)) (def-write-sequence-special-test write-sequence.string.14 "12345" () "12345") (def-write-sequence-special-test write-sequence.string.15 "12345" (:start 1 :end 3) "23") (def-write-sequence-test write-sequence.list.1 (coerce "abcde" 'list) () "abcde") (def-write-sequence-test write-sequence.list.2 (coerce "abcde" 'list) (:start 1) "bcde") (def-write-sequence-test write-sequence.list.3 (coerce "abcde" 'list) (:end 3) "abc") (def-write-sequence-test write-sequence.list.4 (coerce "abcde" 'list) (:start 1 :end 4) "bcd") (def-write-sequence-test write-sequence.list.5 (coerce "abcde" 'list) (:end nil) "abcde") (def-write-sequence-test write-sequence.list.6 (coerce "abcde" 'list) (:start 3 :end 3) "") (def-write-sequence-test write-sequence.list.7 (coerce "abcde" 'list) (:end nil :start 1) "bcde") (def-write-sequence-test write-sequence.list.8 () () "") (def-write-sequence-test write-sequence.simple-vector.1 (coerce "abcde" 'simple-vector) () "abcde") (def-write-sequence-test write-sequence.simple-vector.2 (coerce "abcde" 'simple-vector) (:start 1) "bcde") (def-write-sequence-test write-sequence.simple-vector.3 (coerce "abcde" 'simple-vector) (:end 3) "abc") (def-write-sequence-test write-sequence.simple-vector.4 (coerce "abcde" 'simple-vector) (:start 1 :end 4) "bcd") (def-write-sequence-test write-sequence.simple-vector.5 (coerce "abcde" 'simple-vector) (:end nil) "abcde") (def-write-sequence-test write-sequence.simple-vector.6 (coerce "abcde" 'simple-vector) (:start 3 :end 3) "") (def-write-sequence-test write-sequence.simple-vector.7 (coerce "abcde" 'simple-vector) (:end nil :start 1) "bcde") (def-write-sequence-test write-sequence.simple-vector.8 #() () "") (def-write-sequence-test write-sequence.fill-vector.1 (make-array 10 :initial-contents "abcde " :fill-pointer 5) () "abcde") (def-write-sequence-test write-sequence.fill-vector.2 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:start 1) "bcde") (def-write-sequence-test write-sequence.fill-vector.3 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:end 3) "abc") (def-write-sequence-test write-sequence.fill-vector.4 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:start 1 :end 4) "bcd") (def-write-sequence-test write-sequence.fill-vector.5 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:end nil) "abcde") (def-write-sequence-test write-sequence.fill-vector.6 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:start 3 :end 3) "") (def-write-sequence-test write-sequence.fill-vector.7 (make-array 10 :initial-contents "abcde " :fill-pointer 5) (:end nil :start 1) "bcde") (defmacro def-write-sequence-bv-test (name input args expected) `(deftest ,name (let ((s ,input) (expected ,expected)) (with-open-file (os "tmp.dat" :direction :output :element-type '(unsigned-byte 8) :if-exists :supersede) (assert (eq (write-sequence s os ,@args) s))) (with-open-file (is "tmp.dat" :direction :input :element-type '(unsigned-byte 8)) (loop for i from 0 below (length expected) for e = (elt expected i) always (eql (read-byte is) e)))) t)) (def-write-sequence-bv-test write-sequence.bv.1 #*00111010 () #*00111010) (def-write-sequence-bv-test write-sequence.bv.2 #*00111010 (:start 1) #*0111010) (def-write-sequence-bv-test write-sequence.bv.3 #*00111010 (:end 5) #*00111) (def-write-sequence-bv-test write-sequence.bv.4 #*00111010 (:start 1 :end 6) #*01110) (def-write-sequence-bv-test write-sequence.bv.5 #*00111010 (:start 1 :end nil) #*0111010) (def-write-sequence-bv-test write-sequence.bv.6 #*00111010 (:start 1 :end nil :end 4) #*0111010) (deftest write-sequence.error.1 (signals-error (write-sequence) program-error) t) (deftest write-sequence.error.2 (signals-error (write-sequence "abcde") program-error) t) (deftest write-sequence.error.3 (signals-error (write-sequence '(#\a . #\b) *standard-output*) type-error) t) (deftest write-sequence.error.4 (signals-error (write-sequence #\a *standard-output*) type-error) t) (deftest write-sequence.error.5 (signals-error (write-sequence "ABC" *standard-output* :start -1) type-error) t) (deftest write-sequence.error.6 (signals-error (write-sequence "ABC" *standard-output* :start 'x) type-error) t) (deftest write-sequence.error.7 (signals-error (write-sequence "ABC" *standard-output* :start 0.0) type-error) t) (deftest write-sequence.error.8 (signals-error (write-sequence "ABC" *standard-output* :end -1) type-error) t) (deftest write-sequence.error.9 (signals-error (write-sequence "ABC" *standard-output* :end 'x) type-error) t) (deftest write-sequence.error.10 (signals-error (write-sequence "ABC" *standard-output* :end 2.0) type-error) t) (deftest write-sequence.error.11 (signals-error (write-sequence "abcde" *standard-output* :foo nil) program-error) t) (deftest write-sequence.error.12 (signals-error (write-sequence "abcde" *standard-output* :allow-other-keys nil :foo t) program-error) t) (deftest write-sequence.error.13 (signals-error (write-sequence "abcde" *standard-output* :start) program-error) t) (deftest write-sequence.error.14 (check-type-error #'(lambda (x) (write-sequence x *standard-output*)) #'sequencep) nil) (deftest write-sequence.error.15 (check-type-error #'(lambda (x) (write-sequence "abcde" *standard-output* :start x)) (typef 'unsigned-byte)) nil) (deftest write-sequence.error.16 (check-type-error #'(lambda (x) (write-sequence "abcde" *standard-output* :end x)) (typef '(or null unsigned-byte))) nil)
6f2400aa6467ff4b4f66078aea297ac46027390568f8b3461e849ba16fc4038d
1HaskellADay/1HAD
Exercise.hs
module HAD.Y2014.M03.D18.Exercise where -- $setup -- >>> import Data.Maybe -- >>> let backPartner = (>>= partner) . (>>= partner) data Person a = Single a | Married a (Person a) partner :: Person a -> Maybe (Person a) partner (Married _ p) = Just p partner _ = Nothing get :: Person a -> a get (Single x) = x get (Married x _) = x -- | wedding -- Marry single people, linking them together -- Nothing if one is married -- If you 're used to Haskell , this one should be VERY easy . But remember how strange it was the first time ... And see you tomorrow ! -- -- Examples: -- -- >>> isNothing $ wedding (Married "foo" (Single "foobar")) (Single "bar") -- True -- prop > \(x , y ) - > ( fmap get . backPartner . fmap fst $ wedding ( Single x ) ( Single y ) ) = = Just ( x : : String ) prop > \(x , y ) - > ( fmap get . backPartner . fmap snd $ wedding ( Single x ) ( Single y ) ) = = Just ( y : : String ) wedding :: Person a -> Person a -> Maybe (Person a, Person a) wedding = undefined
null
https://raw.githubusercontent.com/1HaskellADay/1HAD/3b3f9b7448744f9b788034f3aca2d5050d1a5c73/exercises/HAD/Y2014/M03/D18/Exercise.hs
haskell
$setup >>> import Data.Maybe >>> let backPartner = (>>= partner) . (>>= partner) | wedding Marry single people, linking them together Nothing if one is married Examples: >>> isNothing $ wedding (Married "foo" (Single "foobar")) (Single "bar") True
module HAD.Y2014.M03.D18.Exercise where data Person a = Single a | Married a (Person a) partner :: Person a -> Maybe (Person a) partner (Married _ p) = Just p partner _ = Nothing get :: Person a -> a get (Single x) = x get (Married x _) = x If you 're used to Haskell , this one should be VERY easy . But remember how strange it was the first time ... And see you tomorrow ! prop > \(x , y ) - > ( fmap get . backPartner . fmap fst $ wedding ( Single x ) ( Single y ) ) = = Just ( x : : String ) prop > \(x , y ) - > ( fmap get . backPartner . fmap snd $ wedding ( Single x ) ( Single y ) ) = = Just ( y : : String ) wedding :: Person a -> Person a -> Maybe (Person a, Person a) wedding = undefined
aa6131b007666e13ddcc2bff9a614404d917bec66efec2f23471686fec13a9d7
johnlinvc/erruby
erruby_nil.erl
-module(erruby_nil). -export([new_nil/1, install_nil_class/0, nil_instance/0]). install_nil_class() -> {ok, NilClass} = erruby_class:new_class(), 'NilClass' = erruby_object:def_global_const('NilClass', NilClass), erruby_object:def_method(NilClass, '&', fun method_and/2), erruby_object:def_method(NilClass, '^', fun method_xor/2), erruby_object:def_method(NilClass, '|', fun method_xor/2), erruby_object:def_method(NilClass, inspect, fun method_inspect/1), erruby_object:def_method(NilClass, 'nil?', fun 'method_nil_q'/1), erruby_object:def_method(NilClass, 'to_s', fun 'method_to_s'/1), erruby_object:new_object_with_pid_symbol(erruby_nil, NilClass), ok. new_nil(Env) -> erruby_rb:return(nil_instance(), Env). nil_instance() -> whereis(erruby_nil). method_and(Env, _Obj) -> erruby_boolean:new_false(Env). method_xor(Env, Obj) -> Nil = nil_instance(), False = erruby_boolean:false_instance(), case Obj of Nil -> erruby_boolean:new_false(Env); False -> erruby_boolean:new_false(Env); _ -> erruby_boolean:new_true(Env) end. method_inspect(Env) -> erruby_vm:new_string("nil",Env). method_nil_q(Env) -> erruby_boolean:new_true(Env). method_to_s(Env) -> erruby_vm:new_string("",Env).
null
https://raw.githubusercontent.com/johnlinvc/erruby/60df66495a01f9dda08bd3f670bfe9dc0661a168/src/erruby_nil.erl
erlang
-module(erruby_nil). -export([new_nil/1, install_nil_class/0, nil_instance/0]). install_nil_class() -> {ok, NilClass} = erruby_class:new_class(), 'NilClass' = erruby_object:def_global_const('NilClass', NilClass), erruby_object:def_method(NilClass, '&', fun method_and/2), erruby_object:def_method(NilClass, '^', fun method_xor/2), erruby_object:def_method(NilClass, '|', fun method_xor/2), erruby_object:def_method(NilClass, inspect, fun method_inspect/1), erruby_object:def_method(NilClass, 'nil?', fun 'method_nil_q'/1), erruby_object:def_method(NilClass, 'to_s', fun 'method_to_s'/1), erruby_object:new_object_with_pid_symbol(erruby_nil, NilClass), ok. new_nil(Env) -> erruby_rb:return(nil_instance(), Env). nil_instance() -> whereis(erruby_nil). method_and(Env, _Obj) -> erruby_boolean:new_false(Env). method_xor(Env, Obj) -> Nil = nil_instance(), False = erruby_boolean:false_instance(), case Obj of Nil -> erruby_boolean:new_false(Env); False -> erruby_boolean:new_false(Env); _ -> erruby_boolean:new_true(Env) end. method_inspect(Env) -> erruby_vm:new_string("nil",Env). method_nil_q(Env) -> erruby_boolean:new_true(Env). method_to_s(Env) -> erruby_vm:new_string("",Env).
93b1bacb66df90d677eaeb32f66a39735285f4466d9b758794a02b37171443a6
FreeProving/free-compiler
KindCheckPassTests.hs
| This module contains tests for " . " . module FreeC.Pass.KindCheckPassTests ( testKindCheckPass ) where import Test.Hspec import FreeC.Monad.Class.Testable import FreeC.Pass.KindCheckPass import FreeC.Test.Environment import FreeC.Test.Parser | Test group for ' ' tests . testKindCheckPass :: Spec testKindCheckPass = describe "FreeC.Pass.KindCheckPass" $ do testValidTypes testNotValidTypes | Test group for tests that check if ' ' accepts valid types . testValidTypes :: Spec testValidTypes = context "valid types" $ do it "should accept a single type variable" $ do input <- expectParseTestType "a" shouldSucceed $ do _ <- defineTestTypeVar "a" checkType input it "should accept constant type constructors" $ do input <- expectParseTestType "()" shouldSucceed $ do _ <- defineTestTypeCon "()" 0 ["()"] checkType input it "should accept constant type synonyms" $ do input <- expectParseTestType "Name" shouldSucceed $ do _ <- defineTestTypeSyn "Name" [] "String" _ <- defineTestTypeCon "String" 0 [] checkType input it "should accept fully applied type constructors" $ do input <- expectParseTestType "State Int Int" shouldSucceed $ do _ <- defineTestTypeCon "State" 2 [] _ <- defineTestTypeCon "Int" 0 [] checkType input it "should accept fully applied type synonyms" $ do input <- expectParseTestType "State Int Int" shouldSucceed $ do _ <- defineTestTypeSyn "State" ["s", "a"] "s -> (,) s a" _ <- defineTestTypeCon "Int" 0 [] _ <- defineTestTypeCon "(,)" 2 [] checkType input it "should accept a single type variable in function type signatures" $ do input <- expectParseTestModule ["module M where", "f :: forall a. a -> a;", "f x = x;"] shouldSucceed $ do _ <- defineTestTypeVar "a" _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. a -> a" kindCheckPass input it "should accept a single type variable in function return types" $ do input <- expectParseTestModule ["module M where", "f x :: a = x;"] shouldSucceed $ do _ <- defineTestTypeVar "a" _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. a -> a" kindCheckPass input it ("should accept a single type variable in type annotated " ++ "function arguments") $ do input <- expectParseTestModule ["module M where", "f (x :: a) = x;"] shouldSucceed $ do _ <- defineTestTypeVar "a" _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. a -> a" kindCheckPass input it "should accept a single type variable in type annotated variables" $ do input <- expectParseTestModule ["module M where", "f x = x :: a;"] shouldSucceed $ do _ <- defineTestTypeVar "a" _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. a -> a" kindCheckPass input it ("should accept a single type variable in type annotated case " ++ "expression variables") $ do input <- expectParseTestModule ["module M where", "f x = case x of {C (y :: b) -> y};"] shouldSucceed $ do mapM_ defineTestTypeVar ["a", "b"] mapM_ defineTestVar ["x", "y"] _ <- defineTestCon "C" 0 "forall a. a" _ <- defineTestFunc "f" 1 "forall a b. a -> b" kindCheckPass input | Test group for tests that check if ' ' rejects not valid -- types. testNotValidTypes :: Spec testNotValidTypes = context "not valid types" $ do it "should not accept type variable applications" $ do input <- expectParseTestType "m a" shouldFail $ do _ <- defineTestTypeVar "m" _ <- defineTestTypeVar "a" checkType input it "should not accept overapplied function application" $ do input <- expectParseTestType "(a -> b) c" shouldFail $ do mapM_ defineTestTypeVar ["a", "b", "c"] checkType input it "should not accept underapplied type constructors" $ do input <- expectParseTestType "State Int" shouldFail $ do _ <- defineTestTypeCon "State" 2 [] _ <- defineTestTypeCon "Int" 0 [] checkType input it "should not accept underapplied type synonyms" $ do input <- expectParseTestType "State Int" shouldFail $ do _ <- defineTestTypeSyn "State" ["s", "a"] "s -> (,) s a" _ <- defineTestTypeCon "Int" 0 [] _ <- defineTestTypeCon "(,)" 2 [] checkType input it "should not accept overapplied type constructors" $ do input <- expectParseTestType "State Int Int Int" shouldFail $ do _ <- defineTestTypeCon "State" 2 [] _ <- defineTestTypeCon "Int" 0 [] checkType input it "should not accept overapplied type synonyms" $ do input <- expectParseTestType "State Int Int Int" shouldFail $ do _ <- defineTestTypeSyn "State" ["s", "a"] "s -> (,) s a" _ <- defineTestTypeCon "Int" 0 [] _ <- defineTestTypeCon "(,)" 2 [] checkType input it "should not accept type variable applications in function type signatures" $ do input <- expectParseTestModule ["module M where", "f :: forall m a. m a -> m a;", "f x = x;"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a"] _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. m a -> m a" kindCheckPass input it "should not accept type variable applications in function return types" $ do input <- expectParseTestModule ["module M where", "f x :: m a = x;"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a"] _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall m a. m a -> m a" kindCheckPass input it ("should not accept type variable applications in type annotated function" ++ "arguments") $ do input <- expectParseTestModule ["module M where", "f (x :: m a) = x;"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a"] _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall m a. m a -> m a" kindCheckPass input it "should not accept type variable applications in type annotated variables" $ do input <- expectParseTestModule ["module M where", "f x = x :: m a;"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a"] _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall m a. m a -> m a" kindCheckPass input it ("should not accept type variable applications in type annotated case " ++ "expression variables") $ do input <- expectParseTestModule ["module M where", "f x = case x of {C (y :: m b) -> y};"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a", "b"] mapM_ defineTestVar ["x", "y"] _ <- defineTestCon "C" 0 "forall a. a" _ <- defineTestFunc "f" 1 "forall m a b. a -> m b" kindCheckPass input
null
https://raw.githubusercontent.com/FreeProving/free-compiler/6931b9ca652a185a92dd824373f092823aea4ea9/src/test/FreeC/Pass/KindCheckPassTests.hs
haskell
types.
| This module contains tests for " . " . module FreeC.Pass.KindCheckPassTests ( testKindCheckPass ) where import Test.Hspec import FreeC.Monad.Class.Testable import FreeC.Pass.KindCheckPass import FreeC.Test.Environment import FreeC.Test.Parser | Test group for ' ' tests . testKindCheckPass :: Spec testKindCheckPass = describe "FreeC.Pass.KindCheckPass" $ do testValidTypes testNotValidTypes | Test group for tests that check if ' ' accepts valid types . testValidTypes :: Spec testValidTypes = context "valid types" $ do it "should accept a single type variable" $ do input <- expectParseTestType "a" shouldSucceed $ do _ <- defineTestTypeVar "a" checkType input it "should accept constant type constructors" $ do input <- expectParseTestType "()" shouldSucceed $ do _ <- defineTestTypeCon "()" 0 ["()"] checkType input it "should accept constant type synonyms" $ do input <- expectParseTestType "Name" shouldSucceed $ do _ <- defineTestTypeSyn "Name" [] "String" _ <- defineTestTypeCon "String" 0 [] checkType input it "should accept fully applied type constructors" $ do input <- expectParseTestType "State Int Int" shouldSucceed $ do _ <- defineTestTypeCon "State" 2 [] _ <- defineTestTypeCon "Int" 0 [] checkType input it "should accept fully applied type synonyms" $ do input <- expectParseTestType "State Int Int" shouldSucceed $ do _ <- defineTestTypeSyn "State" ["s", "a"] "s -> (,) s a" _ <- defineTestTypeCon "Int" 0 [] _ <- defineTestTypeCon "(,)" 2 [] checkType input it "should accept a single type variable in function type signatures" $ do input <- expectParseTestModule ["module M where", "f :: forall a. a -> a;", "f x = x;"] shouldSucceed $ do _ <- defineTestTypeVar "a" _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. a -> a" kindCheckPass input it "should accept a single type variable in function return types" $ do input <- expectParseTestModule ["module M where", "f x :: a = x;"] shouldSucceed $ do _ <- defineTestTypeVar "a" _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. a -> a" kindCheckPass input it ("should accept a single type variable in type annotated " ++ "function arguments") $ do input <- expectParseTestModule ["module M where", "f (x :: a) = x;"] shouldSucceed $ do _ <- defineTestTypeVar "a" _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. a -> a" kindCheckPass input it "should accept a single type variable in type annotated variables" $ do input <- expectParseTestModule ["module M where", "f x = x :: a;"] shouldSucceed $ do _ <- defineTestTypeVar "a" _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. a -> a" kindCheckPass input it ("should accept a single type variable in type annotated case " ++ "expression variables") $ do input <- expectParseTestModule ["module M where", "f x = case x of {C (y :: b) -> y};"] shouldSucceed $ do mapM_ defineTestTypeVar ["a", "b"] mapM_ defineTestVar ["x", "y"] _ <- defineTestCon "C" 0 "forall a. a" _ <- defineTestFunc "f" 1 "forall a b. a -> b" kindCheckPass input | Test group for tests that check if ' ' rejects not valid testNotValidTypes :: Spec testNotValidTypes = context "not valid types" $ do it "should not accept type variable applications" $ do input <- expectParseTestType "m a" shouldFail $ do _ <- defineTestTypeVar "m" _ <- defineTestTypeVar "a" checkType input it "should not accept overapplied function application" $ do input <- expectParseTestType "(a -> b) c" shouldFail $ do mapM_ defineTestTypeVar ["a", "b", "c"] checkType input it "should not accept underapplied type constructors" $ do input <- expectParseTestType "State Int" shouldFail $ do _ <- defineTestTypeCon "State" 2 [] _ <- defineTestTypeCon "Int" 0 [] checkType input it "should not accept underapplied type synonyms" $ do input <- expectParseTestType "State Int" shouldFail $ do _ <- defineTestTypeSyn "State" ["s", "a"] "s -> (,) s a" _ <- defineTestTypeCon "Int" 0 [] _ <- defineTestTypeCon "(,)" 2 [] checkType input it "should not accept overapplied type constructors" $ do input <- expectParseTestType "State Int Int Int" shouldFail $ do _ <- defineTestTypeCon "State" 2 [] _ <- defineTestTypeCon "Int" 0 [] checkType input it "should not accept overapplied type synonyms" $ do input <- expectParseTestType "State Int Int Int" shouldFail $ do _ <- defineTestTypeSyn "State" ["s", "a"] "s -> (,) s a" _ <- defineTestTypeCon "Int" 0 [] _ <- defineTestTypeCon "(,)" 2 [] checkType input it "should not accept type variable applications in function type signatures" $ do input <- expectParseTestModule ["module M where", "f :: forall m a. m a -> m a;", "f x = x;"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a"] _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall a. m a -> m a" kindCheckPass input it "should not accept type variable applications in function return types" $ do input <- expectParseTestModule ["module M where", "f x :: m a = x;"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a"] _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall m a. m a -> m a" kindCheckPass input it ("should not accept type variable applications in type annotated function" ++ "arguments") $ do input <- expectParseTestModule ["module M where", "f (x :: m a) = x;"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a"] _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall m a. m a -> m a" kindCheckPass input it "should not accept type variable applications in type annotated variables" $ do input <- expectParseTestModule ["module M where", "f x = x :: m a;"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a"] _ <- defineTestVar "x" _ <- defineTestFunc "f" 1 "forall m a. m a -> m a" kindCheckPass input it ("should not accept type variable applications in type annotated case " ++ "expression variables") $ do input <- expectParseTestModule ["module M where", "f x = case x of {C (y :: m b) -> y};"] shouldFail $ do mapM_ defineTestTypeVar ["m", "a", "b"] mapM_ defineTestVar ["x", "y"] _ <- defineTestCon "C" 0 "forall a. a" _ <- defineTestFunc "f" 1 "forall m a b. a -> m b" kindCheckPass input
93d9afe0258736f118e5f971e34509c609e3e34d8fc7474721c0c7c3c377ac7f
mzp/coq-ide-for-ios
extraction_plugin_mod.ml
let _=Mltop.add_known_module"Table" let _=Mltop.add_known_module"Mlutil" let _=Mltop.add_known_module"Modutil" let _=Mltop.add_known_module"Extraction" let _=Mltop.add_known_module"Common" let _=Mltop.add_known_module"Ocaml" let _=Mltop.add_known_module"Haskell" let _=Mltop.add_known_module"Scheme" let _=Mltop.add_known_module"Extract_env" let _=Mltop.add_known_module"G_extraction" let _=Mltop.add_known_module"Extraction_plugin_mod" let _=Mltop.add_known_module"extraction_plugin"
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/CoqIDE/coq-8.2pl2/plugins/extraction/extraction_plugin_mod.ml
ocaml
let _=Mltop.add_known_module"Table" let _=Mltop.add_known_module"Mlutil" let _=Mltop.add_known_module"Modutil" let _=Mltop.add_known_module"Extraction" let _=Mltop.add_known_module"Common" let _=Mltop.add_known_module"Ocaml" let _=Mltop.add_known_module"Haskell" let _=Mltop.add_known_module"Scheme" let _=Mltop.add_known_module"Extract_env" let _=Mltop.add_known_module"G_extraction" let _=Mltop.add_known_module"Extraction_plugin_mod" let _=Mltop.add_known_module"extraction_plugin"
ae559d276f1263dd700213ebf98bfed6d52f43b2473a977b9a2dd32b91c096d9
rescript-lang/rescript-compiler
bsb_ninja_file_groups.ml
Copyright ( C ) 2017 , Authors of ReScript * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let ( // ) = Ext_path.combine let handle_generators oc (group : Bsb_file_groups.file_group) custom_rules = let map_to_source_dir x = Bsb_config.proj_rel (group.dir // x) in Ext_list.iter group.generators (fun { output; input; command } -> (*TODO: add a loc for better error message *) match Map_string.find_opt custom_rules command with | None -> Ext_fmt.failwithf ~loc:__LOC__ "custom rule %s used but not defined" command | Some rule -> Bsb_ninja_targets.output_build oc ~outputs:(Ext_list.map output map_to_source_dir) ~inputs:(Ext_list.map input map_to_source_dir) ~rule) type suffixes = { impl : string; intf : string } let ml_suffixes = { impl = Literals.suffix_ml; intf = Literals.suffix_mli } let res_suffixes = { impl = Literals.suffix_res; intf = Literals.suffix_resi } let emit_module_build (rules : Bsb_ninja_rule.builtin) (package_specs : Bsb_package_specs.t) (is_dev : bool) oc namespace (module_info : Bsb_db.module_info) : unit = let has_intf_file = module_info.info = Impl_intf in let config, ast_rule = match module_info.syntax_kind with | Ml -> (ml_suffixes, rules.build_ast) | Res -> (res_suffixes, rules.build_ast_from_re) (* FIXME: better names *) in let filename_sans_extension = module_info.name_sans_extension in let input_impl = Bsb_config.proj_rel (filename_sans_extension ^ config.impl) in let input_intf = Bsb_config.proj_rel (filename_sans_extension ^ config.intf) in let output_ast = filename_sans_extension ^ Literals.suffix_ast in let output_iast = filename_sans_extension ^ Literals.suffix_iast in let output_d = filename_sans_extension ^ Literals.suffix_d in let output_filename_sans_extension = Ext_namespace_encode.make ?ns:namespace filename_sans_extension in let output_cmi = output_filename_sans_extension ^ Literals.suffix_cmi in let output_cmj = output_filename_sans_extension ^ Literals.suffix_cmj in let output_js = Bsb_package_specs.get_list_of_output_js package_specs output_filename_sans_extension in Bsb_ninja_targets.output_build oc ~outputs:[ output_ast ] ~inputs:[ input_impl ] ~rule:ast_rule; Bsb_ninja_targets.output_build oc ~outputs:[ output_d ] ~inputs: (if has_intf_file then [ output_ast; output_iast ] else [ output_ast ]) ~rule:(if is_dev then rules.build_bin_deps_dev else rules.build_bin_deps); if has_intf_file then ( Bsb_ninja_targets.output_build oc ~outputs: [ output_iast ] (* TODO: we can get rid of absloute path if we fixed the location to be [lib/bs], better for testing? *) ~inputs:[ input_intf ] ~rule:ast_rule; Bsb_ninja_targets.output_build oc ~outputs:[ output_cmi ] ~inputs:[ output_iast ] ~rule:(if is_dev then rules.mi_dev else rules.mi)); let rule = if has_intf_file then if is_dev then rules.mj_dev else rules.mj else if is_dev then rules.mij_dev else rules.mij in Bsb_ninja_targets.output_build oc ~outputs: (if has_intf_file then output_cmj :: output_js else output_cmj :: output_cmi :: output_js) ~inputs: (if has_intf_file then [ output_ast; output_cmi ] else [ output_ast ]) ~rule let handle_files_per_dir oc ~(rules : Bsb_ninja_rule.builtin) ~package_specs ~files_to_install ~(namespace : string option) (group : Bsb_file_groups.file_group) : unit = let is_dev = group.is_dev in handle_generators oc group rules.customs; let installable = match group.public with | Export_all -> fun _ -> true | Export_none -> fun _ -> false | Export_set set -> fun module_name -> Set_string.mem set module_name in Map_string.iter group.sources (fun module_name module_info -> if installable module_name && not is_dev then Queue.add module_info files_to_install; emit_module_build rules package_specs is_dev oc namespace module_info) (* ; Bsb_ninja_targets.phony oc ~order_only_deps:[] ~inputs:[] ~output:group.dir *) (* pseuduo targets per directory *)
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/f25a373f7f42672dc1288c3eb206c476f622b6fa/jscomp/bsb/bsb_ninja_file_groups.ml
ocaml
TODO: add a loc for better error message FIXME: better names TODO: we can get rid of absloute path if we fixed the location to be [lib/bs], better for testing? ; Bsb_ninja_targets.phony oc ~order_only_deps:[] ~inputs:[] ~output:group.dir pseuduo targets per directory
Copyright ( C ) 2017 , Authors of ReScript * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let ( // ) = Ext_path.combine let handle_generators oc (group : Bsb_file_groups.file_group) custom_rules = let map_to_source_dir x = Bsb_config.proj_rel (group.dir // x) in Ext_list.iter group.generators (fun { output; input; command } -> match Map_string.find_opt custom_rules command with | None -> Ext_fmt.failwithf ~loc:__LOC__ "custom rule %s used but not defined" command | Some rule -> Bsb_ninja_targets.output_build oc ~outputs:(Ext_list.map output map_to_source_dir) ~inputs:(Ext_list.map input map_to_source_dir) ~rule) type suffixes = { impl : string; intf : string } let ml_suffixes = { impl = Literals.suffix_ml; intf = Literals.suffix_mli } let res_suffixes = { impl = Literals.suffix_res; intf = Literals.suffix_resi } let emit_module_build (rules : Bsb_ninja_rule.builtin) (package_specs : Bsb_package_specs.t) (is_dev : bool) oc namespace (module_info : Bsb_db.module_info) : unit = let has_intf_file = module_info.info = Impl_intf in let config, ast_rule = match module_info.syntax_kind with | Ml -> (ml_suffixes, rules.build_ast) | Res -> (res_suffixes, rules.build_ast_from_re) in let filename_sans_extension = module_info.name_sans_extension in let input_impl = Bsb_config.proj_rel (filename_sans_extension ^ config.impl) in let input_intf = Bsb_config.proj_rel (filename_sans_extension ^ config.intf) in let output_ast = filename_sans_extension ^ Literals.suffix_ast in let output_iast = filename_sans_extension ^ Literals.suffix_iast in let output_d = filename_sans_extension ^ Literals.suffix_d in let output_filename_sans_extension = Ext_namespace_encode.make ?ns:namespace filename_sans_extension in let output_cmi = output_filename_sans_extension ^ Literals.suffix_cmi in let output_cmj = output_filename_sans_extension ^ Literals.suffix_cmj in let output_js = Bsb_package_specs.get_list_of_output_js package_specs output_filename_sans_extension in Bsb_ninja_targets.output_build oc ~outputs:[ output_ast ] ~inputs:[ input_impl ] ~rule:ast_rule; Bsb_ninja_targets.output_build oc ~outputs:[ output_d ] ~inputs: (if has_intf_file then [ output_ast; output_iast ] else [ output_ast ]) ~rule:(if is_dev then rules.build_bin_deps_dev else rules.build_bin_deps); if has_intf_file then ( Bsb_ninja_targets.output_build oc ~outputs: [ output_iast ] ~inputs:[ input_intf ] ~rule:ast_rule; Bsb_ninja_targets.output_build oc ~outputs:[ output_cmi ] ~inputs:[ output_iast ] ~rule:(if is_dev then rules.mi_dev else rules.mi)); let rule = if has_intf_file then if is_dev then rules.mj_dev else rules.mj else if is_dev then rules.mij_dev else rules.mij in Bsb_ninja_targets.output_build oc ~outputs: (if has_intf_file then output_cmj :: output_js else output_cmj :: output_cmi :: output_js) ~inputs: (if has_intf_file then [ output_ast; output_cmi ] else [ output_ast ]) ~rule let handle_files_per_dir oc ~(rules : Bsb_ninja_rule.builtin) ~package_specs ~files_to_install ~(namespace : string option) (group : Bsb_file_groups.file_group) : unit = let is_dev = group.is_dev in handle_generators oc group rules.customs; let installable = match group.public with | Export_all -> fun _ -> true | Export_none -> fun _ -> false | Export_set set -> fun module_name -> Set_string.mem set module_name in Map_string.iter group.sources (fun module_name module_info -> if installable module_name && not is_dev then Queue.add module_info files_to_install; emit_module_build rules package_specs is_dev oc namespace module_info)
823a481af81ccd73d461c74a61b93e38d7ecd9f984922a8689575372912029b3
grin-compiler/ghc-wpc-sample-programs
IdiomBrackets.hs
module Agda.Syntax.IdiomBrackets (parseIdiomBracketsSeq) where import Control.Monad import Agda.Syntax.Common import Agda.Syntax.Position import Agda.Syntax.Concrete import Agda.Syntax.Concrete.Operators import Agda.Syntax.Concrete.Pretty ( leftIdiomBrkt, rightIdiomBrkt ) import Agda.Syntax.Scope.Base import Agda.Syntax.Scope.Monad import Agda.TypeChecking.Monad import Agda.Utils.Pretty ( prettyShow ) parseIdiomBracketsSeq :: Range -> [Expr] -> ScopeM Expr parseIdiomBracketsSeq r es = do let qEmpty = QName $ Name noRange InScope [Id "empty"] qPlus = QName $ Name noRange InScope [Hole, Id "<|>", Hole] ePlus a b = App r (App r (Ident qPlus) (defaultNamedArg a)) (defaultNamedArg b) case es of [] -> ensureInScope qEmpty >> return (Ident qEmpty) [e] -> parseIdiomBrackets r e es@(_:_) -> do ensureInScope qPlus es' <- mapM (parseIdiomBrackets r) es return $ foldr1 ePlus es' parseIdiomBrackets :: Range -> Expr -> ScopeM Expr parseIdiomBrackets r e = do let qPure = QName $ Name noRange InScope [Id "pure"] qAp = QName $ Name noRange InScope [Hole, Id "<*>", Hole] ePure = App r (Ident qPure) . defaultNamedArg eAp a b = App r (App r (Ident qAp) (defaultNamedArg a)) (defaultNamedArg b) mapM_ ensureInScope [qPure, qAp] case e of RawApp _ es -> do e : es <- appViewM =<< parseApplication es return $ foldl eAp (ePure e) es _ -> return $ ePure e appViewM :: Expr -> ScopeM [Expr] appViewM e = case e of App{} -> let AppView e' es = appView e in (e' :) <$> mapM onlyVisible es OpApp _ op _ es -> (Ident op :) <$> mapM (ordinary <=< noPlaceholder <=< onlyVisible) es _ -> return [e] where onlyVisible a | defaultNamedArg () == fmap (() <$) a = return $ namedArg a | otherwise = genericError "Only regular arguments are allowed in idiom brackets (no implicit or instance arguments)" noPlaceholder Placeholder{} = genericError "Naked sections are not allowed in idiom brackets" noPlaceholder (NoPlaceholder _ x) = return x ordinary (Ordinary a) = return a ordinary _ = genericError "Binding syntax is not allowed in idiom brackets" ensureInScope :: QName -> ScopeM () ensureInScope q = do r <- resolveName q case r of UnknownName -> genericError $ prettyShow q ++ " needs to be in scope to use idiom brackets " ++ prettyShow leftIdiomBrkt ++ " ... " ++ prettyShow rightIdiomBrkt _ -> return ()
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/Syntax/IdiomBrackets.hs
haskell
module Agda.Syntax.IdiomBrackets (parseIdiomBracketsSeq) where import Control.Monad import Agda.Syntax.Common import Agda.Syntax.Position import Agda.Syntax.Concrete import Agda.Syntax.Concrete.Operators import Agda.Syntax.Concrete.Pretty ( leftIdiomBrkt, rightIdiomBrkt ) import Agda.Syntax.Scope.Base import Agda.Syntax.Scope.Monad import Agda.TypeChecking.Monad import Agda.Utils.Pretty ( prettyShow ) parseIdiomBracketsSeq :: Range -> [Expr] -> ScopeM Expr parseIdiomBracketsSeq r es = do let qEmpty = QName $ Name noRange InScope [Id "empty"] qPlus = QName $ Name noRange InScope [Hole, Id "<|>", Hole] ePlus a b = App r (App r (Ident qPlus) (defaultNamedArg a)) (defaultNamedArg b) case es of [] -> ensureInScope qEmpty >> return (Ident qEmpty) [e] -> parseIdiomBrackets r e es@(_:_) -> do ensureInScope qPlus es' <- mapM (parseIdiomBrackets r) es return $ foldr1 ePlus es' parseIdiomBrackets :: Range -> Expr -> ScopeM Expr parseIdiomBrackets r e = do let qPure = QName $ Name noRange InScope [Id "pure"] qAp = QName $ Name noRange InScope [Hole, Id "<*>", Hole] ePure = App r (Ident qPure) . defaultNamedArg eAp a b = App r (App r (Ident qAp) (defaultNamedArg a)) (defaultNamedArg b) mapM_ ensureInScope [qPure, qAp] case e of RawApp _ es -> do e : es <- appViewM =<< parseApplication es return $ foldl eAp (ePure e) es _ -> return $ ePure e appViewM :: Expr -> ScopeM [Expr] appViewM e = case e of App{} -> let AppView e' es = appView e in (e' :) <$> mapM onlyVisible es OpApp _ op _ es -> (Ident op :) <$> mapM (ordinary <=< noPlaceholder <=< onlyVisible) es _ -> return [e] where onlyVisible a | defaultNamedArg () == fmap (() <$) a = return $ namedArg a | otherwise = genericError "Only regular arguments are allowed in idiom brackets (no implicit or instance arguments)" noPlaceholder Placeholder{} = genericError "Naked sections are not allowed in idiom brackets" noPlaceholder (NoPlaceholder _ x) = return x ordinary (Ordinary a) = return a ordinary _ = genericError "Binding syntax is not allowed in idiom brackets" ensureInScope :: QName -> ScopeM () ensureInScope q = do r <- resolveName q case r of UnknownName -> genericError $ prettyShow q ++ " needs to be in scope to use idiom brackets " ++ prettyShow leftIdiomBrkt ++ " ... " ++ prettyShow rightIdiomBrkt _ -> return ()
2b5b60fbf652af7fb88e27aa49f5184314c81c35a4d076a6fe4e3722a1acc94b
mcorbin/meuse
error.clj
(ns meuse.interceptor.error (:require [meuse.error :as err] [meuse.log :as log] [meuse.metric :as metric] [exoscale.ex :as ex])) (defn handle-error [request e] (cond (ex/type? e ::err/user) (err/handle-user-error request e) (ex/type? e ::err/redirect-login) (err/redirect-login-error request e) :else (err/handle-unexpected-error request e))) (def error {:name ::error :error (fn [ctx e] (assoc ctx :response (handle-error (:request ctx) e)))}) (def last-error {:name ::last-error :error (fn [ctx e] (try (metric/increment! :http.fatal.error.total {}) (log/error {} e "fatal error") (assoc ctx :response {:status 500 :body {:error err/default-msg}}) (catch Exception e (log/error {} e "fatal error in the last handler") (assoc ctx :response {:status 500 :body {:error err/default-msg}}))))})
null
https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/src/meuse/interceptor/error.clj
clojure
(ns meuse.interceptor.error (:require [meuse.error :as err] [meuse.log :as log] [meuse.metric :as metric] [exoscale.ex :as ex])) (defn handle-error [request e] (cond (ex/type? e ::err/user) (err/handle-user-error request e) (ex/type? e ::err/redirect-login) (err/redirect-login-error request e) :else (err/handle-unexpected-error request e))) (def error {:name ::error :error (fn [ctx e] (assoc ctx :response (handle-error (:request ctx) e)))}) (def last-error {:name ::last-error :error (fn [ctx e] (try (metric/increment! :http.fatal.error.total {}) (log/error {} e "fatal error") (assoc ctx :response {:status 500 :body {:error err/default-msg}}) (catch Exception e (log/error {} e "fatal error in the last handler") (assoc ctx :response {:status 500 :body {:error err/default-msg}}))))})
15b2741318f9a75ad5073f02838c1468fa5421d262ef96173b1ae584b41bfd7c
gorillalabs/sparkling
dslapi_test.clj
(ns sparkling.ml.dslapi-test (:require [sparkling.conf :as conf] [sparkling.core :as s] [sparkling.ml.core :as m] [sparkling.ml.classification :as cl] [sparkling.ml.transform :as xf] [clojure.test :as t] [sparkling.ml.validation :as v]) (:import [org.apache.spark.api.java JavaSparkContext] [org.apache.spark.sql SQLContext] [org.apache.spark.ml.classification NaiveBayes LogisticRegression DecisionTreeClassifier RandomForestClassifier GBTClassifier ] [java.io File])) ;;new story to use the middleware pattern (def dataset-path "data/ml/svmguide1") (defn add-estimator-pipeline "returns a pipeline consisting of a scaler and an estimator" [options] scale the features to stay in the 0 - 1 range ss (xf/standard-scaler {:input-col "features" :output-col "nfeatures"}) ;tell the classifier to look for the modified features lr1 (doto (cl/logistic-regression) (.setFeaturesCol "nfeatures"))] create a pipeline that scales the features first before training (m/make-pipeline [ss lr1]))) (defn addregularization "sets the regularization parameters to search over" [regparam est] (v/param-grid [[(.regParam est) (double-array regparam)]])) (t/deftest defaults ;;sensible defaults (let [cvhand (-> m/cv-handler (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression) (m/add-evaluator v/binary-classification-evaluator)) res (first (m/run-pipeline cvhand))] (t/is (> res 0.95)))) (t/deftest with-estimator-options ;;add options for the estimator & evaluator (let [cvhand (-> m/cv-handler (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression {:elastic-net-param 0.01}) (m/add-evaluator v/binary-classification-evaluator {:metric-name "areaUnderPR"} )) res (first (m/run-pipeline cvhand))] (t/is (> res 0.95)))) (t/deftest with-handler-options ;;add options for the handler (let [cvhand (-> (partial m/cv-handler {:num-folds 5}) (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression {:elastic-net-param 0.01}) (m/add-evaluator v/binary-classification-evaluator {:metric-name "areaUnderPR"} )) res (first (m/run-pipeline cvhand))] (t/is (> res 0.95)))) ;; train-validation splits (t/deftest train-val-split ;defaults for train-test split validator (let [tvhand (-> m/tv-handler (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression) (m/add-evaluator v/binary-classification-evaluator)) res (first (m/run-pipeline tvhand))] (t/is (> res 0.95))) ;;set the train-test split ratio (let [tvhand (-> (partial m/tv-handler {:train-ratio 0.6} ) (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression) (m/add-evaluator v/binary-classification-evaluator)) res (first (m/run-pipeline tvhand))] (t/is (> res 0.95))) ) (t/deftest gridsearch ;run grid search over regularization parameters provided in the vector (let [cvgrid (-> m/cv-handler (m/add-grid-search (partial addregularization [0.1 0.05 0.01])) (m/add-evaluator v/binary-classification-evaluator) (m/add-estimator cl/logistic-regression) (m/add-dataset (partial m/load-libsvm-dataset dataset-path)))] (t/is (= 3 (count (m/run-pipeline cvgrid)))))) (t/deftest pipelines ;create an estimator pipeline that transforms features prior to ;estimation (let [cvestpipeline (-> m/cv-handler (m/add-evaluator v/binary-classification-evaluator) (m/add-estimator add-estimator-pipeline) (m/add-dataset (partial m/load-libsvm-dataset dataset-path)))] (t/is (< 0.95 (first (m/run-pipeline cvestpipeline)))))) (comment (defn classifier-test-pipeline [cls] (-> m/cv-handler (m/add-dataset (partial m/load-libsvm-dataset "/tmp/svmguide1.txt")) (m/add-estimator cls) (m/add-evaluator v/binary-classification-evaluator))) ;;doesn't work on this dataset as the features are continuous, not binary (let [ classifiers [cl/logistic-regression nb # ( cl / naive - bayes { : model - type " " } ) ]] (->> classifiers (map classifier-test-pipeline) (map m/run-pipeline))))
null
https://raw.githubusercontent.com/gorillalabs/sparkling/ffedcc70fd46bf1b48405be8b1f5a1e1c4f9f578/test/sparkling/ml/dslapi_test.clj
clojure
new story to use the middleware pattern tell the classifier to look for the modified features sensible defaults add options for the estimator & evaluator add options for the handler train-validation splits defaults for train-test split validator set the train-test split ratio run grid search over regularization parameters provided in the vector create an estimator pipeline that transforms features prior to estimation doesn't work on this dataset as the features are continuous, not binary
(ns sparkling.ml.dslapi-test (:require [sparkling.conf :as conf] [sparkling.core :as s] [sparkling.ml.core :as m] [sparkling.ml.classification :as cl] [sparkling.ml.transform :as xf] [clojure.test :as t] [sparkling.ml.validation :as v]) (:import [org.apache.spark.api.java JavaSparkContext] [org.apache.spark.sql SQLContext] [org.apache.spark.ml.classification NaiveBayes LogisticRegression DecisionTreeClassifier RandomForestClassifier GBTClassifier ] [java.io File])) (def dataset-path "data/ml/svmguide1") (defn add-estimator-pipeline "returns a pipeline consisting of a scaler and an estimator" [options] scale the features to stay in the 0 - 1 range ss (xf/standard-scaler {:input-col "features" :output-col "nfeatures"}) lr1 (doto (cl/logistic-regression) (.setFeaturesCol "nfeatures"))] create a pipeline that scales the features first before training (m/make-pipeline [ss lr1]))) (defn addregularization "sets the regularization parameters to search over" [regparam est] (v/param-grid [[(.regParam est) (double-array regparam)]])) (t/deftest defaults (let [cvhand (-> m/cv-handler (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression) (m/add-evaluator v/binary-classification-evaluator)) res (first (m/run-pipeline cvhand))] (t/is (> res 0.95)))) (t/deftest with-estimator-options (let [cvhand (-> m/cv-handler (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression {:elastic-net-param 0.01}) (m/add-evaluator v/binary-classification-evaluator {:metric-name "areaUnderPR"} )) res (first (m/run-pipeline cvhand))] (t/is (> res 0.95)))) (t/deftest with-handler-options (let [cvhand (-> (partial m/cv-handler {:num-folds 5}) (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression {:elastic-net-param 0.01}) (m/add-evaluator v/binary-classification-evaluator {:metric-name "areaUnderPR"} )) res (first (m/run-pipeline cvhand))] (t/is (> res 0.95)))) (t/deftest train-val-split (let [tvhand (-> m/tv-handler (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression) (m/add-evaluator v/binary-classification-evaluator)) res (first (m/run-pipeline tvhand))] (t/is (> res 0.95))) (let [tvhand (-> (partial m/tv-handler {:train-ratio 0.6} ) (m/add-dataset (partial m/load-libsvm-dataset dataset-path)) (m/add-estimator cl/logistic-regression) (m/add-evaluator v/binary-classification-evaluator)) res (first (m/run-pipeline tvhand))] (t/is (> res 0.95))) ) (t/deftest gridsearch (let [cvgrid (-> m/cv-handler (m/add-grid-search (partial addregularization [0.1 0.05 0.01])) (m/add-evaluator v/binary-classification-evaluator) (m/add-estimator cl/logistic-regression) (m/add-dataset (partial m/load-libsvm-dataset dataset-path)))] (t/is (= 3 (count (m/run-pipeline cvgrid)))))) (t/deftest pipelines (let [cvestpipeline (-> m/cv-handler (m/add-evaluator v/binary-classification-evaluator) (m/add-estimator add-estimator-pipeline) (m/add-dataset (partial m/load-libsvm-dataset dataset-path)))] (t/is (< 0.95 (first (m/run-pipeline cvestpipeline)))))) (comment (defn classifier-test-pipeline [cls] (-> m/cv-handler (m/add-dataset (partial m/load-libsvm-dataset "/tmp/svmguide1.txt")) (m/add-estimator cls) (m/add-evaluator v/binary-classification-evaluator))) (let [ classifiers [cl/logistic-regression nb # ( cl / naive - bayes { : model - type " " } ) ]] (->> classifiers (map classifier-test-pipeline) (map m/run-pipeline))))
2075825f04ceaca41fb6f4d87d4c73742acad63d77a8cfe733ea8716eec676d2
elastic/eui-cljs
context_menu_panel.cljs
(ns eui.context-menu-panel (:require ["@elastic/eui/lib/components/context_menu/context_menu_panel.js" :as eui])) (def SIZES eui/SIZES) (def EuiContextMenuPanel eui/EuiContextMenuPanel)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/context_menu_panel.cljs
clojure
(ns eui.context-menu-panel (:require ["@elastic/eui/lib/components/context_menu/context_menu_panel.js" :as eui])) (def SIZES eui/SIZES) (def EuiContextMenuPanel eui/EuiContextMenuPanel)
133854283b5cd378d61da40d5e7cf684b46233fb46ff3f940740e8bcac7b0d97
GumTreeDiff/cgum
oset.ml
* Copyright 2014 , INRIA * * This file is part of Cgen . Much of it comes from Coccinelle , which is * also available under the GPLv2 license * * Cgen 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 , according to version 2 of the License . * * Cgen 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 Cgen . If not , see < / > . * * The authors reserve the right to distribute this or future versions of * Cgen under other licenses . * Copyright 2014, INRIA * Julia Lawall * This file is part of Cgen. Much of it comes from Coccinelle, which is * also available under the GPLv2 license * * Cgen 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, according to version 2 of the License. * * Cgen 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 Cgen. If not, see </>. * * The authors reserve the right to distribute this or future versions of * Cgen under other licenses. *) # 0 "./oset.ml" open Common open Ocollection class virtual ['a] oset = object(o: 'o) inherit ['a] ocollection (* no need virtual, but better to redefine (efficiency) *) method virtual union: 'o -> 'o method virtual inter: 'o -> 'o method virtual minus: 'o -> 'o (* allow binary methods tricks, generate exception when not good type *) method tosetb: 'a Setb.t = raise (Impossible 10) method tosetpt: SetPt.t = raise (Impossible 11) method toseti: Seti.seti = raise (Impossible 12) method virtual toset: 'b. 'b (* generic (not safe) tricks *) (* is_intersect, equal, subset *) method is_subset_of: 'o -> bool = fun o2 -> ((o2#minus o)#cardinal >= 0) && ((o#minus o2)#cardinal =|= 0) method is_equal: 'o -> bool = fun o2 -> ((o2#minus o)#cardinal =|= 0) && ((o#minus o2)#cardinal =|= 0) method is_singleton: bool = (* can be short circuited *) o#length =|= 1 method cardinal: int = (* just to keep naming conventions *) o#length (* dont work: method big_union: 'b. ('a -> 'b oset) -> 'b oset = fun f -> todo() *) end let ($??$) e xs = xs#mem e let ($++$) xs ys = xs#union ys let ($**$) xs ys = xs#inter ys let ($--$) xs ys = xs#minus ys let ($<<=$) xs ys = xs#is_subset_of ys let ($==$) xs ys = xs#is_equal ys (* todo: pas beau le seed. I dont put the type otherwise have to * put explicit :> *) let (mapo: ('a -> 'b) -> 'b oset -> 'a oset -> 'b oset) = fun f seed xs -> xs#fold (fun acc x -> acc#add (f x)) seed
null
https://raw.githubusercontent.com/GumTreeDiff/cgum/8521aa80fcf4873a19e60ce8c846c886aaefb41b/commons/oset.ml
ocaml
no need virtual, but better to redefine (efficiency) allow binary methods tricks, generate exception when not good type generic (not safe) tricks is_intersect, equal, subset can be short circuited just to keep naming conventions dont work: method big_union: 'b. ('a -> 'b oset) -> 'b oset = fun f -> todo() todo: pas beau le seed. I dont put the type otherwise have to * put explicit :>
* Copyright 2014 , INRIA * * This file is part of Cgen . Much of it comes from Coccinelle , which is * also available under the GPLv2 license * * Cgen 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 , according to version 2 of the License . * * Cgen 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 Cgen . If not , see < / > . * * The authors reserve the right to distribute this or future versions of * Cgen under other licenses . * Copyright 2014, INRIA * Julia Lawall * This file is part of Cgen. Much of it comes from Coccinelle, which is * also available under the GPLv2 license * * Cgen 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, according to version 2 of the License. * * Cgen 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 Cgen. If not, see </>. * * The authors reserve the right to distribute this or future versions of * Cgen under other licenses. *) # 0 "./oset.ml" open Common open Ocollection class virtual ['a] oset = object(o: 'o) inherit ['a] ocollection method virtual union: 'o -> 'o method virtual inter: 'o -> 'o method virtual minus: 'o -> 'o method tosetb: 'a Setb.t = raise (Impossible 10) method tosetpt: SetPt.t = raise (Impossible 11) method toseti: Seti.seti = raise (Impossible 12) method is_subset_of: 'o -> bool = fun o2 -> ((o2#minus o)#cardinal >= 0) && ((o#minus o2)#cardinal =|= 0) method is_equal: 'o -> bool = fun o2 -> ((o2#minus o)#cardinal =|= 0) && ((o#minus o2)#cardinal =|= 0) o#length =|= 1 o#length end let ($??$) e xs = xs#mem e let ($++$) xs ys = xs#union ys let ($**$) xs ys = xs#inter ys let ($--$) xs ys = xs#minus ys let ($<<=$) xs ys = xs#is_subset_of ys let ($==$) xs ys = xs#is_equal ys let (mapo: ('a -> 'b) -> 'b oset -> 'a oset -> 'b oset) = fun f seed xs -> xs#fold (fun acc x -> acc#add (f x)) seed
1471a4add3144fda32074df3502d792ff49e6d874c688b4923f5ebff23479229
patperry/hs-linear-algebra
Tri.hs
{-# LANGUAGE Rank2Types #-} ----------------------------------------------------------------------------- -- | Module : Numeric . LinearAlgebra . Matrix . Tri Copyright : Copyright ( c ) 2010 , < > -- License : BSD3 Maintainer : < > -- Stability : experimental -- Triangular views of matrices . -- module Numeric.LinearAlgebra.Matrix.Tri ( -- * Immutable interface -- ** Vector multiplication triMulVector, -- ** Matrix multiplication triMulMatrix, triMulMatrixWithScale, -- ** Vector solving triSolvVector, -- ** Matrix solving triSolvMatrix, triSolvMatrixWithScale, -- * Mutable interface triCreate, -- ** Vector multiplication triMulVectorM_, -- ** Matrix multiplication triMulMatrixM_, triMulMatrixWithScaleM_, -- ** Vector solving triSolvVectorM_, -- ** Matrix solving triSolvMatrixM_, triSolvMatrixWithScaleM_, ) where import Control.Monad( when ) import Control.Monad.ST( ST, runST, unsafeIOToST ) import Text.Printf( printf ) import Numeric.LinearAlgebra.Vector( Vector, STVector ) import qualified Numeric.LinearAlgebra.Vector as V import Numeric.LinearAlgebra.Matrix.Base( Matrix ) import Numeric.LinearAlgebra.Matrix.STBase( STMatrix, RMatrix ) import qualified Numeric.LinearAlgebra.Matrix.STBase as M import Numeric.LinearAlgebra.Types import qualified Foreign.BLAS as BLAS | A safe way to create and work with a mutable Tri Matrix before returning -- an immutable one for later perusal. triCreate :: (Storable e) => (forall s. ST s (Tri (STMatrix s) e)) -> Tri Matrix e triCreate mt = runST $ do (Tri u d ma) <- mt a <- M.unsafeFreeze ma return $ Tri u d a | @triMulVector trans a x@ returns @op(a ) * , where is -- determined by @trans@. triMulVector :: (BLAS2 e) => Trans -> Tri Matrix e -> Vector e -> Vector e triMulVector trans a x = V.create $ do x' <- V.newCopy x triMulVectorM_ trans a x' return x' -- | @triMulMatrix side a b@ -- returns @alpha * op(a) * b@ when @side@ is @LeftSide@ and @alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triMulMatrix :: (BLAS3 e) => Side -> Trans -> Tri Matrix e -> Matrix e -> Matrix e triMulMatrix side trans a b = M.create $ do b' <- M.newCopy b triMulMatrixM_ side trans a b' return b' -- | @triMulMatrixWithScale alpha side trans a b@ -- returns @alpha * op(a) * b@ when @side@ is @LeftSide@ and @alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triMulMatrixWithScale :: (BLAS3 e) => e -> Side -> Trans -> Tri Matrix e -> Matrix e -> Matrix e triMulMatrixWithScale alpha side trans a b = M.create $ do b' <- M.newCopy b triMulMatrixWithScaleM_ alpha side trans a b' return b' | @triMulVectorM _ a x@ sets @x : = op(a ) * , where is determined -- by @trans@. triMulVectorM_ :: (RMatrix m, BLAS2 e) => Trans -> Tri m e -> STVector s e -> ST s () triMulVectorM_ trans (Tri uplo diag a) x = do (ma,na) <- M.getDim a nx <- V.getDim x let n = nx when (ma /= na) $ error $ printf ("triMulVectorM_" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " _" ++ ": matrix is not square") ma na when ((not . and) [ (ma,na) == (n,n) , nx == n ]) $ error $ printf ("triMulVectorM_" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " <vector with dim %d>" ++ ": dimension mismatch") ma na nx unsafeIOToST $ M.unsafeWith a $ \pa lda -> V.unsafeWith x $ \px -> BLAS.trmv uplo trans diag n pa lda px 1 -- | @triMulMatrixM_ side trans a b@ -- sets @b := op(a) * b@ when @side@ is @LeftSide@ and @b : = b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triMulMatrixM_ :: (RMatrix m, BLAS3 e) => Side -> Trans -> Tri m e -> STMatrix s e -> ST s () triMulMatrixM_ = triMulMatrixWithScaleM_ 1 -- | @triMulMatrixWithScaleM_ alpha side trans a b@ -- sets @b := alpha * op(a) * b@ when @side@ is @LeftSide@ and @b : = alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triMulMatrixWithScaleM_ :: (RMatrix m, BLAS3 e) => e -> Side -> Trans -> Tri m e -> STMatrix s e -> ST s () triMulMatrixWithScaleM_ alpha side trans (Tri uplo diag a) b = do (ma,na) <- M.getDim a (mb,nb) <- M.getDim b let (m,n) = (mb,nb) when (ma /= na) $ error $ printf ("triMulMatrixWithScaleM_" ++ " _" ++ " _" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " _" ++ ": matrix is not square") ma na when ((not . and) [ case side of LeftSide -> (ma,na) == (m,m) RightSide -> (ma,na) == (n,n) , (mb, nb ) == (m,n) ]) $ error $ printf ("triMulMatrixWithScaleM_" ++ " _" ++ " %s" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") (show side) ma na mb nb unsafeIOToST $ M.unsafeWith a $ \pa lda -> M.unsafeWith b $ \pb ldb -> BLAS.trmm side uplo trans diag m n alpha pa lda pb ldb | @triSolvVector trans a x@ returns @op(a ) \\ , where is -- determined by @trans@. triSolvVector :: (BLAS2 e) => Trans -> Tri Matrix e -> Vector e -> Vector e triSolvVector trans a x = V.create $ do x' <- V.newCopy x triSolvVectorM_ trans a x' return x' -- | @triSolvMatrix side a b@ -- returns @alpha * op(a) \\ b@ when @side@ is @LeftSide@ and @alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triSolvMatrix :: (BLAS3 e) => Side -> Trans -> Tri Matrix e -> Matrix e -> Matrix e triSolvMatrix side trans a b = M.create $ do b' <- M.newCopy b triSolvMatrixM_ side trans a b' return b' -- | @triSolvMatrixWithScale alpha side trans a b@ -- returns @alpha * op(a) \\ b@ when @side@ is @LeftSide@ and @alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triSolvMatrixWithScale :: (BLAS3 e) => e -> Side -> Trans -> Tri Matrix e -> Matrix e -> Matrix e triSolvMatrixWithScale alpha side trans a b = M.create $ do b' <- M.newCopy b triSolvMatrixWithScaleM_ alpha side trans a b' return b' | @triSolvVectorM _ a x@ sets @x : = op(a ) \\ , where is determined -- by @trans@. triSolvVectorM_ :: (RMatrix m, BLAS2 e) => Trans -> Tri m e -> STVector s e -> ST s () triSolvVectorM_ trans (Tri uplo diag a) x = do (ma,na) <- M.getDim a nx <- V.getDim x let n = nx when (ma /= na) $ error $ printf ("triSolvVectorM_" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " _" ++ ": matrix is not square") ma na when ((not . and) [ (ma,na) == (n,n) , nx == n ]) $ error $ printf ("triSolvVectorM_" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " <vector with dim %d>" ++ ": dimension mismatch") ma na nx unsafeIOToST $ M.unsafeWith a $ \pa lda -> V.unsafeWith x $ \px -> BLAS.trsv uplo trans diag n pa lda px 1 -- | @triSolvMatrixM_ side trans a b@ -- sets @b := op(a) \\ b@ when @side@ is @LeftSide@ and @b : = b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triSolvMatrixM_ :: (RMatrix m, BLAS3 e) => Side -> Trans -> Tri m e -> STMatrix s e -> ST s () triSolvMatrixM_ = triSolvMatrixWithScaleM_ 1 -- | @triSolvMatrixWithScaleM_ alpha side trans a b@ -- sets @b := alpha * op(a) \\ b@ when @side@ is @LeftSide@ and @b : = alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triSolvMatrixWithScaleM_ :: (RMatrix m, BLAS3 e) => e -> Side -> Trans -> Tri m e -> STMatrix s e -> ST s () triSolvMatrixWithScaleM_ alpha side trans (Tri uplo diag a) b = do (ma,na) <- M.getDim a (mb,nb) <- M.getDim b let (m,n) = (mb,nb) when (ma /= na) $ error $ printf ("triSolvMatrixWithScaleM_" ++ " _" ++ " _" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " _" ++ ": matrix is not square") ma na when ((not . and) [ case side of LeftSide -> (ma,na) == (m,m) RightSide -> (ma,na) == (n,n) , (mb, nb ) == (m,n) ]) $ error $ printf ("triSolvMatrixWithScaleM_" ++ " _" ++ " %s" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") (show side) ma na mb nb unsafeIOToST $ M.unsafeWith a $ \pa lda -> M.unsafeWith b $ \pb ldb -> BLAS.trsm side uplo trans diag m n alpha pa lda pb ldb
null
https://raw.githubusercontent.com/patperry/hs-linear-algebra/887939175e03687b12eabe2fce5904b494242a1a/lib/Numeric/LinearAlgebra/Matrix/Tri.hs
haskell
# LANGUAGE Rank2Types # --------------------------------------------------------------------------- | License : BSD3 Stability : experimental * Immutable interface ** Vector multiplication ** Matrix multiplication ** Vector solving ** Matrix solving * Mutable interface ** Vector multiplication ** Matrix multiplication ** Vector solving ** Matrix solving an immutable one for later perusal. determined by @trans@. | @triMulMatrix side a b@ returns @alpha * op(a) * b@ when @side@ is @LeftSide@ and | @triMulMatrixWithScale alpha side trans a b@ returns @alpha * op(a) * b@ when @side@ is @LeftSide@ and by @trans@. | @triMulMatrixM_ side trans a b@ sets @b := op(a) * b@ when @side@ is @LeftSide@ and | @triMulMatrixWithScaleM_ alpha side trans a b@ sets @b := alpha * op(a) * b@ when @side@ is @LeftSide@ and determined by @trans@. | @triSolvMatrix side a b@ returns @alpha * op(a) \\ b@ when @side@ is @LeftSide@ and | @triSolvMatrixWithScale alpha side trans a b@ returns @alpha * op(a) \\ b@ when @side@ is @LeftSide@ and by @trans@. | @triSolvMatrixM_ side trans a b@ sets @b := op(a) \\ b@ when @side@ is @LeftSide@ and | @triSolvMatrixWithScaleM_ alpha side trans a b@ sets @b := alpha * op(a) \\ b@ when @side@ is @LeftSide@ and
Module : Numeric . LinearAlgebra . Matrix . Tri Copyright : Copyright ( c ) 2010 , < > Maintainer : < > Triangular views of matrices . module Numeric.LinearAlgebra.Matrix.Tri ( triMulVector, triMulMatrix, triMulMatrixWithScale, triSolvVector, triSolvMatrix, triSolvMatrixWithScale, triCreate, triMulVectorM_, triMulMatrixM_, triMulMatrixWithScaleM_, triSolvVectorM_, triSolvMatrixM_, triSolvMatrixWithScaleM_, ) where import Control.Monad( when ) import Control.Monad.ST( ST, runST, unsafeIOToST ) import Text.Printf( printf ) import Numeric.LinearAlgebra.Vector( Vector, STVector ) import qualified Numeric.LinearAlgebra.Vector as V import Numeric.LinearAlgebra.Matrix.Base( Matrix ) import Numeric.LinearAlgebra.Matrix.STBase( STMatrix, RMatrix ) import qualified Numeric.LinearAlgebra.Matrix.STBase as M import Numeric.LinearAlgebra.Types import qualified Foreign.BLAS as BLAS | A safe way to create and work with a mutable Tri Matrix before returning triCreate :: (Storable e) => (forall s. ST s (Tri (STMatrix s) e)) -> Tri Matrix e triCreate mt = runST $ do (Tri u d ma) <- mt a <- M.unsafeFreeze ma return $ Tri u d a | @triMulVector trans a x@ returns @op(a ) * , where is triMulVector :: (BLAS2 e) => Trans -> Tri Matrix e -> Vector e -> Vector e triMulVector trans a x = V.create $ do x' <- V.newCopy x triMulVectorM_ trans a x' return x' @alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triMulMatrix :: (BLAS3 e) => Side -> Trans -> Tri Matrix e -> Matrix e -> Matrix e triMulMatrix side trans a b = M.create $ do b' <- M.newCopy b triMulMatrixM_ side trans a b' return b' @alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triMulMatrixWithScale :: (BLAS3 e) => e -> Side -> Trans -> Tri Matrix e -> Matrix e -> Matrix e triMulMatrixWithScale alpha side trans a b = M.create $ do b' <- M.newCopy b triMulMatrixWithScaleM_ alpha side trans a b' return b' | @triMulVectorM _ a x@ sets @x : = op(a ) * , where is determined triMulVectorM_ :: (RMatrix m, BLAS2 e) => Trans -> Tri m e -> STVector s e -> ST s () triMulVectorM_ trans (Tri uplo diag a) x = do (ma,na) <- M.getDim a nx <- V.getDim x let n = nx when (ma /= na) $ error $ printf ("triMulVectorM_" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " _" ++ ": matrix is not square") ma na when ((not . and) [ (ma,na) == (n,n) , nx == n ]) $ error $ printf ("triMulVectorM_" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " <vector with dim %d>" ++ ": dimension mismatch") ma na nx unsafeIOToST $ M.unsafeWith a $ \pa lda -> V.unsafeWith x $ \px -> BLAS.trmv uplo trans diag n pa lda px 1 @b : = b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triMulMatrixM_ :: (RMatrix m, BLAS3 e) => Side -> Trans -> Tri m e -> STMatrix s e -> ST s () triMulMatrixM_ = triMulMatrixWithScaleM_ 1 @b : = alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triMulMatrixWithScaleM_ :: (RMatrix m, BLAS3 e) => e -> Side -> Trans -> Tri m e -> STMatrix s e -> ST s () triMulMatrixWithScaleM_ alpha side trans (Tri uplo diag a) b = do (ma,na) <- M.getDim a (mb,nb) <- M.getDim b let (m,n) = (mb,nb) when (ma /= na) $ error $ printf ("triMulMatrixWithScaleM_" ++ " _" ++ " _" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " _" ++ ": matrix is not square") ma na when ((not . and) [ case side of LeftSide -> (ma,na) == (m,m) RightSide -> (ma,na) == (n,n) , (mb, nb ) == (m,n) ]) $ error $ printf ("triMulMatrixWithScaleM_" ++ " _" ++ " %s" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") (show side) ma na mb nb unsafeIOToST $ M.unsafeWith a $ \pa lda -> M.unsafeWith b $ \pb ldb -> BLAS.trmm side uplo trans diag m n alpha pa lda pb ldb | @triSolvVector trans a x@ returns @op(a ) \\ , where is triSolvVector :: (BLAS2 e) => Trans -> Tri Matrix e -> Vector e -> Vector e triSolvVector trans a x = V.create $ do x' <- V.newCopy x triSolvVectorM_ trans a x' return x' @alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triSolvMatrix :: (BLAS3 e) => Side -> Trans -> Tri Matrix e -> Matrix e -> Matrix e triSolvMatrix side trans a b = M.create $ do b' <- M.newCopy b triSolvMatrixM_ side trans a b' return b' @alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triSolvMatrixWithScale :: (BLAS3 e) => e -> Side -> Trans -> Tri Matrix e -> Matrix e -> Matrix e triSolvMatrixWithScale alpha side trans a b = M.create $ do b' <- M.newCopy b triSolvMatrixWithScaleM_ alpha side trans a b' return b' | @triSolvVectorM _ a x@ sets @x : = op(a ) \\ , where is determined triSolvVectorM_ :: (RMatrix m, BLAS2 e) => Trans -> Tri m e -> STVector s e -> ST s () triSolvVectorM_ trans (Tri uplo diag a) x = do (ma,na) <- M.getDim a nx <- V.getDim x let n = nx when (ma /= na) $ error $ printf ("triSolvVectorM_" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " _" ++ ": matrix is not square") ma na when ((not . and) [ (ma,na) == (n,n) , nx == n ]) $ error $ printf ("triSolvVectorM_" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " <vector with dim %d>" ++ ": dimension mismatch") ma na nx unsafeIOToST $ M.unsafeWith a $ \pa lda -> V.unsafeWith x $ \px -> BLAS.trsv uplo trans diag n pa lda px 1 @b : = b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triSolvMatrixM_ :: (RMatrix m, BLAS3 e) => Side -> Trans -> Tri m e -> STMatrix s e -> ST s () triSolvMatrixM_ = triSolvMatrixWithScaleM_ 1 @b : = alpha * b * op(a)@ when @side@ is @RightSide@. Operation is determined by @trans@. triSolvMatrixWithScaleM_ :: (RMatrix m, BLAS3 e) => e -> Side -> Trans -> Tri m e -> STMatrix s e -> ST s () triSolvMatrixWithScaleM_ alpha side trans (Tri uplo diag a) b = do (ma,na) <- M.getDim a (mb,nb) <- M.getDim b let (m,n) = (mb,nb) when (ma /= na) $ error $ printf ("triSolvMatrixWithScaleM_" ++ " _" ++ " _" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " _" ++ ": matrix is not square") ma na when ((not . and) [ case side of LeftSide -> (ma,na) == (m,m) RightSide -> (ma,na) == (n,n) , (mb, nb ) == (m,n) ]) $ error $ printf ("triSolvMatrixWithScaleM_" ++ " _" ++ " %s" ++ " _" ++ " (Tri _ _ <matrix with dim (%d,%d)>)" ++ " <matrix with dim (%d,%d)>" ++ ": dimension mismatch") (show side) ma na mb nb unsafeIOToST $ M.unsafeWith a $ \pa lda -> M.unsafeWith b $ \pb ldb -> BLAS.trsm side uplo trans diag m n alpha pa lda pb ldb
2b483a550d21e8d81601df2d7adc39fc547bcf6fabae70e2bc92f2849ffb9dfd
mrkkrp/parser-combinators
NonEmpty.hs
-- | -- Module : Control.Applicative.Combinators Copyright : © 2017 – present License : BSD 3 clause -- Maintainer : < > -- Stability : experimental -- Portability : portable -- The module provides ' NonEmpty ' list variants of some of the functions -- from "Control.Applicative.Combinators". -- -- @since 0.2.0 module Control.Applicative.Combinators.NonEmpty ( some, endBy1, someTill, sepBy1, sepEndBy1, ) where import Control.Applicative hiding (some) import qualified Control.Applicative.Combinators as C import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE -- | @'some' p@ applies the parser @p@ /one/ or more times and returns a list of the values returned by @p@. -- -- > word = some letter some :: (Alternative m) => m a -> m (NonEmpty a) some p = NE.fromList <$> C.some p # INLINE some # | @'endBy1 ' p sep@ parses /one/ or more occurrences of @p@ , separated and ended by @sep@. Returns a non - empty list of values returned by @p@. endBy1 :: (Alternative m) => m a -> m sep -> m (NonEmpty a) endBy1 p sep = NE.fromList <$> C.endBy1 p sep # INLINE endBy1 # | @'someTill ' p end@ works similarly to @'C.manyTill ' p end@ , but @p@ -- should succeed at least once. -- See also : ' C.skipSome ' , ' C.skipSomeTill ' . someTill :: (Alternative m) => m a -> m end -> m (NonEmpty a) someTill p end = NE.fromList <$> C.someTill p end # INLINE someTill # | @'sepBy1 ' p sep@ parses /one/ or more occurrences of @p@ , separated by @sep@. Returns a non - empty list of values returned by @p@. sepBy1 :: (Alternative m) => m a -> m sep -> m (NonEmpty a) sepBy1 p sep = NE.fromList <$> C.sepBy1 p sep # INLINE sepBy1 # | @'sepEndBy1 ' p sep@ parses /one/ or more occurrences of @p@ , separated and optionally ended by @sep@. Returns a non - empty list of values returned by -- @p@. sepEndBy1 :: (Alternative m) => m a -> m sep -> m (NonEmpty a) sepEndBy1 p sep = NE.fromList <$> C.sepEndBy1 p sep # INLINE sepEndBy1 #
null
https://raw.githubusercontent.com/mrkkrp/parser-combinators/290852927db8e252baee8ac7521e153d377e01d3/Control/Applicative/Combinators/NonEmpty.hs
haskell
| Module : Control.Applicative.Combinators Stability : experimental Portability : portable from "Control.Applicative.Combinators". @since 0.2.0 | @'some' p@ applies the parser @p@ /one/ or more times and returns a > word = some letter should succeed at least once. @p@.
Copyright : © 2017 – present License : BSD 3 clause Maintainer : < > The module provides ' NonEmpty ' list variants of some of the functions module Control.Applicative.Combinators.NonEmpty ( some, endBy1, someTill, sepBy1, sepEndBy1, ) where import Control.Applicative hiding (some) import qualified Control.Applicative.Combinators as C import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE list of the values returned by @p@. some :: (Alternative m) => m a -> m (NonEmpty a) some p = NE.fromList <$> C.some p # INLINE some # | @'endBy1 ' p sep@ parses /one/ or more occurrences of @p@ , separated and ended by @sep@. Returns a non - empty list of values returned by @p@. endBy1 :: (Alternative m) => m a -> m sep -> m (NonEmpty a) endBy1 p sep = NE.fromList <$> C.endBy1 p sep # INLINE endBy1 # | @'someTill ' p end@ works similarly to @'C.manyTill ' p end@ , but @p@ See also : ' C.skipSome ' , ' C.skipSomeTill ' . someTill :: (Alternative m) => m a -> m end -> m (NonEmpty a) someTill p end = NE.fromList <$> C.someTill p end # INLINE someTill # | @'sepBy1 ' p sep@ parses /one/ or more occurrences of @p@ , separated by @sep@. Returns a non - empty list of values returned by @p@. sepBy1 :: (Alternative m) => m a -> m sep -> m (NonEmpty a) sepBy1 p sep = NE.fromList <$> C.sepBy1 p sep # INLINE sepBy1 # | @'sepEndBy1 ' p sep@ parses /one/ or more occurrences of @p@ , separated and optionally ended by @sep@. Returns a non - empty list of values returned by sepEndBy1 :: (Alternative m) => m a -> m sep -> m (NonEmpty a) sepEndBy1 p sep = NE.fromList <$> C.sepEndBy1 p sep # INLINE sepEndBy1 #
e760a41d9ec7ed99fe7728525b828cbd7ea045f4a823af5e2ac42da7a09d4f77
ogaml/ogaml
program.ml
exception Program_error of string module Uniform = ProgramInternal.Uniform module Attribute = ProgramInternal.Attribute type t = ProgramInternal.t type src = [`File of string | `String of string] let read_file filename = let chan = open_in_bin filename in let len = in_channel_length chan in let str = Bytes.create len in really_input chan str 0 len; close_in chan; str let to_source = function | `File s -> read_file s | `String s -> s let from_source (type s) (module M : RenderTarget.T with type t = s) ?log ~context ~vertex_source ~fragment_source () = let vertex = to_source vertex_source in let fragment = to_source fragment_source in let context = M.context context in try ProgramInternal.create ~vertex ~fragment ~id:(Context.LL.program_id context) with | ProgramInternal.Program_internal_error s -> begin match log with | None -> () | Some l -> OgamlUtils.Log.error l "%s" !(ProgramInternal.last_log) end; raise (Program_error s) let from_source_list (type s) (module M : RenderTarget.T with type t = s) ?log ~context ~vertex_source ~fragment_source () = let vertex = List.map (fun (v,s) -> (v, to_source s)) vertex_source in let fragment = List.map (fun (v,s) -> (v, to_source s)) fragment_source in let context = M.context context in try ProgramInternal.create_list ~vertex ~fragment ~id:(Context.LL.program_id context) ~version:(Context.glsl_version context) with | ProgramInternal.Program_internal_error s -> begin match log with | None -> () | Some l -> OgamlUtils.Log.error l "%s" !(ProgramInternal.last_log) end; raise (Program_error s) let from_source_pp (type s) (module M : RenderTarget.T with type t = s) ?log ~context ~vertex_source ~fragment_source () = let vertex = to_source vertex_source in let fragment = to_source fragment_source in let context = M.context context in try ProgramInternal.create_pp ~vertex ~fragment ~id:(Context.LL.program_id context) ~version:(Context.glsl_version context) with | ProgramInternal.Program_internal_error s -> begin match log with | None -> () | Some l -> OgamlUtils.Log.error l "%s" !(ProgramInternal.last_log) end; raise (Program_error s) module LL = struct let use context prog = match prog with |None when Context.LL.linked_program context <> None -> begin Context.LL.set_linked_program context None; GL.Program.use None end |Some(p) when Context.LL.linked_program context <> Some p.ProgramInternal.id -> begin Context.LL.set_linked_program context (Some (p.ProgramInternal.program, p.ProgramInternal.id)); GL.Program.use (Some p.ProgramInternal.program); end | _ -> () let uniforms prog = prog.ProgramInternal.uniforms let attributes prog = prog.ProgramInternal.attributes end
null
https://raw.githubusercontent.com/ogaml/ogaml/5e74597521abf7ba2833a9247e55780eabfbab78/src/graphics/program/program.ml
ocaml
exception Program_error of string module Uniform = ProgramInternal.Uniform module Attribute = ProgramInternal.Attribute type t = ProgramInternal.t type src = [`File of string | `String of string] let read_file filename = let chan = open_in_bin filename in let len = in_channel_length chan in let str = Bytes.create len in really_input chan str 0 len; close_in chan; str let to_source = function | `File s -> read_file s | `String s -> s let from_source (type s) (module M : RenderTarget.T with type t = s) ?log ~context ~vertex_source ~fragment_source () = let vertex = to_source vertex_source in let fragment = to_source fragment_source in let context = M.context context in try ProgramInternal.create ~vertex ~fragment ~id:(Context.LL.program_id context) with | ProgramInternal.Program_internal_error s -> begin match log with | None -> () | Some l -> OgamlUtils.Log.error l "%s" !(ProgramInternal.last_log) end; raise (Program_error s) let from_source_list (type s) (module M : RenderTarget.T with type t = s) ?log ~context ~vertex_source ~fragment_source () = let vertex = List.map (fun (v,s) -> (v, to_source s)) vertex_source in let fragment = List.map (fun (v,s) -> (v, to_source s)) fragment_source in let context = M.context context in try ProgramInternal.create_list ~vertex ~fragment ~id:(Context.LL.program_id context) ~version:(Context.glsl_version context) with | ProgramInternal.Program_internal_error s -> begin match log with | None -> () | Some l -> OgamlUtils.Log.error l "%s" !(ProgramInternal.last_log) end; raise (Program_error s) let from_source_pp (type s) (module M : RenderTarget.T with type t = s) ?log ~context ~vertex_source ~fragment_source () = let vertex = to_source vertex_source in let fragment = to_source fragment_source in let context = M.context context in try ProgramInternal.create_pp ~vertex ~fragment ~id:(Context.LL.program_id context) ~version:(Context.glsl_version context) with | ProgramInternal.Program_internal_error s -> begin match log with | None -> () | Some l -> OgamlUtils.Log.error l "%s" !(ProgramInternal.last_log) end; raise (Program_error s) module LL = struct let use context prog = match prog with |None when Context.LL.linked_program context <> None -> begin Context.LL.set_linked_program context None; GL.Program.use None end |Some(p) when Context.LL.linked_program context <> Some p.ProgramInternal.id -> begin Context.LL.set_linked_program context (Some (p.ProgramInternal.program, p.ProgramInternal.id)); GL.Program.use (Some p.ProgramInternal.program); end | _ -> () let uniforms prog = prog.ProgramInternal.uniforms let attributes prog = prog.ProgramInternal.attributes end
0531c2e80cad41a475e44eec6b93b2a87ce2600ff0eccf465f546a53e632dc89
pavlobaron/ErlangOTPBookSamples
wechselkurs_worker.erl
-module(wechselkurs_worker). -export([spawn_worker/1, main/0, test1/0, test2/0]). %% Interface Funktionen %% spawn_worker(Job) -> Pid = spawn(?MODULE, main,[]), Pid ! Job. main() -> receive {umrechnen, {Waehrung, Zielwaehrung, Betrag, Kursdatum}, Sender} -> case wechselkurs_db:find_kurs(Waehrung, Zielwaehrung, Kursdatum) of {ok, Wechselkurs} -> Sender ! {ok, Wechselkurs * Betrag}; {error, Grund} -> Sender ! {error, Grund} end; {kursinfo, {Waehrung, Zielwaehrung, Kursdatum}, Sender} -> case wechselkurs_db:find_kursinfo(Waehrung, Zielwaehrung, Kursdatum) of {ok, Info} -> Sender ! {ok, Info}; {error, Grund} -> Sender ! {error, Grund} end; _ -> io:format("Unknown Jobtype\n") end. % % Tests % test1() -> spawn_worker({umrechnen, {eur, usd, 1000, {12,12,2001}}, self()}), receive Result -> Result end. test2() -> spawn_worker({kursinfo, {eur, usd, {12,12,2001}}, self()}), receive Result -> Result end.
null
https://raw.githubusercontent.com/pavlobaron/ErlangOTPBookSamples/50094964ad814932760174914490e49618b2b8c2/entwicklung/chapex/src/wechselkurs_worker.erl
erlang
Tests
-module(wechselkurs_worker). -export([spawn_worker/1, main/0, test1/0, test2/0]). Interface Funktionen spawn_worker(Job) -> Pid = spawn(?MODULE, main,[]), Pid ! Job. main() -> receive {umrechnen, {Waehrung, Zielwaehrung, Betrag, Kursdatum}, Sender} -> case wechselkurs_db:find_kurs(Waehrung, Zielwaehrung, Kursdatum) of {ok, Wechselkurs} -> Sender ! {ok, Wechselkurs * Betrag}; {error, Grund} -> Sender ! {error, Grund} end; {kursinfo, {Waehrung, Zielwaehrung, Kursdatum}, Sender} -> case wechselkurs_db:find_kursinfo(Waehrung, Zielwaehrung, Kursdatum) of {ok, Info} -> Sender ! {ok, Info}; {error, Grund} -> Sender ! {error, Grund} end; _ -> io:format("Unknown Jobtype\n") end. test1() -> spawn_worker({umrechnen, {eur, usd, 1000, {12,12,2001}}, self()}), receive Result -> Result end. test2() -> spawn_worker({kursinfo, {eur, usd, {12,12,2001}}, self()}), receive Result -> Result end.
5abfd527a4b44f31b19722270811a510205f900467223c775df73ffc7236a544
ofmooseandmen/jord
Models.hs
-- | Module : Data . Geo . . Models Copyright : ( c ) 2020 License : BSD3 Maintainer : < > -- Stability: experimental -- Portability: portable -- -- Common ellipsoidal and spherical models. -- -- This module has been generated. module Data.Geo.Jord.Models where import Data.Geo.Jord.Ellipsoids import Data.Geo.Jord.Ellipsoid import Data.Geo.Jord.Model | World Geodetic System 1984 . data WGS84 = WGS84 instance Model WGS84 where modelId _ = ModelId "WGS84" surface _ = eWGS84 longitudeRange _ = L180 instance Eq WGS84 where _ == _ = True instance Show WGS84 where show m = show (modelId m) instance Ellipsoidal WGS84 | Geodetic Reference System 1980 . data GRS80 = GRS80 instance Model GRS80 where modelId _ = ModelId "GRS80" surface _ = eGRS80 longitudeRange _ = L180 instance Eq GRS80 where _ == _ = True instance Show GRS80 where show m = show (modelId m) instance Ellipsoidal GRS80 | World Geodetic System 1972 . data WGS72 = WGS72 instance Model WGS72 where modelId _ = ModelId "WGS72" surface _ = eWGS72 longitudeRange _ = L180 instance Eq WGS72 where _ == _ = True instance Show WGS72 where show m = show (modelId m) instance Ellipsoidal WGS72 | European Terrestrial Reference System 1989 . data ETRS89 = ETRS89 instance Model ETRS89 where modelId _ = ModelId "ETRS89" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ETRS89 where _ == _ = True instance Show ETRS89 where show m = show (modelId m) instance Ellipsoidal ETRS89 | North American Datum of 1983 . data NAD83 = NAD83 instance Model NAD83 where modelId _ = ModelId "NAD83" surface _ = eGRS80 longitudeRange _ = L180 instance Eq NAD83 where _ == _ = True instance Show NAD83 where show m = show (modelId m) instance Ellipsoidal NAD83 | European Datum 1950 . data ED50 = ED50 instance Model ED50 where modelId _ = ModelId "ED50" surface _ = eIntl1924 longitudeRange _ = L180 instance Eq ED50 where _ == _ = True instance Show ED50 where show m = show (modelId m) instance Ellipsoidal ED50 -- | Irland. data Irl1975 = Irl1975 instance Model Irl1975 where modelId _ = ModelId "Irl1975" surface _ = eAiryModified longitudeRange _ = L180 instance Eq Irl1975 where _ == _ = True instance Show Irl1975 where show m = show (modelId m) instance Ellipsoidal Irl1975 | North American Datum of 1927 . data NAD27 = NAD27 instance Model NAD27 where modelId _ = ModelId "NAD27" surface _ = eClarke1866 longitudeRange _ = L180 instance Eq NAD27 where _ == _ = True instance Show NAD27 where show m = show (modelId m) instance Ellipsoidal NAD27 | NTF ( Paris ) / France I. data NTF = NTF instance Model NTF where modelId _ = ModelId "NTF" surface _ = eClarke1880IGN longitudeRange _ = L180 instance Eq NTF where _ == _ = True instance Show NTF where show m = show (modelId m) instance Ellipsoidal NTF | Ordnance Survey Great Britain 1936 . data OSGB36 = OSGB36 instance Model OSGB36 where modelId _ = ModelId "OSGB36" surface _ = eAiry1830 longitudeRange _ = L180 instance Eq OSGB36 where _ == _ = True instance Show OSGB36 where show m = show (modelId m) instance Ellipsoidal OSGB36 | Geodetic Datum for Germany . data Potsdam = Potsdam instance Model Potsdam where modelId _ = ModelId "Potsdam" surface _ = eBessel1841 longitudeRange _ = L180 instance Eq Potsdam where _ == _ = True instance Show Potsdam where show m = show (modelId m) instance Ellipsoidal Potsdam | Tokyo Japan . data TokyoJapan = TokyoJapan instance Model TokyoJapan where modelId _ = ModelId "TokyoJapan" surface _ = eBessel1841 longitudeRange _ = L180 instance Eq TokyoJapan where _ == _ = True instance Show TokyoJapan where show m = show (modelId m) instance Ellipsoidal TokyoJapan | Mars Orbiter Laser Altimeter . data Mars2000 = Mars2000 instance Model Mars2000 where modelId _ = ModelId "Mars2000" surface _ = eMars2000 longitudeRange _ = L360 instance Eq Mars2000 where _ == _ = True instance Show Mars2000 where show m = show (modelId m) instance Ellipsoidal Mars2000 | International Terrestrial Reference System ( 2014 ) . data ITRF2014 = ITRF2014 instance Model ITRF2014 where modelId _ = ModelId "ITRF2014" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF2014 where _ == _ = True instance Show ITRF2014 where show m = show (modelId m) instance Ellipsoidal ITRF2014 instance EllipsoidalT0 ITRF2014 where epoch _ = Epoch 2010.0 | International Terrestrial Reference System ( 2008 ) . data ITRF2008 = ITRF2008 instance Model ITRF2008 where modelId _ = ModelId "ITRF2008" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF2008 where _ == _ = True instance Show ITRF2008 where show m = show (modelId m) instance Ellipsoidal ITRF2008 instance EllipsoidalT0 ITRF2008 where epoch _ = Epoch 2005.0 | International Terrestrial Reference System ( 2005 ) . data ITRF2005 = ITRF2005 instance Model ITRF2005 where modelId _ = ModelId "ITRF2005" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF2005 where _ == _ = True instance Show ITRF2005 where show m = show (modelId m) instance Ellipsoidal ITRF2005 instance EllipsoidalT0 ITRF2005 where epoch _ = Epoch 2000.0 | International Terrestrial Reference System ( 2000 ) . data ITRF2000 = ITRF2000 instance Model ITRF2000 where modelId _ = ModelId "ITRF2000" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF2000 where _ == _ = True instance Show ITRF2000 where show m = show (modelId m) instance Ellipsoidal ITRF2000 instance EllipsoidalT0 ITRF2000 where epoch _ = Epoch 1997.0 | International Terrestrial Reference System ( 93 ) . data ITRF93 = ITRF93 instance Model ITRF93 where modelId _ = ModelId "ITRF93" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF93 where _ == _ = True instance Show ITRF93 where show m = show (modelId m) instance Ellipsoidal ITRF93 instance EllipsoidalT0 ITRF93 where epoch _ = Epoch 1988.0 | International Terrestrial Reference System ( 91 ) . data ITRF91 = ITRF91 instance Model ITRF91 where modelId _ = ModelId "ITRF91" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF91 where _ == _ = True instance Show ITRF91 where show m = show (modelId m) instance Ellipsoidal ITRF91 instance EllipsoidalT0 ITRF91 where epoch _ = Epoch 1988.0 | World Geodetic System 1984 ( G1762 ) . data WGS84_G1762 = WGS84_G1762 instance Model WGS84_G1762 where modelId _ = ModelId "WGS84_G1762" surface _ = eWGS84 longitudeRange _ = L180 instance Eq WGS84_G1762 where _ == _ = True instance Show WGS84_G1762 where show m = show (modelId m) instance Ellipsoidal WGS84_G1762 instance EllipsoidalT0 WGS84_G1762 where epoch _ = Epoch 2005.0 | World Geodetic System 1984 ( G1674 ) . data WGS84_G1674 = WGS84_G1674 instance Model WGS84_G1674 where modelId _ = ModelId "WGS84_G1674" surface _ = eWGS84 longitudeRange _ = L180 instance Eq WGS84_G1674 where _ == _ = True instance Show WGS84_G1674 where show m = show (modelId m) instance Ellipsoidal WGS84_G1674 instance EllipsoidalT0 WGS84_G1674 where epoch _ = Epoch 2005.0 | World Geodetic System 1984 ( G1150 ) . data WGS84_G1150 = WGS84_G1150 instance Model WGS84_G1150 where modelId _ = ModelId "WGS84_G1150" surface _ = eWGS84 longitudeRange _ = L180 instance Eq WGS84_G1150 where _ == _ = True instance Show WGS84_G1150 where show m = show (modelId m) instance Ellipsoidal WGS84_G1150 instance EllipsoidalT0 WGS84_G1150 where epoch _ = Epoch 2001.0 | European Terrestrial Reference System ( 2000 ) . data ETRF2000 = ETRF2000 instance Model ETRF2000 where modelId _ = ModelId "ETRF2000" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ETRF2000 where _ == _ = True instance Show ETRF2000 where show m = show (modelId m) instance Ellipsoidal ETRF2000 instance EllipsoidalT0 ETRF2000 where epoch _ = Epoch 2005.0 | NAD83 ( Continuously Operating Reference Station 1996 ) . data NAD83_CORS96 = NAD83_CORS96 instance Model NAD83_CORS96 where modelId _ = ModelId "NAD83_CORS96" surface _ = eGRS80 longitudeRange _ = L180 instance Eq NAD83_CORS96 where _ == _ = True instance Show NAD83_CORS96 where show m = show (modelId m) instance Ellipsoidal NAD83_CORS96 instance EllipsoidalT0 NAD83_CORS96 where epoch _ = Epoch 1997.0 | Geocentric Datum Of Australia 1994 . data GDA94 = GDA94 instance Model GDA94 where modelId _ = ModelId "GDA94" surface _ = eGRS80 longitudeRange _ = L180 instance Eq GDA94 where _ == _ = True instance Show GDA94 where show m = show (modelId m) instance Ellipsoidal GDA94 instance EllipsoidalT0 GDA94 where epoch _ = Epoch 1994.0 | Spherical Earth model derived from WGS84 ellipsoid . data S84 = S84 instance Model S84 where modelId _ = ModelId "S84" surface _ = toSphere eWGS84 longitudeRange _ = L180 instance Eq S84 where _ == _ = True instance Show S84 where show m = show (modelId m) instance Spherical S84 | Spherical Mars model derived from Mars2000 ellipsoid . data SMars2000 = SMars2000 instance Model SMars2000 where modelId _ = ModelId "SMars2000" surface _ = toSphere eMars2000 longitudeRange _ = L360 instance Eq SMars2000 where _ == _ = True instance Show SMars2000 where show m = show (modelId m) instance Spherical SMars2000 | / IAG . data Moon = Moon instance Model Moon where modelId _ = ModelId "Moon" surface _ = toSphere eMoon longitudeRange _ = L180 instance Eq Moon where _ == _ = True instance Show Moon where show m = show (modelId m) instance Spherical Moon
null
https://raw.githubusercontent.com/ofmooseandmen/jord/9acd8d9aec817ce05de6ed1d78e025437e1193bf/src/Data/Geo/Jord/Models.hs
haskell
| Stability: experimental Portability: portable Common ellipsoidal and spherical models. This module has been generated. | Irland.
Module : Data . Geo . . Models Copyright : ( c ) 2020 License : BSD3 Maintainer : < > module Data.Geo.Jord.Models where import Data.Geo.Jord.Ellipsoids import Data.Geo.Jord.Ellipsoid import Data.Geo.Jord.Model | World Geodetic System 1984 . data WGS84 = WGS84 instance Model WGS84 where modelId _ = ModelId "WGS84" surface _ = eWGS84 longitudeRange _ = L180 instance Eq WGS84 where _ == _ = True instance Show WGS84 where show m = show (modelId m) instance Ellipsoidal WGS84 | Geodetic Reference System 1980 . data GRS80 = GRS80 instance Model GRS80 where modelId _ = ModelId "GRS80" surface _ = eGRS80 longitudeRange _ = L180 instance Eq GRS80 where _ == _ = True instance Show GRS80 where show m = show (modelId m) instance Ellipsoidal GRS80 | World Geodetic System 1972 . data WGS72 = WGS72 instance Model WGS72 where modelId _ = ModelId "WGS72" surface _ = eWGS72 longitudeRange _ = L180 instance Eq WGS72 where _ == _ = True instance Show WGS72 where show m = show (modelId m) instance Ellipsoidal WGS72 | European Terrestrial Reference System 1989 . data ETRS89 = ETRS89 instance Model ETRS89 where modelId _ = ModelId "ETRS89" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ETRS89 where _ == _ = True instance Show ETRS89 where show m = show (modelId m) instance Ellipsoidal ETRS89 | North American Datum of 1983 . data NAD83 = NAD83 instance Model NAD83 where modelId _ = ModelId "NAD83" surface _ = eGRS80 longitudeRange _ = L180 instance Eq NAD83 where _ == _ = True instance Show NAD83 where show m = show (modelId m) instance Ellipsoidal NAD83 | European Datum 1950 . data ED50 = ED50 instance Model ED50 where modelId _ = ModelId "ED50" surface _ = eIntl1924 longitudeRange _ = L180 instance Eq ED50 where _ == _ = True instance Show ED50 where show m = show (modelId m) instance Ellipsoidal ED50 data Irl1975 = Irl1975 instance Model Irl1975 where modelId _ = ModelId "Irl1975" surface _ = eAiryModified longitudeRange _ = L180 instance Eq Irl1975 where _ == _ = True instance Show Irl1975 where show m = show (modelId m) instance Ellipsoidal Irl1975 | North American Datum of 1927 . data NAD27 = NAD27 instance Model NAD27 where modelId _ = ModelId "NAD27" surface _ = eClarke1866 longitudeRange _ = L180 instance Eq NAD27 where _ == _ = True instance Show NAD27 where show m = show (modelId m) instance Ellipsoidal NAD27 | NTF ( Paris ) / France I. data NTF = NTF instance Model NTF where modelId _ = ModelId "NTF" surface _ = eClarke1880IGN longitudeRange _ = L180 instance Eq NTF where _ == _ = True instance Show NTF where show m = show (modelId m) instance Ellipsoidal NTF | Ordnance Survey Great Britain 1936 . data OSGB36 = OSGB36 instance Model OSGB36 where modelId _ = ModelId "OSGB36" surface _ = eAiry1830 longitudeRange _ = L180 instance Eq OSGB36 where _ == _ = True instance Show OSGB36 where show m = show (modelId m) instance Ellipsoidal OSGB36 | Geodetic Datum for Germany . data Potsdam = Potsdam instance Model Potsdam where modelId _ = ModelId "Potsdam" surface _ = eBessel1841 longitudeRange _ = L180 instance Eq Potsdam where _ == _ = True instance Show Potsdam where show m = show (modelId m) instance Ellipsoidal Potsdam | Tokyo Japan . data TokyoJapan = TokyoJapan instance Model TokyoJapan where modelId _ = ModelId "TokyoJapan" surface _ = eBessel1841 longitudeRange _ = L180 instance Eq TokyoJapan where _ == _ = True instance Show TokyoJapan where show m = show (modelId m) instance Ellipsoidal TokyoJapan | Mars Orbiter Laser Altimeter . data Mars2000 = Mars2000 instance Model Mars2000 where modelId _ = ModelId "Mars2000" surface _ = eMars2000 longitudeRange _ = L360 instance Eq Mars2000 where _ == _ = True instance Show Mars2000 where show m = show (modelId m) instance Ellipsoidal Mars2000 | International Terrestrial Reference System ( 2014 ) . data ITRF2014 = ITRF2014 instance Model ITRF2014 where modelId _ = ModelId "ITRF2014" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF2014 where _ == _ = True instance Show ITRF2014 where show m = show (modelId m) instance Ellipsoidal ITRF2014 instance EllipsoidalT0 ITRF2014 where epoch _ = Epoch 2010.0 | International Terrestrial Reference System ( 2008 ) . data ITRF2008 = ITRF2008 instance Model ITRF2008 where modelId _ = ModelId "ITRF2008" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF2008 where _ == _ = True instance Show ITRF2008 where show m = show (modelId m) instance Ellipsoidal ITRF2008 instance EllipsoidalT0 ITRF2008 where epoch _ = Epoch 2005.0 | International Terrestrial Reference System ( 2005 ) . data ITRF2005 = ITRF2005 instance Model ITRF2005 where modelId _ = ModelId "ITRF2005" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF2005 where _ == _ = True instance Show ITRF2005 where show m = show (modelId m) instance Ellipsoidal ITRF2005 instance EllipsoidalT0 ITRF2005 where epoch _ = Epoch 2000.0 | International Terrestrial Reference System ( 2000 ) . data ITRF2000 = ITRF2000 instance Model ITRF2000 where modelId _ = ModelId "ITRF2000" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF2000 where _ == _ = True instance Show ITRF2000 where show m = show (modelId m) instance Ellipsoidal ITRF2000 instance EllipsoidalT0 ITRF2000 where epoch _ = Epoch 1997.0 | International Terrestrial Reference System ( 93 ) . data ITRF93 = ITRF93 instance Model ITRF93 where modelId _ = ModelId "ITRF93" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF93 where _ == _ = True instance Show ITRF93 where show m = show (modelId m) instance Ellipsoidal ITRF93 instance EllipsoidalT0 ITRF93 where epoch _ = Epoch 1988.0 | International Terrestrial Reference System ( 91 ) . data ITRF91 = ITRF91 instance Model ITRF91 where modelId _ = ModelId "ITRF91" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ITRF91 where _ == _ = True instance Show ITRF91 where show m = show (modelId m) instance Ellipsoidal ITRF91 instance EllipsoidalT0 ITRF91 where epoch _ = Epoch 1988.0 | World Geodetic System 1984 ( G1762 ) . data WGS84_G1762 = WGS84_G1762 instance Model WGS84_G1762 where modelId _ = ModelId "WGS84_G1762" surface _ = eWGS84 longitudeRange _ = L180 instance Eq WGS84_G1762 where _ == _ = True instance Show WGS84_G1762 where show m = show (modelId m) instance Ellipsoidal WGS84_G1762 instance EllipsoidalT0 WGS84_G1762 where epoch _ = Epoch 2005.0 | World Geodetic System 1984 ( G1674 ) . data WGS84_G1674 = WGS84_G1674 instance Model WGS84_G1674 where modelId _ = ModelId "WGS84_G1674" surface _ = eWGS84 longitudeRange _ = L180 instance Eq WGS84_G1674 where _ == _ = True instance Show WGS84_G1674 where show m = show (modelId m) instance Ellipsoidal WGS84_G1674 instance EllipsoidalT0 WGS84_G1674 where epoch _ = Epoch 2005.0 | World Geodetic System 1984 ( G1150 ) . data WGS84_G1150 = WGS84_G1150 instance Model WGS84_G1150 where modelId _ = ModelId "WGS84_G1150" surface _ = eWGS84 longitudeRange _ = L180 instance Eq WGS84_G1150 where _ == _ = True instance Show WGS84_G1150 where show m = show (modelId m) instance Ellipsoidal WGS84_G1150 instance EllipsoidalT0 WGS84_G1150 where epoch _ = Epoch 2001.0 | European Terrestrial Reference System ( 2000 ) . data ETRF2000 = ETRF2000 instance Model ETRF2000 where modelId _ = ModelId "ETRF2000" surface _ = eGRS80 longitudeRange _ = L180 instance Eq ETRF2000 where _ == _ = True instance Show ETRF2000 where show m = show (modelId m) instance Ellipsoidal ETRF2000 instance EllipsoidalT0 ETRF2000 where epoch _ = Epoch 2005.0 | NAD83 ( Continuously Operating Reference Station 1996 ) . data NAD83_CORS96 = NAD83_CORS96 instance Model NAD83_CORS96 where modelId _ = ModelId "NAD83_CORS96" surface _ = eGRS80 longitudeRange _ = L180 instance Eq NAD83_CORS96 where _ == _ = True instance Show NAD83_CORS96 where show m = show (modelId m) instance Ellipsoidal NAD83_CORS96 instance EllipsoidalT0 NAD83_CORS96 where epoch _ = Epoch 1997.0 | Geocentric Datum Of Australia 1994 . data GDA94 = GDA94 instance Model GDA94 where modelId _ = ModelId "GDA94" surface _ = eGRS80 longitudeRange _ = L180 instance Eq GDA94 where _ == _ = True instance Show GDA94 where show m = show (modelId m) instance Ellipsoidal GDA94 instance EllipsoidalT0 GDA94 where epoch _ = Epoch 1994.0 | Spherical Earth model derived from WGS84 ellipsoid . data S84 = S84 instance Model S84 where modelId _ = ModelId "S84" surface _ = toSphere eWGS84 longitudeRange _ = L180 instance Eq S84 where _ == _ = True instance Show S84 where show m = show (modelId m) instance Spherical S84 | Spherical Mars model derived from Mars2000 ellipsoid . data SMars2000 = SMars2000 instance Model SMars2000 where modelId _ = ModelId "SMars2000" surface _ = toSphere eMars2000 longitudeRange _ = L360 instance Eq SMars2000 where _ == _ = True instance Show SMars2000 where show m = show (modelId m) instance Spherical SMars2000 | / IAG . data Moon = Moon instance Model Moon where modelId _ = ModelId "Moon" surface _ = toSphere eMoon longitudeRange _ = L180 instance Eq Moon where _ == _ = True instance Show Moon where show m = show (modelId m) instance Spherical Moon
73d0ef5e7acfd5bd54dc56f4121a2652c722d3f7ea691549b0de5fe2fe43a61e
offby1/rudybot
analyze-quotes.rkt
;; Run me in "drRacket" #lang racket (require plot) (module+ test (require rackunit)) ;; jordanb says the quotes aren't coming out randomly. I don't ;; particularly believe him, but let's see. I'll find (what look ;; like) quotes in the log, and then measure how often each appears, ;; and then ... somehow ... do some sorta statistical analysis (the ;; details of which are unclear at the moment). (define (bounding-box vecs) (for/fold ([xmin (vector-ref (car vecs) 0)] [xmax (vector-ref (car vecs) 0)] [ymin (vector-ref (car vecs) 1)] [ymax (vector-ref (car vecs) 1)]) ([p (in-list vecs)]) (let ([x (vector-ref p 0)] [y (vector-ref p 1)]) (values (min x xmin) (max x xmax) (min y ymin) (max y ymax))))) (module+ test (define-simple-check (check-bb vectors xmin xmax ymin ymax) (equal? (call-with-values (lambda () (bounding-box vectors)) list) (list xmin xmax ymin ymax))) (check-bb '(#(0 0)) 0 0 0 0) (check-bb '(#(0 1)) 0 0 1 1) (check-bb '(#(0 0) #(0 1)) 0 0 0 1) (check-bb '(#(0 0) #(0 1) #(1 0)) 0 1 0 1)) (module+ main (define *ifn* "big-log") (call-with-input-file *ifn* (lambda (ip) (define (hash-table-increment! table key) (hash-update! table key add1 0)) (let ([counts-by-quote (make-hash) ] [histogram (make-hash)]) (printf "Reading from ~a ...~%" *ifn*) (printf "Read ~a lines.~%" (for/and ([line (in-lines ip)] [count (in-naturals)]) (match line [(regexp #px"=> \"PRIVMSG #emacs :(.*)\"$" (list _ stuff)) (when (and (not (regexp-match #px"^\\w+:" stuff)) (not (regexp-match #px"Arooooooooooo" stuff))) (hash-table-increment! counts-by-quote stuff))] [_ #f]) count) ) (printf "Snarfed ~a distinct quotes.~%" (hash-count counts-by-quote)) (for ([(k v) (in-hash counts-by-quote)] ) (hash-table-increment! histogram v)) (printf "Histogram: ~a~%" histogram) (let ([vecs (hash-map histogram vector)]) (let-values ([(xmin xmax ymin ymax) (bounding-box vecs)]) (plot (points vecs) #:x-label "Number of Occurrences" #:y-label "Quotes" #:x-min xmin #:x-max xmax #:y-min ymin #:y-max ymax)))))))
null
https://raw.githubusercontent.com/offby1/rudybot/74773ce9c1224813ee963f4d5d8a7748197f6963/analyze-quotes.rkt
racket
Run me in "drRacket" jordanb says the quotes aren't coming out randomly. I don't particularly believe him, but let's see. I'll find (what look like) quotes in the log, and then measure how often each appears, and then ... somehow ... do some sorta statistical analysis (the details of which are unclear at the moment).
#lang racket (require plot) (module+ test (require rackunit)) (define (bounding-box vecs) (for/fold ([xmin (vector-ref (car vecs) 0)] [xmax (vector-ref (car vecs) 0)] [ymin (vector-ref (car vecs) 1)] [ymax (vector-ref (car vecs) 1)]) ([p (in-list vecs)]) (let ([x (vector-ref p 0)] [y (vector-ref p 1)]) (values (min x xmin) (max x xmax) (min y ymin) (max y ymax))))) (module+ test (define-simple-check (check-bb vectors xmin xmax ymin ymax) (equal? (call-with-values (lambda () (bounding-box vectors)) list) (list xmin xmax ymin ymax))) (check-bb '(#(0 0)) 0 0 0 0) (check-bb '(#(0 1)) 0 0 1 1) (check-bb '(#(0 0) #(0 1)) 0 0 0 1) (check-bb '(#(0 0) #(0 1) #(1 0)) 0 1 0 1)) (module+ main (define *ifn* "big-log") (call-with-input-file *ifn* (lambda (ip) (define (hash-table-increment! table key) (hash-update! table key add1 0)) (let ([counts-by-quote (make-hash) ] [histogram (make-hash)]) (printf "Reading from ~a ...~%" *ifn*) (printf "Read ~a lines.~%" (for/and ([line (in-lines ip)] [count (in-naturals)]) (match line [(regexp #px"=> \"PRIVMSG #emacs :(.*)\"$" (list _ stuff)) (when (and (not (regexp-match #px"^\\w+:" stuff)) (not (regexp-match #px"Arooooooooooo" stuff))) (hash-table-increment! counts-by-quote stuff))] [_ #f]) count) ) (printf "Snarfed ~a distinct quotes.~%" (hash-count counts-by-quote)) (for ([(k v) (in-hash counts-by-quote)] ) (hash-table-increment! histogram v)) (printf "Histogram: ~a~%" histogram) (let ([vecs (hash-map histogram vector)]) (let-values ([(xmin xmax ymin ymax) (bounding-box vecs)]) (plot (points vecs) #:x-label "Number of Occurrences" #:y-label "Quotes" #:x-min xmin #:x-max xmax #:y-min ymin #:y-max ymax)))))))
b672f4625d56648fabb870c3ecdbbd729f8305c24cc76b6467e97a3e6ff5481d
typedclojure/typedclojure
zip.clj
(ns clojure.core.typed.test.zip (:require [typed.clojure :as t] [clojure.test :refer :all] [typed.clj.checker.test-utils :refer :all])) (deftest zipper-test (is-tc-e #(zipper vector? seq (fn [_ c] c) "abc") [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [zipper]]]) (is-tc-err #(zipper vector? seq (fn [c] c) "abc") :requires [[clojure.zip :refer [zipper]]])) (deftest seq-zip-test (is-tc-e #(seq-zip "abc") [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [seq-zip]]]) (is-tc-err #(seq-zip "abc") [-> t/Str] :requires [[clojure.zip :refer [seq-zip]]])) (deftest vector-zip-test (is-tc-e #(vector-zip "abc") [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [vector-zip]]]) (is-tc-err #(vector-zip "abc") [-> t/Str] :requires [[clojure.zip :refer [vector-zip]]])) (deftest xml-zip-test (is-tc-e #(xml-zip 1) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [xml-zip]]]) (is-tc-err #(xml-zip 1) [-> t/Str] :requires [[clojure.zip :refer [xml-zip]]])) (deftest node-test (is-tc-e #(node [1 2 3]) :requires [[clojure.zip :refer [node]]]) (is-tc-err #(node 1) :requires [[clojure.zip :refer [node]]])) (deftest branch?-test (is-tc-e #(branch? (vector-zip [1 2])) [-> t/Bool] :requires [[clojure.zip :refer [branch? vector-zip]]]) (is-tc-err #(branch? 1) :requires [[clojure.zip :refer [branch? vector-zip]]])) (deftest children-test (is-tc-e #(children (vector-zip [1 2])) :requires [[clojure.zip :refer [children vector-zip]]])) (deftest root-test (is-tc-e #(root [1 2]) :requires [[clojure.zip :refer [root]]]) (is-tc-err #(root 1) :requires [[clojure.zip :refer [root]]])) (deftest rightmost-test (is-tc-e #(rightmost [1 2 3]) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [rightmost]]]) (is-tc-err #(rightmost [1 2 3]) [-> t/Str] :requires [[clojure.zip :refer [rightmost]]]) (is-tc-err #(rightmost 1) :requires [[clojure.zip :refer [rightmost]]])) (deftest right-test (is-tc-e #(right [1 2 3]) :requires [[clojure.zip :refer [right]]]) (is-tc-err #(right [1 2 3]) [-> t/Str] :requires [[clojure.zip :refer [right]]]) (is-tc-err #(right 1) :requires [[clojure.zip :refer [right]]])) (deftest up-test (is-tc-e #(up (vector-zip [1 2])) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [up vector-zip]]]) (is-tc-err #(up 1) t/Str :requires [[clojure.zip :refer [up vector-zip]]])) (deftest rights-test (is-tc-e #(rights [1 2 3]) :requires [[clojure.zip :refer [rights]]]) (is-tc-err #(rights [1 2 3]) [-> t/Str] :requires [[clojure.zip :refer [rights]]]) (is-tc-err (rights 1) :requires [[clojure.zip :refer [rights]]])) (deftest replace-test (is-tc-e #(zip/replace (vector-zip [1 2 [3 4] 5]) 3) [-> (t/Vec t/Any)] :requires [[clojure.zip :as zip :refer [vector-zip]]]) (is-tc-err #(zip/replace (vector-zip [1 2 [3 4] 5]) 3) [-> t/Str] :requires [[clojure.zip :as zip :refer [vector-zip]]]) (is-tc-err #(zip/replace 1 3) :requires [[clojure.zip :as zip :refer [vector-zip]]])) (deftest down-test (is-tc-e #(down (zipper vector? seq (fn [a b]) [1 3 4])) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [down zipper]]]) (is-tc-err #(down (zipper vector? seq (fn [a b]) [1 3 4])) [-> t/Str] :requires [[clojure.zip :refer [zipper down]]]) (is-tc-err #(down 1) :requires [[clojure.zip :refer [down]]])) (deftest left-test (is-tc-e #(left [1 2 [3 4] 5]) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [left]]]) (is-tc-err #(left [1 2 [3 4] 5]) [-> t/Str] :requires [[clojure.zip :refer [left]]]) (is-tc-err #(left 1) :requires [[clojure.zip :refer [left]]])) (deftest leftmost-test (is-tc-e #(leftmost [1 2 [3 4] 5]) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [leftmost]]]) (is-tc-err #(leftmost [1 2 [3 4] 5]) [-> t/Str] :requires [[clojure.zip :refer [leftmost]]]) (is-tc-err #(leftmost 1) :requires [[clojure.zip :refer [leftmost]]])) (deftest lefts-test (is-tc-e #(lefts [1 2 [3 4] 5]) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [lefts]]]) (is-tc-err #(lefts [1 2 [3 4] 5]) [-> t/Str] :requires [[clojure.zip :refer [lefts]]]) (is-tc-err #(lefts 1) :requires [[clojure.zip :refer [lefts]]])) (deftest append-child-test (is-tc-e #(append-child (vector-zip [1 2]) 9) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [append-child vector-zip]]]) (is-tc-err #(append-child (vector-zip [1 2]) 9) [-> t/Str] :requires [[clojure.zip :refer [append-child vector-zip]]]) (is-tc-err #(append-child 1 9) :requires [[clojure.zip :refer [append-child]]])) (deftest end?-test (is-tc-e #(end? (vector-zip [1 2])) [-> t/Bool] :requires [[clojure.zip :refer [end? vector-zip]]]) (is-tc-err #(end? (vector-zip [1 2])) [-> t/Str] :requires [[clojure.zip :refer [end? vector-zip]]]) (is-tc-err #(end? 1) :requires [[clojure.zip :refer [end?]]])) (deftest insert-child-test (is-tc-e #(insert-child (vector-zip [1 2]) 9) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [insert-child vector-zip]]]) (is-tc-err #(insert-child (vector-zip [1 2]) 9) [-> t/Str] :requires [[clojure.zip :refer [insert-child vector-zip]]]) (is-tc-err #(insert-child 1 9) :requires [[clojure.zip :refer [insert-child]]])) (deftest insert-left-test (is-tc-e #(let [d (down (vector-zip [1 22 3 5]))] (assert d) (insert-left d 6)) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [insert-left down vector-zip]]]) (is-tc-err #(insert-left 1 9) :requires [[clojure.zip :refer [insert-left down vector-zip]]])) (deftest insert-right-test (is-tc-e #(let [d (down (vector-zip [1 22 3 5]))] (assert d) (insert-right d 6)) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [insert-right down vector-zip]]]) (is-tc-err #(let [d (down (vector-zip [1 22 3 5]))] (assert d) (insert-right d 6)) [-> t/Str] :requires [[clojure.zip :refer [insert-right down vector-zip]]]) (is-tc-err #(insert-right 1 9) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [insert-right down vector-zip]]])) (deftest next-test (is-tc-e #(zip/next (vector-zip [1 2])) [-> (t/Vec t/Any)] :requires [[clojure.zip :as zip :refer [vector-zip]]]) (is-tc-err #(zip/next (vector-zip [1 2])) [-> t/Str] :requires [[clojure.zip :as zip :refer [vector-zip]]]) (is-tc-err (zip/next 1) :requires [[clojure.zip :as zip :refer [vector-zip]]])) (deftest prev-test (is-tc-e #(prev (vector-zip [1 2])) [-> (t/U (t/Vec t/Any) nil)] :requires [[clojure.zip :refer [prev vector-zip]]]) (is-tc-err #(prev (vector-zip [1 2])) [-> t/Str] :requires [[clojure.zip :refer [prev vector-zip]]]) (is-tc-err #(prev 1) :requires [[clojure.zip :refer [prev]]])) (deftest path-test (is-tc-e #(path (vector-zip [1 2])) :requires [[clojure.zip :refer [path vector-zip]]]) (is-tc-err #(path 1) :requires [[clojure.zip :refer [path]]])) (deftest remove-test (is-tc-e #(let [d (down (vector-zip [1 22 3 5]))] (assert d) (zip/remove d)) [-> (t/Vec t/Any)] :requires [[clojure.zip :as zip :refer [down vector-zip]]]) (is-tc-err #(zip/remove (down (vector-zip [1 22 3 5]))) [-> t/Str] :requires [[clojure.zip :as zip :refer [down vector-zip]]]) (is-tc-err #(zip/remove nil) :requires [[clojure.zip :as zip]]))
null
https://raw.githubusercontent.com/typedclojure/typedclojure/5fd7cdf7941c6e7d1dd5df88bf44474fa35e1fca/typed/clj.checker/test/clojure/core/typed/test/zip.clj
clojure
(ns clojure.core.typed.test.zip (:require [typed.clojure :as t] [clojure.test :refer :all] [typed.clj.checker.test-utils :refer :all])) (deftest zipper-test (is-tc-e #(zipper vector? seq (fn [_ c] c) "abc") [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [zipper]]]) (is-tc-err #(zipper vector? seq (fn [c] c) "abc") :requires [[clojure.zip :refer [zipper]]])) (deftest seq-zip-test (is-tc-e #(seq-zip "abc") [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [seq-zip]]]) (is-tc-err #(seq-zip "abc") [-> t/Str] :requires [[clojure.zip :refer [seq-zip]]])) (deftest vector-zip-test (is-tc-e #(vector-zip "abc") [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [vector-zip]]]) (is-tc-err #(vector-zip "abc") [-> t/Str] :requires [[clojure.zip :refer [vector-zip]]])) (deftest xml-zip-test (is-tc-e #(xml-zip 1) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [xml-zip]]]) (is-tc-err #(xml-zip 1) [-> t/Str] :requires [[clojure.zip :refer [xml-zip]]])) (deftest node-test (is-tc-e #(node [1 2 3]) :requires [[clojure.zip :refer [node]]]) (is-tc-err #(node 1) :requires [[clojure.zip :refer [node]]])) (deftest branch?-test (is-tc-e #(branch? (vector-zip [1 2])) [-> t/Bool] :requires [[clojure.zip :refer [branch? vector-zip]]]) (is-tc-err #(branch? 1) :requires [[clojure.zip :refer [branch? vector-zip]]])) (deftest children-test (is-tc-e #(children (vector-zip [1 2])) :requires [[clojure.zip :refer [children vector-zip]]])) (deftest root-test (is-tc-e #(root [1 2]) :requires [[clojure.zip :refer [root]]]) (is-tc-err #(root 1) :requires [[clojure.zip :refer [root]]])) (deftest rightmost-test (is-tc-e #(rightmost [1 2 3]) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [rightmost]]]) (is-tc-err #(rightmost [1 2 3]) [-> t/Str] :requires [[clojure.zip :refer [rightmost]]]) (is-tc-err #(rightmost 1) :requires [[clojure.zip :refer [rightmost]]])) (deftest right-test (is-tc-e #(right [1 2 3]) :requires [[clojure.zip :refer [right]]]) (is-tc-err #(right [1 2 3]) [-> t/Str] :requires [[clojure.zip :refer [right]]]) (is-tc-err #(right 1) :requires [[clojure.zip :refer [right]]])) (deftest up-test (is-tc-e #(up (vector-zip [1 2])) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [up vector-zip]]]) (is-tc-err #(up 1) t/Str :requires [[clojure.zip :refer [up vector-zip]]])) (deftest rights-test (is-tc-e #(rights [1 2 3]) :requires [[clojure.zip :refer [rights]]]) (is-tc-err #(rights [1 2 3]) [-> t/Str] :requires [[clojure.zip :refer [rights]]]) (is-tc-err (rights 1) :requires [[clojure.zip :refer [rights]]])) (deftest replace-test (is-tc-e #(zip/replace (vector-zip [1 2 [3 4] 5]) 3) [-> (t/Vec t/Any)] :requires [[clojure.zip :as zip :refer [vector-zip]]]) (is-tc-err #(zip/replace (vector-zip [1 2 [3 4] 5]) 3) [-> t/Str] :requires [[clojure.zip :as zip :refer [vector-zip]]]) (is-tc-err #(zip/replace 1 3) :requires [[clojure.zip :as zip :refer [vector-zip]]])) (deftest down-test (is-tc-e #(down (zipper vector? seq (fn [a b]) [1 3 4])) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [down zipper]]]) (is-tc-err #(down (zipper vector? seq (fn [a b]) [1 3 4])) [-> t/Str] :requires [[clojure.zip :refer [zipper down]]]) (is-tc-err #(down 1) :requires [[clojure.zip :refer [down]]])) (deftest left-test (is-tc-e #(left [1 2 [3 4] 5]) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [left]]]) (is-tc-err #(left [1 2 [3 4] 5]) [-> t/Str] :requires [[clojure.zip :refer [left]]]) (is-tc-err #(left 1) :requires [[clojure.zip :refer [left]]])) (deftest leftmost-test (is-tc-e #(leftmost [1 2 [3 4] 5]) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [leftmost]]]) (is-tc-err #(leftmost [1 2 [3 4] 5]) [-> t/Str] :requires [[clojure.zip :refer [leftmost]]]) (is-tc-err #(leftmost 1) :requires [[clojure.zip :refer [leftmost]]])) (deftest lefts-test (is-tc-e #(lefts [1 2 [3 4] 5]) [-> (t/U nil (t/Vec t/Any))] :requires [[clojure.zip :refer [lefts]]]) (is-tc-err #(lefts [1 2 [3 4] 5]) [-> t/Str] :requires [[clojure.zip :refer [lefts]]]) (is-tc-err #(lefts 1) :requires [[clojure.zip :refer [lefts]]])) (deftest append-child-test (is-tc-e #(append-child (vector-zip [1 2]) 9) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [append-child vector-zip]]]) (is-tc-err #(append-child (vector-zip [1 2]) 9) [-> t/Str] :requires [[clojure.zip :refer [append-child vector-zip]]]) (is-tc-err #(append-child 1 9) :requires [[clojure.zip :refer [append-child]]])) (deftest end?-test (is-tc-e #(end? (vector-zip [1 2])) [-> t/Bool] :requires [[clojure.zip :refer [end? vector-zip]]]) (is-tc-err #(end? (vector-zip [1 2])) [-> t/Str] :requires [[clojure.zip :refer [end? vector-zip]]]) (is-tc-err #(end? 1) :requires [[clojure.zip :refer [end?]]])) (deftest insert-child-test (is-tc-e #(insert-child (vector-zip [1 2]) 9) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [insert-child vector-zip]]]) (is-tc-err #(insert-child (vector-zip [1 2]) 9) [-> t/Str] :requires [[clojure.zip :refer [insert-child vector-zip]]]) (is-tc-err #(insert-child 1 9) :requires [[clojure.zip :refer [insert-child]]])) (deftest insert-left-test (is-tc-e #(let [d (down (vector-zip [1 22 3 5]))] (assert d) (insert-left d 6)) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [insert-left down vector-zip]]]) (is-tc-err #(insert-left 1 9) :requires [[clojure.zip :refer [insert-left down vector-zip]]])) (deftest insert-right-test (is-tc-e #(let [d (down (vector-zip [1 22 3 5]))] (assert d) (insert-right d 6)) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [insert-right down vector-zip]]]) (is-tc-err #(let [d (down (vector-zip [1 22 3 5]))] (assert d) (insert-right d 6)) [-> t/Str] :requires [[clojure.zip :refer [insert-right down vector-zip]]]) (is-tc-err #(insert-right 1 9) [-> (t/Vec t/Any)] :requires [[clojure.zip :refer [insert-right down vector-zip]]])) (deftest next-test (is-tc-e #(zip/next (vector-zip [1 2])) [-> (t/Vec t/Any)] :requires [[clojure.zip :as zip :refer [vector-zip]]]) (is-tc-err #(zip/next (vector-zip [1 2])) [-> t/Str] :requires [[clojure.zip :as zip :refer [vector-zip]]]) (is-tc-err (zip/next 1) :requires [[clojure.zip :as zip :refer [vector-zip]]])) (deftest prev-test (is-tc-e #(prev (vector-zip [1 2])) [-> (t/U (t/Vec t/Any) nil)] :requires [[clojure.zip :refer [prev vector-zip]]]) (is-tc-err #(prev (vector-zip [1 2])) [-> t/Str] :requires [[clojure.zip :refer [prev vector-zip]]]) (is-tc-err #(prev 1) :requires [[clojure.zip :refer [prev]]])) (deftest path-test (is-tc-e #(path (vector-zip [1 2])) :requires [[clojure.zip :refer [path vector-zip]]]) (is-tc-err #(path 1) :requires [[clojure.zip :refer [path]]])) (deftest remove-test (is-tc-e #(let [d (down (vector-zip [1 22 3 5]))] (assert d) (zip/remove d)) [-> (t/Vec t/Any)] :requires [[clojure.zip :as zip :refer [down vector-zip]]]) (is-tc-err #(zip/remove (down (vector-zip [1 22 3 5]))) [-> t/Str] :requires [[clojure.zip :as zip :refer [down vector-zip]]]) (is-tc-err #(zip/remove nil) :requires [[clojure.zip :as zip]]))
c41e5cc4191705f01ad7ac1eda54eb24fa00b14b8ec917feccae992f6bbdf09f
ocaml-multicore/ocaml-effects-tutorial
generator.ml
type ('elt,'container) iterator = ('elt -> unit) -> 'container -> unit type 'elt generator = unit -> 'elt option (* Original solution *) (* let generate (type elt) (i : (elt, 'container) iterator) (c : 'container) : elt generator = *) (* let module M = struct effect Yield : elt -> unit end in *) (* let open M in *) (* let rec step = ref (fun () -> *) (* i (fun v -> perform (Yield v)) c; *) (* step := (fun () -> None); *) (* None) *) (* in *) (* let loop () = *) (* try !step () with *) (* | effect (Yield v) k -> (step := continue k; Some v) *) (* in *) (* loop *) (* My solution *) (* Might be able to do something with a deep handler instead *) let generate (type elt) (i : (elt, 'container) iterator) (c : 'container) : elt generator = let open Effect in let open Effect.Shallow in let module M = struct type _ Effect.t += Yield : elt -> unit Effect.t type ('a, 'b) status = NotStarted | InProgress of ('a,'b) continuation | Finished end in let open M in let yield v = perform (Yield v) in let curr_status = ref NotStarted in let rec helper () = match !curr_status with | Finished -> None | NotStarted -> curr_status := InProgress (fiber (fun () -> i yield c)); helper () | InProgress k -> continue_with k () { retc = (fun _ -> curr_status := Finished; helper ()); exnc = (fun e -> raise e); effc = (fun (type b) (eff: b Effect.t) -> match eff with | Yield x -> Some (fun (k: (b,_) continuation) -> curr_status := InProgress k; Some x ) | _ -> None)} in helper (* * helper : unit -> elt option * i : (elt -> unit) -> container -> unit * continue_with k () * { * * *) (***********************) Traversal generator (***********************) let gen_list : 'a list -> 'a generator = generate List.iter let gl : int generator = gen_list [1;2;3] ;; assert (Some 1 = gl ());; assert (Some 2 = gl ());; assert (Some 3 = gl ());; assert (None = gl ());; assert (None = gl ());; let gen_array : 'a array -> 'a generator = generate Array.iter let ga : float generator = gen_array [| 1.0; 2.0; 3.0 |] ;; assert (Some 1.0 = ga ());; assert (Some 2.0 = ga ());; assert (Some 3.0 = ga ());; assert (None = ga ());; assert (None = ga ());; (***********) (* Streams *) (***********) (* Iterator over nats. Dummy () container. *) let rec nats : int (* init *) -> (int, unit) iterator = fun v f () -> f v; nats (v+1) f () (* Infinite stream *) type 'a stream = unit -> 'a (* Convert generator to an infinite stream *) let inf : 'a generator -> 'a stream = fun g () -> match g () with | Some n -> n | _ -> assert false (* Nat stream *) let gen_nats : int stream = inf (generate (nats 0) ()) ;; assert (0 = gen_nats ());; assert (1 = gen_nats ());; assert (2 = gen_nats ());; assert (3 = gen_nats ());; (* filter stream *) let rec filter : 'a stream -> ('a -> bool) -> 'a stream = fun g p () -> let v = g () in if p v then v else filter g p () (* map stream *) let rec map : 'a stream -> ('a -> 'b) -> 'b stream = fun g f () -> f (g ()) (* Even stream *) let gen_even : int stream = let nat_stream = inf (generate (nats 0) ()) in filter nat_stream (fun n -> n mod 2 = 0) ;; assert (0 = gen_even ());; assert (2 = gen_even ());; assert (4 = gen_even ());; assert (6 = gen_even ());; (* Odd stream *) let gen_odd : int stream = let nat_stream = inf (generate (nats 1) ()) in filter nat_stream (fun n -> n mod 2 == 1) ;; assert (1 = gen_odd ());; assert (3 = gen_odd ());; assert (5 = gen_odd ());; assert (7 = gen_odd ());; Primes using sieve of Eratosthenes let gen_primes = let s = inf (generate (nats 2) ()) in let rs = ref s in fun () -> let s = !rs in let prime = s () in rs := filter s (fun n -> n mod prime != 0); prime ;; assert ( 2 = gen_primes ());; assert ( 3 = gen_primes ());; assert ( 5 = gen_primes ());; assert ( 7 = gen_primes ());; assert (11 = gen_primes ());; assert (13 = gen_primes ());; assert (17 = gen_primes ());; assert (19 = gen_primes ());; assert (23 = gen_primes ());; assert (29 = gen_primes ());; assert (31 = gen_primes ());;
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-effects-tutorial/998376931b7fdaed5d54cb96b39b301b993ba995/sources/solved/generator.ml
ocaml
Original solution let generate (type elt) (i : (elt, 'container) iterator) (c : 'container) : elt generator = let module M = struct effect Yield : elt -> unit end in let open M in let rec step = ref (fun () -> i (fun v -> perform (Yield v)) c; step := (fun () -> None); None) in let loop () = try !step () with | effect (Yield v) k -> (step := continue k; Some v) in loop My solution Might be able to do something with a deep handler instead * helper : unit -> elt option * i : (elt -> unit) -> container -> unit * continue_with k () * { * * ********************* ********************* ********* Streams ********* Iterator over nats. Dummy () container. init Infinite stream Convert generator to an infinite stream Nat stream filter stream map stream Even stream Odd stream
type ('elt,'container) iterator = ('elt -> unit) -> 'container -> unit type 'elt generator = unit -> 'elt option let generate (type elt) (i : (elt, 'container) iterator) (c : 'container) : elt generator = let open Effect in let open Effect.Shallow in let module M = struct type _ Effect.t += Yield : elt -> unit Effect.t type ('a, 'b) status = NotStarted | InProgress of ('a,'b) continuation | Finished end in let open M in let yield v = perform (Yield v) in let curr_status = ref NotStarted in let rec helper () = match !curr_status with | Finished -> None | NotStarted -> curr_status := InProgress (fiber (fun () -> i yield c)); helper () | InProgress k -> continue_with k () { retc = (fun _ -> curr_status := Finished; helper ()); exnc = (fun e -> raise e); effc = (fun (type b) (eff: b Effect.t) -> match eff with | Yield x -> Some (fun (k: (b,_) continuation) -> curr_status := InProgress k; Some x ) | _ -> None)} in helper Traversal generator let gen_list : 'a list -> 'a generator = generate List.iter let gl : int generator = gen_list [1;2;3] ;; assert (Some 1 = gl ());; assert (Some 2 = gl ());; assert (Some 3 = gl ());; assert (None = gl ());; assert (None = gl ());; let gen_array : 'a array -> 'a generator = generate Array.iter let ga : float generator = gen_array [| 1.0; 2.0; 3.0 |] ;; assert (Some 1.0 = ga ());; assert (Some 2.0 = ga ());; assert (Some 3.0 = ga ());; assert (None = ga ());; assert (None = ga ());; fun v f () -> f v; nats (v+1) f () type 'a stream = unit -> 'a let inf : 'a generator -> 'a stream = fun g () -> match g () with | Some n -> n | _ -> assert false let gen_nats : int stream = inf (generate (nats 0) ()) ;; assert (0 = gen_nats ());; assert (1 = gen_nats ());; assert (2 = gen_nats ());; assert (3 = gen_nats ());; let rec filter : 'a stream -> ('a -> bool) -> 'a stream = fun g p () -> let v = g () in if p v then v else filter g p () let rec map : 'a stream -> ('a -> 'b) -> 'b stream = fun g f () -> f (g ()) let gen_even : int stream = let nat_stream = inf (generate (nats 0) ()) in filter nat_stream (fun n -> n mod 2 = 0) ;; assert (0 = gen_even ());; assert (2 = gen_even ());; assert (4 = gen_even ());; assert (6 = gen_even ());; let gen_odd : int stream = let nat_stream = inf (generate (nats 1) ()) in filter nat_stream (fun n -> n mod 2 == 1) ;; assert (1 = gen_odd ());; assert (3 = gen_odd ());; assert (5 = gen_odd ());; assert (7 = gen_odd ());; Primes using sieve of Eratosthenes let gen_primes = let s = inf (generate (nats 2) ()) in let rs = ref s in fun () -> let s = !rs in let prime = s () in rs := filter s (fun n -> n mod prime != 0); prime ;; assert ( 2 = gen_primes ());; assert ( 3 = gen_primes ());; assert ( 5 = gen_primes ());; assert ( 7 = gen_primes ());; assert (11 = gen_primes ());; assert (13 = gen_primes ());; assert (17 = gen_primes ());; assert (19 = gen_primes ());; assert (23 = gen_primes ());; assert (29 = gen_primes ());; assert (31 = gen_primes ());;
4cb76f13744811d41b6ae0af45844f7cddc9873c4e26e8429453868e4b2a7622
racket/eopl
interp.rkt
#lang eopl interpreter for the LETREC language . The \commentboxes are the ;; latex code for inserting the rules into the code in the book. ;; These are too complicated to put here, see the text, sorry. (require "lang.rkt") (require "data-structures.rkt") (require "environments.rkt") (provide value-of-program value-of) ;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;; value - of - program : Program - > ExpVal (define value-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (value-of exp1 (init-env)))))) value - of : Exp * Env - > ExpVal Page : 83 (define value-of (lambda (exp env) (cases expression exp ;;\commentbox{ (value-of (const-exp \n{}) \r) = \n{}} (const-exp (num) (num-val num)) ;;\commentbox{ (value-of (var-exp \x{}) \r) = (apply-env \r \x{})} (var-exp (var) (apply-env env var)) ;;\commentbox{\diffspec} (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) ;;\commentbox{\zerotestspec} (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zero? num1) (bool-val #t) (bool-val #f))))) ;;\commentbox{\ma{\theifspec}} (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) ;;\commentbox{\ma{\theletspecsplit}} (let-exp (var exp1 body) (let ((val1 (value-of exp1 env))) (value-of body (extend-env var val1 env)))) (proc-exp (var body) (proc-val (procedure var body env))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator env))) (arg (value-of rand env))) (apply-procedure proc arg))) (letrec-exp (p-name b-var p-body letrec-body) (value-of letrec-body (extend-env-rec p-name b-var p-body env))) ))) apply - procedure : Proc * ExpVal - > ExpVal (define apply-procedure (lambda (proc1 arg) (cases proc proc1 (procedure (var body saved-env) (value-of body (extend-env var arg saved-env))))))
null
https://raw.githubusercontent.com/racket/eopl/43575d6e95dc34ca6e49b305180f696565e16e0f/tests/chapter3/letrec-lang/interp.rkt
racket
latex code for inserting the rules into the code in the book. These are too complicated to put here, see the text, sorry. the interpreter ;;;;;;;;;;;;;;;; \commentbox{ (value-of (const-exp \n{}) \r) = \n{}} \commentbox{ (value-of (var-exp \x{}) \r) = (apply-env \r \x{})} \commentbox{\diffspec} \commentbox{\zerotestspec} \commentbox{\ma{\theifspec}} \commentbox{\ma{\theletspecsplit}}
#lang eopl interpreter for the LETREC language . The \commentboxes are the (require "lang.rkt") (require "data-structures.rkt") (require "environments.rkt") (provide value-of-program value-of) value - of - program : Program - > ExpVal (define value-of-program (lambda (pgm) (cases program pgm (a-program (exp1) (value-of exp1 (init-env)))))) value - of : Exp * Env - > ExpVal Page : 83 (define value-of (lambda (exp env) (cases expression exp (const-exp (num) (num-val num)) (var-exp (var) (apply-env env var)) (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zero? num1) (bool-val #t) (bool-val #f))))) (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) (let-exp (var exp1 body) (let ((val1 (value-of exp1 env))) (value-of body (extend-env var val1 env)))) (proc-exp (var body) (proc-val (procedure var body env))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator env))) (arg (value-of rand env))) (apply-procedure proc arg))) (letrec-exp (p-name b-var p-body letrec-body) (value-of letrec-body (extend-env-rec p-name b-var p-body env))) ))) apply - procedure : Proc * ExpVal - > ExpVal (define apply-procedure (lambda (proc1 arg) (cases proc proc1 (procedure (var body saved-env) (value-of body (extend-env var arg saved-env))))))
a3db4994bf8149b8d5dcc9993bc76f865bb2e7c511047afcf9a90ef30995ab63
replomancer/Swordfight
cecp_test.clj
(ns swordfight.cecp-test (:require [midje.sweet :refer [contains fact facts has-suffix namespace-state-changes]] [swordfight.ai :refer [hurried-move]] [swordfight.board :refer [->board]] [swordfight.core :refer [initial-game-settings]] [swordfight.rules :refer [initial-game-state]] [swordfight.cecp :refer [initial-communication eval-command thinking-mode]])) (defn cecp-facts-teardown [] (reset! hurried-move false) (reset! thinking-mode false)) (namespace-state-changes [(after :facts (cecp-facts-teardown))]) (facts "about engine start" (fact "Engine sets the name to \"Swordfight\" during initial communication." (with-out-str (initial-communication)) => (contains "myname=\"Swordfight\"")) (fact "Engine requests for signal-free communication with the GUI." (with-out-str (initial-communication)) => (contains "sigint=0 sigterm=0")) (fact "Engine sends done=1 in features." (with-out-str (initial-communication)) => (has-suffix "done=1\n"))) (facts "about force mode" (let [game-state (atom initial-game-state) game-settings (atom initial-game-settings)] (fact "Engine in force mode accepts a series of legal moves." (let [board-after-all-moves (->board [" r n b q k b . r " " . p p p p p p p " " p . . . . . . n " " . . . . . . . . " " P . . . . . . . " " . . N . . . . . " " . P P P P P P P " " R . B Q K B N R "])] (doseq [cmd ["force" "a2a4" "a7a6" "b1c3" "g8h6"]] (eval-command game-state game-settings [cmd])) (:board @game-state) => board-after-all-moves)) (fact "Engine in force mode rejects illegal moves." (with-out-str (eval-command game-state game-settings ["a1a8"])) => "Illegal move: a1a8\n"))) (facts "about board edition" (let [game-state (atom initial-game-state) game-settings (atom initial-game-settings)] (fact "Engine enters edition mode after edit command" (eval-command game-state game-settings ["edit"]) (:edit-mode @game-state) => true) (fact "Edition commands alter the board correctly" (let [board-after-edition (->board [" r n b q k b . r " " . p p . . p p p " " p . . . . . . n " " . . . Q . . . . " " P . . . Q p R . " " . . N . . . . . " " . P P P P P P P " " R . B Q K B N R "])] (doseq [cmd ["#" "Ra1" "Bc1" "Qd1" "Ke1" "Bf1" "Ng1" "Rh1" "Pb2" "Pc2" "Pd2" "Pe2" "Pf2" "Pg2" "Ph2" "Nc3" "Pa4" "c" "Ra8" "Nb8" "Bc8" "Qd8" "Ke8" "Bf8" "Rh8" "Pb7" "Pc7" "Pf7" "Pg7" "Ph7" "Pa6" "Nh6" "c" "Qd5" "Qe4" "Rg4" "c" "Pf4"]] (eval-command game-state game-settings [cmd])) (:board @game-state) => board-after-edition)) (fact "Engine leaves edition mode after . command" (with-out-str (eval-command game-state game-settings ["."])) (:edit-mode @game-state) => false)))
null
https://raw.githubusercontent.com/replomancer/Swordfight/4ac956d0c9076792774dd05db3f258a8c713c49c/test/swordfight/cecp_test.clj
clojure
(ns swordfight.cecp-test (:require [midje.sweet :refer [contains fact facts has-suffix namespace-state-changes]] [swordfight.ai :refer [hurried-move]] [swordfight.board :refer [->board]] [swordfight.core :refer [initial-game-settings]] [swordfight.rules :refer [initial-game-state]] [swordfight.cecp :refer [initial-communication eval-command thinking-mode]])) (defn cecp-facts-teardown [] (reset! hurried-move false) (reset! thinking-mode false)) (namespace-state-changes [(after :facts (cecp-facts-teardown))]) (facts "about engine start" (fact "Engine sets the name to \"Swordfight\" during initial communication." (with-out-str (initial-communication)) => (contains "myname=\"Swordfight\"")) (fact "Engine requests for signal-free communication with the GUI." (with-out-str (initial-communication)) => (contains "sigint=0 sigterm=0")) (fact "Engine sends done=1 in features." (with-out-str (initial-communication)) => (has-suffix "done=1\n"))) (facts "about force mode" (let [game-state (atom initial-game-state) game-settings (atom initial-game-settings)] (fact "Engine in force mode accepts a series of legal moves." (let [board-after-all-moves (->board [" r n b q k b . r " " . p p p p p p p " " p . . . . . . n " " . . . . . . . . " " P . . . . . . . " " . . N . . . . . " " . P P P P P P P " " R . B Q K B N R "])] (doseq [cmd ["force" "a2a4" "a7a6" "b1c3" "g8h6"]] (eval-command game-state game-settings [cmd])) (:board @game-state) => board-after-all-moves)) (fact "Engine in force mode rejects illegal moves." (with-out-str (eval-command game-state game-settings ["a1a8"])) => "Illegal move: a1a8\n"))) (facts "about board edition" (let [game-state (atom initial-game-state) game-settings (atom initial-game-settings)] (fact "Engine enters edition mode after edit command" (eval-command game-state game-settings ["edit"]) (:edit-mode @game-state) => true) (fact "Edition commands alter the board correctly" (let [board-after-edition (->board [" r n b q k b . r " " . p p . . p p p " " p . . . . . . n " " . . . Q . . . . " " P . . . Q p R . " " . . N . . . . . " " . P P P P P P P " " R . B Q K B N R "])] (doseq [cmd ["#" "Ra1" "Bc1" "Qd1" "Ke1" "Bf1" "Ng1" "Rh1" "Pb2" "Pc2" "Pd2" "Pe2" "Pf2" "Pg2" "Ph2" "Nc3" "Pa4" "c" "Ra8" "Nb8" "Bc8" "Qd8" "Ke8" "Bf8" "Rh8" "Pb7" "Pc7" "Pf7" "Pg7" "Ph7" "Pa6" "Nh6" "c" "Qd5" "Qe4" "Rg4" "c" "Pf4"]] (eval-command game-state game-settings [cmd])) (:board @game-state) => board-after-edition)) (fact "Engine leaves edition mode after . command" (with-out-str (eval-command game-state game-settings ["."])) (:edit-mode @game-state) => false)))
e8f8efba35e4ea0760c2c31313395dd3c3a9c2aaa399067e0667e08639df6f7d
benoitc/hackney
hackney_http_tests.erl
-module(hackney_http_tests). -include_lib("eunit/include/eunit.hrl"). -include("hackney_lib.hrl"). parse_response_correct_200_test() -> Response = <<"HTTP/1.1 200 OK">>, St = #hparser{}, {response, _Version, StatusInt, Reason, _NState} = hackney_http:parse_response_version(Response, St), ?assertEqual(StatusInt, 200), ?assertEqual(Reason, <<"OK">>). parse_response_incomplete_200_test() -> Response = <<"HTTP/1.1 200 ">>, St = #hparser{}, {response, _Version, StatusInt, Reason, _NState} = hackney_http:parse_response_version(Response, St), ?assertEqual(StatusInt, 200), ?assertEqual(Reason, <<"">>). parse_response_missing_reason_phrase_test() -> Response = <<"HTTP/1.1 200">>, St = #hparser{}, {response, _Version, StatusInt, Reason, _NState} = hackney_http:parse_response_version(Response, St), ?assertEqual(StatusInt, 200), ?assertEqual(Reason, <<"">>). parse_response_header_with_continuation_line_test() -> Response = <<"HTTP/1.1 200\r\nContent-Type: multipart/related;\r\n\tboundary=\"--:\"\r\nOther-Header: test\r\n\r\n">>, ST1 = #hparser{}, {response, _Version, _StatusInt, _Reason, ST2} = hackney_http:execute(ST1, Response), {header, Header, ST3} = hackney_http:execute(ST2), ?assertEqual({<<"Content-Type">>, <<"multipart/related; boundary=\"--:\"">>}, Header), {header, Header1, ST4} = hackney_http:execute(ST3), ?assertEqual({<<"Other-Header">>, <<"test">>}, Header1), {headers_complete, _ST5} = hackney_http:execute(ST4). parse_request_correct_leading_newlines_test() -> Request = <<"\r\nGET / HTTP/1.1\r\n\r\n">>, ST1 = #hparser{}, {request, Verb, Resource, Version, _ST2} = hackney_http:execute(ST1, Request), ?assertEqual(Verb, <<"GET">>), ?assertEqual(Resource, <<"/">>), ?assertEqual(Version, {1,1}). parse_request_error_too_many_newlines_test() -> Request = <<"\r\nGET / HTTP/1.1\r\n\r\n">>, St = #hparser{max_empty_lines = 0}, {error, bad_request} = hackney_http:execute(St, Request). parse_chunked_response_crlf_test() -> P0 = hackney_http:parser([response]), {_, _, _, _, P1} = hackney_http:execute(P0, <<"HTTP/1.1 200 OK\r\n">>), {_, _, P2} = hackney_http:execute(P1, <<"Transfer-Encoding: chunked\r\n">>), {_, P3} = hackney_http:execute(P2, <<"\r\n">>), ?assertEqual({done, <<>>}, hackney_http:execute(P3, <<"0\r\n\r\n">>)), ?assertEqual({done, <<"a">>}, hackney_http:execute(P3, <<"0\r\n\r\na">>)), {more, P4_1} = hackney_http:execute(P3, <<"0\r\n">>), ?assertEqual({done, <<>>}, hackney_http:execute(P4_1, <<"\r\n">>)), {more, P4_2} = hackney_http:execute(P3, <<"0\r\n\r">>), ?assertEqual({done, <<>>}, hackney_http:execute(P4_2, <<"\n">>)). parse_chunked_response_trailers_test() -> P0 = hackney_http:parser([response]), {_, _, _, _, P1} = hackney_http:execute(P0, <<"HTTP/1.1 200 OK\r\n">>), {_, _, P2} = hackney_http:execute(P1, <<"Transfer-Encoding: chunked\r\n">>), {_, P3} = hackney_http:execute(P2, <<"\r\n">>), {more, P4} = hackney_http:execute(P3, <<"0\r\nFoo: ">>), ?assertEqual({done, <<>>}, hackney_http:execute(P4, <<"Bar\r\n\r\n">>)).
null
https://raw.githubusercontent.com/benoitc/hackney/6e79b2bb11a77389d3ba9ff3a0828a45796fe7a8/test/hackney_http_tests.erl
erlang
-module(hackney_http_tests). -include_lib("eunit/include/eunit.hrl"). -include("hackney_lib.hrl"). parse_response_correct_200_test() -> Response = <<"HTTP/1.1 200 OK">>, St = #hparser{}, {response, _Version, StatusInt, Reason, _NState} = hackney_http:parse_response_version(Response, St), ?assertEqual(StatusInt, 200), ?assertEqual(Reason, <<"OK">>). parse_response_incomplete_200_test() -> Response = <<"HTTP/1.1 200 ">>, St = #hparser{}, {response, _Version, StatusInt, Reason, _NState} = hackney_http:parse_response_version(Response, St), ?assertEqual(StatusInt, 200), ?assertEqual(Reason, <<"">>). parse_response_missing_reason_phrase_test() -> Response = <<"HTTP/1.1 200">>, St = #hparser{}, {response, _Version, StatusInt, Reason, _NState} = hackney_http:parse_response_version(Response, St), ?assertEqual(StatusInt, 200), ?assertEqual(Reason, <<"">>). parse_response_header_with_continuation_line_test() -> Response = <<"HTTP/1.1 200\r\nContent-Type: multipart/related;\r\n\tboundary=\"--:\"\r\nOther-Header: test\r\n\r\n">>, ST1 = #hparser{}, {response, _Version, _StatusInt, _Reason, ST2} = hackney_http:execute(ST1, Response), {header, Header, ST3} = hackney_http:execute(ST2), ?assertEqual({<<"Content-Type">>, <<"multipart/related; boundary=\"--:\"">>}, Header), {header, Header1, ST4} = hackney_http:execute(ST3), ?assertEqual({<<"Other-Header">>, <<"test">>}, Header1), {headers_complete, _ST5} = hackney_http:execute(ST4). parse_request_correct_leading_newlines_test() -> Request = <<"\r\nGET / HTTP/1.1\r\n\r\n">>, ST1 = #hparser{}, {request, Verb, Resource, Version, _ST2} = hackney_http:execute(ST1, Request), ?assertEqual(Verb, <<"GET">>), ?assertEqual(Resource, <<"/">>), ?assertEqual(Version, {1,1}). parse_request_error_too_many_newlines_test() -> Request = <<"\r\nGET / HTTP/1.1\r\n\r\n">>, St = #hparser{max_empty_lines = 0}, {error, bad_request} = hackney_http:execute(St, Request). parse_chunked_response_crlf_test() -> P0 = hackney_http:parser([response]), {_, _, _, _, P1} = hackney_http:execute(P0, <<"HTTP/1.1 200 OK\r\n">>), {_, _, P2} = hackney_http:execute(P1, <<"Transfer-Encoding: chunked\r\n">>), {_, P3} = hackney_http:execute(P2, <<"\r\n">>), ?assertEqual({done, <<>>}, hackney_http:execute(P3, <<"0\r\n\r\n">>)), ?assertEqual({done, <<"a">>}, hackney_http:execute(P3, <<"0\r\n\r\na">>)), {more, P4_1} = hackney_http:execute(P3, <<"0\r\n">>), ?assertEqual({done, <<>>}, hackney_http:execute(P4_1, <<"\r\n">>)), {more, P4_2} = hackney_http:execute(P3, <<"0\r\n\r">>), ?assertEqual({done, <<>>}, hackney_http:execute(P4_2, <<"\n">>)). parse_chunked_response_trailers_test() -> P0 = hackney_http:parser([response]), {_, _, _, _, P1} = hackney_http:execute(P0, <<"HTTP/1.1 200 OK\r\n">>), {_, _, P2} = hackney_http:execute(P1, <<"Transfer-Encoding: chunked\r\n">>), {_, P3} = hackney_http:execute(P2, <<"\r\n">>), {more, P4} = hackney_http:execute(P3, <<"0\r\nFoo: ">>), ?assertEqual({done, <<>>}, hackney_http:execute(P4, <<"Bar\r\n\r\n">>)).
7acb2bcea30c2901db07c64d34b466734304f48353ddc73e5ad90a305018e1a2
thumphries/foundationdb
test-io.hs
import Data.Traversable (sequenceA) import System.Exit (ExitCode (..), exitWith) import qualified Test.IO.FoundationDb.C as C main :: IO () main = do testMain [ C.tests ] testMain :: [IO Bool] -> IO () testMain tests = do bs <- sequenceA tests case and bs of True -> return () False -> exitWith (ExitFailure 1)
null
https://raw.githubusercontent.com/thumphries/foundationdb/4feb5dee361970accf90260f16adc7f0d6ba122b/test/test-io.hs
haskell
import Data.Traversable (sequenceA) import System.Exit (ExitCode (..), exitWith) import qualified Test.IO.FoundationDb.C as C main :: IO () main = do testMain [ C.tests ] testMain :: [IO Bool] -> IO () testMain tests = do bs <- sequenceA tests case and bs of True -> return () False -> exitWith (ExitFailure 1)
632a02862b4e701c8a03981c3e374fbb9897dc2e981f4ef5589902d14d9168b3
georgegarrington/Syphon
Type.hs
module Parse.Testing.Type where import Text.Megaparsec import Test.Hspec.Megaparsec import AST.Type import Parse.Type import Parse.Testing.Root testTup = ("(a,b)" `testParse` pType) `shouldParse` (mkTuple [ParsedQuant 'a',ParsedQuant 'b']) list1 = ("[[a]]" `testParse` pType) `shouldParse` (listConstr `TyApp` (listConstr `TyApp` ParsedQuant 'a')) nested = ("Either (Maybe a) ([a],(b,c))" `testParse` pType) `shouldParse` ((eitherConstr `TyApp` (maybeConstr `TyApp` ParsedQuant 'a')) `TyApp` (mkTuple [listConstr `TyApp` ParsedQuant 'a', mkTuple[ParsedQuant 'b', ParsedQuant 'c']])) binOpFns = ("") ( ( listConstr ` TyApp ` listConstr ` TyApp ` listConstr ` TyApp ` listConstr ) ` TyApp ` ( ' a ' ) ) } testTup = ( " ( a , b ) " ` testParse ` pPattern ) ` shouldParse ` ( TuplePattern [ VarPattern " a",VarPattern " c " ] ) testSpacedPatterns = ( " 1:2 : _ ( Just x ) " ` testParse ` ( some pPattern ) ) ` shouldParse ` [ ConsPattern [ IntPattern 1 , IntPattern 2 , Wildcard ] , Constructor " Just " [ VarPattern " x " ] ] testWrongCons = ( \str - > str ` testParse ` pPattern ) ` shouldFailOn ` " 1:2 : " testTup = ("(a,b)" `testParse` pPattern) `shouldParse` (TuplePattern [VarPattern "a",VarPattern "c"]) testSpacedPatterns = ("1:2:_ (Just x)" `testParse` (some pPattern)) `shouldParse` [ConsPattern [IntPattern 1, IntPattern 2, Wildcard], Constructor "Just" [VarPattern "x"]] testWrongCons = (\str -> str `testParse` pPattern) `shouldFailOn` "1:2:"-}
null
https://raw.githubusercontent.com/georgegarrington/Syphon/402a326b482e3ce627a15b651b3097c2e09e8a53/src/Parse/Testing/Type.hs
haskell
module Parse.Testing.Type where import Text.Megaparsec import Test.Hspec.Megaparsec import AST.Type import Parse.Type import Parse.Testing.Root testTup = ("(a,b)" `testParse` pType) `shouldParse` (mkTuple [ParsedQuant 'a',ParsedQuant 'b']) list1 = ("[[a]]" `testParse` pType) `shouldParse` (listConstr `TyApp` (listConstr `TyApp` ParsedQuant 'a')) nested = ("Either (Maybe a) ([a],(b,c))" `testParse` pType) `shouldParse` ((eitherConstr `TyApp` (maybeConstr `TyApp` ParsedQuant 'a')) `TyApp` (mkTuple [listConstr `TyApp` ParsedQuant 'a', mkTuple[ParsedQuant 'b', ParsedQuant 'c']])) binOpFns = ("") ( ( listConstr ` TyApp ` listConstr ` TyApp ` listConstr ` TyApp ` listConstr ) ` TyApp ` ( ' a ' ) ) } testTup = ( " ( a , b ) " ` testParse ` pPattern ) ` shouldParse ` ( TuplePattern [ VarPattern " a",VarPattern " c " ] ) testSpacedPatterns = ( " 1:2 : _ ( Just x ) " ` testParse ` ( some pPattern ) ) ` shouldParse ` [ ConsPattern [ IntPattern 1 , IntPattern 2 , Wildcard ] , Constructor " Just " [ VarPattern " x " ] ] testWrongCons = ( \str - > str ` testParse ` pPattern ) ` shouldFailOn ` " 1:2 : " testTup = ("(a,b)" `testParse` pPattern) `shouldParse` (TuplePattern [VarPattern "a",VarPattern "c"]) testSpacedPatterns = ("1:2:_ (Just x)" `testParse` (some pPattern)) `shouldParse` [ConsPattern [IntPattern 1, IntPattern 2, Wildcard], Constructor "Just" [VarPattern "x"]] testWrongCons = (\str -> str `testParse` pPattern) `shouldFailOn` "1:2:"-}
8aa5f2bf4d299ed570e36f1b5ec78d82dda02dd5d2edebd412147d3da18b473d
bollu/koans
recursion-schemes-from-talk.hs
-- foldr :: (Maybe (a, b) -> b) -> [a] -> b foldr alg [] = alg $ Nothing foldr alg (x:xs) = alg $ Just(x, foldr alg xs)
null
https://raw.githubusercontent.com/bollu/koans/0204e9bb5ef9c541fe161523acac3cacae5d07fe/recursion-schemes-from-talk.hs
haskell
foldr :: (Maybe (a, b) -> b) -> [a] -> b foldr alg [] = alg $ Nothing foldr alg (x:xs) = alg $ Just(x, foldr alg xs)
72b0fd5276b9b79c252a837e523dfd00544f9a73a2dda321d500050872692bff
spurious/sagittarius-scheme-mirror
bearer.scm
-*- mode : scheme ; coding : utf-8 ; -*- ;;; rfc / / bearer.scm - Bearer extension ;;; Copyright ( c ) 2017 < > ;;; ;;; 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. ;;; ;;; 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. ;;; ;; reference ;; RFC 6750: (library (rfc oauth2 bearer) (export oauth2-generate-authorization) (import (rnrs) (rfc uri)) (define (oauth2-generate-authorization token) (values (string-append "Bearer " token) (string-append "access_token=" (uri-encode-string token)))) )
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/rfc/oauth2/bearer.scm
scheme
coding : utf-8 ; -*- 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 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, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. reference RFC 6750:
rfc / / bearer.scm - Bearer extension Copyright ( c ) 2017 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING (library (rfc oauth2 bearer) (export oauth2-generate-authorization) (import (rnrs) (rfc uri)) (define (oauth2-generate-authorization token) (values (string-append "Bearer " token) (string-append "access_token=" (uri-encode-string token)))) )
22c4d518c355905a27caf855c5e8e67574c9dca6be66dbf1ba77d57bd35d7abe
RedPRL/cooltt
LexingUtil.ml
include Lexing type span = {start : Lexing.position; stop : Lexing.position} let pp_span : span Pp.printer = fun fmt span -> Format.fprintf fmt "%a:%i.%i-%i.%i" (* HACK: We use the basename, rather than the full path here to avoid issues with the test suite. This is bad, and should be changed once more thought is put into how we want to handle fancier imports/project structures. *) Uuseg_string.pp_utf_8 (Filename.basename span.start.pos_fname) span.start.pos_lnum (span.start.pos_cnum - span.start.pos_bol) span.stop.pos_lnum (span.stop.pos_cnum - span.stop.pos_bol) let last_token lexbuf = let tok = lexeme lexbuf in if tok = "" then None else Some tok let current_span lexbuf = {start = lexbuf.lex_start_p; stop = lexbuf.lex_curr_p}
null
https://raw.githubusercontent.com/RedPRL/cooltt/2e451ab8b02e8b4306aabbfe3f2197d775def343/src/basis/LexingUtil.ml
ocaml
HACK: We use the basename, rather than the full path here to avoid issues with the test suite. This is bad, and should be changed once more thought is put into how we want to handle fancier imports/project structures.
include Lexing type span = {start : Lexing.position; stop : Lexing.position} let pp_span : span Pp.printer = fun fmt span -> Format.fprintf fmt "%a:%i.%i-%i.%i" Uuseg_string.pp_utf_8 (Filename.basename span.start.pos_fname) span.start.pos_lnum (span.start.pos_cnum - span.start.pos_bol) span.stop.pos_lnum (span.stop.pos_cnum - span.stop.pos_bol) let last_token lexbuf = let tok = lexeme lexbuf in if tok = "" then None else Some tok let current_span lexbuf = {start = lexbuf.lex_start_p; stop = lexbuf.lex_curr_p}
71fd6a9c7683e80c5e91584755c69b27908eb8c195ab690cc8e9508439c07885
basho/riak_cs
riak_cs_wm_common.erl
%% --------------------------------------------------------------------- %% Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% --------------------------------------------------------------------- -module(riak_cs_wm_common). -export([init/1, service_available/2, forbidden/2, content_types_accepted/2, content_types_provided/2, generate_etag/2, last_modified/2, valid_entity_length/2, validate_content_checksum/2, malformed_request/2, to_xml/2, to_json/2, post_is_create/2, create_path/2, process_post/2, resp_body/2, multiple_choices/2, add_acl_to_context_then_accept/2, accept_body/2, produce_body/2, allowed_methods/2, delete_resource/2, finish_request/2]). -export([default_allowed_methods/0, default_stats_prefix/0, default_content_types_accepted/2, default_content_types_provided/2, default_generate_etag/2, default_last_modified/2, default_finish_request/2, default_init/1, default_authorize/2, default_malformed_request/2, default_valid_entity_length/2, default_validate_content_checksum/2, default_delete_resource/2, default_anon_ok/0, default_produce_body/2, default_multiple_choices/2]). -include("riak_cs.hrl"). -include("oos_api.hrl"). -include_lib("webmachine/include/webmachine.hrl"). %% =================================================================== Webmachine callbacks %% =================================================================== -spec init([{atom(),term()}]) -> {ok, #context{}}. init(Config) -> _ = dyntrace:put_tag(pid_to_list(self())), Mod = proplists:get_value(submodule, Config), riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"init">>), %% Check if authentication is disabled and set that in the context. AuthBypass = proplists:get_value(auth_bypass, Config), AuthModule = proplists:get_value(auth_module, Config), Api = riak_cs_config:api(), RespModule = riak_cs_config:response_module(Api), PolicyModule = proplists:get_value(policy_module, Config), Exports = orddict:from_list(Mod:module_info(exports)), ExportsFun = exports_fun(Exports), StatsPrefix = resource_call(Mod, stats_prefix, [], ExportsFun), Ctx = #context{auth_bypass=AuthBypass, auth_module=AuthModule, response_module=RespModule, policy_module=PolicyModule, exports_fun=ExportsFun, stats_prefix=StatsPrefix, start_time=os:timestamp(), submodule=Mod, api=Api}, resource_call(Mod, init, [Ctx], ExportsFun). -spec service_available(#wm_reqdata{}, #context{}) -> {boolean(), #wm_reqdata{}, #context{}}. service_available(RD, Ctx=#context{rc_pool=undefined}) -> service_available(RD, Ctx#context{rc_pool=request_pool}); service_available(RD, Ctx=#context{submodule=Mod, rc_pool=Pool}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"service_available">>), case riak_cs_riak_client:checkout(Pool) of {ok, RcPid} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"service_available">>, [1], []), {true, RD, Ctx#context{riak_client=RcPid}}; {error, _Reason} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"service_available">>, [0], []), {false, RD, Ctx} end. -spec malformed_request(#wm_reqdata{}, #context{}) -> {boolean(), #wm_reqdata{}, #context{}}. malformed_request(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun, stats_prefix=StatsPrefix}) -> is used in stats keys , updating inflow should be * after * %% allowed_methods assertion. _ = update_stats_inflow(RD, StatsPrefix), riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"malformed_request">>), {Malformed, _, _} = R = resource_call(Mod, malformed_request, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return_bool_with_default({?MODULE, Mod}, <<"malformed_request">>, Malformed, false), R. -spec valid_entity_length(#wm_reqdata{}, #context{}) -> {boolean(), #wm_reqdata{}, #context{}}. valid_entity_length(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"valid_entity_length">>), {Valid, _, _} = R = resource_call(Mod, valid_entity_length, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return_bool_with_default({?MODULE, Mod}, <<"valid_entity_length">>, Valid, true), R. -type validate_checksum_response() :: {error, term()} | {halt, pos_integer()} | boolean(). -spec validate_content_checksum(#wm_reqdata{}, #context{}) -> {validate_checksum_response(), #wm_reqdata{}, #context{}}. validate_content_checksum(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"validate_content_checksum">>), {Valid, _, _} = R = resource_call(Mod, validate_content_checksum, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return_bool_with_default({?MODULE, Mod}, <<"validate_content_checksum">>, Valid, true), R. -spec forbidden(#wm_reqdata{}, #context{}) -> {boolean() | {halt, non_neg_integer()}, #wm_reqdata{}, #context{}}. forbidden(RD, Ctx=#context{auth_module=AuthMod, submodule=Mod, riak_client=RcPid, exports_fun=ExportsFun}) -> {AuthResult, AnonOk} = case AuthMod:identify(RD, Ctx) of failed -> Identification failed , deny access {{error, no_such_key}, false}; {failed, Reason} -> {{error, Reason}, false}; {UserKey, AuthData} -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"forbidden">>, [], [riak_cs_wm_utils:extract_name(UserKey)]), UserLookupResult = maybe_create_user( riak_cs_user:get_user(UserKey, RcPid), UserKey, Ctx#context.api, Ctx#context.auth_module, AuthData, RcPid), {authenticate(UserLookupResult, RD, Ctx, AuthData), resource_call(Mod, anon_ok, [], ExportsFun)} end, post_authentication(AuthResult, RD, Ctx, AnonOk). maybe_create_user({ok, {_, _}}=UserResult, _, _, _, _, _) -> UserResult; maybe_create_user({error, NE}, KeyId, oos, _, {UserData, _}, RcPid) when NE =:= not_found; NE =:= notfound; NE =:= no_user_key -> {Name, Email, UserId} = UserData, {_, Secret} = riak_cs_oos_utils:user_ec2_creds(UserId, KeyId), Attempt to create a Riak CS user to represent the OS tenant _ = riak_cs_user:create_user(Name, Email, KeyId, Secret), riak_cs_user:get_user(KeyId, RcPid); maybe_create_user({error, NE}, KeyId, s3, riak_cs_keystone_auth, {UserData, _}, RcPid) when NE =:= not_found; NE =:= notfound; NE =:= no_user_key -> {Name, Email, UserId} = UserData, {_, Secret} = riak_cs_oos_utils:user_ec2_creds(UserId, KeyId), Attempt to create a Riak CS user to represent the OS tenant _ = riak_cs_user:create_user(Name, Email, KeyId, Secret), riak_cs_user:get_user(KeyId, RcPid); maybe_create_user({error, no_user_key}=Error, _, _, _, _, _) -> Anonymous access may be authorized by ACL or policy afterwards , %% no logging here. Error; maybe_create_user({error, disconnected}=Error, _, _, _, _, RcPid) -> {ok, MasterPid} = riak_cs_riak_client:master_pbc(RcPid), riak_cs_pbc:check_connection_status(MasterPid, maybe_create_user), Error; maybe_create_user({error, Reason}=Error, _, Api, _, _, _) -> _ = lager:error("Retrieval of user record for ~p failed. Reason: ~p", [Api, Reason]), Error. %% @doc Get the list of methods a resource supports. -spec allowed_methods(#wm_reqdata{}, #context{}) -> {[atom()], #wm_reqdata{}, #context{}}. allowed_methods(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"allowed_methods">>), Methods = resource_call(Mod, allowed_methods, [], ExportsFun), {Methods, RD, Ctx}. -spec content_types_accepted(#wm_reqdata{}, #context{}) -> {[{string(), atom()}], #wm_reqdata{}, #context{}}. content_types_accepted(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"content_types_accepted">>), resource_call(Mod, content_types_accepted, [RD,Ctx], ExportsFun). -spec content_types_provided(#wm_reqdata{}, #context{}) -> {[{string(), atom()}], #wm_reqdata{}, #context{}}. content_types_provided(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"content_types_provided">>), resource_call(Mod, content_types_provided, [RD,Ctx], ExportsFun). -spec generate_etag(#wm_reqdata{}, #context{}) -> {string(), #wm_reqdata{}, #context{}}. generate_etag(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"generate_etag">>), resource_call(Mod, generate_etag, [RD,Ctx], ExportsFun). -spec last_modified(#wm_reqdata{}, #context{}) -> {calendar:datetime(), #wm_reqdata{}, #context{}}. last_modified(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"last_modified">>), resource_call(Mod, last_modified, [RD,Ctx], ExportsFun). -spec delete_resource(#wm_reqdata{}, #context{}) -> {boolean() | {halt, non_neg_integer()}, #wm_reqdata{}, #context{}}. delete_resource(RD, Ctx=#context{submodule=Mod,exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"delete_resource">>), %% TODO: add dt_wm_return from subresource? resource_call(Mod, delete_resource, [RD,Ctx], ExportsFun). -spec to_xml(#wm_reqdata{}, #context{}) -> {binary() | {'halt', non_neg_integer()}, #wm_reqdata{}, #context{}}. to_xml(RD, Ctx=#context{user=User, submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"to_xml">>), Res = resource_call(Mod, to_xml, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"to_xml">>, [], [riak_cs_wm_utils:extract_name(User)]), Res. -spec to_json(#wm_reqdata{}, #context{}) -> {binary() | {'halt', non_neg_integer()}, #wm_reqdata{}, #context{}}. to_json(RD, Ctx=#context{user=User, submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"to_json">>), Res = resource_call(Mod, to_json, [RD, Ctx], ExportsFun(to_json)), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"to_json">>, [], [riak_cs_wm_utils:extract_name(User)]), Res. post_is_create(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> resource_call(Mod, post_is_create, [RD, Ctx], ExportsFun). create_path(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> resource_call(Mod, create_path, [RD, Ctx], ExportsFun). process_post(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> resource_call(Mod, process_post, [RD, Ctx], ExportsFun). resp_body(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> resource_call(Mod, resp_body, [RD, Ctx], ExportsFun). multiple_choices(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> try resource_call(Mod, multiple_choices, [RD, Ctx], ExportsFun) catch _:_ -> {false, RD, Ctx} end. %% @doc Add an ACL (or default ACL) to the context, parsed from headers. If %% parsing the headers fails, halt the request. add_acl_to_context_then_accept(RD, Ctx) -> case riak_cs_wm_utils:maybe_update_context_with_acl_from_headers(RD, Ctx) of {ok, ContextWithAcl} -> accept_body(RD, ContextWithAcl); {error, HaltResponse} -> HaltResponse end. -spec accept_body(#wm_reqdata{}, #context{}) -> {boolean() | {'halt', non_neg_integer()}, #wm_reqdata{}, #context{}}. accept_body(RD, Ctx=#context{submodule=Mod,exports_fun=ExportsFun,user=User}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"accept_body">>), Res = resource_call(Mod, accept_body, [RD, Ctx], ExportsFun), %% TODO: extract response code and add to ints field riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"accept_body">>, [], [riak_cs_wm_utils:extract_name(User)]), Res. -spec produce_body(#wm_reqdata{}, #context{}) -> {iolist()|binary(), #wm_reqdata{}, #context{}} | {{known_length_stream, non_neg_integer(), {<<>>, function()}}, #wm_reqdata{}, #context{}}. produce_body(RD, Ctx=#context{user=User, submodule=Mod, exports_fun=ExportsFun}) -> %% TODO: add dt_wm_return w/ content length riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"produce_body">>), Res = resource_call(Mod, produce_body, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"produce_body">>, [], [riak_cs_wm_utils:extract_name(User)]), Res. -spec finish_request(#wm_reqdata{}, #context{}) -> {boolean(), #wm_reqdata{}, #context{}}. finish_request(RD, Ctx=#context{riak_client=RcPid, auto_rc_close=AutoRcClose, submodule=Mod, exports_fun=ExportsFun}) when RcPid =:= undefined orelse AutoRcClose =:= false -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"finish_request">>, [0], []), Res = resource_call(Mod, finish_request, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"finish_request">>, [0], []), update_stats(RD, Ctx), Res; finish_request(RD, Ctx0=#context{riak_client=RcPid, rc_pool=Pool, submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"finish_request">>, [1], []), riak_cs_riak_client:checkin(Pool, RcPid), Ctx = Ctx0#context{riak_client=undefined}, Res = resource_call(Mod, finish_request, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"finish_request">>, [1], []), update_stats(RD, Ctx), Res. %% =================================================================== %% Helper functions %% =================================================================== -spec authorize(#wm_reqdata{}, #context{}) -> {boolean() | {halt, non_neg_integer()}, #wm_reqdata{}, #context{}}. authorize(RD,Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"authorize">>), {Success, _, _} = R = resource_call(Mod, authorize, [RD,Ctx], ExportsFun), case Success of {halt, Code} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authorize">>, [Code], []); false -> %% not forbidden, e.g. success riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authorize">>); true -> %% forbidden riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authorize">>, [403], []) end, R. -type user_lookup_result() :: {ok, {rcs_user(), riakc_obj:riakc_obj()}} | {error, term()}. -spec authenticate(user_lookup_result(), term(), term(), term()) -> {ok, rcs_user(), riakc_obj:riakc_obj()} | {error, term()}. authenticate({ok, {User, UserObj}}, RD, Ctx=#context{auth_module=AuthMod, submodule=Mod}, AuthData) when User?RCS_USER.status =:= enabled -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"authenticate">>, [], [atom_to_binary(AuthMod, latin1)]), case AuthMod:authenticate(User, AuthData, RD, Ctx) of ok -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authenticate">>, [2], [atom_to_binary(AuthMod, latin1)]), {ok, User, UserObj}; {error, reqtime_tooskewed} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authenticate">>, [1], [atom_to_binary(AuthMod, latin1)]), {error, reqtime_tooskewed}; {error, _Reason} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authenticate">>, [0], [atom_to_binary(AuthMod, latin1)]), {error, bad_auth} end; authenticate({ok, {User, _UserObj}}, _RD, _Ctx, _AuthData) when User?RCS_USER.status =/= enabled -> { ok , _ } - > % % disabled account , we are going to 403 {error, bad_auth}; authenticate({error, _}=Error, _RD, _Ctx, _AuthData) -> Error. -spec exports_fun(orddict:orddict()) -> function(). exports_fun(Exports) -> fun(Function) -> orddict:is_key(Function, Exports) end. resource_call(Mod, Fun, Args, true) -> erlang:apply(Mod, Fun, Args); resource_call(_Mod, Fun, Args, false) -> erlang:apply(?MODULE, default(Fun), Args); resource_call(Mod, Fun, Args, ExportsFun) -> resource_call(Mod, Fun, Args, ExportsFun(Fun)). post_authentication(AuthResult, RD, Ctx = #context{submodule=Mod}, AnonOk) -> case post_authentication(AuthResult, RD, Ctx, fun authorize/2, AnonOk) of {false, _RD2, Ctx2} = FalseRet -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"forbidden">>, [], [riak_cs_wm_utils:extract_name(Ctx2#context.user), <<"false">>]), FalseRet; {Rsn, _RD2, Ctx2} = Ret -> Reason = case Rsn of {halt, Code} -> Code; _ -> -1 end, riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"forbidden">>, [Reason], [riak_cs_wm_utils:extract_name(Ctx2#context.user), <<"true">>]), Ret end. post_authentication({ok, User, UserObj}, RD, Ctx, Authorize, _) -> given keyid and signature matched , proceed Authorize(RD, Ctx#context{user=User, user_object=UserObj}); post_authentication({error, no_user_key}, RD, Ctx, Authorize, true) -> no keyid was given , proceed anonymously _ = lager:debug("No user key"), Authorize(RD, Ctx); post_authentication({error, no_user_key}, RD, Ctx, _, false) -> no keyid was given , deny access _ = lager:debug("No user key, deny"), riak_cs_wm_utils:deny_access(RD, Ctx); post_authentication({error, bad_auth}, RD, Ctx, _, _) -> given keyid was found , but signature did n't match _ = lager:debug("bad_auth"), riak_cs_wm_utils:deny_access(RD, Ctx); post_authentication({error, reqtime_tooskewed} = Error, RD, #context{response_module = ResponseMod} = Ctx, _, _) -> _ = lager:debug("reqtime_tooskewed"), ResponseMod:api_error(Error, RD, Ctx); post_authentication({error, {auth_not_supported, AuthType}}, RD, #context{response_module=ResponseMod} = Ctx, _, _) -> _ = lager:debug("auth_not_supported: ~s", [AuthType]), ResponseMod:api_error({auth_not_supported, AuthType}, RD, Ctx); post_authentication({error, notfound}, RD, Ctx, _, _) -> %% This is rubbish. We need to differentiate between %% no key_id being presented and the key_id lookup %% failing in some better way. _ = lager:debug("key_id not present or not found"), riak_cs_wm_utils:deny_access(RD, Ctx); post_authentication({error, Reason}, RD, Ctx, _, _) -> no matching keyid was found , or lookup failed _ = lager:debug("Authentication error: ~p", [Reason]), riak_cs_wm_utils:deny_invalid_key(RD, Ctx). update_stats_inflow(_RD, undefined = _StatsPrefix) -> ok; update_stats_inflow(_RD, no_stats = _StatsPrefix) -> ok; update_stats_inflow(RD, StatsPrefix) -> Method = riak_cs_wm_utils:lower_case_method(wrq:method(RD)), Key = [StatsPrefix, Method], riak_cs_stats:inflow(Key). update_stats(_RD, #context{stats_key=no_stats}) -> ok; update_stats(_RD, #context{stats_prefix=no_stats}) -> ok; update_stats(RD, #context{start_time=StartTime, stats_prefix=StatsPrefix, stats_key=StatsKey}) -> catch update_stats(StartTime, wrq:response_code(RD), StatsPrefix, riak_cs_wm_utils:lower_case_method(wrq:method(RD)), StatsKey). update_stats(StartTime, Code, StatsPrefix, Method, StatsKey0) -> StatsKey = case StatsKey0 of prefix_and_method -> [StatsPrefix, Method]; _ -> StatsKey0 end, case Code of 405 -> %% Method Not Allowed: don't update stats because unallowed mothod may lead to notfound warning in updating stats ok; Success when is_integer(Success) andalso Success < 400 -> riak_cs_stats:update_with_start(StatsKey, StartTime); _Error -> riak_cs_stats:update_error_with_start(StatsKey, StartTime) end. %% =================================================================== %% Resource function defaults %% =================================================================== default(init) -> default_init; default(stats_prefix) -> default_stats_prefix; default(allowed_methods) -> default_allowed_methods; default(content_types_accepted) -> default_content_types_accepted; default(content_types_provided) -> default_content_types_provided; default(generate_etag) -> default_generate_etag; default(last_modified) -> default_last_modified; default(malformed_request) -> default_malformed_request; default(valid_entity_length) -> default_valid_entity_length; default(validate_content_checksum) -> default_validate_content_checksum; default(delete_resource) -> default_delete_resource; default(authorize) -> default_authorize; default(finish_request) -> default_finish_request; default(anon_ok) -> default_anon_ok; default(produce_body) -> default_produce_body; default(multiple_choices) -> default_multiple_choices; default(_) -> undefined. default_init(Ctx) -> {ok, Ctx}. default_stats_prefix() -> no_stats. default_malformed_request(RD, Ctx) -> {false, RD, Ctx}. default_valid_entity_length(RD, Ctx) -> {true, RD, Ctx}. default_validate_content_checksum(RD, Ctx) -> {true, RD, Ctx}. default_content_types_accepted(RD, Ctx) -> {[], RD, Ctx}. -spec default_content_types_provided(#wm_reqdata{}, #context{}) -> {[{string(), atom()}], #wm_reqdata{}, #context{}}. default_content_types_provided(RD, Ctx=#context{api=oos}) -> {[{"text/plain", produce_body}], RD, Ctx}; default_content_types_provided(RD, Ctx) -> {[{"application/xml", produce_body}], RD, Ctx}. default_generate_etag(RD, Ctx) -> {undefined, RD, Ctx}. default_last_modified(RD, Ctx) -> {undefined, RD, Ctx}. default_delete_resource(RD, Ctx) -> {false, RD, Ctx}. default_allowed_methods() -> []. default_finish_request(RD, Ctx) -> {true, RD, Ctx}. default_anon_ok() -> true. default_produce_body(RD, Ctx=#context{submodule=Mod, response_module=ResponseMod, exports_fun=ExportsFun}) -> try ResponseMod:respond( resource_call(Mod, api_request, [RD, Ctx], ExportsFun), RD, Ctx) catch error:{badmatch, {error, Reason}} -> ResponseMod:api_error(Reason, RD, Ctx) end. %% @doc this function will be called by `post_authenticate/2' if the user successfully %% authenticates and the submodule does not provide an implementation %% of authorize/2. The default implementation does not perform any authorization and simply returns false to signify the request is not fobidden -spec default_authorize(term(), term()) -> {false, term(), term()}. default_authorize(RD, Ctx) -> {false, RD, Ctx}. default_multiple_choices(RD, Ctx) -> {false, RD, Ctx}.
null
https://raw.githubusercontent.com/basho/riak_cs/c0c1012d1c9c691c74c8c5d9f69d388f5047bcd2/src/riak_cs_wm_common.erl
erlang
--------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------- =================================================================== =================================================================== Check if authentication is disabled and set that in the context. allowed_methods assertion. no logging here. @doc Get the list of methods a resource supports. TODO: add dt_wm_return from subresource? @doc Add an ACL (or default ACL) to the context, parsed from headers. If parsing the headers fails, halt the request. TODO: extract response code and add to ints field TODO: add dt_wm_return w/ content length =================================================================== Helper functions =================================================================== not forbidden, e.g. success forbidden % disabled account , we are going to 403 This is rubbish. We need to differentiate between no key_id being presented and the key_id lookup failing in some better way. Method Not Allowed: don't update stats because unallowed =================================================================== Resource function defaults =================================================================== @doc this function will be called by `post_authenticate/2' if the user successfully authenticates and the submodule does not provide an implementation of authorize/2. The default implementation does not perform any authorization
Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(riak_cs_wm_common). -export([init/1, service_available/2, forbidden/2, content_types_accepted/2, content_types_provided/2, generate_etag/2, last_modified/2, valid_entity_length/2, validate_content_checksum/2, malformed_request/2, to_xml/2, to_json/2, post_is_create/2, create_path/2, process_post/2, resp_body/2, multiple_choices/2, add_acl_to_context_then_accept/2, accept_body/2, produce_body/2, allowed_methods/2, delete_resource/2, finish_request/2]). -export([default_allowed_methods/0, default_stats_prefix/0, default_content_types_accepted/2, default_content_types_provided/2, default_generate_etag/2, default_last_modified/2, default_finish_request/2, default_init/1, default_authorize/2, default_malformed_request/2, default_valid_entity_length/2, default_validate_content_checksum/2, default_delete_resource/2, default_anon_ok/0, default_produce_body/2, default_multiple_choices/2]). -include("riak_cs.hrl"). -include("oos_api.hrl"). -include_lib("webmachine/include/webmachine.hrl"). Webmachine callbacks -spec init([{atom(),term()}]) -> {ok, #context{}}. init(Config) -> _ = dyntrace:put_tag(pid_to_list(self())), Mod = proplists:get_value(submodule, Config), riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"init">>), AuthBypass = proplists:get_value(auth_bypass, Config), AuthModule = proplists:get_value(auth_module, Config), Api = riak_cs_config:api(), RespModule = riak_cs_config:response_module(Api), PolicyModule = proplists:get_value(policy_module, Config), Exports = orddict:from_list(Mod:module_info(exports)), ExportsFun = exports_fun(Exports), StatsPrefix = resource_call(Mod, stats_prefix, [], ExportsFun), Ctx = #context{auth_bypass=AuthBypass, auth_module=AuthModule, response_module=RespModule, policy_module=PolicyModule, exports_fun=ExportsFun, stats_prefix=StatsPrefix, start_time=os:timestamp(), submodule=Mod, api=Api}, resource_call(Mod, init, [Ctx], ExportsFun). -spec service_available(#wm_reqdata{}, #context{}) -> {boolean(), #wm_reqdata{}, #context{}}. service_available(RD, Ctx=#context{rc_pool=undefined}) -> service_available(RD, Ctx#context{rc_pool=request_pool}); service_available(RD, Ctx=#context{submodule=Mod, rc_pool=Pool}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"service_available">>), case riak_cs_riak_client:checkout(Pool) of {ok, RcPid} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"service_available">>, [1], []), {true, RD, Ctx#context{riak_client=RcPid}}; {error, _Reason} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"service_available">>, [0], []), {false, RD, Ctx} end. -spec malformed_request(#wm_reqdata{}, #context{}) -> {boolean(), #wm_reqdata{}, #context{}}. malformed_request(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun, stats_prefix=StatsPrefix}) -> is used in stats keys , updating inflow should be * after * _ = update_stats_inflow(RD, StatsPrefix), riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"malformed_request">>), {Malformed, _, _} = R = resource_call(Mod, malformed_request, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return_bool_with_default({?MODULE, Mod}, <<"malformed_request">>, Malformed, false), R. -spec valid_entity_length(#wm_reqdata{}, #context{}) -> {boolean(), #wm_reqdata{}, #context{}}. valid_entity_length(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"valid_entity_length">>), {Valid, _, _} = R = resource_call(Mod, valid_entity_length, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return_bool_with_default({?MODULE, Mod}, <<"valid_entity_length">>, Valid, true), R. -type validate_checksum_response() :: {error, term()} | {halt, pos_integer()} | boolean(). -spec validate_content_checksum(#wm_reqdata{}, #context{}) -> {validate_checksum_response(), #wm_reqdata{}, #context{}}. validate_content_checksum(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"validate_content_checksum">>), {Valid, _, _} = R = resource_call(Mod, validate_content_checksum, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return_bool_with_default({?MODULE, Mod}, <<"validate_content_checksum">>, Valid, true), R. -spec forbidden(#wm_reqdata{}, #context{}) -> {boolean() | {halt, non_neg_integer()}, #wm_reqdata{}, #context{}}. forbidden(RD, Ctx=#context{auth_module=AuthMod, submodule=Mod, riak_client=RcPid, exports_fun=ExportsFun}) -> {AuthResult, AnonOk} = case AuthMod:identify(RD, Ctx) of failed -> Identification failed , deny access {{error, no_such_key}, false}; {failed, Reason} -> {{error, Reason}, false}; {UserKey, AuthData} -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"forbidden">>, [], [riak_cs_wm_utils:extract_name(UserKey)]), UserLookupResult = maybe_create_user( riak_cs_user:get_user(UserKey, RcPid), UserKey, Ctx#context.api, Ctx#context.auth_module, AuthData, RcPid), {authenticate(UserLookupResult, RD, Ctx, AuthData), resource_call(Mod, anon_ok, [], ExportsFun)} end, post_authentication(AuthResult, RD, Ctx, AnonOk). maybe_create_user({ok, {_, _}}=UserResult, _, _, _, _, _) -> UserResult; maybe_create_user({error, NE}, KeyId, oos, _, {UserData, _}, RcPid) when NE =:= not_found; NE =:= notfound; NE =:= no_user_key -> {Name, Email, UserId} = UserData, {_, Secret} = riak_cs_oos_utils:user_ec2_creds(UserId, KeyId), Attempt to create a Riak CS user to represent the OS tenant _ = riak_cs_user:create_user(Name, Email, KeyId, Secret), riak_cs_user:get_user(KeyId, RcPid); maybe_create_user({error, NE}, KeyId, s3, riak_cs_keystone_auth, {UserData, _}, RcPid) when NE =:= not_found; NE =:= notfound; NE =:= no_user_key -> {Name, Email, UserId} = UserData, {_, Secret} = riak_cs_oos_utils:user_ec2_creds(UserId, KeyId), Attempt to create a Riak CS user to represent the OS tenant _ = riak_cs_user:create_user(Name, Email, KeyId, Secret), riak_cs_user:get_user(KeyId, RcPid); maybe_create_user({error, no_user_key}=Error, _, _, _, _, _) -> Anonymous access may be authorized by ACL or policy afterwards , Error; maybe_create_user({error, disconnected}=Error, _, _, _, _, RcPid) -> {ok, MasterPid} = riak_cs_riak_client:master_pbc(RcPid), riak_cs_pbc:check_connection_status(MasterPid, maybe_create_user), Error; maybe_create_user({error, Reason}=Error, _, Api, _, _, _) -> _ = lager:error("Retrieval of user record for ~p failed. Reason: ~p", [Api, Reason]), Error. -spec allowed_methods(#wm_reqdata{}, #context{}) -> {[atom()], #wm_reqdata{}, #context{}}. allowed_methods(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"allowed_methods">>), Methods = resource_call(Mod, allowed_methods, [], ExportsFun), {Methods, RD, Ctx}. -spec content_types_accepted(#wm_reqdata{}, #context{}) -> {[{string(), atom()}], #wm_reqdata{}, #context{}}. content_types_accepted(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"content_types_accepted">>), resource_call(Mod, content_types_accepted, [RD,Ctx], ExportsFun). -spec content_types_provided(#wm_reqdata{}, #context{}) -> {[{string(), atom()}], #wm_reqdata{}, #context{}}. content_types_provided(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"content_types_provided">>), resource_call(Mod, content_types_provided, [RD,Ctx], ExportsFun). -spec generate_etag(#wm_reqdata{}, #context{}) -> {string(), #wm_reqdata{}, #context{}}. generate_etag(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"generate_etag">>), resource_call(Mod, generate_etag, [RD,Ctx], ExportsFun). -spec last_modified(#wm_reqdata{}, #context{}) -> {calendar:datetime(), #wm_reqdata{}, #context{}}. last_modified(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"last_modified">>), resource_call(Mod, last_modified, [RD,Ctx], ExportsFun). -spec delete_resource(#wm_reqdata{}, #context{}) -> {boolean() | {halt, non_neg_integer()}, #wm_reqdata{}, #context{}}. delete_resource(RD, Ctx=#context{submodule=Mod,exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"delete_resource">>), resource_call(Mod, delete_resource, [RD,Ctx], ExportsFun). -spec to_xml(#wm_reqdata{}, #context{}) -> {binary() | {'halt', non_neg_integer()}, #wm_reqdata{}, #context{}}. to_xml(RD, Ctx=#context{user=User, submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"to_xml">>), Res = resource_call(Mod, to_xml, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"to_xml">>, [], [riak_cs_wm_utils:extract_name(User)]), Res. -spec to_json(#wm_reqdata{}, #context{}) -> {binary() | {'halt', non_neg_integer()}, #wm_reqdata{}, #context{}}. to_json(RD, Ctx=#context{user=User, submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"to_json">>), Res = resource_call(Mod, to_json, [RD, Ctx], ExportsFun(to_json)), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"to_json">>, [], [riak_cs_wm_utils:extract_name(User)]), Res. post_is_create(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> resource_call(Mod, post_is_create, [RD, Ctx], ExportsFun). create_path(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> resource_call(Mod, create_path, [RD, Ctx], ExportsFun). process_post(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> resource_call(Mod, process_post, [RD, Ctx], ExportsFun). resp_body(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> resource_call(Mod, resp_body, [RD, Ctx], ExportsFun). multiple_choices(RD, Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> try resource_call(Mod, multiple_choices, [RD, Ctx], ExportsFun) catch _:_ -> {false, RD, Ctx} end. add_acl_to_context_then_accept(RD, Ctx) -> case riak_cs_wm_utils:maybe_update_context_with_acl_from_headers(RD, Ctx) of {ok, ContextWithAcl} -> accept_body(RD, ContextWithAcl); {error, HaltResponse} -> HaltResponse end. -spec accept_body(#wm_reqdata{}, #context{}) -> {boolean() | {'halt', non_neg_integer()}, #wm_reqdata{}, #context{}}. accept_body(RD, Ctx=#context{submodule=Mod,exports_fun=ExportsFun,user=User}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"accept_body">>), Res = resource_call(Mod, accept_body, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"accept_body">>, [], [riak_cs_wm_utils:extract_name(User)]), Res. -spec produce_body(#wm_reqdata{}, #context{}) -> {iolist()|binary(), #wm_reqdata{}, #context{}} | {{known_length_stream, non_neg_integer(), {<<>>, function()}}, #wm_reqdata{}, #context{}}. produce_body(RD, Ctx=#context{user=User, submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"produce_body">>), Res = resource_call(Mod, produce_body, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"produce_body">>, [], [riak_cs_wm_utils:extract_name(User)]), Res. -spec finish_request(#wm_reqdata{}, #context{}) -> {boolean(), #wm_reqdata{}, #context{}}. finish_request(RD, Ctx=#context{riak_client=RcPid, auto_rc_close=AutoRcClose, submodule=Mod, exports_fun=ExportsFun}) when RcPid =:= undefined orelse AutoRcClose =:= false -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"finish_request">>, [0], []), Res = resource_call(Mod, finish_request, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"finish_request">>, [0], []), update_stats(RD, Ctx), Res; finish_request(RD, Ctx0=#context{riak_client=RcPid, rc_pool=Pool, submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"finish_request">>, [1], []), riak_cs_riak_client:checkin(Pool, RcPid), Ctx = Ctx0#context{riak_client=undefined}, Res = resource_call(Mod, finish_request, [RD, Ctx], ExportsFun), riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"finish_request">>, [1], []), update_stats(RD, Ctx), Res. -spec authorize(#wm_reqdata{}, #context{}) -> {boolean() | {halt, non_neg_integer()}, #wm_reqdata{}, #context{}}. authorize(RD,Ctx=#context{submodule=Mod, exports_fun=ExportsFun}) -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"authorize">>), {Success, _, _} = R = resource_call(Mod, authorize, [RD,Ctx], ExportsFun), case Success of {halt, Code} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authorize">>, [Code], []); riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authorize">>); riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authorize">>, [403], []) end, R. -type user_lookup_result() :: {ok, {rcs_user(), riakc_obj:riakc_obj()}} | {error, term()}. -spec authenticate(user_lookup_result(), term(), term(), term()) -> {ok, rcs_user(), riakc_obj:riakc_obj()} | {error, term()}. authenticate({ok, {User, UserObj}}, RD, Ctx=#context{auth_module=AuthMod, submodule=Mod}, AuthData) when User?RCS_USER.status =:= enabled -> riak_cs_dtrace:dt_wm_entry({?MODULE, Mod}, <<"authenticate">>, [], [atom_to_binary(AuthMod, latin1)]), case AuthMod:authenticate(User, AuthData, RD, Ctx) of ok -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authenticate">>, [2], [atom_to_binary(AuthMod, latin1)]), {ok, User, UserObj}; {error, reqtime_tooskewed} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authenticate">>, [1], [atom_to_binary(AuthMod, latin1)]), {error, reqtime_tooskewed}; {error, _Reason} -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"authenticate">>, [0], [atom_to_binary(AuthMod, latin1)]), {error, bad_auth} end; authenticate({ok, {User, _UserObj}}, _RD, _Ctx, _AuthData) when User?RCS_USER.status =/= enabled -> {error, bad_auth}; authenticate({error, _}=Error, _RD, _Ctx, _AuthData) -> Error. -spec exports_fun(orddict:orddict()) -> function(). exports_fun(Exports) -> fun(Function) -> orddict:is_key(Function, Exports) end. resource_call(Mod, Fun, Args, true) -> erlang:apply(Mod, Fun, Args); resource_call(_Mod, Fun, Args, false) -> erlang:apply(?MODULE, default(Fun), Args); resource_call(Mod, Fun, Args, ExportsFun) -> resource_call(Mod, Fun, Args, ExportsFun(Fun)). post_authentication(AuthResult, RD, Ctx = #context{submodule=Mod}, AnonOk) -> case post_authentication(AuthResult, RD, Ctx, fun authorize/2, AnonOk) of {false, _RD2, Ctx2} = FalseRet -> riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"forbidden">>, [], [riak_cs_wm_utils:extract_name(Ctx2#context.user), <<"false">>]), FalseRet; {Rsn, _RD2, Ctx2} = Ret -> Reason = case Rsn of {halt, Code} -> Code; _ -> -1 end, riak_cs_dtrace:dt_wm_return({?MODULE, Mod}, <<"forbidden">>, [Reason], [riak_cs_wm_utils:extract_name(Ctx2#context.user), <<"true">>]), Ret end. post_authentication({ok, User, UserObj}, RD, Ctx, Authorize, _) -> given keyid and signature matched , proceed Authorize(RD, Ctx#context{user=User, user_object=UserObj}); post_authentication({error, no_user_key}, RD, Ctx, Authorize, true) -> no keyid was given , proceed anonymously _ = lager:debug("No user key"), Authorize(RD, Ctx); post_authentication({error, no_user_key}, RD, Ctx, _, false) -> no keyid was given , deny access _ = lager:debug("No user key, deny"), riak_cs_wm_utils:deny_access(RD, Ctx); post_authentication({error, bad_auth}, RD, Ctx, _, _) -> given keyid was found , but signature did n't match _ = lager:debug("bad_auth"), riak_cs_wm_utils:deny_access(RD, Ctx); post_authentication({error, reqtime_tooskewed} = Error, RD, #context{response_module = ResponseMod} = Ctx, _, _) -> _ = lager:debug("reqtime_tooskewed"), ResponseMod:api_error(Error, RD, Ctx); post_authentication({error, {auth_not_supported, AuthType}}, RD, #context{response_module=ResponseMod} = Ctx, _, _) -> _ = lager:debug("auth_not_supported: ~s", [AuthType]), ResponseMod:api_error({auth_not_supported, AuthType}, RD, Ctx); post_authentication({error, notfound}, RD, Ctx, _, _) -> _ = lager:debug("key_id not present or not found"), riak_cs_wm_utils:deny_access(RD, Ctx); post_authentication({error, Reason}, RD, Ctx, _, _) -> no matching keyid was found , or lookup failed _ = lager:debug("Authentication error: ~p", [Reason]), riak_cs_wm_utils:deny_invalid_key(RD, Ctx). update_stats_inflow(_RD, undefined = _StatsPrefix) -> ok; update_stats_inflow(_RD, no_stats = _StatsPrefix) -> ok; update_stats_inflow(RD, StatsPrefix) -> Method = riak_cs_wm_utils:lower_case_method(wrq:method(RD)), Key = [StatsPrefix, Method], riak_cs_stats:inflow(Key). update_stats(_RD, #context{stats_key=no_stats}) -> ok; update_stats(_RD, #context{stats_prefix=no_stats}) -> ok; update_stats(RD, #context{start_time=StartTime, stats_prefix=StatsPrefix, stats_key=StatsKey}) -> catch update_stats(StartTime, wrq:response_code(RD), StatsPrefix, riak_cs_wm_utils:lower_case_method(wrq:method(RD)), StatsKey). update_stats(StartTime, Code, StatsPrefix, Method, StatsKey0) -> StatsKey = case StatsKey0 of prefix_and_method -> [StatsPrefix, Method]; _ -> StatsKey0 end, case Code of 405 -> mothod may lead to notfound warning in updating stats ok; Success when is_integer(Success) andalso Success < 400 -> riak_cs_stats:update_with_start(StatsKey, StartTime); _Error -> riak_cs_stats:update_error_with_start(StatsKey, StartTime) end. default(init) -> default_init; default(stats_prefix) -> default_stats_prefix; default(allowed_methods) -> default_allowed_methods; default(content_types_accepted) -> default_content_types_accepted; default(content_types_provided) -> default_content_types_provided; default(generate_etag) -> default_generate_etag; default(last_modified) -> default_last_modified; default(malformed_request) -> default_malformed_request; default(valid_entity_length) -> default_valid_entity_length; default(validate_content_checksum) -> default_validate_content_checksum; default(delete_resource) -> default_delete_resource; default(authorize) -> default_authorize; default(finish_request) -> default_finish_request; default(anon_ok) -> default_anon_ok; default(produce_body) -> default_produce_body; default(multiple_choices) -> default_multiple_choices; default(_) -> undefined. default_init(Ctx) -> {ok, Ctx}. default_stats_prefix() -> no_stats. default_malformed_request(RD, Ctx) -> {false, RD, Ctx}. default_valid_entity_length(RD, Ctx) -> {true, RD, Ctx}. default_validate_content_checksum(RD, Ctx) -> {true, RD, Ctx}. default_content_types_accepted(RD, Ctx) -> {[], RD, Ctx}. -spec default_content_types_provided(#wm_reqdata{}, #context{}) -> {[{string(), atom()}], #wm_reqdata{}, #context{}}. default_content_types_provided(RD, Ctx=#context{api=oos}) -> {[{"text/plain", produce_body}], RD, Ctx}; default_content_types_provided(RD, Ctx) -> {[{"application/xml", produce_body}], RD, Ctx}. default_generate_etag(RD, Ctx) -> {undefined, RD, Ctx}. default_last_modified(RD, Ctx) -> {undefined, RD, Ctx}. default_delete_resource(RD, Ctx) -> {false, RD, Ctx}. default_allowed_methods() -> []. default_finish_request(RD, Ctx) -> {true, RD, Ctx}. default_anon_ok() -> true. default_produce_body(RD, Ctx=#context{submodule=Mod, response_module=ResponseMod, exports_fun=ExportsFun}) -> try ResponseMod:respond( resource_call(Mod, api_request, [RD, Ctx], ExportsFun), RD, Ctx) catch error:{badmatch, {error, Reason}} -> ResponseMod:api_error(Reason, RD, Ctx) end. and simply returns false to signify the request is not fobidden -spec default_authorize(term(), term()) -> {false, term(), term()}. default_authorize(RD, Ctx) -> {false, RD, Ctx}. default_multiple_choices(RD, Ctx) -> {false, RD, Ctx}.
269da5a15de6163b53488efd871094dd0a82ef8bf7607065d3534cf0a5760650
metosin/reitit
server.clj
(ns example.server (:require [reitit.http :as http] [reitit.ring :as ring] [reitit.interceptor.sieppari] [sieppari.async.core-async] ;; needed for core.async [sieppari.async.manifold] ;; needed for manifold [ring.adapter.jetty :as jetty] [muuntaja.interceptor] [clojure.core.async :as a] [manifold.deferred :as d] [promesa.core :as p])) (defn interceptor [f x] {:enter (fn [ctx] (f (update-in ctx [:request :via] (fnil conj []) {:enter x}))) :leave (fn [ctx] (f (update-in ctx [:response :body] conj {:leave x})))}) (defn handler [f] (fn [{:keys [via]}] (f {:status 200, :body (conj via :handler)}))) (def <sync> identity) (def <future> #(future %)) (def <async> #(a/go %)) (def <deferred> d/success-deferred) (def <promesa> p/promise) (def app (http/ring-handler (http/router ["/api" {:interceptors [(interceptor <sync> :api)]} ["/sync" {:interceptors [(interceptor <sync> :sync)] :get {:interceptors [(interceptor <sync> :get)] :handler (handler <sync>)}}] ["/future" {:interceptors [(interceptor <future> :future)] :get {:interceptors [(interceptor <future> :get)] :handler (handler <future>)}}] ["/async" {:interceptors [(interceptor <async> :async)] :get {:interceptors [(interceptor <async> :get)] :handler (handler <async>)}}] ["/deferred" {:interceptors [(interceptor <deferred> :deferred)] :get {:interceptors [(interceptor <deferred> :get)] :handler (handler <deferred>)}}] ["/promesa" {:interceptors [(interceptor <promesa> :promesa)] :get {:interceptors [(interceptor <promesa> :get)] :handler (handler <promesa>)}}]]) (ring/create-default-handler) {:executor reitit.interceptor.sieppari/executor :interceptors [(muuntaja.interceptor/format-interceptor)]})) (defn start [] (jetty/run-jetty #'app {:port 3000, :join? false, :async? true}) (println "server running in port 3000")) (comment (start))
null
https://raw.githubusercontent.com/metosin/reitit/1ab075bd353966636f154ac36ae9b7990efeb008/examples/http/src/example/server.clj
clojure
needed for core.async needed for manifold
(ns example.server (:require [reitit.http :as http] [reitit.ring :as ring] [reitit.interceptor.sieppari] [ring.adapter.jetty :as jetty] [muuntaja.interceptor] [clojure.core.async :as a] [manifold.deferred :as d] [promesa.core :as p])) (defn interceptor [f x] {:enter (fn [ctx] (f (update-in ctx [:request :via] (fnil conj []) {:enter x}))) :leave (fn [ctx] (f (update-in ctx [:response :body] conj {:leave x})))}) (defn handler [f] (fn [{:keys [via]}] (f {:status 200, :body (conj via :handler)}))) (def <sync> identity) (def <future> #(future %)) (def <async> #(a/go %)) (def <deferred> d/success-deferred) (def <promesa> p/promise) (def app (http/ring-handler (http/router ["/api" {:interceptors [(interceptor <sync> :api)]} ["/sync" {:interceptors [(interceptor <sync> :sync)] :get {:interceptors [(interceptor <sync> :get)] :handler (handler <sync>)}}] ["/future" {:interceptors [(interceptor <future> :future)] :get {:interceptors [(interceptor <future> :get)] :handler (handler <future>)}}] ["/async" {:interceptors [(interceptor <async> :async)] :get {:interceptors [(interceptor <async> :get)] :handler (handler <async>)}}] ["/deferred" {:interceptors [(interceptor <deferred> :deferred)] :get {:interceptors [(interceptor <deferred> :get)] :handler (handler <deferred>)}}] ["/promesa" {:interceptors [(interceptor <promesa> :promesa)] :get {:interceptors [(interceptor <promesa> :get)] :handler (handler <promesa>)}}]]) (ring/create-default-handler) {:executor reitit.interceptor.sieppari/executor :interceptors [(muuntaja.interceptor/format-interceptor)]})) (defn start [] (jetty/run-jetty #'app {:port 3000, :join? false, :async? true}) (println "server running in port 3000")) (comment (start))
c555aae4dd215f226f8c26f2428cab43dacea3d6c94c114b6f628e623f4f9f84
metosin/komponentit
mixins.cljs
(ns komponentit.mixins (:require [reagent.core :as r] [clojure.set :as set] [clojure.string :as string])) (defn ->event-type [k] (-> k name (string/replace #"^on-" "") (string/replace #"-" ""))) (defn- update-listeners [el listeners props this] (swap! listeners (fn [listeners] (let [current-event-types (set (keys listeners)) new-event-types (set (keys props))] (as-> listeners $ (reduce (fn [listeners k] (let [f (fn [e] ;; Need to retrieve latest callback in case the props have been updated (let [f (get (r/props this) k)] (f e)))] (.addEventListener el (->event-type k) f) (assoc listeners k f))) $ (set/difference new-event-types current-event-types)) (reduce (fn [listeners k] (.removeEventListener el (->event-type k) (get listeners k)) (dissoc listeners k)) $ (set/difference current-event-types new-event-types))))))) (defn window-event-listener [_] (let [listeners (atom nil)] (r/create-class {:display-name "komponentit.mixins.window_event_listener_class" :component-did-mount (fn [this] (update-listeners js/window listeners (r/props this) this)) :component-did-update (fn [this] (update-listeners js/window listeners (r/props this) this)) :component-will-unmount (fn [this] (update-listeners js/window listeners {} this)) :reagent-render (fn [props child] child)})))
null
https://raw.githubusercontent.com/metosin/komponentit/d962ce1d69ccc3800db0d6b4fc18fc2fd30b494a/src/cljs/komponentit/mixins.cljs
clojure
Need to retrieve latest callback in case the props have been updated
(ns komponentit.mixins (:require [reagent.core :as r] [clojure.set :as set] [clojure.string :as string])) (defn ->event-type [k] (-> k name (string/replace #"^on-" "") (string/replace #"-" ""))) (defn- update-listeners [el listeners props this] (swap! listeners (fn [listeners] (let [current-event-types (set (keys listeners)) new-event-types (set (keys props))] (as-> listeners $ (reduce (fn [listeners k] (let [f (fn [e] (let [f (get (r/props this) k)] (f e)))] (.addEventListener el (->event-type k) f) (assoc listeners k f))) $ (set/difference new-event-types current-event-types)) (reduce (fn [listeners k] (.removeEventListener el (->event-type k) (get listeners k)) (dissoc listeners k)) $ (set/difference current-event-types new-event-types))))))) (defn window-event-listener [_] (let [listeners (atom nil)] (r/create-class {:display-name "komponentit.mixins.window_event_listener_class" :component-did-mount (fn [this] (update-listeners js/window listeners (r/props this) this)) :component-did-update (fn [this] (update-listeners js/window listeners (r/props this) this)) :component-will-unmount (fn [this] (update-listeners js/window listeners {} this)) :reagent-render (fn [props child] child)})))
3ce9f2672c7376e35d4e5d2fee0df030b07f05ccc521a37322ff6570a6c28688
brendanhay/terrafomo
Resources.hs
-- This module is auto-generated. # LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - unused - imports # -- | -- Module : Terrafomo.SoftLayer.Resources Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- module Terrafomo.SoftLayer.Resources ( -- * softlayer_ssh_key newSshKeyR , SshKeyR (..) , SshKeyR_Required (..) -- * softlayer_virtual_guest , newVirtualGuestR , VirtualGuestR (..) , VirtualGuestR_Required (..) ) where import Data.Functor ((<$>)) import Data.Semigroup ((<>)) import GHC.Base (Proxy#, proxy#, ($)) import qualified Data.Functor.Const as P import qualified Data.List.NonEmpty as P import qualified Data.Map.Strict as P import qualified Data.Maybe as P import qualified Data.Text.Lazy as P import qualified Prelude as P import qualified Terrafomo.Encode as Encode import qualified Terrafomo.HCL as TF import qualified Terrafomo.HIL as TF import qualified Terrafomo.Lens as Lens import qualified Terrafomo.Schema as TF import qualified Terrafomo.SoftLayer.Provider as P import qualified Terrafomo.SoftLayer.Types as P | The main @softlayer_ssh_key@ resource definition . data SshKeyR s = SshKeyR_Internal { name :: TF.Expr s P.Text -- ^ @name@ -- - (Required) , notes :: P.Maybe (TF.Expr s P.Text) -- ^ @notes@ -- - (Optional) , public_key :: TF.Expr s P.Text ^ @public_key@ -- - (Required, Forces New) } deriving (P.Show) | Construct a new @softlayer_ssh_key@ resource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal via : @ SoftLayer.newSshKeyR ( SoftLayer . SshKeyR { SoftLayer.public_key = public_key -- s Text , SoftLayer.name = name -- s Text } ) @ = = = Argument Reference The following arguments are supported : @ # name : : Lens ' ( Resource SshKeyR s ) ( Expr s Text ) # notes : : Lens ' ( Resource SshKeyR s ) ( Maybe ( s Text ) ) # public_key : : ' ( Resource SshKeyR s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # fingerprint : : Getting r ( Ref SshKeyR s ) ( Expr s Text ) # i d : : Getting r ( Ref SshKeyR s ) ( s Int ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # prevent_destroy : : Lens ' ( Resource SshKeyR s ) Bool # create_before_destroy : : ' ( Resource SshKeyR s ) Bool # ignore_changes : : ' ( Resource SshKeyR s ) ( Changes s ) # depends_on : : ' ( Resource SshKeyR s ) ( Set ( Depends s ) ) # provider : : ' ( Resource SshKeyR s ) ( Maybe SoftLayer ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @softlayer_ssh_key@ via: @ SoftLayer.newSshKeyR (SoftLayer.SshKeyR { SoftLayer.public_key = public_key -- Expr s Text , SoftLayer.name = name -- Expr s Text }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (Resource SshKeyR s) (Expr s Text) #notes :: Lens' (Resource SshKeyR s) (Maybe (Expr s Text)) #public_key :: Lens' (Resource SshKeyR s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #fingerprint :: Getting r (Ref SshKeyR s) (Expr s Text) #id :: Getting r (Ref SshKeyR s) (Expr s Int) @ === Configuring Meta-parameters The following additional configuration is supported: @ #prevent_destroy :: Lens' (Resource SshKeyR s) Bool #create_before_destroy :: Lens' (Resource SshKeyR s) Bool #ignore_changes :: Lens' (Resource SshKeyR s) (Changes s) #depends_on :: Lens' (Resource SshKeyR s) (Set (Depends s)) #provider :: Lens' (Resource SshKeyR s) (Maybe SoftLayer) @ -} newSshKeyR :: SshKeyR_Required s -- ^ The minimal/required arguments. -> P.Resource SshKeyR s newSshKeyR x = TF.unsafeResource "softlayer_ssh_key" Encode.metadata (\SshKeyR_Internal{..} -> P.mempty <> TF.pair "name" name <> P.maybe P.mempty (TF.pair "notes") notes <> TF.pair "public_key" public_key ) (let SshKeyR{..} = x in SshKeyR_Internal { name = name , notes = P.Nothing , public_key = public_key }) -- | The required arguments for 'newSshKeyR'. data SshKeyR_Required s = SshKeyR { public_key :: TF.Expr s P.Text ^ ( Required , Forces New ) , name :: TF.Expr s P.Text -- ^ (Required) } deriving (P.Show) instance Lens.HasField "name" f (P.Resource SshKeyR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: SshKeyR s -> TF.Expr s P.Text) (\s a -> s { name = a } :: SshKeyR s) instance Lens.HasField "notes" f (P.Resource SshKeyR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (notes :: SshKeyR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { notes = a } :: SshKeyR s) instance Lens.HasField "public_key" f (P.Resource SshKeyR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (public_key :: SshKeyR s -> TF.Expr s P.Text) (\s a -> s { public_key = a } :: SshKeyR s) instance Lens.HasField "fingerprint" (P.Const r) (TF.Ref SshKeyR s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "fingerprint")) instance Lens.HasField "id" (P.Const r) (TF.Ref SshKeyR s) (TF.Expr s P.Int) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) -- | The main @softlayer_virtual_guest@ resource definition. data VirtualGuestR s = VirtualGuestR_Internal { backend_vlan_id :: P.Maybe (TF.Expr s TF.Id) ^ -- - (Optional, Forces New) , block_device_template_group_gid :: P.Maybe (TF.Expr s P.Text) -- ^ @block_device_template_group_gid@ -- - (Optional, Forces New) , cpu :: TF.Expr s P.Int ^ @cpu@ -- - (Required, Forces New) , dedicated_acct_host_only :: P.Maybe (TF.Expr s P.Bool) -- ^ @dedicated_acct_host_only@ -- - (Optional, Forces New) , disks :: P.Maybe (TF.Expr s [TF.Expr s P.Int]) -- ^ @disks@ -- - (Optional) , domain :: TF.Expr s P.Text -- ^ @domain@ -- - (Required) , frontend_vlan_id :: P.Maybe (TF.Expr s TF.Id) -- ^ @frontend_vlan_id@ -- - (Optional, Forces New) , hourly_billing :: TF.Expr s P.Bool -- ^ @hourly_billing@ -- - (Required, Forces New) , image :: P.Maybe (TF.Expr s P.Text) -- ^ @image@ -- - (Optional, Forces New) , local_disk :: TF.Expr s P.Bool ^ @local_disk@ -- - (Required, Forces New) , name :: TF.Expr s P.Text -- ^ @name@ -- - (Required) , post_install_script_uri :: P.Maybe (TF.Expr s P.Text) ^ -- - (Optional, Forces New) , private_network_only :: TF.Expr s P.Bool -- ^ @private_network_only@ -- - (Default __@false@__, Forces New) , public_network_speed :: TF.Expr s P.Int ^ - ( Default _ _ _ _ ) , ram :: TF.Expr s P.Int ^ @ram@ -- - (Required) , region :: TF.Expr s P.Text -- ^ @region@ -- - (Required, Forces New) , ssh_keys :: P.Maybe (TF.Expr s [TF.Expr s P.Int]) -- ^ @ssh_keys@ -- - (Optional) , user_data :: P.Maybe (TF.Expr s P.Text) -- ^ @user_data@ -- - (Optional) } deriving (P.Show) | Construct a new @softlayer_virtual_guest@ resource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @softlayer_virtual_guest@ via : @ ( SoftLayer . VirtualGuestR { SoftLayer.hourly_billing = hourly_billing -- Expr s Bool , SoftLayer.cpu = cpu -- Expr s Int , SoftLayer.local_disk = local_disk -- Expr s Bool , SoftLayer.domain = domain -- Expr s Text , SoftLayer.name = name -- s Text , SoftLayer.ram = ram -- Expr s Int , SoftLayer.region = region -- s Text } ) @ = = = Argument Reference The following arguments are supported : @ # backend_vlan_id : : Lens ' ( Resource VirtualGuestR s ) ( Maybe ( s I d ) ) # block_device_template_group_gid : : ' ( Resource VirtualGuestR s ) ( Maybe ( s Text ) ) # cpu : : ' ( Resource VirtualGuestR s ) ( s Int ) # dedicated_acct_host_only : : ' ( Resource VirtualGuestR s ) ( Maybe ( s Bool ) ) # disks : : Lens ' ( Resource VirtualGuestR s ) ( Maybe ( s [ Expr s Int ] ) ) # domain : : Lens ' ( Resource VirtualGuestR s ) ( Expr s Text ) # frontend_vlan_id : : ' ( Resource VirtualGuestR s ) ( Maybe ( s I d ) ) : : ' ( Resource VirtualGuestR s ) ( s Bool ) # image : : Lens ' ( Resource VirtualGuestR s ) ( Maybe ( s Text ) ) # local_disk : : ' ( Resource VirtualGuestR s ) ( s Bool ) # name : : Lens ' ( Resource VirtualGuestR s ) ( Expr s Text ) # post_install_script_uri : : ' ( Resource VirtualGuestR s ) ( Maybe ( s Text ) ) # private_network_only : : ' ( Resource VirtualGuestR s ) ( s Bool ) # public_network_speed : : ' ( Resource VirtualGuestR s ) ( s Int ) # ram : : ' ( Resource VirtualGuestR s ) ( s Int ) # region : : Lens ' ( Resource VirtualGuestR s ) ( Expr s Text ) # ssh_keys : : ' ( Resource VirtualGuestR s ) ( Maybe ( s [ Expr s Int ] ) ) # user_data : : ' ( Resource VirtualGuestR s ) ( Maybe ( s Text ) ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref VirtualGuestR s ) ( s I d ) # ipv4_address : : Getting r ( Ref VirtualGuestR s ) ( Expr s Text ) # ipv4_address_private : : Getting r ( Ref VirtualGuestR s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # prevent_destroy : : Lens ' ( Resource VirtualGuestR s ) Bool # create_before_destroy : : ' ( Resource VirtualGuestR s ) Bool # ignore_changes : : ' ( Resource VirtualGuestR s ) ( Changes s ) # depends_on : : ' ( Resource VirtualGuestR s ) ( Set ( Depends s ) ) # provider : : ' ( Resource VirtualGuestR s ) ( Maybe SoftLayer ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @softlayer_virtual_guest@ via: @ SoftLayer.newVirtualGuestR (SoftLayer.VirtualGuestR { SoftLayer.hourly_billing = hourly_billing -- Expr s Bool , SoftLayer.cpu = cpu -- Expr s Int , SoftLayer.local_disk = local_disk -- Expr s Bool , SoftLayer.domain = domain -- Expr s Text , SoftLayer.name = name -- Expr s Text , SoftLayer.ram = ram -- Expr s Int , SoftLayer.region = region -- Expr s Text }) @ === Argument Reference The following arguments are supported: @ #backend_vlan_id :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Id)) #block_device_template_group_gid :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Text)) #cpu :: Lens' (Resource VirtualGuestR s) (Expr s Int) #dedicated_acct_host_only :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Bool)) #disks :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s [Expr s Int])) #domain :: Lens' (Resource VirtualGuestR s) (Expr s Text) #frontend_vlan_id :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Id)) #hourly_billing :: Lens' (Resource VirtualGuestR s) (Expr s Bool) #image :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Text)) #local_disk :: Lens' (Resource VirtualGuestR s) (Expr s Bool) #name :: Lens' (Resource VirtualGuestR s) (Expr s Text) #post_install_script_uri :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Text)) #private_network_only :: Lens' (Resource VirtualGuestR s) (Expr s Bool) #public_network_speed :: Lens' (Resource VirtualGuestR s) (Expr s Int) #ram :: Lens' (Resource VirtualGuestR s) (Expr s Int) #region :: Lens' (Resource VirtualGuestR s) (Expr s Text) #ssh_keys :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s [Expr s Int])) #user_data :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Text)) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref VirtualGuestR s) (Expr s Id) #ipv4_address :: Getting r (Ref VirtualGuestR s) (Expr s Text) #ipv4_address_private :: Getting r (Ref VirtualGuestR s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #prevent_destroy :: Lens' (Resource VirtualGuestR s) Bool #create_before_destroy :: Lens' (Resource VirtualGuestR s) Bool #ignore_changes :: Lens' (Resource VirtualGuestR s) (Changes s) #depends_on :: Lens' (Resource VirtualGuestR s) (Set (Depends s)) #provider :: Lens' (Resource VirtualGuestR s) (Maybe SoftLayer) @ -} newVirtualGuestR :: VirtualGuestR_Required s -- ^ The minimal/required arguments. -> P.Resource VirtualGuestR s newVirtualGuestR x = TF.unsafeResource "softlayer_virtual_guest" Encode.metadata (\VirtualGuestR_Internal{..} -> P.mempty <> P.maybe P.mempty (TF.pair "backend_vlan_id") backend_vlan_id <> P.maybe P.mempty (TF.pair "block_device_template_group_gid") block_device_template_group_gid <> TF.pair "cpu" cpu <> P.maybe P.mempty (TF.pair "dedicated_acct_host_only") dedicated_acct_host_only <> P.maybe P.mempty (TF.pair "disks") disks <> TF.pair "domain" domain <> P.maybe P.mempty (TF.pair "frontend_vlan_id") frontend_vlan_id <> TF.pair "hourly_billing" hourly_billing <> P.maybe P.mempty (TF.pair "image") image <> TF.pair "local_disk" local_disk <> TF.pair "name" name <> P.maybe P.mempty (TF.pair "post_install_script_uri") post_install_script_uri <> TF.pair "private_network_only" private_network_only <> TF.pair "public_network_speed" public_network_speed <> TF.pair "ram" ram <> TF.pair "region" region <> P.maybe P.mempty (TF.pair "ssh_keys") ssh_keys <> P.maybe P.mempty (TF.pair "user_data") user_data ) (let VirtualGuestR{..} = x in VirtualGuestR_Internal { backend_vlan_id = P.Nothing , block_device_template_group_gid = P.Nothing , cpu = cpu , dedicated_acct_host_only = P.Nothing , disks = P.Nothing , domain = domain , frontend_vlan_id = P.Nothing , hourly_billing = hourly_billing , image = P.Nothing , local_disk = local_disk , name = name , post_install_script_uri = P.Nothing , private_network_only = TF.expr P.False , public_network_speed = TF.expr 1000 , ram = ram , region = region , ssh_keys = P.Nothing , user_data = P.Nothing }) -- | The required arguments for 'newVirtualGuestR'. data VirtualGuestR_Required s = VirtualGuestR { hourly_billing :: TF.Expr s P.Bool ^ ( Required , Forces New ) , cpu :: TF.Expr s P.Int ^ ( Required , Forces New ) , local_disk :: TF.Expr s P.Bool ^ ( Required , Forces New ) , domain :: TF.Expr s P.Text -- ^ (Required) , name :: TF.Expr s P.Text -- ^ (Required) , ram :: TF.Expr s P.Int -- ^ (Required) , region :: TF.Expr s P.Text ^ ( Required , Forces New ) } deriving (P.Show) instance Lens.HasField "backend_vlan_id" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s TF.Id)) where field = Lens.resourceLens P.. Lens.lens' (backend_vlan_id :: VirtualGuestR s -> P.Maybe (TF.Expr s TF.Id)) (\s a -> s { backend_vlan_id = a } :: VirtualGuestR s) instance Lens.HasField "block_device_template_group_gid" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (block_device_template_group_gid :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { block_device_template_group_gid = a } :: VirtualGuestR s) instance Lens.HasField "cpu" f (P.Resource VirtualGuestR s) (TF.Expr s P.Int) where field = Lens.resourceLens P.. Lens.lens' (cpu :: VirtualGuestR s -> TF.Expr s P.Int) (\s a -> s { cpu = a } :: VirtualGuestR s) instance Lens.HasField "dedicated_acct_host_only" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Bool)) where field = Lens.resourceLens P.. Lens.lens' (dedicated_acct_host_only :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Bool)) (\s a -> s { dedicated_acct_host_only = a } :: VirtualGuestR s) instance Lens.HasField "disks" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s [TF.Expr s P.Int])) where field = Lens.resourceLens P.. Lens.lens' (disks :: VirtualGuestR s -> P.Maybe (TF.Expr s [TF.Expr s P.Int])) (\s a -> s { disks = a } :: VirtualGuestR s) instance Lens.HasField "domain" f (P.Resource VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (domain :: VirtualGuestR s -> TF.Expr s P.Text) (\s a -> s { domain = a } :: VirtualGuestR s) instance Lens.HasField "frontend_vlan_id" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s TF.Id)) where field = Lens.resourceLens P.. Lens.lens' (frontend_vlan_id :: VirtualGuestR s -> P.Maybe (TF.Expr s TF.Id)) (\s a -> s { frontend_vlan_id = a } :: VirtualGuestR s) instance Lens.HasField "hourly_billing" f (P.Resource VirtualGuestR s) (TF.Expr s P.Bool) where field = Lens.resourceLens P.. Lens.lens' (hourly_billing :: VirtualGuestR s -> TF.Expr s P.Bool) (\s a -> s { hourly_billing = a } :: VirtualGuestR s) instance Lens.HasField "image" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (image :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { image = a } :: VirtualGuestR s) instance Lens.HasField "local_disk" f (P.Resource VirtualGuestR s) (TF.Expr s P.Bool) where field = Lens.resourceLens P.. Lens.lens' (local_disk :: VirtualGuestR s -> TF.Expr s P.Bool) (\s a -> s { local_disk = a } :: VirtualGuestR s) instance Lens.HasField "name" f (P.Resource VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: VirtualGuestR s -> TF.Expr s P.Text) (\s a -> s { name = a } :: VirtualGuestR s) instance Lens.HasField "post_install_script_uri" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (post_install_script_uri :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { post_install_script_uri = a } :: VirtualGuestR s) instance Lens.HasField "private_network_only" f (P.Resource VirtualGuestR s) (TF.Expr s P.Bool) where field = Lens.resourceLens P.. Lens.lens' (private_network_only :: VirtualGuestR s -> TF.Expr s P.Bool) (\s a -> s { private_network_only = a } :: VirtualGuestR s) instance Lens.HasField "public_network_speed" f (P.Resource VirtualGuestR s) (TF.Expr s P.Int) where field = Lens.resourceLens P.. Lens.lens' (public_network_speed :: VirtualGuestR s -> TF.Expr s P.Int) (\s a -> s { public_network_speed = a } :: VirtualGuestR s) instance Lens.HasField "ram" f (P.Resource VirtualGuestR s) (TF.Expr s P.Int) where field = Lens.resourceLens P.. Lens.lens' (ram :: VirtualGuestR s -> TF.Expr s P.Int) (\s a -> s { ram = a } :: VirtualGuestR s) instance Lens.HasField "region" f (P.Resource VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (region :: VirtualGuestR s -> TF.Expr s P.Text) (\s a -> s { region = a } :: VirtualGuestR s) instance Lens.HasField "ssh_keys" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s [TF.Expr s P.Int])) where field = Lens.resourceLens P.. Lens.lens' (ssh_keys :: VirtualGuestR s -> P.Maybe (TF.Expr s [TF.Expr s P.Int])) (\s a -> s { ssh_keys = a } :: VirtualGuestR s) instance Lens.HasField "user_data" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (user_data :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { user_data = a } :: VirtualGuestR s) instance Lens.HasField "id" (P.Const r) (TF.Ref VirtualGuestR s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "ipv4_address" (P.Const r) (TF.Ref VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "ipv4_address")) instance Lens.HasField "ipv4_address_private" (P.Const r) (TF.Ref VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "ipv4_address_private"))
null
https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-softlayer/gen/Terrafomo/SoftLayer/Resources.hs
haskell
This module is auto-generated. | Module : Terrafomo.SoftLayer.Resources Stability : auto-generated * softlayer_ssh_key * softlayer_virtual_guest ^ @name@ - (Required) ^ @notes@ - (Optional) - (Required, Forces New) s Text s Text Expr s Text Expr s Text ^ The minimal/required arguments. | The required arguments for 'newSshKeyR'. ^ (Required) | The main @softlayer_virtual_guest@ resource definition. - (Optional, Forces New) ^ @block_device_template_group_gid@ - (Optional, Forces New) - (Required, Forces New) ^ @dedicated_acct_host_only@ - (Optional, Forces New) ^ @disks@ - (Optional) ^ @domain@ - (Required) ^ @frontend_vlan_id@ - (Optional, Forces New) ^ @hourly_billing@ - (Required, Forces New) ^ @image@ - (Optional, Forces New) - (Required, Forces New) ^ @name@ - (Required) - (Optional, Forces New) ^ @private_network_only@ - (Default __@false@__, Forces New) - (Required) ^ @region@ - (Required, Forces New) ^ @ssh_keys@ - (Optional) ^ @user_data@ - (Optional) Expr s Bool Expr s Int Expr s Bool Expr s Text s Text Expr s Int s Text Expr s Bool Expr s Int Expr s Bool Expr s Text Expr s Text Expr s Int Expr s Text ^ The minimal/required arguments. | The required arguments for 'newVirtualGuestR'. ^ (Required) ^ (Required) ^ (Required)
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - unused - imports # Copyright : ( c ) 2017 - 2018 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Terrafomo.SoftLayer.Resources ( newSshKeyR , SshKeyR (..) , SshKeyR_Required (..) , newVirtualGuestR , VirtualGuestR (..) , VirtualGuestR_Required (..) ) where import Data.Functor ((<$>)) import Data.Semigroup ((<>)) import GHC.Base (Proxy#, proxy#, ($)) import qualified Data.Functor.Const as P import qualified Data.List.NonEmpty as P import qualified Data.Map.Strict as P import qualified Data.Maybe as P import qualified Data.Text.Lazy as P import qualified Prelude as P import qualified Terrafomo.Encode as Encode import qualified Terrafomo.HCL as TF import qualified Terrafomo.HIL as TF import qualified Terrafomo.Lens as Lens import qualified Terrafomo.Schema as TF import qualified Terrafomo.SoftLayer.Provider as P import qualified Terrafomo.SoftLayer.Types as P | The main @softlayer_ssh_key@ resource definition . data SshKeyR s = SshKeyR_Internal { name :: TF.Expr s P.Text , notes :: P.Maybe (TF.Expr s P.Text) , public_key :: TF.Expr s P.Text ^ @public_key@ } deriving (P.Show) | Construct a new @softlayer_ssh_key@ resource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal via : @ SoftLayer.newSshKeyR ( SoftLayer . SshKeyR } ) @ = = = Argument Reference The following arguments are supported : @ # name : : Lens ' ( Resource SshKeyR s ) ( Expr s Text ) # notes : : Lens ' ( Resource SshKeyR s ) ( Maybe ( s Text ) ) # public_key : : ' ( Resource SshKeyR s ) ( Expr s Text ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # fingerprint : : Getting r ( Ref SshKeyR s ) ( Expr s Text ) # i d : : Getting r ( Ref SshKeyR s ) ( s Int ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # prevent_destroy : : Lens ' ( Resource SshKeyR s ) Bool # create_before_destroy : : ' ( Resource SshKeyR s ) Bool # ignore_changes : : ' ( Resource SshKeyR s ) ( Changes s ) # depends_on : : ' ( Resource SshKeyR s ) ( Set ( Depends s ) ) # provider : : ' ( Resource SshKeyR s ) ( Maybe SoftLayer ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @softlayer_ssh_key@ via: @ SoftLayer.newSshKeyR (SoftLayer.SshKeyR }) @ === Argument Reference The following arguments are supported: @ #name :: Lens' (Resource SshKeyR s) (Expr s Text) #notes :: Lens' (Resource SshKeyR s) (Maybe (Expr s Text)) #public_key :: Lens' (Resource SshKeyR s) (Expr s Text) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #fingerprint :: Getting r (Ref SshKeyR s) (Expr s Text) #id :: Getting r (Ref SshKeyR s) (Expr s Int) @ === Configuring Meta-parameters The following additional configuration is supported: @ #prevent_destroy :: Lens' (Resource SshKeyR s) Bool #create_before_destroy :: Lens' (Resource SshKeyR s) Bool #ignore_changes :: Lens' (Resource SshKeyR s) (Changes s) #depends_on :: Lens' (Resource SshKeyR s) (Set (Depends s)) #provider :: Lens' (Resource SshKeyR s) (Maybe SoftLayer) @ -} newSshKeyR -> P.Resource SshKeyR s newSshKeyR x = TF.unsafeResource "softlayer_ssh_key" Encode.metadata (\SshKeyR_Internal{..} -> P.mempty <> TF.pair "name" name <> P.maybe P.mempty (TF.pair "notes") notes <> TF.pair "public_key" public_key ) (let SshKeyR{..} = x in SshKeyR_Internal { name = name , notes = P.Nothing , public_key = public_key }) data SshKeyR_Required s = SshKeyR { public_key :: TF.Expr s P.Text ^ ( Required , Forces New ) , name :: TF.Expr s P.Text } deriving (P.Show) instance Lens.HasField "name" f (P.Resource SshKeyR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: SshKeyR s -> TF.Expr s P.Text) (\s a -> s { name = a } :: SshKeyR s) instance Lens.HasField "notes" f (P.Resource SshKeyR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (notes :: SshKeyR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { notes = a } :: SshKeyR s) instance Lens.HasField "public_key" f (P.Resource SshKeyR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (public_key :: SshKeyR s -> TF.Expr s P.Text) (\s a -> s { public_key = a } :: SshKeyR s) instance Lens.HasField "fingerprint" (P.Const r) (TF.Ref SshKeyR s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "fingerprint")) instance Lens.HasField "id" (P.Const r) (TF.Ref SshKeyR s) (TF.Expr s P.Int) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) data VirtualGuestR s = VirtualGuestR_Internal { backend_vlan_id :: P.Maybe (TF.Expr s TF.Id) ^ , block_device_template_group_gid :: P.Maybe (TF.Expr s P.Text) , cpu :: TF.Expr s P.Int ^ @cpu@ , dedicated_acct_host_only :: P.Maybe (TF.Expr s P.Bool) , disks :: P.Maybe (TF.Expr s [TF.Expr s P.Int]) , domain :: TF.Expr s P.Text , frontend_vlan_id :: P.Maybe (TF.Expr s TF.Id) , hourly_billing :: TF.Expr s P.Bool , image :: P.Maybe (TF.Expr s P.Text) , local_disk :: TF.Expr s P.Bool ^ @local_disk@ , name :: TF.Expr s P.Text , post_install_script_uri :: P.Maybe (TF.Expr s P.Text) ^ , private_network_only :: TF.Expr s P.Bool , public_network_speed :: TF.Expr s P.Int ^ - ( Default _ _ _ _ ) , ram :: TF.Expr s P.Int ^ @ram@ , region :: TF.Expr s P.Text , ssh_keys :: P.Maybe (TF.Expr s [TF.Expr s P.Int]) , user_data :: P.Maybe (TF.Expr s P.Text) } deriving (P.Show) | Construct a new @softlayer_virtual_guest@ resource . The available argument lenses and computed attribute getters are documented below . See the < terraform documentation > for more information . = = = Example Usage You can define a minimal @softlayer_virtual_guest@ via : @ ( SoftLayer . VirtualGuestR } ) @ = = = Argument Reference The following arguments are supported : @ # backend_vlan_id : : Lens ' ( Resource VirtualGuestR s ) ( Maybe ( s I d ) ) # block_device_template_group_gid : : ' ( Resource VirtualGuestR s ) ( Maybe ( s Text ) ) # cpu : : ' ( Resource VirtualGuestR s ) ( s Int ) # dedicated_acct_host_only : : ' ( Resource VirtualGuestR s ) ( Maybe ( s Bool ) ) # disks : : Lens ' ( Resource VirtualGuestR s ) ( Maybe ( s [ Expr s Int ] ) ) # domain : : Lens ' ( Resource VirtualGuestR s ) ( Expr s Text ) # frontend_vlan_id : : ' ( Resource VirtualGuestR s ) ( Maybe ( s I d ) ) : : ' ( Resource VirtualGuestR s ) ( s Bool ) # image : : Lens ' ( Resource VirtualGuestR s ) ( Maybe ( s Text ) ) # local_disk : : ' ( Resource VirtualGuestR s ) ( s Bool ) # name : : Lens ' ( Resource VirtualGuestR s ) ( Expr s Text ) # post_install_script_uri : : ' ( Resource VirtualGuestR s ) ( Maybe ( s Text ) ) # private_network_only : : ' ( Resource VirtualGuestR s ) ( s Bool ) # public_network_speed : : ' ( Resource VirtualGuestR s ) ( s Int ) # ram : : ' ( Resource VirtualGuestR s ) ( s Int ) # region : : Lens ' ( Resource VirtualGuestR s ) ( Expr s Text ) # ssh_keys : : ' ( Resource VirtualGuestR s ) ( Maybe ( s [ Expr s Int ] ) ) # user_data : : ' ( Resource VirtualGuestR s ) ( Maybe ( s Text ) ) @ = = = Attributes Reference In addition to the arguments above , the following computed attributes are available : @ # i d : : Getting r ( Ref VirtualGuestR s ) ( s I d ) # ipv4_address : : Getting r ( Ref VirtualGuestR s ) ( Expr s Text ) # ipv4_address_private : : Getting r ( Ref VirtualGuestR s ) ( Expr s Text ) @ = = = Configuring Meta - parameters The following additional configuration is supported : @ # prevent_destroy : : Lens ' ( Resource VirtualGuestR s ) Bool # create_before_destroy : : ' ( Resource VirtualGuestR s ) Bool # ignore_changes : : ' ( Resource VirtualGuestR s ) ( Changes s ) # depends_on : : ' ( Resource VirtualGuestR s ) ( Set ( Depends s ) ) # provider : : ' ( Resource VirtualGuestR s ) ( Maybe SoftLayer ) @ available argument lenses and computed attribute getters are documented below. See the < terraform documentation> for more information. === Example Usage You can define a minimal @softlayer_virtual_guest@ via: @ SoftLayer.newVirtualGuestR (SoftLayer.VirtualGuestR }) @ === Argument Reference The following arguments are supported: @ #backend_vlan_id :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Id)) #block_device_template_group_gid :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Text)) #cpu :: Lens' (Resource VirtualGuestR s) (Expr s Int) #dedicated_acct_host_only :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Bool)) #disks :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s [Expr s Int])) #domain :: Lens' (Resource VirtualGuestR s) (Expr s Text) #frontend_vlan_id :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Id)) #hourly_billing :: Lens' (Resource VirtualGuestR s) (Expr s Bool) #image :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Text)) #local_disk :: Lens' (Resource VirtualGuestR s) (Expr s Bool) #name :: Lens' (Resource VirtualGuestR s) (Expr s Text) #post_install_script_uri :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Text)) #private_network_only :: Lens' (Resource VirtualGuestR s) (Expr s Bool) #public_network_speed :: Lens' (Resource VirtualGuestR s) (Expr s Int) #ram :: Lens' (Resource VirtualGuestR s) (Expr s Int) #region :: Lens' (Resource VirtualGuestR s) (Expr s Text) #ssh_keys :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s [Expr s Int])) #user_data :: Lens' (Resource VirtualGuestR s) (Maybe (Expr s Text)) @ === Attributes Reference In addition to the arguments above, the following computed attributes are available: @ #id :: Getting r (Ref VirtualGuestR s) (Expr s Id) #ipv4_address :: Getting r (Ref VirtualGuestR s) (Expr s Text) #ipv4_address_private :: Getting r (Ref VirtualGuestR s) (Expr s Text) @ === Configuring Meta-parameters The following additional configuration is supported: @ #prevent_destroy :: Lens' (Resource VirtualGuestR s) Bool #create_before_destroy :: Lens' (Resource VirtualGuestR s) Bool #ignore_changes :: Lens' (Resource VirtualGuestR s) (Changes s) #depends_on :: Lens' (Resource VirtualGuestR s) (Set (Depends s)) #provider :: Lens' (Resource VirtualGuestR s) (Maybe SoftLayer) @ -} newVirtualGuestR -> P.Resource VirtualGuestR s newVirtualGuestR x = TF.unsafeResource "softlayer_virtual_guest" Encode.metadata (\VirtualGuestR_Internal{..} -> P.mempty <> P.maybe P.mempty (TF.pair "backend_vlan_id") backend_vlan_id <> P.maybe P.mempty (TF.pair "block_device_template_group_gid") block_device_template_group_gid <> TF.pair "cpu" cpu <> P.maybe P.mempty (TF.pair "dedicated_acct_host_only") dedicated_acct_host_only <> P.maybe P.mempty (TF.pair "disks") disks <> TF.pair "domain" domain <> P.maybe P.mempty (TF.pair "frontend_vlan_id") frontend_vlan_id <> TF.pair "hourly_billing" hourly_billing <> P.maybe P.mempty (TF.pair "image") image <> TF.pair "local_disk" local_disk <> TF.pair "name" name <> P.maybe P.mempty (TF.pair "post_install_script_uri") post_install_script_uri <> TF.pair "private_network_only" private_network_only <> TF.pair "public_network_speed" public_network_speed <> TF.pair "ram" ram <> TF.pair "region" region <> P.maybe P.mempty (TF.pair "ssh_keys") ssh_keys <> P.maybe P.mempty (TF.pair "user_data") user_data ) (let VirtualGuestR{..} = x in VirtualGuestR_Internal { backend_vlan_id = P.Nothing , block_device_template_group_gid = P.Nothing , cpu = cpu , dedicated_acct_host_only = P.Nothing , disks = P.Nothing , domain = domain , frontend_vlan_id = P.Nothing , hourly_billing = hourly_billing , image = P.Nothing , local_disk = local_disk , name = name , post_install_script_uri = P.Nothing , private_network_only = TF.expr P.False , public_network_speed = TF.expr 1000 , ram = ram , region = region , ssh_keys = P.Nothing , user_data = P.Nothing }) data VirtualGuestR_Required s = VirtualGuestR { hourly_billing :: TF.Expr s P.Bool ^ ( Required , Forces New ) , cpu :: TF.Expr s P.Int ^ ( Required , Forces New ) , local_disk :: TF.Expr s P.Bool ^ ( Required , Forces New ) , domain :: TF.Expr s P.Text , name :: TF.Expr s P.Text , ram :: TF.Expr s P.Int , region :: TF.Expr s P.Text ^ ( Required , Forces New ) } deriving (P.Show) instance Lens.HasField "backend_vlan_id" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s TF.Id)) where field = Lens.resourceLens P.. Lens.lens' (backend_vlan_id :: VirtualGuestR s -> P.Maybe (TF.Expr s TF.Id)) (\s a -> s { backend_vlan_id = a } :: VirtualGuestR s) instance Lens.HasField "block_device_template_group_gid" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (block_device_template_group_gid :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { block_device_template_group_gid = a } :: VirtualGuestR s) instance Lens.HasField "cpu" f (P.Resource VirtualGuestR s) (TF.Expr s P.Int) where field = Lens.resourceLens P.. Lens.lens' (cpu :: VirtualGuestR s -> TF.Expr s P.Int) (\s a -> s { cpu = a } :: VirtualGuestR s) instance Lens.HasField "dedicated_acct_host_only" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Bool)) where field = Lens.resourceLens P.. Lens.lens' (dedicated_acct_host_only :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Bool)) (\s a -> s { dedicated_acct_host_only = a } :: VirtualGuestR s) instance Lens.HasField "disks" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s [TF.Expr s P.Int])) where field = Lens.resourceLens P.. Lens.lens' (disks :: VirtualGuestR s -> P.Maybe (TF.Expr s [TF.Expr s P.Int])) (\s a -> s { disks = a } :: VirtualGuestR s) instance Lens.HasField "domain" f (P.Resource VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (domain :: VirtualGuestR s -> TF.Expr s P.Text) (\s a -> s { domain = a } :: VirtualGuestR s) instance Lens.HasField "frontend_vlan_id" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s TF.Id)) where field = Lens.resourceLens P.. Lens.lens' (frontend_vlan_id :: VirtualGuestR s -> P.Maybe (TF.Expr s TF.Id)) (\s a -> s { frontend_vlan_id = a } :: VirtualGuestR s) instance Lens.HasField "hourly_billing" f (P.Resource VirtualGuestR s) (TF.Expr s P.Bool) where field = Lens.resourceLens P.. Lens.lens' (hourly_billing :: VirtualGuestR s -> TF.Expr s P.Bool) (\s a -> s { hourly_billing = a } :: VirtualGuestR s) instance Lens.HasField "image" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (image :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { image = a } :: VirtualGuestR s) instance Lens.HasField "local_disk" f (P.Resource VirtualGuestR s) (TF.Expr s P.Bool) where field = Lens.resourceLens P.. Lens.lens' (local_disk :: VirtualGuestR s -> TF.Expr s P.Bool) (\s a -> s { local_disk = a } :: VirtualGuestR s) instance Lens.HasField "name" f (P.Resource VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (name :: VirtualGuestR s -> TF.Expr s P.Text) (\s a -> s { name = a } :: VirtualGuestR s) instance Lens.HasField "post_install_script_uri" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (post_install_script_uri :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { post_install_script_uri = a } :: VirtualGuestR s) instance Lens.HasField "private_network_only" f (P.Resource VirtualGuestR s) (TF.Expr s P.Bool) where field = Lens.resourceLens P.. Lens.lens' (private_network_only :: VirtualGuestR s -> TF.Expr s P.Bool) (\s a -> s { private_network_only = a } :: VirtualGuestR s) instance Lens.HasField "public_network_speed" f (P.Resource VirtualGuestR s) (TF.Expr s P.Int) where field = Lens.resourceLens P.. Lens.lens' (public_network_speed :: VirtualGuestR s -> TF.Expr s P.Int) (\s a -> s { public_network_speed = a } :: VirtualGuestR s) instance Lens.HasField "ram" f (P.Resource VirtualGuestR s) (TF.Expr s P.Int) where field = Lens.resourceLens P.. Lens.lens' (ram :: VirtualGuestR s -> TF.Expr s P.Int) (\s a -> s { ram = a } :: VirtualGuestR s) instance Lens.HasField "region" f (P.Resource VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.resourceLens P.. Lens.lens' (region :: VirtualGuestR s -> TF.Expr s P.Text) (\s a -> s { region = a } :: VirtualGuestR s) instance Lens.HasField "ssh_keys" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s [TF.Expr s P.Int])) where field = Lens.resourceLens P.. Lens.lens' (ssh_keys :: VirtualGuestR s -> P.Maybe (TF.Expr s [TF.Expr s P.Int])) (\s a -> s { ssh_keys = a } :: VirtualGuestR s) instance Lens.HasField "user_data" f (P.Resource VirtualGuestR s) (P.Maybe (TF.Expr s P.Text)) where field = Lens.resourceLens P.. Lens.lens' (user_data :: VirtualGuestR s -> P.Maybe (TF.Expr s P.Text)) (\s a -> s { user_data = a } :: VirtualGuestR s) instance Lens.HasField "id" (P.Const r) (TF.Ref VirtualGuestR s) (TF.Expr s TF.Id) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "id")) instance Lens.HasField "ipv4_address" (P.Const r) (TF.Ref VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "ipv4_address")) instance Lens.HasField "ipv4_address_private" (P.Const r) (TF.Ref VirtualGuestR s) (TF.Expr s P.Text) where field = Lens.to (TF.unsafeComputed Encode.attribute (proxy# :: Proxy# "ipv4_address_private"))
8e320cf064386cce3955d8d66935371c937aa982ab3949be4dc2f2d54e1ba30d
ulricha/dsh
Quote.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE TemplateHaskell # # LANGUAGE StandaloneDeriving # module Database.DSH.NKL.Quote ( nkl , ty , Var , ExprQ(..) , TypeQ(..) , varName , toExprQ , fromExprQ , typeOf , (.->) , elemT , freeVars ) where import Control.Monad import Data.Functor import qualified Data.Set as S import Data.Data(Data) import Data.Generics.Aliases import Data.Typeable(Typeable, Typeable1) import qualified Language.Haskell.TH as TH import Language.Haskell.TH.Quote import Text.Parsec hiding (Column) import Text.Parsec.Language import qualified Text.Parsec.Token as P import qualified Text.PrettyPrint.HughesPJ as PP import Text.PrettyPrint.HughesPJ((<+>), (<>)) import Database.DSH.Common.Impossible import Database.DSH.Common.Data.Op import Database.DSH.Common.Data.Val import qualified Database.DSH.Common.Data.Type as T import qualified Database.DSH.NKL.Lang as NKL data Anti = AntiBind String | AntiWild deriving (Show, Data, Typeable) data Var = VarLit String | VarAntiBind String | VarAntiWild deriving (Eq, Ord, Show, Data, Typeable) type Column = (String, TypeQ) data ExprQ = Table TypeQ String [Column] [NKL.Key] | App TypeQ ExprQ ExprQ | AppE1 TypeQ (NKL.Prim1 TypeQ) ExprQ | AppE2 TypeQ (NKL.Prim2 TypeQ) ExprQ ExprQ | BinOp TypeQ ScalarBinOp ExprQ ExprQ | Lam TypeQ Var ExprQ | If TypeQ ExprQ ExprQ ExprQ | Const TypeQ Val | Var TypeQ Var -- Antiquotation node | AntiE Anti deriving (Data, Typeable) data TypeQ = FunT TypeQ TypeQ | NatT | IntT | BoolT | DoubleT | StringT | UnitT | VarT String | PairT TypeQ TypeQ | ListT TypeQ -- Antiquotation node | AntiT Anti deriving (Show, Typeable, Data) deriving instance Typeable NKL.Prim2Op deriving instance Data NKL.Prim2Op deriving instance Typeable NKL.Prim1Op deriving instance Data NKL.Prim1Op deriving instance Typeable1 NKL.Prim2 deriving instance Data t => Data (NKL.Prim2 t) deriving instance Typeable1 NKL.Prim1 deriving instance Data t => Data (NKL.Prim1 t) -------------------------------------------------------------------------- -- Conversion to and from quotation types toTypeQ :: T.Type -> TypeQ toTypeQ (T.FunT t1 t2) = FunT (toTypeQ t1) (toTypeQ t2) toTypeQ T.NatT = NatT toTypeQ T.IntT = IntT toTypeQ T.BoolT = BoolT toTypeQ T.DoubleT = DoubleT toTypeQ T.StringT = StringT toTypeQ T.UnitT = UnitT toTypeQ (T.VarT v) = VarT v toTypeQ (T.PairT t1 t2) = PairT (toTypeQ t1) (toTypeQ t2) toTypeQ (T.ListT t) = ListT (toTypeQ t) fromTypeQ :: TypeQ -> T.Type fromTypeQ (FunT t1 t2) = T.FunT (fromTypeQ t1) (fromTypeQ t2) fromTypeQ NatT = T.NatT fromTypeQ IntT = T.IntT fromTypeQ BoolT = T.BoolT fromTypeQ DoubleT = T.DoubleT fromTypeQ StringT = T.StringT fromTypeQ UnitT = T.UnitT fromTypeQ (VarT v) = T.VarT v fromTypeQ (PairT t1 t2) = T.PairT (fromTypeQ t1) (fromTypeQ t2) fromTypeQ (ListT t) = T.ListT (fromTypeQ t) fromTypeQ (AntiT _) = $impossible toExprQ :: NKL.Expr -> ExprQ toExprQ ( NKL.Table t n cs ks ) = Table ( toTypeQ t ) n cs ks toExprQ (NKL.Table t n cs ks) = Table (toTypeQ t) n (map (\(x, y) -> (x, toTypeQ y)) cs) ks toExprQ (NKL.App t e1 e2) = App (toTypeQ t) (toExprQ e1) (toExprQ e2) toExprQ (NKL.AppE1 t p e) = AppE1 (toTypeQ t) (toPrim1Q p) (toExprQ e) toExprQ (NKL.AppE2 t p e1 e2) = AppE2 (toTypeQ t) (toPrim2Q p) (toExprQ e1) (toExprQ e2) toExprQ (NKL.BinOp t o e1 e2) = BinOp (toTypeQ t) o (toExprQ e1) (toExprQ e2) toExprQ (NKL.Lam t v e) = Lam (toTypeQ t) (VarLit v) (toExprQ e) toExprQ (NKL.If t c thenE elseE) = If (toTypeQ t) (toExprQ c) (toExprQ thenE) (toExprQ elseE) toExprQ (NKL.Const t v) = Const (toTypeQ t) v toExprQ (NKL.Var t v) = Var (toTypeQ t) (VarLit v) fromExprQ :: ExprQ -> NKL.Expr -- fromExprQ (Table t n cs ks) = NKL.Table (fromTypeQ t) n cs ks fromExprQ (Table t n cs ks) = NKL.Table (fromTypeQ t) n (map (\(x, y) -> (x, fromTypeQ y)) cs) ks fromExprQ (App t e1 e2) = NKL.App (fromTypeQ t) (fromExprQ e1) (fromExprQ e2) fromExprQ (AppE1 t p e) = NKL.AppE1 (fromTypeQ t) (fromPrim1Q p) (fromExprQ e) fromExprQ (AppE2 t p e1 e2) = NKL.AppE2 (fromTypeQ t) (fromPrim2Q p) (fromExprQ e1) (fromExprQ e2) fromExprQ (BinOp t o e1 e2) = NKL.BinOp (fromTypeQ t) o (fromExprQ e1) (fromExprQ e2) fromExprQ (Lam t b e) = NKL.Lam (fromTypeQ t) (varName b) (fromExprQ e) fromExprQ (If t c thenE elseE) = NKL.If (fromTypeQ t) (fromExprQ c) (fromExprQ thenE) (fromExprQ elseE) fromExprQ (Const t v) = NKL.Const (fromTypeQ t) v fromExprQ (Var t v) = NKL.Var (fromTypeQ t) (varName v) fromExprQ (AntiE e) = error $ show e varName :: Var -> String varName (VarLit s) = s varName (VarAntiBind _) = $impossible varName VarAntiWild = $impossible fromPrim1Q :: NKL.Prim1 TypeQ -> NKL.Prim1 T.Type fromPrim1Q (NKL.Prim1 o t) = NKL.Prim1 o (fromTypeQ t) toPrim1Q :: NKL.Prim1 T.Type -> NKL.Prim1 TypeQ toPrim1Q (NKL.Prim1 o t) = NKL.Prim1 o (toTypeQ t) fromPrim2Q :: NKL.Prim2 TypeQ -> NKL.Prim2 T.Type fromPrim2Q (NKL.Prim2 o t) = NKL.Prim2 o (fromTypeQ t) toPrim2Q :: NKL.Prim2 T.Type -> NKL.Prim2 TypeQ toPrim2Q (NKL.Prim2 o t) = NKL.Prim2 o (toTypeQ t) -------------------------------------------------------------------------- -- Some helper functions on quotable types and expressions, analogous to those in NKL and Type . -- | Extract the type annotation from an expression typeOf :: ExprQ -> TypeQ typeOf (Table t _ _ _) = t typeOf (App t _ _) = t typeOf (AppE1 t _ _) = t typeOf (AppE2 t _ _ _) = t typeOf (BinOp t _ _ _) = t typeOf (Lam t _ _) = t typeOf (If t _ _ _) = t typeOf (Const t _) = t typeOf (Var t _) = t typeOf (AntiE _) = $impossible (.->) :: TypeQ -> TypeQ -> TypeQ (.->) t1 t2 = FunT t1 t2 elemT :: TypeQ -> TypeQ elemT (ListT t) = t elemT _ = $impossible freeVars :: ExprQ -> S.Set Var freeVars (Table _ _ _ _) = S.empty freeVars (App _ e1 e2) = freeVars e1 `S.union` freeVars e2 freeVars (AppE1 _ _ e1) = freeVars e1 freeVars (AppE2 _ _ e1 e2) = freeVars e1 `S.union` freeVars e2 freeVars (Lam _ x e) = (freeVars e) S.\\ S.singleton x freeVars (If _ e1 e2 e3) = freeVars e1 `S.union` freeVars e2 `S.union` freeVars e3 freeVars (BinOp _ _ e1 e2) = freeVars e1 `S.union` freeVars e2 freeVars (Const _ _) = S.empty freeVars (Var _ x) = S.singleton x freeVars (AntiE _) = $impossible instance Show ExprQ where show e = PP.render $ pp e pp :: ExprQ -> PP.Doc pp (Table _ n _ _) = PP.text "table" <+> PP.text n pp (App _ e1 e2) = (PP.parens $ pp e1) <+> (PP.parens $ pp e2) pp (AppE1 _ p1 e) = (PP.text $ show p1) <+> (PP.parens $ pp e) pp (AppE2 _ p1 e1 e2) = (PP.text $ show p1) <+> (PP.parens $ pp e1) <+> (PP.parens $ pp e2) pp (BinOp _ o e1 e2) = (PP.parens $ pp e1) <+> (PP.text $ show o) <+> (PP.parens $ pp e2) pp (Lam _ v e) = PP.char '\\' <> PP.text (varName v) <+> PP.text "->" <+> pp e pp (If _ c t e) = PP.text "if" <+> pp c <+> PP.text "then" <+> (PP.parens $ pp t) <+> PP.text "else" <+> (PP.parens $ pp e) pp (Const _ v) = PP.text $ show v pp (Var _ s) = PP.text $ varName s pp (AntiE _) = $impossible -------------------------------------------------------------------------- A parser for NKL expressions and types , including anti - quotation syntax type Parse = Parsec String () lexer :: P.TokenParser () lexer = P.makeTokenParser haskellDef reserved :: String -> Parse () reserved = P.reserved lexer parens :: Parse a -> Parse a parens = P.parens lexer reservedOp :: String -> Parse () reservedOp = P.reservedOp lexer comma :: Parse String comma = P.comma lexer identifier :: Parse String identifier = P.identifier lexer brackets :: Parse a -> Parse a brackets = P.brackets lexer commaSep :: Parse a -> Parse [a] commaSep = P.commaSep lexer float :: Parse Double float = P.float lexer natural :: Parse Int natural = fromInteger <$> P.natural lexer stringLiteral :: Parse String stringLiteral = P.stringLiteral lexer commaSep1 :: Parse a -> Parse [a] commaSep1 = P.commaSep1 lexer typ :: Parse TypeQ typ = do { void $ char '\''; AntiT <$> AntiBind <$> identifier } *<|> do { reservedOp "_"; return (AntiT AntiWild) } *<|> do { reserved "nat"; return NatT } *<|> do { reserved "int"; return IntT } *<|> do { reserved "bool"; return BoolT } *<|> do { reserved "double"; return DoubleT } *<|> do { reserved "string"; return StringT } *<|> do { reserved "unit"; return UnitT } *<|> do { i <- identifier; return $ VarT i } *<|> try (parens $ do { t1 <- typ ; reservedOp "->" ; t2 <- typ ; return $ FunT t1 t2 } ) *<|> (parens $ do { t1 <- typ ; void comma ; t2 <- typ ; return $ PairT t1 t2 } ) *<|> do { t <- brackets typ; return $ ListT t } prim1s :: [Parse (TypeQ -> NKL.Prim1 TypeQ)] prim1s = [ reserved "length" >> return (NKL.Prim1 NKL.Length) , reserved "concat" >> return (NKL.Prim1 NKL.Concat) , reserved "sum" >> return (NKL.Prim1 NKL.Sum) , reserved "avg" >> return (NKL.Prim1 NKL.Avg) , reserved "the" >> return (NKL.Prim1 NKL.The) , reserved "fst" >> return (NKL.Prim1 NKL.Fst) , reserved "snd" >> return (NKL.Prim1 NKL.Snd) , reserved "head" >> return (NKL.Prim1 NKL.Head) , reserved "minimum" >> return (NKL.Prim1 NKL.Minimum) , reserved "maximum" >> return (NKL.Prim1 NKL.Maximum) , reserved "tail" >> return (NKL.Prim1 NKL.Tail) , reserved "reverse" >> return (NKL.Prim1 NKL.Reverse) , reserved "and" >> return (NKL.Prim1 NKL.And) , reserved "or" >> return (NKL.Prim1 NKL.Or) , reserved "init" >> return (NKL.Prim1 NKL.Init) , reserved "last" >> return (NKL.Prim1 NKL.Last) , reserved "nub" >> return (NKL.Prim1 NKL.Nub) ] prim1 :: Parse (NKL.Prim1 TypeQ) prim1 = do { p <- choice prim1s ; reservedOp "::" ; t <- typ ; return $ p t } prim2s :: [Parse (TypeQ -> NKL.Prim2 TypeQ)] prim2s = [ reserved "map" >> return (NKL.Prim2 NKL.Map) , reserved "groupWithKey" >> return (NKL.Prim2 NKL.GroupWithKey) , reserved "sortWith" >> return (NKL.Prim2 NKL.SortWith) , reserved "pair" >> return (NKL.Prim2 NKL.Pair) , reserved "filter" >> return (NKL.Prim2 NKL.Filter) , reserved "append" >> return (NKL.Prim2 NKL.Append) , reserved "index" >> return (NKL.Prim2 NKL.Index) , reserved "zip" >> return (NKL.Prim2 NKL.Zip) , reserved "cartProduct" >> return (NKL.Prim2 NKL.CartProduct) ] prim2 :: Parse (NKL.Prim2 TypeQ) prim2 = do { p <- choice prim2s ; reservedOp "::" ; t <- typ ; return $ p t } val :: Parse Val val = (IntV <$> natural) <|> (StringV <$> stringLiteral) <|> (DoubleV <$> float) <|> (reserved "true" >> return (BoolV True)) <|> (reserved "false" >> return (BoolV False)) <|> (reserved "unit" >> return UnitV) <|> (ListV <$> (brackets $ commaSep val)) <|> (parens $ do { v1 <- val ; void comma ; v2 <- val ; return $ PairV v1 v2 } ) op :: Parse ScalarBinOp op = choice [ reservedOp "+" >> return Add , reservedOp "-" >> return Sub , reservedOp "/" >> return Div , reservedOp "*" >> return Mul , reservedOp "%" >> return Mod , reservedOp "==" >> return Eq , reservedOp ">" >> return Gt , reservedOp ">=" >> return GtE , reservedOp "<" >> return Lt , reservedOp "<=" >> return LtE , reservedOp "&&" >> return Conj , reservedOp "||" >> return Disj , reservedOp "LIKE" >> return Like ] infixr 1 *<|> (*<|>) :: ParsecT s u m a -> ParsecT s u m a -> ParsecT s u m a a *<|> b = try a <|> b expr :: Parse ExprQ expr = do { v <- val ; reservedOp "::" ; t <- typ ; return $ Const t v } *<|> do { e <- parens cexpr ; reservedOp "::" ; t <- typ ; return $ e t } *<|> do { i <- identifier ; reservedOp "::" ; t <- typ ; return $ Var t (VarLit i) } *<|> do { void $ char '\'' ; i <- identifier ; reservedOp "::" ; t <- typ ; return $ Var t (VarAntiBind i) } *<|> do { void $ char '_' ; reservedOp "::" ; t <- typ ; return $ Var t VarAntiWild } *<|> do { reservedOp "_"; return (AntiE AntiWild) } *<|> do { void $ char '\'' ; i <- identifier ; return $ AntiE $ AntiBind i } var :: Parse Var var = do { void $ char '\''; VarAntiBind <$> identifier } *<|> do { void $ char '_'; return VarAntiWild } *<|> do { VarLit <$> identifier } keys :: Parse [NKL.Key] keys = brackets $ commaSep $ brackets $ commaSep1 identifier columns :: Parse [Column] columns = brackets $ commaSep1 $ parens $ do c <- identifier void comma t <- typ return (c, t) cexpr :: Parse (TypeQ -> ExprQ) cexpr = do { reserved "table" ; n <- identifier ; cs <- columns ; ks <- keys ; return $ \t -> Table t n cs ks } *<|> do { e1 <- expr ; o <- op ; e2 <- expr ; return $ \t -> BinOp t o e1 e2 } *<|> do { p <- prim1 ; e <- expr ; return $ \t -> AppE1 t p e } *<|> do { p <- prim2 ; e1 <- expr ; e2 <- expr ; return $ \t -> AppE2 t p e1 e2 } *<|> do { e1 <- expr ; e2 <- expr ; return $ \t -> App t e1 e2 } *<|> do { reserved "if" ; condE <- expr ; reserved "then" ; thenE <- expr ; reserved "else" ; elseE <- expr ; return $ \t -> If t condE thenE elseE } *<|> do { reservedOp "\\" ; v <- var ; reservedOp "->" ; e <- expr ; return $ \t -> Lam t v e } parseType :: String -> TypeQ parseType i = case parse typ "" i of Left e -> error $ show e Right t -> t parseExpr :: String -> ExprQ parseExpr i = case parse expr "" i of Left e -> error $ i ++ " " ++ show e Right t -> t -------------------------------------------------------------------------- -- Quasi-Quoting antiExprExp :: ExprQ -> Maybe (TH.Q TH.Exp) antiExprExp (AntiE (AntiBind s)) = Just $ TH.varE (TH.mkName s) antiExprExp (AntiE AntiWild) = error "NKL.Quote: wildcard pattern (expr) used in expression quote" antiExprExp _ = Nothing antiExprPat :: ExprQ -> Maybe (TH.Q TH.Pat) antiExprPat (AntiE (AntiBind s)) = Just $ TH.varP (TH.mkName s) antiExprPat (AntiE AntiWild) = Just TH.wildP antiExprPat _ = Nothing antiTypeExp :: TypeQ -> Maybe (TH.Q TH.Exp) antiTypeExp (AntiT (AntiBind s)) = Just $ TH.varE (TH.mkName s) antiTypeExp (AntiT AntiWild) = error "NKL.Quote: wildcard pattern (type) used in expression quote" antiTypeExp _ = Nothing antiTypePat :: TypeQ -> Maybe (TH.Q TH.Pat) antiTypePat (AntiT (AntiBind s)) = Just $ TH.varP (TH.mkName s) antiTypePat (AntiT AntiWild) = Just TH.wildP antiTypePat _ = Nothing antiVarExp :: Var -> Maybe (TH.Q TH.Exp) antiVarExp (VarAntiBind s) = Just $ TH.varE (TH.mkName s) antiVarExp VarAntiWild = error "NKL.Quote: wildcard pattern (variable) used in expression quote" antiVarExp (VarLit _) = Nothing antiVarPat :: Var -> Maybe (TH.Q TH.Pat) antiVarPat (VarAntiBind s) = Just $ TH.varP (TH.mkName s) antiVarPat VarAntiWild = Just TH.wildP antiVarPat _ = Nothing quoteExprExp :: String -> TH.ExpQ quoteExprExp s = dataToExpQ (const Nothing `extQ` antiExprExp `extQ` antiTypeExp `extQ` antiVarExp) $ parseExpr s quoteExprPat :: String -> TH.PatQ quoteExprPat s = dataToPatQ (const Nothing `extQ` antiExprPat `extQ` antiTypePat `extQ` antiVarPat) $ parseExpr s quoteTypeExp :: String -> TH.ExpQ quoteTypeExp s = dataToExpQ (const Nothing `extQ` antiTypeExp) $ parseType s quoteTypePat :: String -> TH.PatQ quoteTypePat s = dataToPatQ (const Nothing `extQ` antiTypePat) $ parseType s -- | A quasi quoter for the Flattening type language ty :: QuasiQuoter ty = QuasiQuoter { quoteExp = quoteTypeExp , quotePat = quoteTypePat , quoteDec = error "Can't use NKL quasiquoter for declarations" , quoteType = error "Can't use NKL quasiquoter for types" } | A quasi quoter for NKL expressions nkl :: QuasiQuoter nkl = QuasiQuoter { quoteExp = quoteExprExp , quotePat = quoteExprPat , quoteDec = error "Can't use NKL quasiquoter for declarations" , quoteType = error "Can't use NKL quasiquoter for types" }
null
https://raw.githubusercontent.com/ulricha/dsh/e6cd5c6bea575e62a381e89bfc4cc7cb97485106/src/Database/DSH/NKL/Quote.hs
haskell
# LANGUAGE DeriveDataTypeable # Antiquotation node Antiquotation node ------------------------------------------------------------------------ Conversion to and from quotation types fromExprQ (Table t n cs ks) = NKL.Table (fromTypeQ t) n cs ks ------------------------------------------------------------------------ Some helper functions on quotable types and expressions, analogous to | Extract the type annotation from an expression ------------------------------------------------------------------------ ------------------------------------------------------------------------ Quasi-Quoting | A quasi quoter for the Flattening type language
# LANGUAGE TemplateHaskell # # LANGUAGE StandaloneDeriving # module Database.DSH.NKL.Quote ( nkl , ty , Var , ExprQ(..) , TypeQ(..) , varName , toExprQ , fromExprQ , typeOf , (.->) , elemT , freeVars ) where import Control.Monad import Data.Functor import qualified Data.Set as S import Data.Data(Data) import Data.Generics.Aliases import Data.Typeable(Typeable, Typeable1) import qualified Language.Haskell.TH as TH import Language.Haskell.TH.Quote import Text.Parsec hiding (Column) import Text.Parsec.Language import qualified Text.Parsec.Token as P import qualified Text.PrettyPrint.HughesPJ as PP import Text.PrettyPrint.HughesPJ((<+>), (<>)) import Database.DSH.Common.Impossible import Database.DSH.Common.Data.Op import Database.DSH.Common.Data.Val import qualified Database.DSH.Common.Data.Type as T import qualified Database.DSH.NKL.Lang as NKL data Anti = AntiBind String | AntiWild deriving (Show, Data, Typeable) data Var = VarLit String | VarAntiBind String | VarAntiWild deriving (Eq, Ord, Show, Data, Typeable) type Column = (String, TypeQ) data ExprQ = Table TypeQ String [Column] [NKL.Key] | App TypeQ ExprQ ExprQ | AppE1 TypeQ (NKL.Prim1 TypeQ) ExprQ | AppE2 TypeQ (NKL.Prim2 TypeQ) ExprQ ExprQ | BinOp TypeQ ScalarBinOp ExprQ ExprQ | Lam TypeQ Var ExprQ | If TypeQ ExprQ ExprQ ExprQ | Const TypeQ Val | Var TypeQ Var | AntiE Anti deriving (Data, Typeable) data TypeQ = FunT TypeQ TypeQ | NatT | IntT | BoolT | DoubleT | StringT | UnitT | VarT String | PairT TypeQ TypeQ | ListT TypeQ | AntiT Anti deriving (Show, Typeable, Data) deriving instance Typeable NKL.Prim2Op deriving instance Data NKL.Prim2Op deriving instance Typeable NKL.Prim1Op deriving instance Data NKL.Prim1Op deriving instance Typeable1 NKL.Prim2 deriving instance Data t => Data (NKL.Prim2 t) deriving instance Typeable1 NKL.Prim1 deriving instance Data t => Data (NKL.Prim1 t) toTypeQ :: T.Type -> TypeQ toTypeQ (T.FunT t1 t2) = FunT (toTypeQ t1) (toTypeQ t2) toTypeQ T.NatT = NatT toTypeQ T.IntT = IntT toTypeQ T.BoolT = BoolT toTypeQ T.DoubleT = DoubleT toTypeQ T.StringT = StringT toTypeQ T.UnitT = UnitT toTypeQ (T.VarT v) = VarT v toTypeQ (T.PairT t1 t2) = PairT (toTypeQ t1) (toTypeQ t2) toTypeQ (T.ListT t) = ListT (toTypeQ t) fromTypeQ :: TypeQ -> T.Type fromTypeQ (FunT t1 t2) = T.FunT (fromTypeQ t1) (fromTypeQ t2) fromTypeQ NatT = T.NatT fromTypeQ IntT = T.IntT fromTypeQ BoolT = T.BoolT fromTypeQ DoubleT = T.DoubleT fromTypeQ StringT = T.StringT fromTypeQ UnitT = T.UnitT fromTypeQ (VarT v) = T.VarT v fromTypeQ (PairT t1 t2) = T.PairT (fromTypeQ t1) (fromTypeQ t2) fromTypeQ (ListT t) = T.ListT (fromTypeQ t) fromTypeQ (AntiT _) = $impossible toExprQ :: NKL.Expr -> ExprQ toExprQ ( NKL.Table t n cs ks ) = Table ( toTypeQ t ) n cs ks toExprQ (NKL.Table t n cs ks) = Table (toTypeQ t) n (map (\(x, y) -> (x, toTypeQ y)) cs) ks toExprQ (NKL.App t e1 e2) = App (toTypeQ t) (toExprQ e1) (toExprQ e2) toExprQ (NKL.AppE1 t p e) = AppE1 (toTypeQ t) (toPrim1Q p) (toExprQ e) toExprQ (NKL.AppE2 t p e1 e2) = AppE2 (toTypeQ t) (toPrim2Q p) (toExprQ e1) (toExprQ e2) toExprQ (NKL.BinOp t o e1 e2) = BinOp (toTypeQ t) o (toExprQ e1) (toExprQ e2) toExprQ (NKL.Lam t v e) = Lam (toTypeQ t) (VarLit v) (toExprQ e) toExprQ (NKL.If t c thenE elseE) = If (toTypeQ t) (toExprQ c) (toExprQ thenE) (toExprQ elseE) toExprQ (NKL.Const t v) = Const (toTypeQ t) v toExprQ (NKL.Var t v) = Var (toTypeQ t) (VarLit v) fromExprQ :: ExprQ -> NKL.Expr fromExprQ (Table t n cs ks) = NKL.Table (fromTypeQ t) n (map (\(x, y) -> (x, fromTypeQ y)) cs) ks fromExprQ (App t e1 e2) = NKL.App (fromTypeQ t) (fromExprQ e1) (fromExprQ e2) fromExprQ (AppE1 t p e) = NKL.AppE1 (fromTypeQ t) (fromPrim1Q p) (fromExprQ e) fromExprQ (AppE2 t p e1 e2) = NKL.AppE2 (fromTypeQ t) (fromPrim2Q p) (fromExprQ e1) (fromExprQ e2) fromExprQ (BinOp t o e1 e2) = NKL.BinOp (fromTypeQ t) o (fromExprQ e1) (fromExprQ e2) fromExprQ (Lam t b e) = NKL.Lam (fromTypeQ t) (varName b) (fromExprQ e) fromExprQ (If t c thenE elseE) = NKL.If (fromTypeQ t) (fromExprQ c) (fromExprQ thenE) (fromExprQ elseE) fromExprQ (Const t v) = NKL.Const (fromTypeQ t) v fromExprQ (Var t v) = NKL.Var (fromTypeQ t) (varName v) fromExprQ (AntiE e) = error $ show e varName :: Var -> String varName (VarLit s) = s varName (VarAntiBind _) = $impossible varName VarAntiWild = $impossible fromPrim1Q :: NKL.Prim1 TypeQ -> NKL.Prim1 T.Type fromPrim1Q (NKL.Prim1 o t) = NKL.Prim1 o (fromTypeQ t) toPrim1Q :: NKL.Prim1 T.Type -> NKL.Prim1 TypeQ toPrim1Q (NKL.Prim1 o t) = NKL.Prim1 o (toTypeQ t) fromPrim2Q :: NKL.Prim2 TypeQ -> NKL.Prim2 T.Type fromPrim2Q (NKL.Prim2 o t) = NKL.Prim2 o (fromTypeQ t) toPrim2Q :: NKL.Prim2 T.Type -> NKL.Prim2 TypeQ toPrim2Q (NKL.Prim2 o t) = NKL.Prim2 o (toTypeQ t) those in NKL and Type . typeOf :: ExprQ -> TypeQ typeOf (Table t _ _ _) = t typeOf (App t _ _) = t typeOf (AppE1 t _ _) = t typeOf (AppE2 t _ _ _) = t typeOf (BinOp t _ _ _) = t typeOf (Lam t _ _) = t typeOf (If t _ _ _) = t typeOf (Const t _) = t typeOf (Var t _) = t typeOf (AntiE _) = $impossible (.->) :: TypeQ -> TypeQ -> TypeQ (.->) t1 t2 = FunT t1 t2 elemT :: TypeQ -> TypeQ elemT (ListT t) = t elemT _ = $impossible freeVars :: ExprQ -> S.Set Var freeVars (Table _ _ _ _) = S.empty freeVars (App _ e1 e2) = freeVars e1 `S.union` freeVars e2 freeVars (AppE1 _ _ e1) = freeVars e1 freeVars (AppE2 _ _ e1 e2) = freeVars e1 `S.union` freeVars e2 freeVars (Lam _ x e) = (freeVars e) S.\\ S.singleton x freeVars (If _ e1 e2 e3) = freeVars e1 `S.union` freeVars e2 `S.union` freeVars e3 freeVars (BinOp _ _ e1 e2) = freeVars e1 `S.union` freeVars e2 freeVars (Const _ _) = S.empty freeVars (Var _ x) = S.singleton x freeVars (AntiE _) = $impossible instance Show ExprQ where show e = PP.render $ pp e pp :: ExprQ -> PP.Doc pp (Table _ n _ _) = PP.text "table" <+> PP.text n pp (App _ e1 e2) = (PP.parens $ pp e1) <+> (PP.parens $ pp e2) pp (AppE1 _ p1 e) = (PP.text $ show p1) <+> (PP.parens $ pp e) pp (AppE2 _ p1 e1 e2) = (PP.text $ show p1) <+> (PP.parens $ pp e1) <+> (PP.parens $ pp e2) pp (BinOp _ o e1 e2) = (PP.parens $ pp e1) <+> (PP.text $ show o) <+> (PP.parens $ pp e2) pp (Lam _ v e) = PP.char '\\' <> PP.text (varName v) <+> PP.text "->" <+> pp e pp (If _ c t e) = PP.text "if" <+> pp c <+> PP.text "then" <+> (PP.parens $ pp t) <+> PP.text "else" <+> (PP.parens $ pp e) pp (Const _ v) = PP.text $ show v pp (Var _ s) = PP.text $ varName s pp (AntiE _) = $impossible A parser for NKL expressions and types , including anti - quotation syntax type Parse = Parsec String () lexer :: P.TokenParser () lexer = P.makeTokenParser haskellDef reserved :: String -> Parse () reserved = P.reserved lexer parens :: Parse a -> Parse a parens = P.parens lexer reservedOp :: String -> Parse () reservedOp = P.reservedOp lexer comma :: Parse String comma = P.comma lexer identifier :: Parse String identifier = P.identifier lexer brackets :: Parse a -> Parse a brackets = P.brackets lexer commaSep :: Parse a -> Parse [a] commaSep = P.commaSep lexer float :: Parse Double float = P.float lexer natural :: Parse Int natural = fromInteger <$> P.natural lexer stringLiteral :: Parse String stringLiteral = P.stringLiteral lexer commaSep1 :: Parse a -> Parse [a] commaSep1 = P.commaSep1 lexer typ :: Parse TypeQ typ = do { void $ char '\''; AntiT <$> AntiBind <$> identifier } *<|> do { reservedOp "_"; return (AntiT AntiWild) } *<|> do { reserved "nat"; return NatT } *<|> do { reserved "int"; return IntT } *<|> do { reserved "bool"; return BoolT } *<|> do { reserved "double"; return DoubleT } *<|> do { reserved "string"; return StringT } *<|> do { reserved "unit"; return UnitT } *<|> do { i <- identifier; return $ VarT i } *<|> try (parens $ do { t1 <- typ ; reservedOp "->" ; t2 <- typ ; return $ FunT t1 t2 } ) *<|> (parens $ do { t1 <- typ ; void comma ; t2 <- typ ; return $ PairT t1 t2 } ) *<|> do { t <- brackets typ; return $ ListT t } prim1s :: [Parse (TypeQ -> NKL.Prim1 TypeQ)] prim1s = [ reserved "length" >> return (NKL.Prim1 NKL.Length) , reserved "concat" >> return (NKL.Prim1 NKL.Concat) , reserved "sum" >> return (NKL.Prim1 NKL.Sum) , reserved "avg" >> return (NKL.Prim1 NKL.Avg) , reserved "the" >> return (NKL.Prim1 NKL.The) , reserved "fst" >> return (NKL.Prim1 NKL.Fst) , reserved "snd" >> return (NKL.Prim1 NKL.Snd) , reserved "head" >> return (NKL.Prim1 NKL.Head) , reserved "minimum" >> return (NKL.Prim1 NKL.Minimum) , reserved "maximum" >> return (NKL.Prim1 NKL.Maximum) , reserved "tail" >> return (NKL.Prim1 NKL.Tail) , reserved "reverse" >> return (NKL.Prim1 NKL.Reverse) , reserved "and" >> return (NKL.Prim1 NKL.And) , reserved "or" >> return (NKL.Prim1 NKL.Or) , reserved "init" >> return (NKL.Prim1 NKL.Init) , reserved "last" >> return (NKL.Prim1 NKL.Last) , reserved "nub" >> return (NKL.Prim1 NKL.Nub) ] prim1 :: Parse (NKL.Prim1 TypeQ) prim1 = do { p <- choice prim1s ; reservedOp "::" ; t <- typ ; return $ p t } prim2s :: [Parse (TypeQ -> NKL.Prim2 TypeQ)] prim2s = [ reserved "map" >> return (NKL.Prim2 NKL.Map) , reserved "groupWithKey" >> return (NKL.Prim2 NKL.GroupWithKey) , reserved "sortWith" >> return (NKL.Prim2 NKL.SortWith) , reserved "pair" >> return (NKL.Prim2 NKL.Pair) , reserved "filter" >> return (NKL.Prim2 NKL.Filter) , reserved "append" >> return (NKL.Prim2 NKL.Append) , reserved "index" >> return (NKL.Prim2 NKL.Index) , reserved "zip" >> return (NKL.Prim2 NKL.Zip) , reserved "cartProduct" >> return (NKL.Prim2 NKL.CartProduct) ] prim2 :: Parse (NKL.Prim2 TypeQ) prim2 = do { p <- choice prim2s ; reservedOp "::" ; t <- typ ; return $ p t } val :: Parse Val val = (IntV <$> natural) <|> (StringV <$> stringLiteral) <|> (DoubleV <$> float) <|> (reserved "true" >> return (BoolV True)) <|> (reserved "false" >> return (BoolV False)) <|> (reserved "unit" >> return UnitV) <|> (ListV <$> (brackets $ commaSep val)) <|> (parens $ do { v1 <- val ; void comma ; v2 <- val ; return $ PairV v1 v2 } ) op :: Parse ScalarBinOp op = choice [ reservedOp "+" >> return Add , reservedOp "-" >> return Sub , reservedOp "/" >> return Div , reservedOp "*" >> return Mul , reservedOp "%" >> return Mod , reservedOp "==" >> return Eq , reservedOp ">" >> return Gt , reservedOp ">=" >> return GtE , reservedOp "<" >> return Lt , reservedOp "<=" >> return LtE , reservedOp "&&" >> return Conj , reservedOp "||" >> return Disj , reservedOp "LIKE" >> return Like ] infixr 1 *<|> (*<|>) :: ParsecT s u m a -> ParsecT s u m a -> ParsecT s u m a a *<|> b = try a <|> b expr :: Parse ExprQ expr = do { v <- val ; reservedOp "::" ; t <- typ ; return $ Const t v } *<|> do { e <- parens cexpr ; reservedOp "::" ; t <- typ ; return $ e t } *<|> do { i <- identifier ; reservedOp "::" ; t <- typ ; return $ Var t (VarLit i) } *<|> do { void $ char '\'' ; i <- identifier ; reservedOp "::" ; t <- typ ; return $ Var t (VarAntiBind i) } *<|> do { void $ char '_' ; reservedOp "::" ; t <- typ ; return $ Var t VarAntiWild } *<|> do { reservedOp "_"; return (AntiE AntiWild) } *<|> do { void $ char '\'' ; i <- identifier ; return $ AntiE $ AntiBind i } var :: Parse Var var = do { void $ char '\''; VarAntiBind <$> identifier } *<|> do { void $ char '_'; return VarAntiWild } *<|> do { VarLit <$> identifier } keys :: Parse [NKL.Key] keys = brackets $ commaSep $ brackets $ commaSep1 identifier columns :: Parse [Column] columns = brackets $ commaSep1 $ parens $ do c <- identifier void comma t <- typ return (c, t) cexpr :: Parse (TypeQ -> ExprQ) cexpr = do { reserved "table" ; n <- identifier ; cs <- columns ; ks <- keys ; return $ \t -> Table t n cs ks } *<|> do { e1 <- expr ; o <- op ; e2 <- expr ; return $ \t -> BinOp t o e1 e2 } *<|> do { p <- prim1 ; e <- expr ; return $ \t -> AppE1 t p e } *<|> do { p <- prim2 ; e1 <- expr ; e2 <- expr ; return $ \t -> AppE2 t p e1 e2 } *<|> do { e1 <- expr ; e2 <- expr ; return $ \t -> App t e1 e2 } *<|> do { reserved "if" ; condE <- expr ; reserved "then" ; thenE <- expr ; reserved "else" ; elseE <- expr ; return $ \t -> If t condE thenE elseE } *<|> do { reservedOp "\\" ; v <- var ; reservedOp "->" ; e <- expr ; return $ \t -> Lam t v e } parseType :: String -> TypeQ parseType i = case parse typ "" i of Left e -> error $ show e Right t -> t parseExpr :: String -> ExprQ parseExpr i = case parse expr "" i of Left e -> error $ i ++ " " ++ show e Right t -> t antiExprExp :: ExprQ -> Maybe (TH.Q TH.Exp) antiExprExp (AntiE (AntiBind s)) = Just $ TH.varE (TH.mkName s) antiExprExp (AntiE AntiWild) = error "NKL.Quote: wildcard pattern (expr) used in expression quote" antiExprExp _ = Nothing antiExprPat :: ExprQ -> Maybe (TH.Q TH.Pat) antiExprPat (AntiE (AntiBind s)) = Just $ TH.varP (TH.mkName s) antiExprPat (AntiE AntiWild) = Just TH.wildP antiExprPat _ = Nothing antiTypeExp :: TypeQ -> Maybe (TH.Q TH.Exp) antiTypeExp (AntiT (AntiBind s)) = Just $ TH.varE (TH.mkName s) antiTypeExp (AntiT AntiWild) = error "NKL.Quote: wildcard pattern (type) used in expression quote" antiTypeExp _ = Nothing antiTypePat :: TypeQ -> Maybe (TH.Q TH.Pat) antiTypePat (AntiT (AntiBind s)) = Just $ TH.varP (TH.mkName s) antiTypePat (AntiT AntiWild) = Just TH.wildP antiTypePat _ = Nothing antiVarExp :: Var -> Maybe (TH.Q TH.Exp) antiVarExp (VarAntiBind s) = Just $ TH.varE (TH.mkName s) antiVarExp VarAntiWild = error "NKL.Quote: wildcard pattern (variable) used in expression quote" antiVarExp (VarLit _) = Nothing antiVarPat :: Var -> Maybe (TH.Q TH.Pat) antiVarPat (VarAntiBind s) = Just $ TH.varP (TH.mkName s) antiVarPat VarAntiWild = Just TH.wildP antiVarPat _ = Nothing quoteExprExp :: String -> TH.ExpQ quoteExprExp s = dataToExpQ (const Nothing `extQ` antiExprExp `extQ` antiTypeExp `extQ` antiVarExp) $ parseExpr s quoteExprPat :: String -> TH.PatQ quoteExprPat s = dataToPatQ (const Nothing `extQ` antiExprPat `extQ` antiTypePat `extQ` antiVarPat) $ parseExpr s quoteTypeExp :: String -> TH.ExpQ quoteTypeExp s = dataToExpQ (const Nothing `extQ` antiTypeExp) $ parseType s quoteTypePat :: String -> TH.PatQ quoteTypePat s = dataToPatQ (const Nothing `extQ` antiTypePat) $ parseType s ty :: QuasiQuoter ty = QuasiQuoter { quoteExp = quoteTypeExp , quotePat = quoteTypePat , quoteDec = error "Can't use NKL quasiquoter for declarations" , quoteType = error "Can't use NKL quasiquoter for types" } | A quasi quoter for NKL expressions nkl :: QuasiQuoter nkl = QuasiQuoter { quoteExp = quoteExprExp , quotePat = quoteExprPat , quoteDec = error "Can't use NKL quasiquoter for declarations" , quoteType = error "Can't use NKL quasiquoter for types" }
66e7f4678b6ee7f667d28f4cb38c400823ed396564f238b1237c230959b976c5
penpot/penpot
util_snap_data_test.cljs
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) KALEIDOS INC (ns frontend-tests.util-snap-data-test (:require [app.common.file-builder :as fb] [app.common.uuid :as uuid] [app.util.snap-data :as sd] [cljs.pprint :refer [pprint]] [cljs.test :as t :include-macros true])) (t/deftest test-create-index (t/testing "Create empty data" (let [data (sd/make-snap-data)] (t/is (some? data)))) (t/testing "Add empty page (only root-frame)" (let [page (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/get-current-page)) data (-> (sd/make-snap-data) (sd/add-page page))] (t/is (some? data)))) (t/testing "Create simple shape on root" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/create-rect {:x 0 :y 0 :width 100 :height 100})) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) result-x (sd/query data (:id page) uuid/zero :x [0 100])] (t/is (some? data)) 3 = left side , center and right side (t/is (= (count result-x) 3)) Left side : two points (t/is (= (first (nth result-x 0)) 0)) ;; Center one point (t/is (= (first (nth result-x 1)) 50)) Right side two points (t/is (= (first (nth result-x 2)) 100)))) (t/testing "Add page with single empty frame" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) ;; frame-id (:last-id file) data (-> (sd/make-snap-data) (sd/add-page page)) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 3)) (t/is (= (count result-frame-x) 3)))) (t/testing "Add page with some shapes inside frames" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100})) frame-id (:last-id file) file (-> file (fb/create-rect {:x 25 :y 25 :width 50 :height 50}) (fb/close-artboard)) page (fb/get-current-page file) ;; frame-id (:last-id file) data (-> (sd/make-snap-data) (sd/add-page page)) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 3)) (t/is (= (count result-frame-x) 5)))) (t/testing "Add a global guide" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-guide {:position 50 :axis :x}) (fb/add-artboard {:x 200 :y 200 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) ;; frame-id (:last-id file) data (-> (sd/make-snap-data) (sd/add-page page)) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100]) result-frame-y (sd/query data (:id page) frame-id :y [0 100])] (t/is (some? data)) ;; We can snap in the root (t/is (= (count result-zero-x) 1)) (t/is (= (count result-zero-y) 0)) ;; We can snap in the frame (t/is (= (count result-frame-x) 1)) (t/is (= (count result-frame-y) 0)))) (t/testing "Add a frame guide" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 200 :y 200 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) file (-> file (fb/add-guide {:position 50 :axis :x :frame-id frame-id})) page (fb/get-current-page file) ;; frame-id (:last-id file) data (-> (sd/make-snap-data) (sd/add-page page)) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100]) result-frame-y (sd/query data (:id page) frame-id :y [0 100])] (t/is (some? data)) ;; We can snap in the root (t/is (= (count result-zero-x) 0)) (t/is (= (count result-zero-y) 0)) ;; We can snap in the frame (t/is (= (count result-frame-x) 1)) (t/is (= (count result-frame-y) 0))))) (t/deftest test-update-index (t/testing "Create frame on root and then remove it." (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100}) (fb/close-artboard)) shape-id (:last-id file) page (fb/get-current-page file) ;; frame-id (:last-id file) data (-> (sd/make-snap-data) (sd/add-page page)) file (-> file (fb/delete-object shape-id)) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-x (sd/query data (:id page) uuid/zero :x [0 100]) result-y (sd/query data (:id page) uuid/zero :y [0 100])] (t/is (some? data)) (t/is (= (count result-x) 0)) (t/is (= (count result-y) 0)))) (t/testing "Create simple shape on root. Then remove it" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/create-rect {:x 0 :y 0 :width 100 :height 100})) shape-id (:last-id file) page (fb/get-current-page file) ;; frame-id (:last-id file) data (-> (sd/make-snap-data) (sd/add-page page)) file (fb/delete-object file shape-id) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-x (sd/query data (:id page) uuid/zero :x [0 100]) result-y (sd/query data (:id page) uuid/zero :y [0 100])] (t/is (some? data)) (t/is (= (count result-x) 0)) (t/is (= (count result-y) 0)))) (t/testing "Create shape inside frame, then remove it" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100})) frame-id (:last-id file) file (fb/create-rect file {:x 25 :y 25 :width 50 :height 50}) shape-id (:last-id file) file (fb/close-artboard file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) file (fb/delete-object file shape-id) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 3)) (t/is (= (count result-frame-x) 3)))) (t/testing "Create global guide then remove it" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-guide {:position 50 :axis :x})) guide-id (:last-id file) file (-> (fb/add-artboard file {:x 200 :y 200 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) new-page (-> (fb/delete-guide file guide-id) (fb/get-current-page)) data (sd/update-page data page new-page) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100]) result-frame-y (sd/query data (:id page) frame-id :y [0 100])] (t/is (some? data)) ;; We can snap in the root (t/is (= (count result-zero-x) 0)) (t/is (= (count result-zero-y) 0)) ;; We can snap in the frame (t/is (= (count result-frame-x) 0)) (t/is (= (count result-frame-y) 0)))) (t/testing "Create frame guide then remove it" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 200 :y 200 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) file (fb/add-guide file {:position 50 :axis :x :frame-id frame-id}) guide-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) new-page (-> (fb/delete-guide file guide-id) (fb/get-current-page)) data (sd/update-page data page new-page) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100]) result-frame-y (sd/query data (:id page) frame-id :y [0 100])] (t/is (some? data)) ;; We can snap in the root (t/is (= (count result-zero-x) 0)) (t/is (= (count result-zero-y) 0)) ;; We can snap in the frame (t/is (= (count result-frame-x) 0)) (t/is (= (count result-frame-y) 0)))) (t/testing "Update frame coordinates" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) frame (fb/lookup-shape file frame-id) new-frame (-> frame (assoc :x 200 :y 200)) file (fb/update-object file frame new-frame) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-zero-x-1 (sd/query data (:id page) uuid/zero :x [0 100]) result-frame-x-1 (sd/query data (:id page) frame-id :x [0 100]) result-zero-x-2 (sd/query data (:id page) uuid/zero :x [200 300]) result-frame-x-2 (sd/query data (:id page) frame-id :x [200 300])] (t/is (some? data)) (t/is (= (count result-zero-x-1) 0)) (t/is (= (count result-frame-x-1) 0)) (t/is (= (count result-zero-x-2) 3)) (t/is (= (count result-frame-x-2) 3)))) (t/testing "Update shape coordinates" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/create-rect {:x 0 :y 0 :width 100 :height 100})) shape-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) shape (fb/lookup-shape file shape-id) new-shape (-> shape (assoc :x 200 :y 200)) file (fb/update-object file shape new-shape) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-zero-x-1 (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-x-2 (sd/query data (:id page) uuid/zero :x [200 300])] (t/is (some? data)) (t/is (= (count result-zero-x-1) 0)) (t/is (= (count result-zero-x-2) 3)))) (t/testing "Update global guide" (let [guide {:position 50 :axis :x} file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-guide guide)) guide-id (:last-id file) guide (assoc guide :id guide-id) file (-> (fb/add-artboard file {:x 500 :y 500 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) new-page (-> (fb/update-guide file (assoc guide :position 150)) (fb/get-current-page)) data (sd/update-page data page new-page) result-zero-x-1 (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y-1 (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x-1 (sd/query data (:id page) frame-id :x [0 100]) result-frame-y-1 (sd/query data (:id page) frame-id :y [0 100]) result-zero-x-2 (sd/query data (:id page) uuid/zero :x [0 200]) result-zero-y-2 (sd/query data (:id page) uuid/zero :y [0 200]) result-frame-x-2 (sd/query data (:id page) frame-id :x [0 200]) result-frame-y-2 (sd/query data (:id page) frame-id :y [0 200]) ] (t/is (some? data)) (t/is (= (count result-zero-x-1) 0)) (t/is (= (count result-zero-y-1) 0)) (t/is (= (count result-frame-x-1) 0)) (t/is (= (count result-frame-y-1) 0)) (t/is (= (count result-zero-x-2) 1)) (t/is (= (count result-zero-y-2) 0)) (t/is (= (count result-frame-x-2) 1)) (t/is (= (count result-frame-y-2) 0)))))
null
https://raw.githubusercontent.com/penpot/penpot/2ea81c0114fb13ece945b7082aff0bcd7383e563/frontend/test/frontend_tests/util_snap_data_test.cljs
clojure
Copyright (c) KALEIDOS INC Center one point frame-id (:last-id file) frame-id (:last-id file) frame-id (:last-id file) We can snap in the root We can snap in the frame frame-id (:last-id file) We can snap in the root We can snap in the frame frame-id (:last-id file) frame-id (:last-id file) We can snap in the root We can snap in the frame We can snap in the root We can snap in the frame
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 /. (ns frontend-tests.util-snap-data-test (:require [app.common.file-builder :as fb] [app.common.uuid :as uuid] [app.util.snap-data :as sd] [cljs.pprint :refer [pprint]] [cljs.test :as t :include-macros true])) (t/deftest test-create-index (t/testing "Create empty data" (let [data (sd/make-snap-data)] (t/is (some? data)))) (t/testing "Add empty page (only root-frame)" (let [page (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/get-current-page)) data (-> (sd/make-snap-data) (sd/add-page page))] (t/is (some? data)))) (t/testing "Create simple shape on root" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/create-rect {:x 0 :y 0 :width 100 :height 100})) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) result-x (sd/query data (:id page) uuid/zero :x [0 100])] (t/is (some? data)) 3 = left side , center and right side (t/is (= (count result-x) 3)) Left side : two points (t/is (= (first (nth result-x 0)) 0)) (t/is (= (first (nth result-x 1)) 50)) Right side two points (t/is (= (first (nth result-x 2)) 100)))) (t/testing "Add page with single empty frame" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 3)) (t/is (= (count result-frame-x) 3)))) (t/testing "Add page with some shapes inside frames" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100})) frame-id (:last-id file) file (-> file (fb/create-rect {:x 25 :y 25 :width 50 :height 50}) (fb/close-artboard)) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 3)) (t/is (= (count result-frame-x) 5)))) (t/testing "Add a global guide" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-guide {:position 50 :axis :x}) (fb/add-artboard {:x 200 :y 200 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100]) result-frame-y (sd/query data (:id page) frame-id :y [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 1)) (t/is (= (count result-zero-y) 0)) (t/is (= (count result-frame-x) 1)) (t/is (= (count result-frame-y) 0)))) (t/testing "Add a frame guide" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 200 :y 200 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) file (-> file (fb/add-guide {:position 50 :axis :x :frame-id frame-id})) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100]) result-frame-y (sd/query data (:id page) frame-id :y [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 0)) (t/is (= (count result-zero-y) 0)) (t/is (= (count result-frame-x) 1)) (t/is (= (count result-frame-y) 0))))) (t/deftest test-update-index (t/testing "Create frame on root and then remove it." (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100}) (fb/close-artboard)) shape-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) file (-> file (fb/delete-object shape-id)) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-x (sd/query data (:id page) uuid/zero :x [0 100]) result-y (sd/query data (:id page) uuid/zero :y [0 100])] (t/is (some? data)) (t/is (= (count result-x) 0)) (t/is (= (count result-y) 0)))) (t/testing "Create simple shape on root. Then remove it" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/create-rect {:x 0 :y 0 :width 100 :height 100})) shape-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) file (fb/delete-object file shape-id) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-x (sd/query data (:id page) uuid/zero :x [0 100]) result-y (sd/query data (:id page) uuid/zero :y [0 100])] (t/is (some? data)) (t/is (= (count result-x) 0)) (t/is (= (count result-y) 0)))) (t/testing "Create shape inside frame, then remove it" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100})) frame-id (:last-id file) file (fb/create-rect file {:x 25 :y 25 :width 50 :height 50}) shape-id (:last-id file) file (fb/close-artboard file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) file (fb/delete-object file shape-id) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 3)) (t/is (= (count result-frame-x) 3)))) (t/testing "Create global guide then remove it" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-guide {:position 50 :axis :x})) guide-id (:last-id file) file (-> (fb/add-artboard file {:x 200 :y 200 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) new-page (-> (fb/delete-guide file guide-id) (fb/get-current-page)) data (sd/update-page data page new-page) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100]) result-frame-y (sd/query data (:id page) frame-id :y [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 0)) (t/is (= (count result-zero-y) 0)) (t/is (= (count result-frame-x) 0)) (t/is (= (count result-frame-y) 0)))) (t/testing "Create frame guide then remove it" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 200 :y 200 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) file (fb/add-guide file {:position 50 :axis :x :frame-id frame-id}) guide-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) new-page (-> (fb/delete-guide file guide-id) (fb/get-current-page)) data (sd/update-page data page new-page) result-zero-x (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x (sd/query data (:id page) frame-id :x [0 100]) result-frame-y (sd/query data (:id page) frame-id :y [0 100])] (t/is (some? data)) (t/is (= (count result-zero-x) 0)) (t/is (= (count result-zero-y) 0)) (t/is (= (count result-frame-x) 0)) (t/is (= (count result-frame-y) 0)))) (t/testing "Update frame coordinates" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-artboard {:x 0 :y 0 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) frame (fb/lookup-shape file frame-id) new-frame (-> frame (assoc :x 200 :y 200)) file (fb/update-object file frame new-frame) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-zero-x-1 (sd/query data (:id page) uuid/zero :x [0 100]) result-frame-x-1 (sd/query data (:id page) frame-id :x [0 100]) result-zero-x-2 (sd/query data (:id page) uuid/zero :x [200 300]) result-frame-x-2 (sd/query data (:id page) frame-id :x [200 300])] (t/is (some? data)) (t/is (= (count result-zero-x-1) 0)) (t/is (= (count result-frame-x-1) 0)) (t/is (= (count result-zero-x-2) 3)) (t/is (= (count result-frame-x-2) 3)))) (t/testing "Update shape coordinates" (let [file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/create-rect {:x 0 :y 0 :width 100 :height 100})) shape-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) shape (fb/lookup-shape file shape-id) new-shape (-> shape (assoc :x 200 :y 200)) file (fb/update-object file shape new-shape) new-page (fb/get-current-page file) data (sd/update-page data page new-page) result-zero-x-1 (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-x-2 (sd/query data (:id page) uuid/zero :x [200 300])] (t/is (some? data)) (t/is (= (count result-zero-x-1) 0)) (t/is (= (count result-zero-x-2) 3)))) (t/testing "Update global guide" (let [guide {:position 50 :axis :x} file (-> (fb/create-file "Test") (fb/add-page {:name "Page 1"}) (fb/add-guide guide)) guide-id (:last-id file) guide (assoc guide :id guide-id) file (-> (fb/add-artboard file {:x 500 :y 500 :width 100 :height 100}) (fb/close-artboard)) frame-id (:last-id file) page (fb/get-current-page file) data (-> (sd/make-snap-data) (sd/add-page page)) new-page (-> (fb/update-guide file (assoc guide :position 150)) (fb/get-current-page)) data (sd/update-page data page new-page) result-zero-x-1 (sd/query data (:id page) uuid/zero :x [0 100]) result-zero-y-1 (sd/query data (:id page) uuid/zero :y [0 100]) result-frame-x-1 (sd/query data (:id page) frame-id :x [0 100]) result-frame-y-1 (sd/query data (:id page) frame-id :y [0 100]) result-zero-x-2 (sd/query data (:id page) uuid/zero :x [0 200]) result-zero-y-2 (sd/query data (:id page) uuid/zero :y [0 200]) result-frame-x-2 (sd/query data (:id page) frame-id :x [0 200]) result-frame-y-2 (sd/query data (:id page) frame-id :y [0 200]) ] (t/is (some? data)) (t/is (= (count result-zero-x-1) 0)) (t/is (= (count result-zero-y-1) 0)) (t/is (= (count result-frame-x-1) 0)) (t/is (= (count result-frame-y-1) 0)) (t/is (= (count result-zero-x-2) 1)) (t/is (= (count result-zero-y-2) 0)) (t/is (= (count result-frame-x-2) 1)) (t/is (= (count result-frame-y-2) 0)))))
947e9e68514ba5ae0a89714705f761fcf069782f148afdb6242a2775f06790a3
cloudant-labs/couchdb-erlfdb
erlfdb_03_transaction_options_test.erl
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(erlfdb_03_transaction_options_test). -include_lib("eunit/include/eunit.hrl"). get_approximate_tx_size_test() -> Db1 = erlfdb_util:get_test_db(), erlfdb:transactional(Db1, fun(Tx) -> ok = erlfdb:set(Tx, gen(10), gen(5000)), TxSize1 = erlfdb:wait(erlfdb:get_approximate_size(Tx)), ?assert(TxSize1 > 5000 andalso TxSize1 < 6000), ok = erlfdb:set(Tx, gen(10), gen(5000)), TxSize2 = erlfdb:wait(erlfdb:get_approximate_size(Tx)), ?assert(TxSize2 > 10000) end). size_limit_test() -> Db1 = erlfdb_util:get_test_db(), ?assertError({erlfdb_error, 2101}, erlfdb:transactional(Db1, fun(Tx) -> erlfdb:set_option(Tx, size_limit, 10000), erlfdb:set(Tx, gen(10), gen(11000)) end)). writes_allowed_test() -> Db1 = erlfdb_util:get_test_db(), ?assertError(writes_not_allowed, erlfdb:transactional(Db1, fun(Tx) -> ?assert(erlfdb:get_writes_allowed(Tx)), erlfdb:set_option(Tx, disallow_writes), ?assert(not erlfdb:get_writes_allowed(Tx)), erlfdb:set_option(Tx, allow_writes), ?assert(erlfdb:get_writes_allowed(Tx)), erlfdb:set_option(Tx, disallow_writes), erlfdb:set(Tx, gen(10), gen(10)) end)). once_writes_happend_cannot_disallow_them_test() -> Db1 = erlfdb_util:get_test_db(), ?assertError(badarg, erlfdb:transactional(Db1, fun(Tx) -> ok = erlfdb:set(Tx, gen(10), gen(10)), erlfdb:set_option(Tx, disallow_writes) end)). gen(Size) -> crypto:strong_rand_bytes(Size).
null
https://raw.githubusercontent.com/cloudant-labs/couchdb-erlfdb/510664facbc28c946960db2d12b3baf33923f4ea/test/erlfdb_03_transaction_options_test.erl
erlang
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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not distributed under the License is distributed on an " AS IS " BASIS , WITHOUT -module(erlfdb_03_transaction_options_test). -include_lib("eunit/include/eunit.hrl"). get_approximate_tx_size_test() -> Db1 = erlfdb_util:get_test_db(), erlfdb:transactional(Db1, fun(Tx) -> ok = erlfdb:set(Tx, gen(10), gen(5000)), TxSize1 = erlfdb:wait(erlfdb:get_approximate_size(Tx)), ?assert(TxSize1 > 5000 andalso TxSize1 < 6000), ok = erlfdb:set(Tx, gen(10), gen(5000)), TxSize2 = erlfdb:wait(erlfdb:get_approximate_size(Tx)), ?assert(TxSize2 > 10000) end). size_limit_test() -> Db1 = erlfdb_util:get_test_db(), ?assertError({erlfdb_error, 2101}, erlfdb:transactional(Db1, fun(Tx) -> erlfdb:set_option(Tx, size_limit, 10000), erlfdb:set(Tx, gen(10), gen(11000)) end)). writes_allowed_test() -> Db1 = erlfdb_util:get_test_db(), ?assertError(writes_not_allowed, erlfdb:transactional(Db1, fun(Tx) -> ?assert(erlfdb:get_writes_allowed(Tx)), erlfdb:set_option(Tx, disallow_writes), ?assert(not erlfdb:get_writes_allowed(Tx)), erlfdb:set_option(Tx, allow_writes), ?assert(erlfdb:get_writes_allowed(Tx)), erlfdb:set_option(Tx, disallow_writes), erlfdb:set(Tx, gen(10), gen(10)) end)). once_writes_happend_cannot_disallow_them_test() -> Db1 = erlfdb_util:get_test_db(), ?assertError(badarg, erlfdb:transactional(Db1, fun(Tx) -> ok = erlfdb:set(Tx, gen(10), gen(10)), erlfdb:set_option(Tx, disallow_writes) end)). gen(Size) -> crypto:strong_rand_bytes(Size).
7d881d97683112a22e36ae01377a8e738db25fa0a084908df23c51439ca516bd
ocaml/opam
opamAdminCommand.ml
(**************************************************************************) (* *) Copyright 2012 - 2020 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. *) (* *) (**************************************************************************) open OpamTypes open OpamProcess.Job.Op open OpamStateTypes open Cmdliner type command = unit Cmdliner.Term.t * Cmdliner.Cmd.info let checked_repo_root () = let repo_root = OpamFilename.cwd () in if not (OpamFilename.exists_dir (OpamRepositoryPath.packages_dir repo_root)) then OpamConsole.error_and_exit `Bad_arguments "No repository found in current directory.\n\ Please make sure there is a \"packages%s\" directory" OpamArg.dir_sep; repo_root let global_options cli = let apply_cli options = { options with OpamArg.cli = options.OpamArg.cli} in Term.(const apply_cli $ OpamArg.global_options cli) let admin_command_doc = "Tools for repository administrators" let admin_command_man = [ `S Manpage.s_description; `P (Printf.sprintf "This command can perform various actions on repositories in the opam \ format. It is expected to be run from the root of a repository, i.e. a \ directory containing a 'repo' file and a subdirectory 'packages%s' \ holding package definition within subdirectories. A 'compilers%s' \ subdirectory (opam repository format version < 2) will also be used by \ the $(b,upgrade-format) subcommand." OpamArg.dir_sep OpamArg.dir_sep) ] let index_command_doc = "Generate an inclusive index file for serving over HTTP." let index_command cli = let command = "index" in let doc = index_command_doc in let man = [ `S Manpage.s_description; `P "An opam repository can be served over HTTP or HTTPS using any web \ server. To that purpose, an inclusive index needs to be generated \ first: this command generates the files the opam client will expect \ when fetching from an HTTP remote, and should be run after any changes \ are done to the contents of the repository." ] in let urls_txt_arg cli = OpamArg.mk_vflag ~cli `minimal_urls_txt [ OpamArg.cli_original, `no_urls_txt, ["no-urls-txt"], "Don't generate a 'urls.txt' file. That index file is no longer \ needed from opam 2.0 on, but is still used by older versions."; OpamArg.cli_original, `full_urls_txt, ["full-urls-txt"], "Generate an inclusive 'urls.txt', for a repository that will be \ used by opam versions earlier than 2.0."; OpamArg.cli_original, `minimal_urls_txt, ["minimal-urls-txt"], "Generate a minimal 'urls.txt' file, that only includes the 'repo' \ file. This allows opam versions earlier than 2.0 to read that file, \ and be properly redirected to a repository dedicated to their \ version, assuming a suitable 'redirect:' field is defined, instead \ of failing. This is the default."; ] in let cmd global_options urls_txt () = OpamArg.apply_global_options cli global_options; let repo_root = checked_repo_root () in let repo_file = OpamRepositoryPath.repo repo_root in let repo_def = match OpamFile.Repo.read_opt repo_file with | None -> OpamConsole.warning "No \"repo\" file found. Creating a minimal one."; OpamFile.Repo.create () | Some r -> r in let repo_stamp = let date () = let t = Unix.gmtime (Unix.time ()) in Printf.sprintf "%04d-%02d-%02d %02d:%02d" (t.Unix.tm_year + 1900) (t.Unix.tm_mon +1) t.Unix.tm_mday t.Unix.tm_hour t.Unix.tm_min in match OpamUrl.guess_version_control (OpamFilename.Dir.to_string repo_root) with | None -> date () | Some vcs -> let module VCS = (val OpamRepository.find_backend_by_kind vcs) in match OpamProcess.Job.run (VCS.revision repo_root) with | None -> date () | Some hash -> OpamPackage.Version.to_string hash in let repo_def = OpamFile.Repo.with_stamp repo_stamp repo_def in OpamFile.Repo.write repo_file repo_def; if urls_txt <> `no_urls_txt then (OpamConsole.msg "Generating urls.txt...\n"; OpamFilename.of_string "repo" :: (if urls_txt = `full_urls_txt then OpamFilename.rec_files OpamFilename.Op.(repo_root / "compilers") @ OpamFilename.rec_files (OpamRepositoryPath.packages_dir repo_root) else []) |> List.fold_left (fun set f -> if not (OpamFilename.exists f) then set else let attr = OpamFilename.to_attribute repo_root f in OpamFilename.Attribute.Set.add attr set ) OpamFilename.Attribute.Set.empty |> OpamFile.File_attributes.write (OpamFile.make (OpamFilename.of_string "urls.txt"))); OpamConsole.msg "Generating index.tar.gz...\n"; OpamHTTP.make_index_tar_gz repo_root; OpamConsole.msg "Done.\n"; in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ urls_txt_arg cli) let cache_urls repo_root repo_def = let global_dl_cache = OpamStd.Option.Op.(OpamStateConfig.(load ~lock_kind:`Lock_read !r.root_dir) +! OpamFile.Config.empty) |> OpamFile.Config.dl_cache in let repo_dl_cache = OpamStd.List.filter_map (fun rel -> if OpamStd.String.contains ~sub:"://" rel then OpamUrl.parse_opt ~handle_suffix:false rel else Some OpamUrl.Op.(OpamUrl.of_string (OpamFilename.Dir.to_string repo_root) / rel)) (OpamFile.Repo.dl_cache repo_def) in repo_dl_cache @ global_dl_cache Downloads all urls of the given package to the given let package_files_to_cache repo_root cache_dir cache_urls ~recheck ?link (nv, prefix) = match OpamFileTools.read_opam (OpamRepositoryPath.packages repo_root prefix nv) with | None -> Done (OpamPackage.Map.empty) | Some opam -> let add_to_cache ?name urlf errors = let label = OpamPackage.to_string nv ^ OpamStd.Option.to_string ((^) "/") name in let checksums = OpamHash.sort (OpamFile.URL.checksum urlf) in match checksums with | [] -> OpamConsole.warning "[%s] no checksum, not caching" (OpamConsole.colorise `green label); Done errors | best_chks :: _ -> let cache_file = OpamRepository.cache_file cache_dir best_chks in let error_opt = if not recheck && OpamFilename.exists cache_file then Done None else OpamRepository.pull_file_to_cache label ~cache_urls ~cache_dir checksums (OpamFile.URL.url urlf :: OpamFile.URL.mirrors urlf) @@| fun r -> match OpamRepository.report_fetch_result nv r with | Not_available (_,m) -> Some m | Up_to_date () | Result () -> None in error_opt @@| function | Some m -> OpamPackage.Map.update nv (fun l -> m::l) [] errors | None -> OpamStd.Option.iter (fun link_dir -> let name = OpamStd.Option.default (OpamUrl.basename (OpamFile.URL.url urlf)) name in let link = OpamFilename.Op.(link_dir / OpamPackage.to_string nv // name) in OpamFilename.link ~relative:true ~target:cache_file ~link) link; errors in let urls = (match OpamFile.OPAM.url opam with | None -> [] | Some urlf -> [add_to_cache urlf]) @ (List.map (fun (name,urlf) -> add_to_cache ~name:(OpamFilename.Base.to_string name) urlf) (OpamFile.OPAM.extra_sources opam)) in OpamProcess.Job.seq urls OpamPackage.Map.empty let cache_command_doc = "Fills a local cache of package archives" let cache_command cli = let command = "cache" in let doc = cache_command_doc in let man = [ `S Manpage.s_description; `P "Downloads the archives for all packages to fill a local cache, that \ can be used when serving the repository." ] in let cache_dir_arg = Arg.(value & pos 0 OpamArg.dirname (OpamFilename.Dir.of_string "./cache") & info [] ~docv:"DIR" ~doc: "Name of the cache directory to use.") in let no_repo_update_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["no-repo-update";"n"] "Don't check, create or update the 'repo' file to point to the \ generated cache ('archive-mirrors:' field)." in let link_arg = OpamArg.mk_opt ~cli OpamArg.cli_original ["link"] "DIR" (Printf.sprintf "Create reverse symbolic links to the archives within $(i,DIR), in \ the form $(b,DIR%sPKG.VERSION%sFILENAME)." OpamArg.dir_sep OpamArg.dir_sep) Arg.(some OpamArg.dirname) None in let jobs_arg = OpamArg.mk_opt ~cli OpamArg.cli_original ["jobs"; "j"] "JOBS" "Number of parallel downloads" OpamArg.positive_integer 8 in let recheck_arg = OpamArg.mk_flag ~cli OpamArg.(cli_from cli2_2) ["check-all"; "c"] "Run a full integrity check on the existing cache. If this is not set, \ only missing cache files are handled." in let cmd global_options cache_dir no_repo_update link jobs recheck () = OpamArg.apply_global_options cli global_options; this option was the default until 2.1 let recheck = recheck || OpamCLIVersion.Op.(cli @< OpamArg.cli2_2) in let repo_root = checked_repo_root () in let repo_file = OpamRepositoryPath.repo repo_root in let repo_def = OpamFile.Repo.safe_read repo_file in let pkg_prefixes = OpamRepository.packages_with_prefixes repo_root in let cache_urls = cache_urls repo_root repo_def in let errors = OpamParallel.reduce ~jobs ~nil:OpamPackage.Map.empty ~merge:(OpamPackage.Map.union (fun a _ -> a)) ~command:(package_files_to_cache repo_root cache_dir cache_urls ~recheck ?link) (List.sort (fun (nv1,_) (nv2,_) -> (* Some pseudo-randomisation to avoid downloading all files from the same host simultaneously *) match compare (Hashtbl.hash nv1) (Hashtbl.hash nv2) with | 0 -> compare nv1 nv2 | n -> n) (OpamPackage.Map.bindings pkg_prefixes)) in let cache_dir_url = OpamFilename.remove_prefix_dir repo_root cache_dir in if not no_repo_update then if not (List.mem cache_dir_url (OpamFile.Repo.dl_cache repo_def)) then (OpamConsole.msg "Adding %s to %s...\n" cache_dir_url (OpamFile.to_string repo_file); OpamFile.Repo.write repo_file (OpamFile.Repo.with_dl_cache (cache_dir_url :: OpamFile.Repo.dl_cache repo_def) repo_def)); if not (OpamPackage.Map.is_empty errors) then ( OpamConsole.error "Got some errors while processing: %s" (OpamStd.List.concat_map ", " OpamPackage.to_string (OpamPackage.Map.keys errors)); OpamConsole.errmsg "%s" (OpamStd.Format.itemize (fun (nv,el) -> Printf.sprintf "[%s] %s" (OpamPackage.to_string nv) (String.concat "\n" el)) (OpamPackage.Map.bindings errors)) ); OpamConsole.msg "Done.\n"; in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ cache_dir_arg $ no_repo_update_arg $ link_arg $ jobs_arg $ recheck_arg) let add_hashes_command_doc = "Add archive hashes to an opam repository." let add_hashes_command cli = let command = "add-hashes" in let doc = add_hashes_command_doc in let cache_dir = OpamFilename.Dir.of_string "~/.cache/opam-hash-cache" in let man = [ `S Manpage.s_description; `P (Printf.sprintf "This command scans through package definitions, and add hashes as \ requested (fetching the archives if required). A cache is generated \ in %s for subsequent runs." (OpamArg.escape_path (OpamFilename.Dir.to_string cache_dir))); ] in let hash_kinds = [`MD5; `SHA256; `SHA512] in let hash_types_arg = OpamArg.nonempty_arg_list "HASH_ALGO" "The hash, or hashes to be added" (Arg.enum (List.map (fun k -> OpamHash.string_of_kind k, k) hash_kinds)) in let packages = OpamArg.mk_opt ~cli OpamArg.(cli_from cli2_1) ["p";"packages"] "PACKAGES" "Only add hashes for the given packages" Arg.(list OpamArg.package) [] in let replace_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["replace"] "Replace the existing hashes rather than adding to them" in let hash_tables = let t = Hashtbl.create (List.length hash_kinds) in List.iter (fun k1 -> List.iter (fun k2 -> if k1 <> k2 then ( let cache_file : string list list OpamFile.t = OpamFile.make @@ OpamFilename.Op.( cache_dir // (OpamHash.string_of_kind k1 ^ "_to_" ^ OpamHash.string_of_kind k2)) in let t_mapping = Hashtbl.create 187 in (OpamStd.Option.default [] (OpamFile.Lines.read_opt cache_file) |> List.iter @@ function | [src; dst] -> Hashtbl.add t_mapping (OpamHash.of_string src) (OpamHash.of_string dst) | _ -> failwith ("Bad cache at "^OpamFile.to_string cache_file)); Hashtbl.add t (k1,k2) (cache_file, t_mapping); )) hash_kinds ) hash_kinds; t in let save_hashes () = Hashtbl.iter (fun _ (file, tbl) -> Hashtbl.fold (fun src dst l -> [OpamHash.to_string src; OpamHash.to_string dst]::l) tbl [] |> fun lines -> try OpamFile.Lines.write file lines with e -> OpamStd.Exn.fatal e; OpamConsole.log "ADMIN" "Could not write hash cache to %s, skipping (%s)" (OpamFile.to_string file) (Printexc.to_string e)) hash_tables in let additions_count = ref 0 in let get_hash cache_urls kind known_hashes url = let found = List.fold_left (fun result hash -> match result with | None -> let known_kind = OpamHash.kind hash in let _, tbl = Hashtbl.find hash_tables (known_kind, kind) in (try Some (Hashtbl.find tbl hash) with Not_found -> None) | some -> some) None known_hashes in match found with | Some h -> Some h | None -> let h = OpamProcess.Job.run @@ OpamFilename.with_tmp_dir_job @@ fun dir -> let f = OpamFilename.Op.(dir // OpamUrl.basename url) in OpamProcess.Job.ignore_errors ~default:None (fun () -> OpamRepository.pull_file (OpamUrl.to_string url) ~cache_dir:(OpamRepositoryPath.download_cache OpamStateConfig.(!r.root_dir)) ~cache_urls f known_hashes [url] @@| function | Result () | Up_to_date () -> OpamHash.compute ~kind (OpamFilename.to_string f) |> OpamStd.Option.some | Not_available _ -> None) in (match h with | Some h -> List.iter (fun h0 -> Hashtbl.replace (snd (Hashtbl.find hash_tables (OpamHash.kind h0, kind))) h0 h ) known_hashes; incr additions_count; if !additions_count mod 20 = 0 then save_hashes () | None -> ()); h in let cmd global_options hash_types replace packages () = OpamArg.apply_global_options cli global_options; let repo_root = checked_repo_root () in let cache_urls = cache_urls repo_root (OpamFile.Repo.safe_read (OpamRepositoryPath.repo repo_root)) in let pkg_prefixes = let pkgs_map = OpamRepository.packages_with_prefixes repo_root in if packages = [] then pkgs_map else (let pkgs_map, missing_pkgs = List.fold_left (fun ((map: string option OpamPackage.Map.t),error) (n,vo)-> match vo with | Some v -> let nv = OpamPackage.create n v in (match OpamPackage.Map.find_opt nv pkgs_map with | Some pre ->( OpamPackage.Map.add nv pre map), error | None -> map, (n,vo)::error) | None -> let n_map = OpamPackage.packages_of_name_map pkgs_map n in if OpamPackage.Map.is_empty n_map then map, (n,vo)::error else (OpamPackage.Map.union (fun _nv _nv' -> assert false) n_map map), error ) (OpamPackage.Map.empty, []) packages in if missing_pkgs <> [] then OpamConsole.warning "Not found package%s %s. Ignoring them." (if List.length missing_pkgs = 1 then "" else "s") (OpamStd.List.concat_map ~left:"" ~right:"" ~last_sep:" and " ", " (fun (n,vo) -> OpamConsole.colorise `underline (match vo with | Some v -> OpamPackage.to_string (OpamPackage.create n v) | None -> OpamPackage.Name.to_string n)) missing_pkgs); pkgs_map) in let has_error = OpamPackage.Map.fold (fun nv prefix has_error -> let opam_file = OpamRepositoryPath.opam repo_root prefix nv in let opam = OpamFile.OPAM.read opam_file in let has_error = if OpamFile.exists (OpamRepositoryPath.url repo_root prefix nv) then (OpamConsole.warning "Not updating external URL file at %s" (OpamFile.to_string (OpamRepositoryPath.url repo_root prefix nv)); true) else has_error in let process_url has_error urlf = let hashes = OpamFile.URL.checksum urlf in let hashes = if replace then List.filter (fun h -> List.mem (OpamHash.kind h) hash_types) hashes else hashes in let has_error, hashes = List.fold_left (fun (has_error, hashes) kind -> if List.exists (fun h -> OpamHash.kind h = kind) hashes then has_error, hashes else match get_hash cache_urls kind hashes (OpamFile.URL.url urlf) with | Some h -> has_error, hashes @ [h] | None -> OpamConsole.error "Could not get hash for %s: %s" (OpamPackage.to_string nv) (OpamUrl.to_string (OpamFile.URL.url urlf)); true, hashes) (has_error, hashes) hash_types in has_error, OpamFile.URL.with_checksum hashes urlf in let has_error, url_opt = match OpamFile.OPAM.url opam with | None -> has_error, None | Some urlf -> let has_error, urlf = process_url has_error urlf in has_error, Some urlf in let has_error, extra_sources = List.fold_right (fun (basename, urlf) (has_error, acc) -> let has_error, urlf = process_url has_error urlf in has_error, (basename, urlf) :: acc) (OpamFile.OPAM.extra_sources opam) (has_error, []) in let opam1 = OpamFile.OPAM.with_url_opt url_opt opam in let opam1 = OpamFile.OPAM.with_extra_sources extra_sources opam1 in if opam1 <> opam then OpamFile.OPAM.write_with_preserved_format opam_file opam1; has_error ) pkg_prefixes false in save_hashes (); if has_error then OpamStd.Sys.exit_because `Sync_error else OpamStd.Sys.exit_because `Success in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ hash_types_arg $ replace_arg $ packages) let upgrade_command_doc = "Upgrades repository from earlier opam versions." let upgrade_command cli = let command = "upgrade" in let doc = upgrade_command_doc in let man = [ `S Manpage.s_description; `P (Printf.sprintf "This command reads repositories from earlier opam versions, and \ converts them to repositories suitable for the current opam version. \ Packages might be created or renamed, and any compilers defined in the \ old format ('compilers%s' directory) will be turned into packages, \ using a pre-defined hierarchy that assumes OCaml compilers." OpamArg.dir_sep) ] in let clear_cache_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["clear-cache"] (Printf.sprintf "Instead of running the upgrade, clear the cache of archive hashes (held \ in ~%s.cache), that is used to avoid re-downloading files to obtain \ their hashes at every run." OpamArg.dir_sep) in let create_mirror_arg = OpamArg.mk_opt ~cli OpamArg.cli_original ["m"; "mirror"] "URL" "Don't overwrite the current repository, but put an upgraded mirror in \ place in a subdirectory, with proper redirections. Needs the URL the \ repository will be served from to put in the redirects (older versions \ of opam don't understand relative redirects)." Arg.(some OpamArg.url) None in let cmd global_options clear_cache create_mirror () = OpamArg.apply_global_options cli global_options; if clear_cache then OpamAdminRepoUpgrade.clear_cache () else match create_mirror with | None -> OpamAdminRepoUpgrade.do_upgrade (OpamFilename.cwd ()); if OpamFilename.exists (OpamFilename.of_string "index.tar.gz") || OpamFilename.exists (OpamFilename.of_string "urls.txt") then OpamConsole.note "Indexes need updating: you should now run:\n\ \n\ \ opam admin index" | Some m -> OpamAdminRepoUpgrade.do_upgrade_mirror (OpamFilename.cwd ()) m in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ clear_cache_arg $ create_mirror_arg) let lint_command_doc = "Runs 'opam lint' and reports on a whole repository" let lint_command cli = let command = "lint" in let doc = lint_command_doc in let man = [ `S Manpage.s_description; `P "This command gathers linting results on all files in a repository. The \ warnings and errors to show or hide can be selected" ] in let short_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["s";"short"] "Print only packages and warning/error numbers, without explanations" in let list_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["list";"l"] "Only list package names, without warning details" in let include_arg = OpamArg.arg_list "INT" "Show only these warnings" OpamArg.positive_integer in let exclude_arg = OpamArg.mk_opt_all ~cli OpamArg.cli_original ["exclude";"x"] "INT" "Exclude the given warnings or errors" OpamArg.positive_integer in let ignore_arg = OpamArg.mk_opt_all ~cli OpamArg.cli_original ["ignore-packages";"i"] "INT" "Ignore any packages having one of these warnings or errors" OpamArg.positive_integer in let warn_error_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["warn-error";"W"] "Return failure on any warnings, not only on errors" in let cmd global_options short list incl excl ign warn_error () = OpamArg.apply_global_options cli global_options; let repo_root = OpamFilename.cwd () in if not (OpamFilename.exists_dir OpamFilename.Op.(repo_root / "packages")) then OpamConsole.error_and_exit `Bad_arguments "No repository found in current directory.\n\ Please make sure there is a \"packages\" directory"; let pkg_prefixes = OpamRepository.packages_with_prefixes repo_root in let ret = OpamPackage.Map.fold (fun nv prefix ret -> let opam_file = OpamRepositoryPath.opam repo_root prefix nv in let w, _ = OpamFileTools.lint_file ~handle_dirname:true opam_file in if List.exists (fun (n,_,_) -> List.mem n ign) w then ret else let w = List.filter (fun (n,_,_) -> (incl = [] || List.mem n incl) && not (List.mem n excl)) w in if w <> [] then if list then OpamConsole.msg "%s\n" (OpamPackage.to_string nv) else if short then OpamConsole.msg "%s %s\n" (OpamPackage.to_string nv) (OpamStd.List.concat_map " " (fun (n,k,_) -> OpamConsole.colorise (match k with `Warning -> `yellow | `Error -> `red) (string_of_int n)) w) else begin OpamConsole.carriage_delete (); OpamConsole.msg "In %s:\n%s\n" (OpamPackage.to_string nv) (OpamFileTools.warns_to_string w) end; ret && not (warn_error && w <> [] || List.exists (fun (_,k,_) -> k = `Error) w)) pkg_prefixes true in OpamStd.Sys.exit_because (if ret then `Success else `False) in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ short_arg $ list_arg $ include_arg $ exclude_arg $ ignore_arg $ warn_error_arg) let check_command_doc = "Runs some consistency checks on a repository" let check_command cli = let command = "check" in let doc = check_command_doc in let man = [ `S Manpage.s_description; `P "This command runs consistency checks on a repository, and prints a \ report to stdout. Checks include packages that are not installable \ (due e.g. to a missing dependency) and dependency cycles. The \ 'available' field is ignored for these checks, that is, all packages \ are supposed to be available. By default, all checks are run." ] in let ignore_test_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["ignore-test-doc";"i"] "By default, $(b,{with-test}) and $(b,{with-doc}) dependencies are \ included. This ignores them, and makes the test more tolerant." in let print_short_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["s";"short"] "Only output a list of uninstallable packages" in let installability_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["installability"] "Do the installability check (and disable the others by default)" in let cycles_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["cycles"] "Do the cycles check (and disable the others by default)" in let obsolete_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["obsolete"] "Analyse for obsolete packages" in let cmd global_options ignore_test print_short installability cycles obsolete () = OpamArg.apply_global_options cli global_options; let repo_root = checked_repo_root () in let installability, cycles, obsolete = if installability || cycles || obsolete then installability, cycles, obsolete else true, true, false in let pkgs, unav_roots, uninstallable, cycle_packages, obsolete = OpamAdminCheck.check ~quiet:print_short ~installability ~cycles ~obsolete ~ignore_test repo_root in let all_ok = OpamPackage.Set.is_empty uninstallable && OpamPackage.Set.is_empty cycle_packages && OpamPackage.Set.is_empty obsolete in let open OpamPackage.Set.Op in (if print_short then OpamConsole.msg "%s\n" (OpamStd.List.concat_map "\n" OpamPackage.to_string (OpamPackage.Set.elements (uninstallable ++ cycle_packages ++ obsolete))) else if all_ok then OpamConsole.msg "No issues detected on this repository's %d packages\n" (OpamPackage.Set.cardinal pkgs) else let pr set msg = if OpamPackage.Set.is_empty set then "" else Printf.sprintf "- %d %s\n" (OpamPackage.Set.cardinal set) msg in OpamConsole.msg "Summary: out of %d packages (%d distinct names)\n\ %s%s%s%s\n" (OpamPackage.Set.cardinal pkgs) (OpamPackage.Name.Set.cardinal (OpamPackage.names_of_packages pkgs)) (pr unav_roots "uninstallable roots") (pr (uninstallable -- unav_roots) "uninstallable dependent packages") (pr (cycle_packages -- uninstallable) "packages part of dependency cycles") (pr obsolete "obsolete packages")); OpamStd.Sys.exit_because (if all_ok then `Success else `False) in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ ignore_test_arg $ print_short_arg $ installability_arg $ cycles_arg $ obsolete_arg) let pattern_list_arg = OpamArg.arg_list "PATTERNS" "Package patterns with globs. matching against $(b,NAME) or \ $(b,NAME.VERSION)" Arg.string let env_arg cli = OpamArg.mk_opt ~cli OpamArg.cli_original ["environment"] "VAR=VALUE[,VAR=VALUE]" (Printf.sprintf "Use the given opam environment, in the form of a list of \ comma-separated 'var=value' bindings, when resolving variables. This \ is used e.g. when computing available packages: if undefined, \ availability of packages will be assumed as soon as it can not be \ resolved purely from globally defined variables. Note that, unless \ overridden, variables like 'root' or 'opam-version' may be taken \ from the current opam installation. What is defined in \ $(i,~%s.opam%sconfig) is always ignored." OpamArg.dir_sep OpamArg.dir_sep) Arg.(list string) [] let state_selection_arg cli = OpamArg.mk_vflag ~cli ~section:OpamArg.package_selection_section OpamListCommand.Available [ OpamArg.cli_original, OpamListCommand.Any, ["A";"all"], "Include all, even uninstalled or unavailable packages"; OpamArg.cli_original, OpamListCommand.Available, ["a";"available"], "List only packages that are available according to the defined \ $(b,environment). Without $(b,--environment), this will include \ any packages for which availability is not resolvable at this \ point."; OpamArg.cli_original, OpamListCommand.Installable, ["installable"], "List only packages that are installable according to the defined \ $(b,environment) (this calls the solver and may be more costly; \ a package depending on an unavailable one may be available, but \ is never installable)"; ] let get_virtual_switch_state repo_root env = let env = List.map (fun s -> match OpamStd.String.cut_at s '=' with | Some (var,value) -> OpamVariable.of_string var, S value | None -> OpamVariable.of_string s, B true) env in let repo = { repo_name = OpamRepositoryName.of_string "local"; repo_url = OpamUrl.empty; repo_trust = None; } in let repo_file = OpamRepositoryPath.repo repo_root in let repo_def = OpamFile.Repo.safe_read repo_file in let opams = OpamRepositoryState.load_opams_from_dir repo.repo_name repo_root in let gt = { global_lock = OpamSystem.lock_none; root = OpamStateConfig.(!r.root_dir); config = OpamStd.Option.Op.(OpamStateConfig.( load ~lock_kind:`Lock_read !r.root_dir) +! OpamFile.Config.empty); global_variables = OpamVariable.Map.empty; global_state_to_upgrade = { gtc_repo = false; gtc_switch = false; }; } in let singl x = OpamRepositoryName.Map.singleton repo.repo_name x in let repos_tmp = let t = Hashtbl.create 1 in Hashtbl.add t repo.repo_name (lazy repo_root); t in let rt = { repos_global = gt; repos_lock = OpamSystem.lock_none; repositories = singl repo; repos_definitions = singl repo_def; repo_opams = singl opams; repos_tmp; } in let gt = {gt with global_variables = OpamVariable.Map.of_list @@ List.map (fun (var, value) -> var, (lazy (Some value), "Manually defined")) env } in OpamSwitchState.load_virtual ~repos_list:[repo.repo_name] ~avail_default:(env = []) gt rt let or_arg cli = OpamArg.mk_flag ~cli OpamArg.cli_original ~section:OpamArg.package_selection_section ["or"] "Instead of selecting packages that match $(i,all) the \ criteria, select packages that match $(i,any) of them" let list_command_doc = "Lists packages from a repository" let list_command cli = let command = "list" in let doc = list_command_doc in let man = [ `S Manpage.s_description; `P "This command is similar to 'opam list', but allows listing packages \ directly from a repository instead of what is available in a given \ opam installation."; `S Manpage.s_arguments; `S Manpage.s_options; `S OpamArg.package_selection_section; `S OpamArg.package_listing_section; ] in let cmd global_options package_selection disjunction state_selection package_listing env packages () = OpamArg.apply_global_options cli global_options; let format = let force_all_versions = match packages with | [single] -> let nameglob = match OpamStd.String.cut_at single '.' with | None -> single | Some (n, _v) -> n in (try ignore (OpamPackage.Name.of_string nameglob); true with Failure _ -> false) | _ -> false in package_listing ~force_all_versions in let pattern_selector = OpamListCommand.pattern_selector packages in let join = if disjunction then OpamFormula.ors else OpamFormula.ands in let filter = OpamFormula.ands [ Atom state_selection; join (pattern_selector :: List.map (fun x -> Atom x) package_selection); ] in let st = get_virtual_switch_state (OpamFilename.cwd ()) env in if not format.OpamListCommand.short && filter <> OpamFormula.Empty then OpamConsole.msg "# Packages matching: %s\n" (OpamListCommand.string_of_formula filter); let results = OpamListCommand.filter ~base:st.packages st filter in OpamListCommand.display st format results in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ OpamArg.package_selection cli $ or_arg cli $ state_selection_arg cli $ OpamArg.package_listing cli $ env_arg cli $ pattern_list_arg) let filter_command_doc = "Filters a repository to only keep selected packages" let filter_command cli = let command = "filter" in let doc = filter_command_doc in let man = [ `S Manpage.s_description; `P "This command removes all package definitions that don't match the \ search criteria (specified similarly to 'opam admin list') from a \ repository."; `S Manpage.s_arguments; `S Manpage.s_options; `S OpamArg.package_selection_section; ] in let remove_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["remove"] "Invert the behaviour and remove the matching packages, keeping the ones \ that don't match." in let dryrun_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["dry-run"] "List the removal commands, without actually performing them" in let cmd global_options package_selection disjunction state_selection env remove dryrun packages () = OpamArg.apply_global_options cli global_options; let repo_root = OpamFilename.cwd () in let pattern_selector = OpamListCommand.pattern_selector packages in let join = if disjunction then OpamFormula.ors else OpamFormula.ands in let filter = OpamFormula.ands [ Atom state_selection; join (pattern_selector :: List.map (fun x -> Atom x) package_selection) ] in let st = get_virtual_switch_state repo_root env in let packages = OpamListCommand.filter ~base:st.packages st filter in if OpamPackage.Set.is_empty packages then if remove then (OpamConsole.warning "No packages match the selection criteria"; OpamStd.Sys.exit_because `Success) else OpamConsole.error_and_exit `Not_found "No packages match the selection criteria"; let num_total = OpamPackage.Set.cardinal st.packages in let num_selected = OpamPackage.Set.cardinal packages in if remove then OpamConsole.formatted_msg "The following %d packages will be REMOVED from the repository (%d \ packages will be kept):\n%s\n" num_selected (num_total - num_selected) (OpamStd.List.concat_map " " OpamPackage.to_string (OpamPackage.Set.elements packages)) else OpamConsole.formatted_msg "The following %d packages will be kept in the repository (%d packages \ will be REMOVED):\n%s\n" num_selected (num_total - num_selected) (OpamStd.List.concat_map " " OpamPackage.to_string (OpamPackage.Set.elements packages)); let packages = if remove then packages else OpamPackage.Set.Op.(st.packages -- packages) in if not (dryrun || OpamConsole.confirm "Confirm?") then OpamStd.Sys.exit_because `Aborted else let pkg_prefixes = OpamRepository.packages_with_prefixes repo_root in OpamPackage.Map.iter (fun nv prefix -> if OpamPackage.Set.mem nv packages then let d = OpamRepositoryPath.packages repo_root prefix nv in if dryrun then OpamConsole.msg "rm -rf %s\n" (OpamFilename.Dir.to_string d) else (OpamFilename.cleandir d; OpamFilename.rmdir_cleanup d)) pkg_prefixes in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ OpamArg.package_selection cli $ or_arg cli $ state_selection_arg cli $ env_arg cli $ remove_arg $ dryrun_arg $ pattern_list_arg) let add_constraint_command_doc = "Adds version constraints on all dependencies towards a given package" let add_constraint_command cli = let command = "add-constraint" in let doc = add_constraint_command_doc in let man = [ `S Manpage.s_description; `P "This command searches to all dependencies towards a given package, and \ adds a version constraint to them. It is particularly useful to add \ upper bounds to existing dependencies when a new, incompatible major \ version of a library is added to a repository. The new version \ constraint is merged with the existing one, and simplified if \ possible (e.g. $(b,>=3 & >5) becomes $(b,>5))."; `S Manpage.s_arguments; `S Manpage.s_options; ] in let atom_arg = Arg.(required & pos 0 (some OpamArg.atom) None & info [] ~docv:"PACKAGE" ~doc: "A package name with a version constraint, e.g. $(b,name>=version). \ If no version constraint is specified, the command will just \ simplify existing version constraints on dependencies to the named \ package.") in let force_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["force"] "Force updating of constraints even if the resulting constraint is \ unsatisfiable (e.g. when adding $(b,>3) to the constraint \ $(b,<2)). The default in this case is to print a warning and keep \ the existing constraint unchanged." in let cmd global_options force atom () = OpamArg.apply_global_options cli global_options; let repo_root = checked_repo_root () in let pkg_prefixes = OpamRepository.packages_with_prefixes repo_root in let name, cstr_opt = atom in let cstr = match cstr_opt with | Some (relop, v) -> OpamFormula.Atom (Constraint (relop, FString (OpamPackage.Version.to_string v))) | None -> OpamFormula.Empty in let add_cstr op cstr nv n c = let f = op [ cstr; c] in match OpamFilter.simplify_extended_version_formula f with | Some f -> f | None -> (* conflicting constraint *) if force then f else (OpamConsole.warning "In package %s, updated constraint %s cannot be satisfied, not \ updating (use `--force' to update anyway)" (OpamPackage.to_string nv) (OpamConsole.colorise `bold (OpamFilter.string_of_filtered_formula (Atom (n, f)))); c) in OpamPackage.Map.iter (fun nv prefix -> let opam_file = OpamRepositoryPath.opam repo_root prefix nv in let opam = OpamFile.OPAM.read opam_file in let deps0 = OpamFile.OPAM.depends opam in let deps = OpamFormula.map (function | (n,c as atom) -> if n = name then Atom (n, (add_cstr OpamFormula.ands cstr nv n c)) else Atom atom) deps0 in let depopts0 = OpamFile.OPAM.depopts opam in let conflicts0 = OpamFile.OPAM.conflicts opam in let contains name = OpamFormula.fold_left (fun contains (n,_) -> contains || n = name) false in let conflicts = if contains name depopts0 then match cstr_opt with | Some (relop, v) -> let icstr = OpamFormula.Atom (Constraint (OpamFormula.neg_relop relop, FString (OpamPackage.Version.to_string v))) in if contains name conflicts0 then OpamFormula.map (function | (n,c as atom) -> if n = name then Atom (n, (add_cstr OpamFormula.ors icstr nv n c)) else Atom atom) conflicts0 else OpamFormula.ors [ conflicts0; Atom (name, icstr) ] | None -> conflicts0 else conflicts0 in if deps <> deps0 || conflicts <> conflicts0 then OpamFile.OPAM.write_with_preserved_format opam_file (OpamFile.OPAM.with_depends deps opam |> OpamFile.OPAM.with_conflicts conflicts)) pkg_prefixes in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ force_arg $ atom_arg) (* HELP *) let help = let doc = "Display help about opam admin and opam admin subcommands." in let man = [ `S Manpage.s_description; `P "Prints help about opam admin commands."; `P "Use `$(mname) help topics' to get the full list of help topics."; ] in let topic = let doc = Arg.info [] ~docv:"TOPIC" ~doc:"The topic to get help on." in Arg.(value & pos 0 (some string) None & doc ) in let help man_format cmds topic = match topic with | None -> `Help (`Pager, None) | Some topic -> let topics = "topics" :: cmds in let conv, _ = Cmdliner.Arg.enum (List.rev_map (fun s -> (s, s)) topics) in match conv topic with | `Error e -> `Error (false, e) | `Ok t when t = "topics" -> List.iter (OpamConsole.msg "%s\n") cmds; `Ok () | `Ok t -> `Help (man_format, Some t) in Term.(ret (const help $Arg.man_format $Term.choice_names $topic)), Cmd.info "help" ~doc ~man let admin_subcommands cli = let index_command = index_command cli in [ index_command; OpamArg.make_command_alias ~cli index_command "make"; cache_command cli; upgrade_command cli; lint_command cli; check_command cli; list_command cli; filter_command cli; add_constraint_command cli; add_hashes_command cli; help; ] let default_subcommand cli = let man = admin_command_man @ [ `S Manpage.s_commands; `S "COMMAND ALIASES"; ] @ OpamArg.help_sections cli in let usage global_options = OpamArg.apply_global_options cli global_options; OpamConsole.formatted_msg "usage: opam admin [--version]\n\ \ [--help]\n\ \ <command> [<args>]\n\ \n\ The most commonly used opam admin commands are:\n\ \ index %s\n\ \ cache %s\n\ \ upgrade-format %s\n\ \n\ See 'opam admin <command> --help' for more information on a specific \ command.\n" index_command_doc cache_command_doc upgrade_command_doc in Term.(const usage $ global_options cli), Cmd.info "opam admin" ~version:(OpamVersion.to_string OpamVersion.current) ~sdocs:OpamArg.global_option_section ~doc:admin_command_doc ~man let get_cmdliner_parser cli = default_subcommand cli, admin_subcommands cli
null
https://raw.githubusercontent.com/ocaml/opam/88002fb3ec9e827ae8d1885593efc0d18c196d3c/src/client/opamAdminCommand.ml
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ Some pseudo-randomisation to avoid downloading all files from the same host simultaneously conflicting constraint HELP
Copyright 2012 - 2020 OCamlPro Copyright 2012 INRIA GNU Lesser General Public License version 2.1 , with the special open OpamTypes open OpamProcess.Job.Op open OpamStateTypes open Cmdliner type command = unit Cmdliner.Term.t * Cmdliner.Cmd.info let checked_repo_root () = let repo_root = OpamFilename.cwd () in if not (OpamFilename.exists_dir (OpamRepositoryPath.packages_dir repo_root)) then OpamConsole.error_and_exit `Bad_arguments "No repository found in current directory.\n\ Please make sure there is a \"packages%s\" directory" OpamArg.dir_sep; repo_root let global_options cli = let apply_cli options = { options with OpamArg.cli = options.OpamArg.cli} in Term.(const apply_cli $ OpamArg.global_options cli) let admin_command_doc = "Tools for repository administrators" let admin_command_man = [ `S Manpage.s_description; `P (Printf.sprintf "This command can perform various actions on repositories in the opam \ format. It is expected to be run from the root of a repository, i.e. a \ directory containing a 'repo' file and a subdirectory 'packages%s' \ holding package definition within subdirectories. A 'compilers%s' \ subdirectory (opam repository format version < 2) will also be used by \ the $(b,upgrade-format) subcommand." OpamArg.dir_sep OpamArg.dir_sep) ] let index_command_doc = "Generate an inclusive index file for serving over HTTP." let index_command cli = let command = "index" in let doc = index_command_doc in let man = [ `S Manpage.s_description; `P "An opam repository can be served over HTTP or HTTPS using any web \ server. To that purpose, an inclusive index needs to be generated \ first: this command generates the files the opam client will expect \ when fetching from an HTTP remote, and should be run after any changes \ are done to the contents of the repository." ] in let urls_txt_arg cli = OpamArg.mk_vflag ~cli `minimal_urls_txt [ OpamArg.cli_original, `no_urls_txt, ["no-urls-txt"], "Don't generate a 'urls.txt' file. That index file is no longer \ needed from opam 2.0 on, but is still used by older versions."; OpamArg.cli_original, `full_urls_txt, ["full-urls-txt"], "Generate an inclusive 'urls.txt', for a repository that will be \ used by opam versions earlier than 2.0."; OpamArg.cli_original, `minimal_urls_txt, ["minimal-urls-txt"], "Generate a minimal 'urls.txt' file, that only includes the 'repo' \ file. This allows opam versions earlier than 2.0 to read that file, \ and be properly redirected to a repository dedicated to their \ version, assuming a suitable 'redirect:' field is defined, instead \ of failing. This is the default."; ] in let cmd global_options urls_txt () = OpamArg.apply_global_options cli global_options; let repo_root = checked_repo_root () in let repo_file = OpamRepositoryPath.repo repo_root in let repo_def = match OpamFile.Repo.read_opt repo_file with | None -> OpamConsole.warning "No \"repo\" file found. Creating a minimal one."; OpamFile.Repo.create () | Some r -> r in let repo_stamp = let date () = let t = Unix.gmtime (Unix.time ()) in Printf.sprintf "%04d-%02d-%02d %02d:%02d" (t.Unix.tm_year + 1900) (t.Unix.tm_mon +1) t.Unix.tm_mday t.Unix.tm_hour t.Unix.tm_min in match OpamUrl.guess_version_control (OpamFilename.Dir.to_string repo_root) with | None -> date () | Some vcs -> let module VCS = (val OpamRepository.find_backend_by_kind vcs) in match OpamProcess.Job.run (VCS.revision repo_root) with | None -> date () | Some hash -> OpamPackage.Version.to_string hash in let repo_def = OpamFile.Repo.with_stamp repo_stamp repo_def in OpamFile.Repo.write repo_file repo_def; if urls_txt <> `no_urls_txt then (OpamConsole.msg "Generating urls.txt...\n"; OpamFilename.of_string "repo" :: (if urls_txt = `full_urls_txt then OpamFilename.rec_files OpamFilename.Op.(repo_root / "compilers") @ OpamFilename.rec_files (OpamRepositoryPath.packages_dir repo_root) else []) |> List.fold_left (fun set f -> if not (OpamFilename.exists f) then set else let attr = OpamFilename.to_attribute repo_root f in OpamFilename.Attribute.Set.add attr set ) OpamFilename.Attribute.Set.empty |> OpamFile.File_attributes.write (OpamFile.make (OpamFilename.of_string "urls.txt"))); OpamConsole.msg "Generating index.tar.gz...\n"; OpamHTTP.make_index_tar_gz repo_root; OpamConsole.msg "Done.\n"; in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ urls_txt_arg cli) let cache_urls repo_root repo_def = let global_dl_cache = OpamStd.Option.Op.(OpamStateConfig.(load ~lock_kind:`Lock_read !r.root_dir) +! OpamFile.Config.empty) |> OpamFile.Config.dl_cache in let repo_dl_cache = OpamStd.List.filter_map (fun rel -> if OpamStd.String.contains ~sub:"://" rel then OpamUrl.parse_opt ~handle_suffix:false rel else Some OpamUrl.Op.(OpamUrl.of_string (OpamFilename.Dir.to_string repo_root) / rel)) (OpamFile.Repo.dl_cache repo_def) in repo_dl_cache @ global_dl_cache Downloads all urls of the given package to the given let package_files_to_cache repo_root cache_dir cache_urls ~recheck ?link (nv, prefix) = match OpamFileTools.read_opam (OpamRepositoryPath.packages repo_root prefix nv) with | None -> Done (OpamPackage.Map.empty) | Some opam -> let add_to_cache ?name urlf errors = let label = OpamPackage.to_string nv ^ OpamStd.Option.to_string ((^) "/") name in let checksums = OpamHash.sort (OpamFile.URL.checksum urlf) in match checksums with | [] -> OpamConsole.warning "[%s] no checksum, not caching" (OpamConsole.colorise `green label); Done errors | best_chks :: _ -> let cache_file = OpamRepository.cache_file cache_dir best_chks in let error_opt = if not recheck && OpamFilename.exists cache_file then Done None else OpamRepository.pull_file_to_cache label ~cache_urls ~cache_dir checksums (OpamFile.URL.url urlf :: OpamFile.URL.mirrors urlf) @@| fun r -> match OpamRepository.report_fetch_result nv r with | Not_available (_,m) -> Some m | Up_to_date () | Result () -> None in error_opt @@| function | Some m -> OpamPackage.Map.update nv (fun l -> m::l) [] errors | None -> OpamStd.Option.iter (fun link_dir -> let name = OpamStd.Option.default (OpamUrl.basename (OpamFile.URL.url urlf)) name in let link = OpamFilename.Op.(link_dir / OpamPackage.to_string nv // name) in OpamFilename.link ~relative:true ~target:cache_file ~link) link; errors in let urls = (match OpamFile.OPAM.url opam with | None -> [] | Some urlf -> [add_to_cache urlf]) @ (List.map (fun (name,urlf) -> add_to_cache ~name:(OpamFilename.Base.to_string name) urlf) (OpamFile.OPAM.extra_sources opam)) in OpamProcess.Job.seq urls OpamPackage.Map.empty let cache_command_doc = "Fills a local cache of package archives" let cache_command cli = let command = "cache" in let doc = cache_command_doc in let man = [ `S Manpage.s_description; `P "Downloads the archives for all packages to fill a local cache, that \ can be used when serving the repository." ] in let cache_dir_arg = Arg.(value & pos 0 OpamArg.dirname (OpamFilename.Dir.of_string "./cache") & info [] ~docv:"DIR" ~doc: "Name of the cache directory to use.") in let no_repo_update_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["no-repo-update";"n"] "Don't check, create or update the 'repo' file to point to the \ generated cache ('archive-mirrors:' field)." in let link_arg = OpamArg.mk_opt ~cli OpamArg.cli_original ["link"] "DIR" (Printf.sprintf "Create reverse symbolic links to the archives within $(i,DIR), in \ the form $(b,DIR%sPKG.VERSION%sFILENAME)." OpamArg.dir_sep OpamArg.dir_sep) Arg.(some OpamArg.dirname) None in let jobs_arg = OpamArg.mk_opt ~cli OpamArg.cli_original ["jobs"; "j"] "JOBS" "Number of parallel downloads" OpamArg.positive_integer 8 in let recheck_arg = OpamArg.mk_flag ~cli OpamArg.(cli_from cli2_2) ["check-all"; "c"] "Run a full integrity check on the existing cache. If this is not set, \ only missing cache files are handled." in let cmd global_options cache_dir no_repo_update link jobs recheck () = OpamArg.apply_global_options cli global_options; this option was the default until 2.1 let recheck = recheck || OpamCLIVersion.Op.(cli @< OpamArg.cli2_2) in let repo_root = checked_repo_root () in let repo_file = OpamRepositoryPath.repo repo_root in let repo_def = OpamFile.Repo.safe_read repo_file in let pkg_prefixes = OpamRepository.packages_with_prefixes repo_root in let cache_urls = cache_urls repo_root repo_def in let errors = OpamParallel.reduce ~jobs ~nil:OpamPackage.Map.empty ~merge:(OpamPackage.Map.union (fun a _ -> a)) ~command:(package_files_to_cache repo_root cache_dir cache_urls ~recheck ?link) (List.sort (fun (nv1,_) (nv2,_) -> match compare (Hashtbl.hash nv1) (Hashtbl.hash nv2) with | 0 -> compare nv1 nv2 | n -> n) (OpamPackage.Map.bindings pkg_prefixes)) in let cache_dir_url = OpamFilename.remove_prefix_dir repo_root cache_dir in if not no_repo_update then if not (List.mem cache_dir_url (OpamFile.Repo.dl_cache repo_def)) then (OpamConsole.msg "Adding %s to %s...\n" cache_dir_url (OpamFile.to_string repo_file); OpamFile.Repo.write repo_file (OpamFile.Repo.with_dl_cache (cache_dir_url :: OpamFile.Repo.dl_cache repo_def) repo_def)); if not (OpamPackage.Map.is_empty errors) then ( OpamConsole.error "Got some errors while processing: %s" (OpamStd.List.concat_map ", " OpamPackage.to_string (OpamPackage.Map.keys errors)); OpamConsole.errmsg "%s" (OpamStd.Format.itemize (fun (nv,el) -> Printf.sprintf "[%s] %s" (OpamPackage.to_string nv) (String.concat "\n" el)) (OpamPackage.Map.bindings errors)) ); OpamConsole.msg "Done.\n"; in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ cache_dir_arg $ no_repo_update_arg $ link_arg $ jobs_arg $ recheck_arg) let add_hashes_command_doc = "Add archive hashes to an opam repository." let add_hashes_command cli = let command = "add-hashes" in let doc = add_hashes_command_doc in let cache_dir = OpamFilename.Dir.of_string "~/.cache/opam-hash-cache" in let man = [ `S Manpage.s_description; `P (Printf.sprintf "This command scans through package definitions, and add hashes as \ requested (fetching the archives if required). A cache is generated \ in %s for subsequent runs." (OpamArg.escape_path (OpamFilename.Dir.to_string cache_dir))); ] in let hash_kinds = [`MD5; `SHA256; `SHA512] in let hash_types_arg = OpamArg.nonempty_arg_list "HASH_ALGO" "The hash, or hashes to be added" (Arg.enum (List.map (fun k -> OpamHash.string_of_kind k, k) hash_kinds)) in let packages = OpamArg.mk_opt ~cli OpamArg.(cli_from cli2_1) ["p";"packages"] "PACKAGES" "Only add hashes for the given packages" Arg.(list OpamArg.package) [] in let replace_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["replace"] "Replace the existing hashes rather than adding to them" in let hash_tables = let t = Hashtbl.create (List.length hash_kinds) in List.iter (fun k1 -> List.iter (fun k2 -> if k1 <> k2 then ( let cache_file : string list list OpamFile.t = OpamFile.make @@ OpamFilename.Op.( cache_dir // (OpamHash.string_of_kind k1 ^ "_to_" ^ OpamHash.string_of_kind k2)) in let t_mapping = Hashtbl.create 187 in (OpamStd.Option.default [] (OpamFile.Lines.read_opt cache_file) |> List.iter @@ function | [src; dst] -> Hashtbl.add t_mapping (OpamHash.of_string src) (OpamHash.of_string dst) | _ -> failwith ("Bad cache at "^OpamFile.to_string cache_file)); Hashtbl.add t (k1,k2) (cache_file, t_mapping); )) hash_kinds ) hash_kinds; t in let save_hashes () = Hashtbl.iter (fun _ (file, tbl) -> Hashtbl.fold (fun src dst l -> [OpamHash.to_string src; OpamHash.to_string dst]::l) tbl [] |> fun lines -> try OpamFile.Lines.write file lines with e -> OpamStd.Exn.fatal e; OpamConsole.log "ADMIN" "Could not write hash cache to %s, skipping (%s)" (OpamFile.to_string file) (Printexc.to_string e)) hash_tables in let additions_count = ref 0 in let get_hash cache_urls kind known_hashes url = let found = List.fold_left (fun result hash -> match result with | None -> let known_kind = OpamHash.kind hash in let _, tbl = Hashtbl.find hash_tables (known_kind, kind) in (try Some (Hashtbl.find tbl hash) with Not_found -> None) | some -> some) None known_hashes in match found with | Some h -> Some h | None -> let h = OpamProcess.Job.run @@ OpamFilename.with_tmp_dir_job @@ fun dir -> let f = OpamFilename.Op.(dir // OpamUrl.basename url) in OpamProcess.Job.ignore_errors ~default:None (fun () -> OpamRepository.pull_file (OpamUrl.to_string url) ~cache_dir:(OpamRepositoryPath.download_cache OpamStateConfig.(!r.root_dir)) ~cache_urls f known_hashes [url] @@| function | Result () | Up_to_date () -> OpamHash.compute ~kind (OpamFilename.to_string f) |> OpamStd.Option.some | Not_available _ -> None) in (match h with | Some h -> List.iter (fun h0 -> Hashtbl.replace (snd (Hashtbl.find hash_tables (OpamHash.kind h0, kind))) h0 h ) known_hashes; incr additions_count; if !additions_count mod 20 = 0 then save_hashes () | None -> ()); h in let cmd global_options hash_types replace packages () = OpamArg.apply_global_options cli global_options; let repo_root = checked_repo_root () in let cache_urls = cache_urls repo_root (OpamFile.Repo.safe_read (OpamRepositoryPath.repo repo_root)) in let pkg_prefixes = let pkgs_map = OpamRepository.packages_with_prefixes repo_root in if packages = [] then pkgs_map else (let pkgs_map, missing_pkgs = List.fold_left (fun ((map: string option OpamPackage.Map.t),error) (n,vo)-> match vo with | Some v -> let nv = OpamPackage.create n v in (match OpamPackage.Map.find_opt nv pkgs_map with | Some pre ->( OpamPackage.Map.add nv pre map), error | None -> map, (n,vo)::error) | None -> let n_map = OpamPackage.packages_of_name_map pkgs_map n in if OpamPackage.Map.is_empty n_map then map, (n,vo)::error else (OpamPackage.Map.union (fun _nv _nv' -> assert false) n_map map), error ) (OpamPackage.Map.empty, []) packages in if missing_pkgs <> [] then OpamConsole.warning "Not found package%s %s. Ignoring them." (if List.length missing_pkgs = 1 then "" else "s") (OpamStd.List.concat_map ~left:"" ~right:"" ~last_sep:" and " ", " (fun (n,vo) -> OpamConsole.colorise `underline (match vo with | Some v -> OpamPackage.to_string (OpamPackage.create n v) | None -> OpamPackage.Name.to_string n)) missing_pkgs); pkgs_map) in let has_error = OpamPackage.Map.fold (fun nv prefix has_error -> let opam_file = OpamRepositoryPath.opam repo_root prefix nv in let opam = OpamFile.OPAM.read opam_file in let has_error = if OpamFile.exists (OpamRepositoryPath.url repo_root prefix nv) then (OpamConsole.warning "Not updating external URL file at %s" (OpamFile.to_string (OpamRepositoryPath.url repo_root prefix nv)); true) else has_error in let process_url has_error urlf = let hashes = OpamFile.URL.checksum urlf in let hashes = if replace then List.filter (fun h -> List.mem (OpamHash.kind h) hash_types) hashes else hashes in let has_error, hashes = List.fold_left (fun (has_error, hashes) kind -> if List.exists (fun h -> OpamHash.kind h = kind) hashes then has_error, hashes else match get_hash cache_urls kind hashes (OpamFile.URL.url urlf) with | Some h -> has_error, hashes @ [h] | None -> OpamConsole.error "Could not get hash for %s: %s" (OpamPackage.to_string nv) (OpamUrl.to_string (OpamFile.URL.url urlf)); true, hashes) (has_error, hashes) hash_types in has_error, OpamFile.URL.with_checksum hashes urlf in let has_error, url_opt = match OpamFile.OPAM.url opam with | None -> has_error, None | Some urlf -> let has_error, urlf = process_url has_error urlf in has_error, Some urlf in let has_error, extra_sources = List.fold_right (fun (basename, urlf) (has_error, acc) -> let has_error, urlf = process_url has_error urlf in has_error, (basename, urlf) :: acc) (OpamFile.OPAM.extra_sources opam) (has_error, []) in let opam1 = OpamFile.OPAM.with_url_opt url_opt opam in let opam1 = OpamFile.OPAM.with_extra_sources extra_sources opam1 in if opam1 <> opam then OpamFile.OPAM.write_with_preserved_format opam_file opam1; has_error ) pkg_prefixes false in save_hashes (); if has_error then OpamStd.Sys.exit_because `Sync_error else OpamStd.Sys.exit_because `Success in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ hash_types_arg $ replace_arg $ packages) let upgrade_command_doc = "Upgrades repository from earlier opam versions." let upgrade_command cli = let command = "upgrade" in let doc = upgrade_command_doc in let man = [ `S Manpage.s_description; `P (Printf.sprintf "This command reads repositories from earlier opam versions, and \ converts them to repositories suitable for the current opam version. \ Packages might be created or renamed, and any compilers defined in the \ old format ('compilers%s' directory) will be turned into packages, \ using a pre-defined hierarchy that assumes OCaml compilers." OpamArg.dir_sep) ] in let clear_cache_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["clear-cache"] (Printf.sprintf "Instead of running the upgrade, clear the cache of archive hashes (held \ in ~%s.cache), that is used to avoid re-downloading files to obtain \ their hashes at every run." OpamArg.dir_sep) in let create_mirror_arg = OpamArg.mk_opt ~cli OpamArg.cli_original ["m"; "mirror"] "URL" "Don't overwrite the current repository, but put an upgraded mirror in \ place in a subdirectory, with proper redirections. Needs the URL the \ repository will be served from to put in the redirects (older versions \ of opam don't understand relative redirects)." Arg.(some OpamArg.url) None in let cmd global_options clear_cache create_mirror () = OpamArg.apply_global_options cli global_options; if clear_cache then OpamAdminRepoUpgrade.clear_cache () else match create_mirror with | None -> OpamAdminRepoUpgrade.do_upgrade (OpamFilename.cwd ()); if OpamFilename.exists (OpamFilename.of_string "index.tar.gz") || OpamFilename.exists (OpamFilename.of_string "urls.txt") then OpamConsole.note "Indexes need updating: you should now run:\n\ \n\ \ opam admin index" | Some m -> OpamAdminRepoUpgrade.do_upgrade_mirror (OpamFilename.cwd ()) m in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ clear_cache_arg $ create_mirror_arg) let lint_command_doc = "Runs 'opam lint' and reports on a whole repository" let lint_command cli = let command = "lint" in let doc = lint_command_doc in let man = [ `S Manpage.s_description; `P "This command gathers linting results on all files in a repository. The \ warnings and errors to show or hide can be selected" ] in let short_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["s";"short"] "Print only packages and warning/error numbers, without explanations" in let list_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["list";"l"] "Only list package names, without warning details" in let include_arg = OpamArg.arg_list "INT" "Show only these warnings" OpamArg.positive_integer in let exclude_arg = OpamArg.mk_opt_all ~cli OpamArg.cli_original ["exclude";"x"] "INT" "Exclude the given warnings or errors" OpamArg.positive_integer in let ignore_arg = OpamArg.mk_opt_all ~cli OpamArg.cli_original ["ignore-packages";"i"] "INT" "Ignore any packages having one of these warnings or errors" OpamArg.positive_integer in let warn_error_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["warn-error";"W"] "Return failure on any warnings, not only on errors" in let cmd global_options short list incl excl ign warn_error () = OpamArg.apply_global_options cli global_options; let repo_root = OpamFilename.cwd () in if not (OpamFilename.exists_dir OpamFilename.Op.(repo_root / "packages")) then OpamConsole.error_and_exit `Bad_arguments "No repository found in current directory.\n\ Please make sure there is a \"packages\" directory"; let pkg_prefixes = OpamRepository.packages_with_prefixes repo_root in let ret = OpamPackage.Map.fold (fun nv prefix ret -> let opam_file = OpamRepositoryPath.opam repo_root prefix nv in let w, _ = OpamFileTools.lint_file ~handle_dirname:true opam_file in if List.exists (fun (n,_,_) -> List.mem n ign) w then ret else let w = List.filter (fun (n,_,_) -> (incl = [] || List.mem n incl) && not (List.mem n excl)) w in if w <> [] then if list then OpamConsole.msg "%s\n" (OpamPackage.to_string nv) else if short then OpamConsole.msg "%s %s\n" (OpamPackage.to_string nv) (OpamStd.List.concat_map " " (fun (n,k,_) -> OpamConsole.colorise (match k with `Warning -> `yellow | `Error -> `red) (string_of_int n)) w) else begin OpamConsole.carriage_delete (); OpamConsole.msg "In %s:\n%s\n" (OpamPackage.to_string nv) (OpamFileTools.warns_to_string w) end; ret && not (warn_error && w <> [] || List.exists (fun (_,k,_) -> k = `Error) w)) pkg_prefixes true in OpamStd.Sys.exit_because (if ret then `Success else `False) in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ short_arg $ list_arg $ include_arg $ exclude_arg $ ignore_arg $ warn_error_arg) let check_command_doc = "Runs some consistency checks on a repository" let check_command cli = let command = "check" in let doc = check_command_doc in let man = [ `S Manpage.s_description; `P "This command runs consistency checks on a repository, and prints a \ report to stdout. Checks include packages that are not installable \ (due e.g. to a missing dependency) and dependency cycles. The \ 'available' field is ignored for these checks, that is, all packages \ are supposed to be available. By default, all checks are run." ] in let ignore_test_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["ignore-test-doc";"i"] "By default, $(b,{with-test}) and $(b,{with-doc}) dependencies are \ included. This ignores them, and makes the test more tolerant." in let print_short_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["s";"short"] "Only output a list of uninstallable packages" in let installability_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["installability"] "Do the installability check (and disable the others by default)" in let cycles_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["cycles"] "Do the cycles check (and disable the others by default)" in let obsolete_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["obsolete"] "Analyse for obsolete packages" in let cmd global_options ignore_test print_short installability cycles obsolete () = OpamArg.apply_global_options cli global_options; let repo_root = checked_repo_root () in let installability, cycles, obsolete = if installability || cycles || obsolete then installability, cycles, obsolete else true, true, false in let pkgs, unav_roots, uninstallable, cycle_packages, obsolete = OpamAdminCheck.check ~quiet:print_short ~installability ~cycles ~obsolete ~ignore_test repo_root in let all_ok = OpamPackage.Set.is_empty uninstallable && OpamPackage.Set.is_empty cycle_packages && OpamPackage.Set.is_empty obsolete in let open OpamPackage.Set.Op in (if print_short then OpamConsole.msg "%s\n" (OpamStd.List.concat_map "\n" OpamPackage.to_string (OpamPackage.Set.elements (uninstallable ++ cycle_packages ++ obsolete))) else if all_ok then OpamConsole.msg "No issues detected on this repository's %d packages\n" (OpamPackage.Set.cardinal pkgs) else let pr set msg = if OpamPackage.Set.is_empty set then "" else Printf.sprintf "- %d %s\n" (OpamPackage.Set.cardinal set) msg in OpamConsole.msg "Summary: out of %d packages (%d distinct names)\n\ %s%s%s%s\n" (OpamPackage.Set.cardinal pkgs) (OpamPackage.Name.Set.cardinal (OpamPackage.names_of_packages pkgs)) (pr unav_roots "uninstallable roots") (pr (uninstallable -- unav_roots) "uninstallable dependent packages") (pr (cycle_packages -- uninstallable) "packages part of dependency cycles") (pr obsolete "obsolete packages")); OpamStd.Sys.exit_because (if all_ok then `Success else `False) in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ ignore_test_arg $ print_short_arg $ installability_arg $ cycles_arg $ obsolete_arg) let pattern_list_arg = OpamArg.arg_list "PATTERNS" "Package patterns with globs. matching against $(b,NAME) or \ $(b,NAME.VERSION)" Arg.string let env_arg cli = OpamArg.mk_opt ~cli OpamArg.cli_original ["environment"] "VAR=VALUE[,VAR=VALUE]" (Printf.sprintf "Use the given opam environment, in the form of a list of \ comma-separated 'var=value' bindings, when resolving variables. This \ is used e.g. when computing available packages: if undefined, \ availability of packages will be assumed as soon as it can not be \ resolved purely from globally defined variables. Note that, unless \ overridden, variables like 'root' or 'opam-version' may be taken \ from the current opam installation. What is defined in \ $(i,~%s.opam%sconfig) is always ignored." OpamArg.dir_sep OpamArg.dir_sep) Arg.(list string) [] let state_selection_arg cli = OpamArg.mk_vflag ~cli ~section:OpamArg.package_selection_section OpamListCommand.Available [ OpamArg.cli_original, OpamListCommand.Any, ["A";"all"], "Include all, even uninstalled or unavailable packages"; OpamArg.cli_original, OpamListCommand.Available, ["a";"available"], "List only packages that are available according to the defined \ $(b,environment). Without $(b,--environment), this will include \ any packages for which availability is not resolvable at this \ point."; OpamArg.cli_original, OpamListCommand.Installable, ["installable"], "List only packages that are installable according to the defined \ $(b,environment) (this calls the solver and may be more costly; \ a package depending on an unavailable one may be available, but \ is never installable)"; ] let get_virtual_switch_state repo_root env = let env = List.map (fun s -> match OpamStd.String.cut_at s '=' with | Some (var,value) -> OpamVariable.of_string var, S value | None -> OpamVariable.of_string s, B true) env in let repo = { repo_name = OpamRepositoryName.of_string "local"; repo_url = OpamUrl.empty; repo_trust = None; } in let repo_file = OpamRepositoryPath.repo repo_root in let repo_def = OpamFile.Repo.safe_read repo_file in let opams = OpamRepositoryState.load_opams_from_dir repo.repo_name repo_root in let gt = { global_lock = OpamSystem.lock_none; root = OpamStateConfig.(!r.root_dir); config = OpamStd.Option.Op.(OpamStateConfig.( load ~lock_kind:`Lock_read !r.root_dir) +! OpamFile.Config.empty); global_variables = OpamVariable.Map.empty; global_state_to_upgrade = { gtc_repo = false; gtc_switch = false; }; } in let singl x = OpamRepositoryName.Map.singleton repo.repo_name x in let repos_tmp = let t = Hashtbl.create 1 in Hashtbl.add t repo.repo_name (lazy repo_root); t in let rt = { repos_global = gt; repos_lock = OpamSystem.lock_none; repositories = singl repo; repos_definitions = singl repo_def; repo_opams = singl opams; repos_tmp; } in let gt = {gt with global_variables = OpamVariable.Map.of_list @@ List.map (fun (var, value) -> var, (lazy (Some value), "Manually defined")) env } in OpamSwitchState.load_virtual ~repos_list:[repo.repo_name] ~avail_default:(env = []) gt rt let or_arg cli = OpamArg.mk_flag ~cli OpamArg.cli_original ~section:OpamArg.package_selection_section ["or"] "Instead of selecting packages that match $(i,all) the \ criteria, select packages that match $(i,any) of them" let list_command_doc = "Lists packages from a repository" let list_command cli = let command = "list" in let doc = list_command_doc in let man = [ `S Manpage.s_description; `P "This command is similar to 'opam list', but allows listing packages \ directly from a repository instead of what is available in a given \ opam installation."; `S Manpage.s_arguments; `S Manpage.s_options; `S OpamArg.package_selection_section; `S OpamArg.package_listing_section; ] in let cmd global_options package_selection disjunction state_selection package_listing env packages () = OpamArg.apply_global_options cli global_options; let format = let force_all_versions = match packages with | [single] -> let nameglob = match OpamStd.String.cut_at single '.' with | None -> single | Some (n, _v) -> n in (try ignore (OpamPackage.Name.of_string nameglob); true with Failure _ -> false) | _ -> false in package_listing ~force_all_versions in let pattern_selector = OpamListCommand.pattern_selector packages in let join = if disjunction then OpamFormula.ors else OpamFormula.ands in let filter = OpamFormula.ands [ Atom state_selection; join (pattern_selector :: List.map (fun x -> Atom x) package_selection); ] in let st = get_virtual_switch_state (OpamFilename.cwd ()) env in if not format.OpamListCommand.short && filter <> OpamFormula.Empty then OpamConsole.msg "# Packages matching: %s\n" (OpamListCommand.string_of_formula filter); let results = OpamListCommand.filter ~base:st.packages st filter in OpamListCommand.display st format results in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ OpamArg.package_selection cli $ or_arg cli $ state_selection_arg cli $ OpamArg.package_listing cli $ env_arg cli $ pattern_list_arg) let filter_command_doc = "Filters a repository to only keep selected packages" let filter_command cli = let command = "filter" in let doc = filter_command_doc in let man = [ `S Manpage.s_description; `P "This command removes all package definitions that don't match the \ search criteria (specified similarly to 'opam admin list') from a \ repository."; `S Manpage.s_arguments; `S Manpage.s_options; `S OpamArg.package_selection_section; ] in let remove_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["remove"] "Invert the behaviour and remove the matching packages, keeping the ones \ that don't match." in let dryrun_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["dry-run"] "List the removal commands, without actually performing them" in let cmd global_options package_selection disjunction state_selection env remove dryrun packages () = OpamArg.apply_global_options cli global_options; let repo_root = OpamFilename.cwd () in let pattern_selector = OpamListCommand.pattern_selector packages in let join = if disjunction then OpamFormula.ors else OpamFormula.ands in let filter = OpamFormula.ands [ Atom state_selection; join (pattern_selector :: List.map (fun x -> Atom x) package_selection) ] in let st = get_virtual_switch_state repo_root env in let packages = OpamListCommand.filter ~base:st.packages st filter in if OpamPackage.Set.is_empty packages then if remove then (OpamConsole.warning "No packages match the selection criteria"; OpamStd.Sys.exit_because `Success) else OpamConsole.error_and_exit `Not_found "No packages match the selection criteria"; let num_total = OpamPackage.Set.cardinal st.packages in let num_selected = OpamPackage.Set.cardinal packages in if remove then OpamConsole.formatted_msg "The following %d packages will be REMOVED from the repository (%d \ packages will be kept):\n%s\n" num_selected (num_total - num_selected) (OpamStd.List.concat_map " " OpamPackage.to_string (OpamPackage.Set.elements packages)) else OpamConsole.formatted_msg "The following %d packages will be kept in the repository (%d packages \ will be REMOVED):\n%s\n" num_selected (num_total - num_selected) (OpamStd.List.concat_map " " OpamPackage.to_string (OpamPackage.Set.elements packages)); let packages = if remove then packages else OpamPackage.Set.Op.(st.packages -- packages) in if not (dryrun || OpamConsole.confirm "Confirm?") then OpamStd.Sys.exit_because `Aborted else let pkg_prefixes = OpamRepository.packages_with_prefixes repo_root in OpamPackage.Map.iter (fun nv prefix -> if OpamPackage.Set.mem nv packages then let d = OpamRepositoryPath.packages repo_root prefix nv in if dryrun then OpamConsole.msg "rm -rf %s\n" (OpamFilename.Dir.to_string d) else (OpamFilename.cleandir d; OpamFilename.rmdir_cleanup d)) pkg_prefixes in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ OpamArg.package_selection cli $ or_arg cli $ state_selection_arg cli $ env_arg cli $ remove_arg $ dryrun_arg $ pattern_list_arg) let add_constraint_command_doc = "Adds version constraints on all dependencies towards a given package" let add_constraint_command cli = let command = "add-constraint" in let doc = add_constraint_command_doc in let man = [ `S Manpage.s_description; `P "This command searches to all dependencies towards a given package, and \ adds a version constraint to them. It is particularly useful to add \ upper bounds to existing dependencies when a new, incompatible major \ version of a library is added to a repository. The new version \ constraint is merged with the existing one, and simplified if \ possible (e.g. $(b,>=3 & >5) becomes $(b,>5))."; `S Manpage.s_arguments; `S Manpage.s_options; ] in let atom_arg = Arg.(required & pos 0 (some OpamArg.atom) None & info [] ~docv:"PACKAGE" ~doc: "A package name with a version constraint, e.g. $(b,name>=version). \ If no version constraint is specified, the command will just \ simplify existing version constraints on dependencies to the named \ package.") in let force_arg = OpamArg.mk_flag ~cli OpamArg.cli_original ["force"] "Force updating of constraints even if the resulting constraint is \ unsatisfiable (e.g. when adding $(b,>3) to the constraint \ $(b,<2)). The default in this case is to print a warning and keep \ the existing constraint unchanged." in let cmd global_options force atom () = OpamArg.apply_global_options cli global_options; let repo_root = checked_repo_root () in let pkg_prefixes = OpamRepository.packages_with_prefixes repo_root in let name, cstr_opt = atom in let cstr = match cstr_opt with | Some (relop, v) -> OpamFormula.Atom (Constraint (relop, FString (OpamPackage.Version.to_string v))) | None -> OpamFormula.Empty in let add_cstr op cstr nv n c = let f = op [ cstr; c] in match OpamFilter.simplify_extended_version_formula f with | Some f -> f if force then f else (OpamConsole.warning "In package %s, updated constraint %s cannot be satisfied, not \ updating (use `--force' to update anyway)" (OpamPackage.to_string nv) (OpamConsole.colorise `bold (OpamFilter.string_of_filtered_formula (Atom (n, f)))); c) in OpamPackage.Map.iter (fun nv prefix -> let opam_file = OpamRepositoryPath.opam repo_root prefix nv in let opam = OpamFile.OPAM.read opam_file in let deps0 = OpamFile.OPAM.depends opam in let deps = OpamFormula.map (function | (n,c as atom) -> if n = name then Atom (n, (add_cstr OpamFormula.ands cstr nv n c)) else Atom atom) deps0 in let depopts0 = OpamFile.OPAM.depopts opam in let conflicts0 = OpamFile.OPAM.conflicts opam in let contains name = OpamFormula.fold_left (fun contains (n,_) -> contains || n = name) false in let conflicts = if contains name depopts0 then match cstr_opt with | Some (relop, v) -> let icstr = OpamFormula.Atom (Constraint (OpamFormula.neg_relop relop, FString (OpamPackage.Version.to_string v))) in if contains name conflicts0 then OpamFormula.map (function | (n,c as atom) -> if n = name then Atom (n, (add_cstr OpamFormula.ors icstr nv n c)) else Atom atom) conflicts0 else OpamFormula.ors [ conflicts0; Atom (name, icstr) ] | None -> conflicts0 else conflicts0 in if deps <> deps0 || conflicts <> conflicts0 then OpamFile.OPAM.write_with_preserved_format opam_file (OpamFile.OPAM.with_depends deps opam |> OpamFile.OPAM.with_conflicts conflicts)) pkg_prefixes in OpamArg.mk_command ~cli OpamArg.cli_original command ~doc ~man Term.(const cmd $ global_options cli $ force_arg $ atom_arg) let help = let doc = "Display help about opam admin and opam admin subcommands." in let man = [ `S Manpage.s_description; `P "Prints help about opam admin commands."; `P "Use `$(mname) help topics' to get the full list of help topics."; ] in let topic = let doc = Arg.info [] ~docv:"TOPIC" ~doc:"The topic to get help on." in Arg.(value & pos 0 (some string) None & doc ) in let help man_format cmds topic = match topic with | None -> `Help (`Pager, None) | Some topic -> let topics = "topics" :: cmds in let conv, _ = Cmdliner.Arg.enum (List.rev_map (fun s -> (s, s)) topics) in match conv topic with | `Error e -> `Error (false, e) | `Ok t when t = "topics" -> List.iter (OpamConsole.msg "%s\n") cmds; `Ok () | `Ok t -> `Help (man_format, Some t) in Term.(ret (const help $Arg.man_format $Term.choice_names $topic)), Cmd.info "help" ~doc ~man let admin_subcommands cli = let index_command = index_command cli in [ index_command; OpamArg.make_command_alias ~cli index_command "make"; cache_command cli; upgrade_command cli; lint_command cli; check_command cli; list_command cli; filter_command cli; add_constraint_command cli; add_hashes_command cli; help; ] let default_subcommand cli = let man = admin_command_man @ [ `S Manpage.s_commands; `S "COMMAND ALIASES"; ] @ OpamArg.help_sections cli in let usage global_options = OpamArg.apply_global_options cli global_options; OpamConsole.formatted_msg "usage: opam admin [--version]\n\ \ [--help]\n\ \ <command> [<args>]\n\ \n\ The most commonly used opam admin commands are:\n\ \ index %s\n\ \ cache %s\n\ \ upgrade-format %s\n\ \n\ See 'opam admin <command> --help' for more information on a specific \ command.\n" index_command_doc cache_command_doc upgrade_command_doc in Term.(const usage $ global_options cli), Cmd.info "opam admin" ~version:(OpamVersion.to_string OpamVersion.current) ~sdocs:OpamArg.global_option_section ~doc:admin_command_doc ~man let get_cmdliner_parser cli = default_subcommand cli, admin_subcommands cli
b3f8881978c982148d623a6912e02c2a5377ce5ba5549274bb56b2efc176c2c2
shaunlebron/parinfer
util.clj
(ns parinfer-site.util) ; Case 1: Show the state of a bunch of variables. ; ; > (inspect a b c) ; a = > 1 ; b => :foo-bar ; c => ["hi" "world"] ; ; Case 2: Print an expression and its result. ; ; > (inspect (+ 1 2 3)) ; ( + 1 2 3 ) = > 6 ; (defn- inspect-1 [expr] `(let [result# ~expr] (js/console.info (str (pr-str '~expr) " => " (pr-str result#))) result#)) (defmacro inspect [& exprs] `(do ~@(map inspect-1 exprs)))
null
https://raw.githubusercontent.com/shaunlebron/parinfer/6705c35adbabc90cc0af3bb4ddf3a60c390f93df/site/src/parinfer_site/util.clj
clojure
Case 1: Show the state of a bunch of variables. > (inspect a b c) b => :foo-bar c => ["hi" "world"] Case 2: Print an expression and its result. > (inspect (+ 1 2 3))
(ns parinfer-site.util) a = > 1 ( + 1 2 3 ) = > 6 (defn- inspect-1 [expr] `(let [result# ~expr] (js/console.info (str (pr-str '~expr) " => " (pr-str result#))) result#)) (defmacro inspect [& exprs] `(do ~@(map inspect-1 exprs)))
53f928a72c8c606ab7326ffe26b9b3d3ff2b90c6372d28064c86a27989c77276
austinhaas/kanren
tests.cljc
(ns pettomato.kanren.cKanren.tests (:refer-clojure :exclude [==]) (:require [clojure.test :refer [is deftest]] [pettomato.kanren.cKanren.cKanren-api :refer [empty-llist llist llist* llist->seq lcons lvar lvar? lvar=? empty-pkg empty-s ext-s unit mzero choice unit? mzero? take* walk* walk reify-var == succeed fail emptyo conso firsto resto appendo anyo alwayso onceo trace-lvar trace-pkg trace-s log != membero nonmembero]] [pettomato.kanren.cKanren.fd-goals :as fd] #?(:clj [pettomato.kanren.cKanren.run :refer [run* run]]) #?(:clj [pettomato.kanren.cKanren.miniKanren-operators :refer [fresh conde all condu]]) #?(:clj [pettomato.kanren.cKanren.in-dom :refer [in-dom]])) #?(:cljs (:require-macros [pettomato.kanren.cKanren.run :refer [run* run]] [pettomato.kanren.cKanren.miniKanren-operators :refer [fresh conde all condu]] [pettomato.kanren.cKanren.in-dom :refer [in-dom]]))) ;; Most of these tests were taken from core.logic: ;; ;; ============================================================================= ;; walk* (defn to-s [v] (reduce (fn [s [k v]] (ext-s s k v)) empty-s v)) (deftest test-basic-walk (is (= (let [x (lvar) y (lvar) ss (to-s [[x 5] [y x]])] (walk y ss)) 5))) (deftest test-deep-walk (is (= (let [[x y z c b a :as s] (repeatedly lvar) ss (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])] (walk a ss)) 5))) (deftest test-walk* (is (= (let [x (lvar) y (lvar)] (walk* `(~x ~y) (to-s [[x 5] [y x]]))) '(5 5)))) ;; ============================================================================= ;; run and unify (deftest test-basic-unify (is (= (run* [q] (== true q)) '(true)))) (deftest test-basic-unify-2 (is (= (run* [q] (fresh [x y] (== [x y] [1 5]) (== [x y] q))) [[1 5]]))) (deftest test-basic-unify-3 (is (= (run* [q] (fresh [x y] (== [x y] q))) '[[_.0 _.1]]))) ;; ============================================================================= ;; fail (deftest test-basic-failure (is (= (run* [q] fail (== true q)) []))) ;; ============================================================================= ;; Basic (deftest test-all (is (= (run* [q] (all (== 1 1) (== q true))) '(true)))) ;; ============================================================================= TRS (defn pairo [p] (fresh [a d] (== (lcons a d) p))) (defn twino [p] (fresh [x] (conso x x p))) (defn listo [l] (conde [(emptyo l) succeed] [(pairo l) (fresh [d] (resto l d) (listo d))])) (defn flatteno [s out] (conde [(emptyo s) (== '() out)] [(pairo s) (fresh [a d res-a res-d] (conso a d s) (flatteno a res-a) (flatteno d res-d) (appendo res-a res-d out))] [(conso s '() out)])) ;; ============================================================================= ;; conde (deftest test-basic-conde (is (= (into #{} (run* [x] (conde [(== x 'olive) succeed] [succeed succeed] [(== x 'oil) succeed]))) (into #{} '[olive _.0 oil])))) (deftest test-basic-conde-2 (is (= (into #{} (run* [r] (fresh [x y] (conde [(== 'split x) (== 'pea y)] [(== 'navy x) (== 'bean y)]) (== (cons x (cons y ())) r)))) (into #{} '[(split pea) (navy bean)])))) (defn teacupo [x] (conde [(== 'tea x) succeed] [(== 'cup x) succeed])) (deftest test-basic-conde-e-3 (is (= (into #{} (run* [r] (fresh [x y] (conde [(teacupo x) (== true y) succeed] [(== false x) (== true y)]) (== (cons x (cons y ())) r)))) (into #{} '((false true) (tea true) (cup true)))))) ;; ============================================================================= ;; conso (deftest test-conso (is (= (run* [q] (fresh [a d] (conso a d '()))) ()))) (deftest test-conso-1 (let [a (lvar) d (lvar)] (is (= (run* [q] (conso a d q)) ['[_.0 _.1]])))) (deftest test-conso-2 (is (= (run* [q] (== [q] nil)) []))) (deftest test-conso-3 (is (= (run* [q] (conso 'a '() q)) [(llist '(a))]))) (deftest test-conso-4 (is (= (run* [q] (conso 'a (llist '(d)) q)) [(llist '(a d))]))) (deftest test-conso-empty-list (is (= (run* [q] (conso 'a q (llist '(a)))) '[()]))) (deftest test-conso-5 (is (= (run* [q] (conso q (llist '(b c)) (llist '(a b c)))) '[a]))) ;; ============================================================================= firsto (deftest test-firsto (is (= (run* [q] (firsto '(1 2) q)) '(1)))) ;; ============================================================================= ;; resto (deftest test-resto (is (= (run* [q] (resto q (llist '(1 2)))) [(llist '(_.0 1 2))]))) (deftest test-resto-2 (is (= (run* [q] (resto q (llist '[1 2]))) [(llist '(_.0 1 2))]))) (deftest test-resto-3 (is (= (run* [q] (resto (llist [1 2]) q)) [(llist '(2))]))) (deftest test-resto-4 (is (= (run* [q] (resto (llist [1 2 3 4 5 6 7 8]) q)) [(llist '(2 3 4 5 6 7 8))]))) ;; ============================================================================= ;; flatteno (deftest test-flatteno #_(is (= (into #{} (run* [x] (flatteno '[[a b] c] x))) (into #{} '(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ()) (a (b) (c)) (a (b) c) (a (b) c ()) (a b (c)) (a b () (c)) (a b c) (a b c ()) (a b () c) (a b () c ())))))) ;; ============================================================================= ;; membero (deftest membero-1 ;; This this broken b/c llist is required. #_(is (= (run* [q] (all (== q [(lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar]])))) (deftest membero-2 (is (= (into #{} (run* [q] (membero q (llist [1 2 3])))) #{1 2 3}))) (deftest membero-3 (is (= (run* [q] (membero q (llist [1 1 1 1 1]))) '(1)))) ;; ============================================================================= ;; nonmembero (deftest nonmembero-1 (is (= (run* [q] (nonmembero 1 (llist [1 2 3]))) '()))) (deftest nonmembero-2 (is (= (run* [q] (nonmembero 0 (llist [1 2 3]))) '(_.0)))) ;; ----------------------------------------------------------------------------- ;; conde clause count (defn digit-1 [x] (conde [(== 0 x)])) (defn digit-4 [x] (conde [(== 0 x)] [(== 1 x)] [(== 2 x)] [(== 3 x)])) (deftest test-conde-1-clause (is (= (run* [q] (fresh [x y] (digit-1 x) (digit-1 y) (== q [x y]))) '([0 0])))) (deftest test-conde-4-clauses (is (= (into #{} (run* [q] (fresh [x y] (digit-4 x) (digit-4 y) (== q [x y])))) (into #{} '([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0] [1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3]))))) ;; ----------------------------------------------------------------------------- ;; anyo (deftest test-anyo-1 (is (= (run 1 [q] (anyo succeed) (== true q)) (list true)))) (deftest test-anyo-2 (is (= (run 5 [q] (anyo succeed) (== true q)) (list true true true true true)))) ;; ----------------------------------------------------------------------------- ;; divergence (def f1 (fresh [] f1)) (deftest test-divergence-1 (is (= (run 1 [q] (conde [f1] [(== false false)])) '(_.0)))) (deftest test-divergence-2 (is (= (run 1 [q] (conde [f1 (== false false)] [(== false false)])) '(_.0)))) (def f2 (fresh [] (conde [f2 (conde [f2] [(== false false)])] [(== false false)]))) (deftest test-divergence-3 (is (= (run 5 [q] f2) '(_.0 _.0 _.0 _.0 _.0)))) ;; ----------------------------------------------------------------------------- ;; nil in collection (deftest test-nil-in-coll-1 (is (= (run* [q] (== q [nil])) '([nil])))) (deftest test-nil-in-coll-2 (is (= (run* [q] (== q [1 nil])) '([1 nil])))) (deftest test-nil-in-coll-3 (is (= (run* [q] (== q [nil 1])) '([nil 1])))) (deftest test-nil-in-coll-4 (is (= (run* [q] (== q '(nil))) '((nil))))) (deftest test-nil-in-coll-5 (is (= (run* [q] (== q {:foo nil})) '({:foo nil})))) (deftest test-nil-in-coll-6 (is (= (run* [q] (== q {nil :foo})) '({nil :foo})))) ;; ----------------------------------------------------------------------------- ;; Occurs Check #_(deftest test-occurs-check-1 (is (= (run* [q] (== q [q])) ()))) ;; ----------------------------------------------------------------------------- Unifications that should fail (deftest test-unify-fail-1 (is (= (run* [p] (fresh [a b] (== b ()) (== '(0 1) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-2 (is (= (run* [p] (fresh [a b] (== b '(1)) (== '(0) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-3 (is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d]))) ()))) ;; ----------------------------------------------------------------------------- ;; disequality (deftest test-disequality-1 (is (= (run* [q] (fresh [x] (!= x 1) (== q x))) '((_.0 :- (!= {_.0 1})))))) (deftest test-disequality-2 (is (= (run* [q] (fresh [x] (== q x) (!= x 1))) '((_.0 :- (!= {_.0 1})))))) (deftest test-disequality-3 (is (= (run* [q] (fresh [x] (!= x 1) (== x 1) (== q x))) ()))) (deftest test-disequality-4 (is (= (run* [q] (fresh [x] (== x 1) (!= x 1) (== q x))) ()))) (deftest test-disequality-5 (is (= (run* [q] (fresh [x y] (!= x y) (== x 1) (== y 1) (== q x))) ()))) (deftest test-disequality-6 (is (= (run* [q] (fresh [x y] (== x 1) (== y 1) (!= x y) (== q x))) ()))) (deftest test-disequality-7 (is (= (run* [q] (fresh [x y] (== x 1) (!= x y) (== y 2) (== q x))) '(1)))) (deftest test-disequality-8 (is (= (run* [q] (fresh [x y] (!= [x 2] [y 1]) (== x 1) (== y 3) (== q [x y]))) '([1 3])))) (deftest test-disequality-9 (is (= (run* [q] (fresh [x y] (== x 1) (== y 3) (!= [x 2] [y 1]) (== q [x y]))) '([1 3])))) (deftest test-disequality-10 (is (= (run* [q] (fresh [x y] (!= [x 2] [1 y]) (== x 1) (== y 2) (== q [x y]))) ()))) (deftest test-disequality-11 (is (= (run* [q] (fresh [x y] (== x 1) (== y 2) (!= [x 2] [1 y]) (== q [x y]))) ()))) (deftest test-disequality-12 (is (= (run* [q] (fresh [x y z] (!= x y) (== y z) (== x z) (== q x))) ()))) (deftest test-disequality-13 (is (= (run* [q] (fresh [x y z] (== y z) (== x z) (!= x y) (== q x))) ()))) (deftest test-disequality-14 (is (= (run* [q] (fresh [x y z] (== z y) (== x z) (!= x y) (== q x))) ()))) (deftest test-disequality-15 (is (= (run* [q] (fresh [x y] (== q [x y]) (!= x 1) (!= y 2))) '(([_.0 _.1] :- (!= {_.0 1, _.1 2})))))) (deftest test-disequality-16 (is (= (run* [q] (fresh [x y z] (== y [z]) (!= [z] x) (== z 'foo) (== x ['foo]))) '()))) (deftest test-disequality-17 (is (= (run* [q] (fresh [x y] (!= [1 x] [y 2]) (== q [x y]))) '(([_.0 _.1] :- (!= {_.0 2, _.1 1}))))) ;; This works in core.logic, but I don't see why the disequality ;; portion of this result is desirable, since it doesn't include the ;; query variable. #_(is (= (run* [q] (fresh [x y] (!= [x 1] [2 y]))) '((_.0 :- (!= ([_.1 1]) ([_.2 2]))))))) (deftest test-logic-95-disequality-1 (is (= (run* [q] (fresh [x y w z] (!= x y) (!= w z) (== z y) (== x 'foo) (== y 'foo))) ()))) (deftest test-logic-95-disequality-2 (is (= (run* [q] (fresh [x y w z] (!= x [y]) (== x ['foo]) (== y 'foo))) ()))) (deftest test-logic-96-disequality-1 (is (= (run* [q] (fresh [x y z] (!= x [y]) (== x [z]) (== y 'foo) (== z 'bar))) '(_.0)))) (deftest test-logic-100-disequality-1 (is (= (run* [q] (fresh [a b] (== q [a b]) (!= a q) (== a 1))) '([1 _.0])))) (deftest test-logic-100-disequality-2 (is (= (run* [q] (fresh [a b] (!= a q) (== q [a b]))) '([_.0 _.1]))) (is (= (run* [q] (fresh [a b] (== q [a b]) (!= a q))) '([_.0 _.1])))) (deftest test-logic-100-disequality-3 (is (= (run* [q] (fresh [x y w z] (== x [1 w]) (== y [2 z]) (!= x y))) '(_.0))) (is (= (run* [q] (fresh [x y w z] (!= x y) (== x [1 w]) (== y [2 z]))) '(_.0)))) (deftest test-logic-119-disequality-1 (is (= (run* [q] (!= {1 2 3 4} 'foo)) '(_.0)))) (deftest norvig-test ;; -bug.pdf (is (run* [q] (fresh [x y] (== ['p x y] ['p y x]))) '(_.0)) (is (run* [x] (fresh [x y z] (== ['q ['p x y] ['p y x]] ['q z z]))) '(_.0))) (deftest condu-1 [] (is (= (run* [q] (onceo (teacupo q))) '(tea)))) (deftest condu-2 [] (is (= (run* [q] (== false q) (condu [(teacupo q) succeed] [(== false q) succeed] [fail])) '(false)))) (deftest test-arch-friends-problem-logic-124 (let [expected [{:wedges 2, :flats 4, :pumps 1, :sandals 3, :foot-farm 2, :heels-in-a-hand-cart 4, :shoe-palace 1, :tootsies 3}]] (is (= expected (run* [q] (fresh [wedges flats pumps sandals ff hh sp tt pumps+1] (in-dom wedges flats pumps sandals ff hh sp tt pumps+1 (range 1 5)) (fd/distinct [wedges flats pumps sandals]) (fd/distinct [ff hh sp tt]) (== flats hh) (fd/+ pumps 1 pumps+1) (fd/!= pumps+1 tt) (== ff 2) (fd/+ sp 2 sandals) (== q {:wedges wedges :flats flats :pumps pumps :sandals sandals :foot-farm ff :heels-in-a-hand-cart hh :shoe-palace sp :tootsies tt}))))))) ;;; cKanren (deftest test-ckanren-1 (is (= (into #{} (run* [q] (fresh [x] (in-dom x (range 1 4)) (== q x)))) (into #{} '(1 2 3))))) (deftest test-ckanren-2 (is (= (into #{} (run* [q] (fresh [x y z] (in-dom x z (range 1 6)) (in-dom y (range 3 6)) (fd/+ x y z) (== q [x y z])))) (into #{} '([1 3 4] [2 3 5] [1 4 5]))))) (deftest test-ckanren-3 (is (= (into #{} (run* [q] (fresh [x y] (in-dom x y (range 1 4)) (== x y) (== q [x y])))) (into #{} '([1 1] [2 2] [3 3]))))) (deftest test-ckanren-4 (is (true? (every? (fn [[x y]] (not= x y)) (run* [q] (fresh [x y] (in-dom x y (range 1 10)) (fd/!= x y) (== q [x y]))))))) (deftest test-ckanren-5 (is (= (into #{} (run* [q] (fresh [x y] (in-dom x y (range 1 4)) (== x 2) (fd/!= x y) (== q [x y])))) (into #{} '([2 1] [2 3]))))) (deftest test-ckanren-6 (is (= (run* [q] (fresh [x] (in-dom x (range 1 3)) (fd/+ x 1 x) (== q x))) '()))) (deftest test-ckanren-7 (is (= (run* [q] (fresh [x] (in-dom x (range 1 3)) (fd/+ x x x))) '()))) (deftest test-ckanren-8 (is (= (into #{} (run* [q] (fresh [x y] (in-dom x y (range 1 4)) (fd/<= x y) (== q [x y])))) (into #{} '([1 1] [1 2] [2 2] [1 3] [3 3] [2 3]))))) (deftest test-ckanren-9 (is (= (into #{} (run* [q] (fresh [x y] (in-dom x y (range 1 4)) (fd/< x y) (== q [x y])))) (into #{} '([1 2] [2 3] [1 3]))))) (defn subgoal [x] (fresh [y] (== y x) (fd/+ 1 y 3))) (deftest test-ckanren-10 (is (= (run* [q] (fresh [x] (in-dom x (range 1 10)) (subgoal x) (== q x))) '(2)))) (deftest test-distinct (is (= (into #{} (run* [q] (fresh [x y z] (in-dom x y z (range 1 4)) (fd/distinct [x y z]) (== q [x y z])))) (into #{} '([1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]))))) (deftest test-=fd-2 (is (= (into #{} (run* [q] (fresh [a b] (in-dom a b (range 1 4)) (== a b) (== q [a b])))) (into #{} '([1 1] [2 2] [3 3]))))) (deftest test-fd-!=-1 (is (= (into #{} (run* [q] (fresh [a b] (in-dom a b (range 1 4)) (fd/!= a b) (== q [a b])))) (into #{} '([1 2] [1 3] [2 1] [2 3] [3 1] [3 2]))))) (deftest test-fd-<-1 (is (= (into #{} (run* [q] (fresh [a b c] (in-dom a b c (range 1 4)) (fd/< a b) (fd/< b c) (== q [a b c])))) (into #{} '([1 2 3]))))) (deftest test-fd-<-2 (is (= (into #{} (run* [q] (fresh [x y z] (in-dom x y z (range 1 11)) (fd/+ x y z) (fd/< x y) (== z 10) (== q [x y z])))) (into #{} '([1 9 10] [2 8 10] [3 7 10] [4 6 10]))))) (deftest test-fd->-1 (is (= (into #{} (run* [q] (fresh [x y z] (in-dom x y z (range 1 11)) (fd/+ x y z) (fd/> x y) (== z 10) (== q [x y z])))) (into #{} '([6 4 10] [7 3 10] [8 2 10] [9 1 10]))))) (deftest test-logic-62-fd (is (= (run 1 [q] (fresh [x y a b] (fd/distinct [x y]) (== [x y] [a b]) (== q [a b]) (== a 1) (== b 1))) ())) (is (= (run 1 [q] (fresh [x y a b] (== [x y] [a b]) (== q [a b]) (== a 1) (== b 1) (fd/distinct [x y]))) ()))) (deftest test-logic-81-fd (is (= (run* [q] (fresh [x y] (== q x) (fd/distinct [q y]) (== y x) (in-dom q x y (range 1 4)))) ())) (is (= (run* [q] (fresh [x y z] (== q x) (== y z) (fd/distinct [q y]) (fd/distinct [q x]) (== z q) (in-dom q x y z (range 1 3)))) ()))) (defn righto [x y l] (conde [(fresh [d] (conso x d l) (firsto d y))] [(fresh [d] (resto l d) (righto x y d))])) (defn nexto [x y l] (conde ((righto x y l)) ((righto y x l)))) (defn membero1 [x l] (fresh [head tail] (conso head tail l) (conde [(== x head)] [(membero1 x tail)]))) (defn zebrao [hs] (all (== (llist [(lvar) (lvar) [(lvar) (lvar) 'milk (lvar) (lvar)] (lvar) (lvar)]) hs) (firsto hs ['norwegian (lvar) (lvar) (lvar) (lvar)]) (nexto ['norwegian (lvar) (lvar) (lvar) (lvar)] [(lvar) (lvar) (lvar) (lvar) 'blue] hs) (righto [(lvar) (lvar) (lvar) (lvar) 'ivory] [(lvar) (lvar) (lvar) (lvar) 'green] hs) (membero1 ['englishman (lvar) (lvar) (lvar) 'red] hs) (membero1 [(lvar) 'kools (lvar) (lvar) 'yellow] hs) (membero1 ['spaniard (lvar) (lvar) 'dog (lvar)] hs) (membero1 [(lvar) (lvar) 'coffee (lvar) 'green] hs) (membero1 ['ukrainian (lvar) 'tea (lvar) (lvar)] hs) (membero1 [(lvar) 'lucky-strikes 'oj (lvar) (lvar)] hs) (membero1 ['japanese 'parliaments (lvar) (lvar) (lvar)] hs) (membero1 [(lvar) 'oldgolds (lvar) 'snails (lvar)] hs) (nexto [(lvar) (lvar) (lvar) 'horse (lvar)] [(lvar) 'kools (lvar) (lvar) (lvar)] hs) (nexto [(lvar) (lvar) (lvar) 'fox (lvar)] [(lvar) 'chesterfields (lvar) (lvar) (lvar)] hs))) #_(run 1 [q] (zebrao q)) #_(dotimes [_ 100] (time (doall (run 1 [q] (zebrao q))))) #_(clojure.test/run-tests)
null
https://raw.githubusercontent.com/austinhaas/kanren/f55b68279ade01dbaae67a074ea3441370a27f9e/test/pettomato/kanren/cKanren/tests.cljc
clojure
Most of these tests were taken from core.logic: ============================================================================= walk* ============================================================================= run and unify ============================================================================= fail ============================================================================= Basic ============================================================================= ============================================================================= conde ============================================================================= conso ============================================================================= ============================================================================= resto ============================================================================= flatteno ============================================================================= membero This this broken b/c llist is required. ============================================================================= nonmembero ----------------------------------------------------------------------------- conde clause count ----------------------------------------------------------------------------- anyo ----------------------------------------------------------------------------- divergence ----------------------------------------------------------------------------- nil in collection ----------------------------------------------------------------------------- Occurs Check ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- disequality This works in core.logic, but I don't see why the disequality portion of this result is desirable, since it doesn't include the query variable. -bug.pdf cKanren
(ns pettomato.kanren.cKanren.tests (:refer-clojure :exclude [==]) (:require [clojure.test :refer [is deftest]] [pettomato.kanren.cKanren.cKanren-api :refer [empty-llist llist llist* llist->seq lcons lvar lvar? lvar=? empty-pkg empty-s ext-s unit mzero choice unit? mzero? take* walk* walk reify-var == succeed fail emptyo conso firsto resto appendo anyo alwayso onceo trace-lvar trace-pkg trace-s log != membero nonmembero]] [pettomato.kanren.cKanren.fd-goals :as fd] #?(:clj [pettomato.kanren.cKanren.run :refer [run* run]]) #?(:clj [pettomato.kanren.cKanren.miniKanren-operators :refer [fresh conde all condu]]) #?(:clj [pettomato.kanren.cKanren.in-dom :refer [in-dom]])) #?(:cljs (:require-macros [pettomato.kanren.cKanren.run :refer [run* run]] [pettomato.kanren.cKanren.miniKanren-operators :refer [fresh conde all condu]] [pettomato.kanren.cKanren.in-dom :refer [in-dom]]))) (defn to-s [v] (reduce (fn [s [k v]] (ext-s s k v)) empty-s v)) (deftest test-basic-walk (is (= (let [x (lvar) y (lvar) ss (to-s [[x 5] [y x]])] (walk y ss)) 5))) (deftest test-deep-walk (is (= (let [[x y z c b a :as s] (repeatedly lvar) ss (to-s [[x 5] [y x] [z y] [c z] [b c] [a b]])] (walk a ss)) 5))) (deftest test-walk* (is (= (let [x (lvar) y (lvar)] (walk* `(~x ~y) (to-s [[x 5] [y x]]))) '(5 5)))) (deftest test-basic-unify (is (= (run* [q] (== true q)) '(true)))) (deftest test-basic-unify-2 (is (= (run* [q] (fresh [x y] (== [x y] [1 5]) (== [x y] q))) [[1 5]]))) (deftest test-basic-unify-3 (is (= (run* [q] (fresh [x y] (== [x y] q))) '[[_.0 _.1]]))) (deftest test-basic-failure (is (= (run* [q] fail (== true q)) []))) (deftest test-all (is (= (run* [q] (all (== 1 1) (== q true))) '(true)))) TRS (defn pairo [p] (fresh [a d] (== (lcons a d) p))) (defn twino [p] (fresh [x] (conso x x p))) (defn listo [l] (conde [(emptyo l) succeed] [(pairo l) (fresh [d] (resto l d) (listo d))])) (defn flatteno [s out] (conde [(emptyo s) (== '() out)] [(pairo s) (fresh [a d res-a res-d] (conso a d s) (flatteno a res-a) (flatteno d res-d) (appendo res-a res-d out))] [(conso s '() out)])) (deftest test-basic-conde (is (= (into #{} (run* [x] (conde [(== x 'olive) succeed] [succeed succeed] [(== x 'oil) succeed]))) (into #{} '[olive _.0 oil])))) (deftest test-basic-conde-2 (is (= (into #{} (run* [r] (fresh [x y] (conde [(== 'split x) (== 'pea y)] [(== 'navy x) (== 'bean y)]) (== (cons x (cons y ())) r)))) (into #{} '[(split pea) (navy bean)])))) (defn teacupo [x] (conde [(== 'tea x) succeed] [(== 'cup x) succeed])) (deftest test-basic-conde-e-3 (is (= (into #{} (run* [r] (fresh [x y] (conde [(teacupo x) (== true y) succeed] [(== false x) (== true y)]) (== (cons x (cons y ())) r)))) (into #{} '((false true) (tea true) (cup true)))))) (deftest test-conso (is (= (run* [q] (fresh [a d] (conso a d '()))) ()))) (deftest test-conso-1 (let [a (lvar) d (lvar)] (is (= (run* [q] (conso a d q)) ['[_.0 _.1]])))) (deftest test-conso-2 (is (= (run* [q] (== [q] nil)) []))) (deftest test-conso-3 (is (= (run* [q] (conso 'a '() q)) [(llist '(a))]))) (deftest test-conso-4 (is (= (run* [q] (conso 'a (llist '(d)) q)) [(llist '(a d))]))) (deftest test-conso-empty-list (is (= (run* [q] (conso 'a q (llist '(a)))) '[()]))) (deftest test-conso-5 (is (= (run* [q] (conso q (llist '(b c)) (llist '(a b c)))) '[a]))) firsto (deftest test-firsto (is (= (run* [q] (firsto '(1 2) q)) '(1)))) (deftest test-resto (is (= (run* [q] (resto q (llist '(1 2)))) [(llist '(_.0 1 2))]))) (deftest test-resto-2 (is (= (run* [q] (resto q (llist '[1 2]))) [(llist '(_.0 1 2))]))) (deftest test-resto-3 (is (= (run* [q] (resto (llist [1 2]) q)) [(llist '(2))]))) (deftest test-resto-4 (is (= (run* [q] (resto (llist [1 2 3 4 5 6 7 8]) q)) [(llist '(2 3 4 5 6 7 8))]))) (deftest test-flatteno #_(is (= (into #{} (run* [x] (flatteno '[[a b] c] x))) (into #{} '(([[a b] c]) ([a b] (c)) ([a b] c) ([a b] c ()) (a (b) (c)) (a (b) c) (a (b) c ()) (a b (c)) (a b () (c)) (a b c) (a b c ()) (a b () c) (a b () c ())))))) (deftest membero-1 #_(is (= (run* [q] (all (== q [(lvar)]) (membero ['foo (lvar)] q) (membero [(lvar) 'bar] q))) '([[foo bar]])))) (deftest membero-2 (is (= (into #{} (run* [q] (membero q (llist [1 2 3])))) #{1 2 3}))) (deftest membero-3 (is (= (run* [q] (membero q (llist [1 1 1 1 1]))) '(1)))) (deftest nonmembero-1 (is (= (run* [q] (nonmembero 1 (llist [1 2 3]))) '()))) (deftest nonmembero-2 (is (= (run* [q] (nonmembero 0 (llist [1 2 3]))) '(_.0)))) (defn digit-1 [x] (conde [(== 0 x)])) (defn digit-4 [x] (conde [(== 0 x)] [(== 1 x)] [(== 2 x)] [(== 3 x)])) (deftest test-conde-1-clause (is (= (run* [q] (fresh [x y] (digit-1 x) (digit-1 y) (== q [x y]))) '([0 0])))) (deftest test-conde-4-clauses (is (= (into #{} (run* [q] (fresh [x y] (digit-4 x) (digit-4 y) (== q [x y])))) (into #{} '([0 0] [0 1] [0 2] [1 0] [0 3] [1 1] [1 2] [2 0] [1 3] [2 1] [3 0] [2 2] [3 1] [2 3] [3 2] [3 3]))))) (deftest test-anyo-1 (is (= (run 1 [q] (anyo succeed) (== true q)) (list true)))) (deftest test-anyo-2 (is (= (run 5 [q] (anyo succeed) (== true q)) (list true true true true true)))) (def f1 (fresh [] f1)) (deftest test-divergence-1 (is (= (run 1 [q] (conde [f1] [(== false false)])) '(_.0)))) (deftest test-divergence-2 (is (= (run 1 [q] (conde [f1 (== false false)] [(== false false)])) '(_.0)))) (def f2 (fresh [] (conde [f2 (conde [f2] [(== false false)])] [(== false false)]))) (deftest test-divergence-3 (is (= (run 5 [q] f2) '(_.0 _.0 _.0 _.0 _.0)))) (deftest test-nil-in-coll-1 (is (= (run* [q] (== q [nil])) '([nil])))) (deftest test-nil-in-coll-2 (is (= (run* [q] (== q [1 nil])) '([1 nil])))) (deftest test-nil-in-coll-3 (is (= (run* [q] (== q [nil 1])) '([nil 1])))) (deftest test-nil-in-coll-4 (is (= (run* [q] (== q '(nil))) '((nil))))) (deftest test-nil-in-coll-5 (is (= (run* [q] (== q {:foo nil})) '({:foo nil})))) (deftest test-nil-in-coll-6 (is (= (run* [q] (== q {nil :foo})) '({nil :foo})))) #_(deftest test-occurs-check-1 (is (= (run* [q] (== q [q])) ()))) Unifications that should fail (deftest test-unify-fail-1 (is (= (run* [p] (fresh [a b] (== b ()) (== '(0 1) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-2 (is (= (run* [p] (fresh [a b] (== b '(1)) (== '(0) (lcons a b)) (== p [a b]))) ()))) (deftest test-unify-fail-3 (is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d]))) ()))) (deftest test-disequality-1 (is (= (run* [q] (fresh [x] (!= x 1) (== q x))) '((_.0 :- (!= {_.0 1})))))) (deftest test-disequality-2 (is (= (run* [q] (fresh [x] (== q x) (!= x 1))) '((_.0 :- (!= {_.0 1})))))) (deftest test-disequality-3 (is (= (run* [q] (fresh [x] (!= x 1) (== x 1) (== q x))) ()))) (deftest test-disequality-4 (is (= (run* [q] (fresh [x] (== x 1) (!= x 1) (== q x))) ()))) (deftest test-disequality-5 (is (= (run* [q] (fresh [x y] (!= x y) (== x 1) (== y 1) (== q x))) ()))) (deftest test-disequality-6 (is (= (run* [q] (fresh [x y] (== x 1) (== y 1) (!= x y) (== q x))) ()))) (deftest test-disequality-7 (is (= (run* [q] (fresh [x y] (== x 1) (!= x y) (== y 2) (== q x))) '(1)))) (deftest test-disequality-8 (is (= (run* [q] (fresh [x y] (!= [x 2] [y 1]) (== x 1) (== y 3) (== q [x y]))) '([1 3])))) (deftest test-disequality-9 (is (= (run* [q] (fresh [x y] (== x 1) (== y 3) (!= [x 2] [y 1]) (== q [x y]))) '([1 3])))) (deftest test-disequality-10 (is (= (run* [q] (fresh [x y] (!= [x 2] [1 y]) (== x 1) (== y 2) (== q [x y]))) ()))) (deftest test-disequality-11 (is (= (run* [q] (fresh [x y] (== x 1) (== y 2) (!= [x 2] [1 y]) (== q [x y]))) ()))) (deftest test-disequality-12 (is (= (run* [q] (fresh [x y z] (!= x y) (== y z) (== x z) (== q x))) ()))) (deftest test-disequality-13 (is (= (run* [q] (fresh [x y z] (== y z) (== x z) (!= x y) (== q x))) ()))) (deftest test-disequality-14 (is (= (run* [q] (fresh [x y z] (== z y) (== x z) (!= x y) (== q x))) ()))) (deftest test-disequality-15 (is (= (run* [q] (fresh [x y] (== q [x y]) (!= x 1) (!= y 2))) '(([_.0 _.1] :- (!= {_.0 1, _.1 2})))))) (deftest test-disequality-16 (is (= (run* [q] (fresh [x y z] (== y [z]) (!= [z] x) (== z 'foo) (== x ['foo]))) '()))) (deftest test-disequality-17 (is (= (run* [q] (fresh [x y] (!= [1 x] [y 2]) (== q [x y]))) '(([_.0 _.1] :- (!= {_.0 2, _.1 1}))))) #_(is (= (run* [q] (fresh [x y] (!= [x 1] [2 y]))) '((_.0 :- (!= ([_.1 1]) ([_.2 2]))))))) (deftest test-logic-95-disequality-1 (is (= (run* [q] (fresh [x y w z] (!= x y) (!= w z) (== z y) (== x 'foo) (== y 'foo))) ()))) (deftest test-logic-95-disequality-2 (is (= (run* [q] (fresh [x y w z] (!= x [y]) (== x ['foo]) (== y 'foo))) ()))) (deftest test-logic-96-disequality-1 (is (= (run* [q] (fresh [x y z] (!= x [y]) (== x [z]) (== y 'foo) (== z 'bar))) '(_.0)))) (deftest test-logic-100-disequality-1 (is (= (run* [q] (fresh [a b] (== q [a b]) (!= a q) (== a 1))) '([1 _.0])))) (deftest test-logic-100-disequality-2 (is (= (run* [q] (fresh [a b] (!= a q) (== q [a b]))) '([_.0 _.1]))) (is (= (run* [q] (fresh [a b] (== q [a b]) (!= a q))) '([_.0 _.1])))) (deftest test-logic-100-disequality-3 (is (= (run* [q] (fresh [x y w z] (== x [1 w]) (== y [2 z]) (!= x y))) '(_.0))) (is (= (run* [q] (fresh [x y w z] (!= x y) (== x [1 w]) (== y [2 z]))) '(_.0)))) (deftest test-logic-119-disequality-1 (is (= (run* [q] (!= {1 2 3 4} 'foo)) '(_.0)))) (deftest norvig-test (is (run* [q] (fresh [x y] (== ['p x y] ['p y x]))) '(_.0)) (is (run* [x] (fresh [x y z] (== ['q ['p x y] ['p y x]] ['q z z]))) '(_.0))) (deftest condu-1 [] (is (= (run* [q] (onceo (teacupo q))) '(tea)))) (deftest condu-2 [] (is (= (run* [q] (== false q) (condu [(teacupo q) succeed] [(== false q) succeed] [fail])) '(false)))) (deftest test-arch-friends-problem-logic-124 (let [expected [{:wedges 2, :flats 4, :pumps 1, :sandals 3, :foot-farm 2, :heels-in-a-hand-cart 4, :shoe-palace 1, :tootsies 3}]] (is (= expected (run* [q] (fresh [wedges flats pumps sandals ff hh sp tt pumps+1] (in-dom wedges flats pumps sandals ff hh sp tt pumps+1 (range 1 5)) (fd/distinct [wedges flats pumps sandals]) (fd/distinct [ff hh sp tt]) (== flats hh) (fd/+ pumps 1 pumps+1) (fd/!= pumps+1 tt) (== ff 2) (fd/+ sp 2 sandals) (== q {:wedges wedges :flats flats :pumps pumps :sandals sandals :foot-farm ff :heels-in-a-hand-cart hh :shoe-palace sp :tootsies tt}))))))) (deftest test-ckanren-1 (is (= (into #{} (run* [q] (fresh [x] (in-dom x (range 1 4)) (== q x)))) (into #{} '(1 2 3))))) (deftest test-ckanren-2 (is (= (into #{} (run* [q] (fresh [x y z] (in-dom x z (range 1 6)) (in-dom y (range 3 6)) (fd/+ x y z) (== q [x y z])))) (into #{} '([1 3 4] [2 3 5] [1 4 5]))))) (deftest test-ckanren-3 (is (= (into #{} (run* [q] (fresh [x y] (in-dom x y (range 1 4)) (== x y) (== q [x y])))) (into #{} '([1 1] [2 2] [3 3]))))) (deftest test-ckanren-4 (is (true? (every? (fn [[x y]] (not= x y)) (run* [q] (fresh [x y] (in-dom x y (range 1 10)) (fd/!= x y) (== q [x y]))))))) (deftest test-ckanren-5 (is (= (into #{} (run* [q] (fresh [x y] (in-dom x y (range 1 4)) (== x 2) (fd/!= x y) (== q [x y])))) (into #{} '([2 1] [2 3]))))) (deftest test-ckanren-6 (is (= (run* [q] (fresh [x] (in-dom x (range 1 3)) (fd/+ x 1 x) (== q x))) '()))) (deftest test-ckanren-7 (is (= (run* [q] (fresh [x] (in-dom x (range 1 3)) (fd/+ x x x))) '()))) (deftest test-ckanren-8 (is (= (into #{} (run* [q] (fresh [x y] (in-dom x y (range 1 4)) (fd/<= x y) (== q [x y])))) (into #{} '([1 1] [1 2] [2 2] [1 3] [3 3] [2 3]))))) (deftest test-ckanren-9 (is (= (into #{} (run* [q] (fresh [x y] (in-dom x y (range 1 4)) (fd/< x y) (== q [x y])))) (into #{} '([1 2] [2 3] [1 3]))))) (defn subgoal [x] (fresh [y] (== y x) (fd/+ 1 y 3))) (deftest test-ckanren-10 (is (= (run* [q] (fresh [x] (in-dom x (range 1 10)) (subgoal x) (== q x))) '(2)))) (deftest test-distinct (is (= (into #{} (run* [q] (fresh [x y z] (in-dom x y z (range 1 4)) (fd/distinct [x y z]) (== q [x y z])))) (into #{} '([1 2 3] [1 3 2] [2 1 3] [2 3 1] [3 1 2] [3 2 1]))))) (deftest test-=fd-2 (is (= (into #{} (run* [q] (fresh [a b] (in-dom a b (range 1 4)) (== a b) (== q [a b])))) (into #{} '([1 1] [2 2] [3 3]))))) (deftest test-fd-!=-1 (is (= (into #{} (run* [q] (fresh [a b] (in-dom a b (range 1 4)) (fd/!= a b) (== q [a b])))) (into #{} '([1 2] [1 3] [2 1] [2 3] [3 1] [3 2]))))) (deftest test-fd-<-1 (is (= (into #{} (run* [q] (fresh [a b c] (in-dom a b c (range 1 4)) (fd/< a b) (fd/< b c) (== q [a b c])))) (into #{} '([1 2 3]))))) (deftest test-fd-<-2 (is (= (into #{} (run* [q] (fresh [x y z] (in-dom x y z (range 1 11)) (fd/+ x y z) (fd/< x y) (== z 10) (== q [x y z])))) (into #{} '([1 9 10] [2 8 10] [3 7 10] [4 6 10]))))) (deftest test-fd->-1 (is (= (into #{} (run* [q] (fresh [x y z] (in-dom x y z (range 1 11)) (fd/+ x y z) (fd/> x y) (== z 10) (== q [x y z])))) (into #{} '([6 4 10] [7 3 10] [8 2 10] [9 1 10]))))) (deftest test-logic-62-fd (is (= (run 1 [q] (fresh [x y a b] (fd/distinct [x y]) (== [x y] [a b]) (== q [a b]) (== a 1) (== b 1))) ())) (is (= (run 1 [q] (fresh [x y a b] (== [x y] [a b]) (== q [a b]) (== a 1) (== b 1) (fd/distinct [x y]))) ()))) (deftest test-logic-81-fd (is (= (run* [q] (fresh [x y] (== q x) (fd/distinct [q y]) (== y x) (in-dom q x y (range 1 4)))) ())) (is (= (run* [q] (fresh [x y z] (== q x) (== y z) (fd/distinct [q y]) (fd/distinct [q x]) (== z q) (in-dom q x y z (range 1 3)))) ()))) (defn righto [x y l] (conde [(fresh [d] (conso x d l) (firsto d y))] [(fresh [d] (resto l d) (righto x y d))])) (defn nexto [x y l] (conde ((righto x y l)) ((righto y x l)))) (defn membero1 [x l] (fresh [head tail] (conso head tail l) (conde [(== x head)] [(membero1 x tail)]))) (defn zebrao [hs] (all (== (llist [(lvar) (lvar) [(lvar) (lvar) 'milk (lvar) (lvar)] (lvar) (lvar)]) hs) (firsto hs ['norwegian (lvar) (lvar) (lvar) (lvar)]) (nexto ['norwegian (lvar) (lvar) (lvar) (lvar)] [(lvar) (lvar) (lvar) (lvar) 'blue] hs) (righto [(lvar) (lvar) (lvar) (lvar) 'ivory] [(lvar) (lvar) (lvar) (lvar) 'green] hs) (membero1 ['englishman (lvar) (lvar) (lvar) 'red] hs) (membero1 [(lvar) 'kools (lvar) (lvar) 'yellow] hs) (membero1 ['spaniard (lvar) (lvar) 'dog (lvar)] hs) (membero1 [(lvar) (lvar) 'coffee (lvar) 'green] hs) (membero1 ['ukrainian (lvar) 'tea (lvar) (lvar)] hs) (membero1 [(lvar) 'lucky-strikes 'oj (lvar) (lvar)] hs) (membero1 ['japanese 'parliaments (lvar) (lvar) (lvar)] hs) (membero1 [(lvar) 'oldgolds (lvar) 'snails (lvar)] hs) (nexto [(lvar) (lvar) (lvar) 'horse (lvar)] [(lvar) 'kools (lvar) (lvar) (lvar)] hs) (nexto [(lvar) (lvar) (lvar) 'fox (lvar)] [(lvar) 'chesterfields (lvar) (lvar) (lvar)] hs))) #_(run 1 [q] (zebrao q)) #_(dotimes [_ 100] (time (doall (run 1 [q] (zebrao q))))) #_(clojure.test/run-tests)
4612c623d722e18b2a242791cae3566b41d9b1230991859081e6662f1b8b1f58
oakes/play-clj-examples
desktop_launcher.clj
(ns super-koalio.core.desktop-launcher (:require [super-koalio.core :refer :all]) (:import [com.badlogic.gdx.backends.lwjgl LwjglApplication] [org.lwjgl.input Keyboard]) (:gen-class)) (defn -main [] (LwjglApplication. super-koalio "super-koalio" 800 600) (Keyboard/enableRepeatEvents true))
null
https://raw.githubusercontent.com/oakes/play-clj-examples/449a505a068faeeb35d4ee4622c6a05e3fff6763/super-koalio/desktop/src/super_koalio/core/desktop_launcher.clj
clojure
(ns super-koalio.core.desktop-launcher (:require [super-koalio.core :refer :all]) (:import [com.badlogic.gdx.backends.lwjgl LwjglApplication] [org.lwjgl.input Keyboard]) (:gen-class)) (defn -main [] (LwjglApplication. super-koalio "super-koalio" 800 600) (Keyboard/enableRepeatEvents true))
5f346095af33137ba36102024423410570daf5271b599b4176f034fde7b18a64
rtoy/cmucl
values.lisp
-*- Mode : LISP ; Syntax : Common - Lisp ; Base : 10 ; Package : x86 -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . If you want to use this code or any part of CMU Common Lisp , please contact or . ;;; (ext:file-comment "$Header: src/compiler/amd64/values.lisp $") ;;; ;;; ********************************************************************** ;;; ;;; This file contains the implementation of unknown-values VOPs. ;;; Written by . ;;; by Spring / Summer 1995 . % more - arg - values by , March 1996 . Enhancements / debugging by 1996 . (in-package :amd64) (define-vop (reset-stack-pointer) (:args (ptr :scs (any-reg))) (:generator 1 (move rsp-tn ptr))) ;;; Push some values onto the stack, returning the start and number of values pushed as results . It is assumed that the Vals are wired to the standard ;;; argument locations. Nvals is the number of values to push. ;;; ;;; The generator cost is pseudo-random. We could get it right by defining a bogus SC that reflects the costs of the memory - to - memory moves for each ;;; operand, but this seems unworthwhile. ;;; (define-vop (push-values) (:args (vals :more t)) (:temporary (:sc unsigned-reg :to (:result 0) :target start) temp) (:results (start) (count)) (:info nvals) (:generator 20 WARN pointing 1 below (do ((val vals (tn-ref-across val))) ((null val)) (inst push (tn-ref-tn val))) (move start temp) (inst mov count (fixnumize nvals)))) ;;; Push a list of values on the stack, returning Start and Count as used in ;;; unknown values continuations. ;;; (define-vop (values-list) (:args (arg :scs (descriptor-reg) :target list)) (:arg-types list) (:policy :fast-safe) (:results (start :scs (any-reg)) (count :scs (any-reg))) (:temporary (:sc descriptor-reg :from (:argument 0) :to (:result 1)) list) (:temporary (:sc descriptor-reg :to (:result 1)) nil-temp) (:temporary (:sc unsigned-reg :offset rax-offset :to (:result 1)) rax) (:vop-var vop) (:save-p :compute-only) (:generator 0 (move list arg) WARN pointing 1 below (inst mov nil-temp nil-value) LOOP (inst cmp list nil-temp) (inst jmp :e done) (pushw list cons-car-slot list-pointer-type) (loadw list list cons-cdr-slot list-pointer-type) (inst mov rax list) (inst and al-tn lowtag-mask) (inst cmp al-tn list-pointer-type) (inst jmp :e loop) (error-call vop bogus-argument-to-values-list-error list) DONE (inst mov count start) ; start is high address stackp is low address this is unnecessary if we use 4 - bit low - tag ;;; Copy the more arg block to the top of the stack so we can use them ;;; as function arguments. ;;; Accepts a context as produced by more - arg - context ; points to the first value on the stack , not 4 bytes above as in other contexts . ;;; Return a context that is 4 bytes above the first value , suitable for ;;; defining a new stack frame. ;;; ;;; (define-vop (%more-arg-values) (:args (context :scs (descriptor-reg any-reg) :target src) (skip :scs (any-reg immediate)) (num :scs (any-reg) :target count)) (:arg-types * positive-fixnum positive-fixnum) (:temporary (:sc any-reg :offset rsi-offset :from (:argument 0)) src) (:temporary (:sc descriptor-reg :offset rax-offset) temp) (:temporary (:sc unsigned-reg :offset rcx-offset) temp1) (:results (start :scs (any-reg)) (count :scs (any-reg))) (:generator 20 (sc-case skip (immediate (cond ((zerop (tn-value skip)) (move src context) (move count num)) (t (inst lea src (make-ea :qword :base context :disp (- (* (tn-value skip) word-bytes)))) (move count num) (inst sub count (* (tn-value skip) word-bytes))))) (any-reg (move src context) (inst sub src skip) (move count num) (inst sub count skip))) (move temp1 count) (inst mov start rsp-tn) (inst jrcxz done) ; check for 0 count? (inst shr temp1 word-shift) ; convert the fixnum to a count. (inst std) ; move down the stack as more value are copied to the bottom. LOOP (inst lods temp) (inst push temp) (inst loop loop) DONE))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/amd64/values.lisp
lisp
Syntax : Common - Lisp ; Base : 10 ; Package : x86 -*- ********************************************************************** ********************************************************************** This file contains the implementation of unknown-values VOPs. Push some values onto the stack, returning the start and number of values argument locations. Nvals is the number of values to push. The generator cost is pseudo-random. We could get it right by defining a operand, but this seems unworthwhile. Push a list of values on the stack, returning Start and Count as used in unknown values continuations. start is high address Copy the more arg block to the top of the stack so we can use them as function arguments. points to the first defining a new stack frame. check for 0 count? convert the fixnum to a count. move down the stack as more value are copied to the bottom.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . If you want to use this code or any part of CMU Common Lisp , please contact or . (ext:file-comment "$Header: src/compiler/amd64/values.lisp $") Written by . by Spring / Summer 1995 . % more - arg - values by , March 1996 . Enhancements / debugging by 1996 . (in-package :amd64) (define-vop (reset-stack-pointer) (:args (ptr :scs (any-reg))) (:generator 1 (move rsp-tn ptr))) pushed as results . It is assumed that the Vals are wired to the standard bogus SC that reflects the costs of the memory - to - memory moves for each (define-vop (push-values) (:args (vals :more t)) (:temporary (:sc unsigned-reg :to (:result 0) :target start) temp) (:results (start) (count)) (:info nvals) (:generator 20 WARN pointing 1 below (do ((val vals (tn-ref-across val))) ((null val)) (inst push (tn-ref-tn val))) (move start temp) (inst mov count (fixnumize nvals)))) (define-vop (values-list) (:args (arg :scs (descriptor-reg) :target list)) (:arg-types list) (:policy :fast-safe) (:results (start :scs (any-reg)) (count :scs (any-reg))) (:temporary (:sc descriptor-reg :from (:argument 0) :to (:result 1)) list) (:temporary (:sc descriptor-reg :to (:result 1)) nil-temp) (:temporary (:sc unsigned-reg :offset rax-offset :to (:result 1)) rax) (:vop-var vop) (:save-p :compute-only) (:generator 0 (move list arg) WARN pointing 1 below (inst mov nil-temp nil-value) LOOP (inst cmp list nil-temp) (inst jmp :e done) (pushw list cons-car-slot list-pointer-type) (loadw list list cons-cdr-slot list-pointer-type) (inst mov rax list) (inst and al-tn lowtag-mask) (inst cmp al-tn list-pointer-type) (inst jmp :e loop) (error-call vop bogus-argument-to-values-list-error list) DONE stackp is low address this is unnecessary if we use 4 - bit low - tag value on the stack , not 4 bytes above as in other contexts . Return a context that is 4 bytes above the first value , suitable for (define-vop (%more-arg-values) (:args (context :scs (descriptor-reg any-reg) :target src) (skip :scs (any-reg immediate)) (num :scs (any-reg) :target count)) (:arg-types * positive-fixnum positive-fixnum) (:temporary (:sc any-reg :offset rsi-offset :from (:argument 0)) src) (:temporary (:sc descriptor-reg :offset rax-offset) temp) (:temporary (:sc unsigned-reg :offset rcx-offset) temp1) (:results (start :scs (any-reg)) (count :scs (any-reg))) (:generator 20 (sc-case skip (immediate (cond ((zerop (tn-value skip)) (move src context) (move count num)) (t (inst lea src (make-ea :qword :base context :disp (- (* (tn-value skip) word-bytes)))) (move count num) (inst sub count (* (tn-value skip) word-bytes))))) (any-reg (move src context) (inst sub src skip) (move count num) (inst sub count skip))) (move temp1 count) (inst mov start rsp-tn) LOOP (inst lods temp) (inst push temp) (inst loop loop) DONE))
6d9c324a305975bc8039b773e196ab3c43c92ab5288c543ca7560bb3e07daca3
kandersen/dpc
DistributedLocking.hs
{-# LANGUAGE RecordWildCards #-} # LANGUAGE ScopedTypeVariables # module DPC.Examples.DistributedLocking where import DPC.Types import DPC.Specifications data State = ClientInit NodeID NodeID Int | ClientAcquired NodeID NodeID Int Int | ClientUpdateDone NodeID Int | ClientDone | LockIdle Int | LockHeld Int Int | ResourceIdle NodeID Int | ResourceVerifying NodeID (NodeID, Int, Int) Int | ResourceModifySucceeded NodeID NodeID Int | ResourceModifyFailed NodeID NodeID Int deriving Show Spec acquire :: Protlet f State acquire = RPC "Acquire" client server where client :: ClientStep State client state = case state of ClientInit lock resource val -> pure (lock, [], clientReceive lock resource val) _ -> empty clientReceive lock resource val [token] = ClientAcquired lock resource val token server :: ServerStep State server [] state = case state of LockIdle nextToken -> pure ([nextToken], LockHeld (nextToken + 1) nextToken) _ -> empty release :: Alternative f => Protlet f State release = Notification "Release" client server where client this state = case state of ClientUpdateDone lock token -> pure (buildNotification lock token, ClientDone) _ -> empty where buildNotification lock token = Message { _msgFrom = this, _msgBody = [token], _msgTag = "Release__Notification", _msgTo = lock, _msgLabel = undefined } server :: Receive State server Message{..} state = case state of LockIdle n -> Just (LockIdle n) LockHeld this held -> pure $ if held == head _msgBody then LockIdle this else LockHeld this held _ -> empty modifyResource :: Alternative f => Protlet f State modifyResource = ARPC "Modify" clientStep serverReceive serverRespond where clientStep :: ClientStep State clientStep state = case state of ClientAcquired lock resource val token -> pure (resource, [val, token], clientReceive lock resource val token) _ -> empty clientReceive lock resource val token [ans] = case ans of 0 -> ClientInit lock resource val _ -> ClientUpdateDone lock token serverReceive :: Receive State serverReceive Message{..} state = case state of ResourceIdle lock val -> do let [val', token] = _msgBody pure $ ResourceVerifying lock (_msgFrom, val', token) val _ -> empty : : Send State serverRespond nodeID snode = case snode of ResourceModifySucceeded lock client val' -> pure (buildReply client [1], ResourceIdle lock val') ResourceModifyFailed lock client val -> pure (buildReply client [0], ResourceIdle lock val) _ -> empty where buildReply to ans = Message { _msgTag = "Modify__Response", _msgFrom = nodeID, _msgTo = to, _msgBody = ans, _msgLabel = undefined } verifyToken :: Alternative f => Protlet f State verifyToken = RPC "Verify" clientStep serverStep where clientStep :: ClientStep State clientStep state = case state of ResourceVerifying lock (client, write, token) val -> pure (lock, [token], clientReceive lock client write val) _ -> empty clientReceive lock client write val [ans] = case ans of 0 -> ResourceModifyFailed lock client val _ -> ResourceModifySucceeded lock client write serverStep :: ServerStep State serverStep [token] state = case state of LockIdle _ -> pure ([0], state) LockHeld _ heldBy -> pure ([if heldBy == token then 1 else 0], state) _ -> empty initNetwork :: Alternative f => SpecNetwork f State initNetwork = initializeNetwork nodes protlets where nodes :: [(NodeID, [(NodeID, State)])] nodes = [ (0, [(0, ClientInit 2 3 42)]) , (1, [(0, ClientInit 2 3 99)]) , (2, [(0, LockIdle 0)]) , (3, [(0, ResourceIdle 2 0)]) ] protlets :: Alternative f => [(NodeID, [Protlet f State])] protlets = [(0, [acquire, modifyResource, verifyToken, release])]
null
https://raw.githubusercontent.com/kandersen/dpc/c2d40a4bbbc1a3bd3f1a0b1b827786e76c5b1bb0/examples/DPC/Examples/DistributedLocking.hs
haskell
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables # module DPC.Examples.DistributedLocking where import DPC.Types import DPC.Specifications data State = ClientInit NodeID NodeID Int | ClientAcquired NodeID NodeID Int Int | ClientUpdateDone NodeID Int | ClientDone | LockIdle Int | LockHeld Int Int | ResourceIdle NodeID Int | ResourceVerifying NodeID (NodeID, Int, Int) Int | ResourceModifySucceeded NodeID NodeID Int | ResourceModifyFailed NodeID NodeID Int deriving Show Spec acquire :: Protlet f State acquire = RPC "Acquire" client server where client :: ClientStep State client state = case state of ClientInit lock resource val -> pure (lock, [], clientReceive lock resource val) _ -> empty clientReceive lock resource val [token] = ClientAcquired lock resource val token server :: ServerStep State server [] state = case state of LockIdle nextToken -> pure ([nextToken], LockHeld (nextToken + 1) nextToken) _ -> empty release :: Alternative f => Protlet f State release = Notification "Release" client server where client this state = case state of ClientUpdateDone lock token -> pure (buildNotification lock token, ClientDone) _ -> empty where buildNotification lock token = Message { _msgFrom = this, _msgBody = [token], _msgTag = "Release__Notification", _msgTo = lock, _msgLabel = undefined } server :: Receive State server Message{..} state = case state of LockIdle n -> Just (LockIdle n) LockHeld this held -> pure $ if held == head _msgBody then LockIdle this else LockHeld this held _ -> empty modifyResource :: Alternative f => Protlet f State modifyResource = ARPC "Modify" clientStep serverReceive serverRespond where clientStep :: ClientStep State clientStep state = case state of ClientAcquired lock resource val token -> pure (resource, [val, token], clientReceive lock resource val token) _ -> empty clientReceive lock resource val token [ans] = case ans of 0 -> ClientInit lock resource val _ -> ClientUpdateDone lock token serverReceive :: Receive State serverReceive Message{..} state = case state of ResourceIdle lock val -> do let [val', token] = _msgBody pure $ ResourceVerifying lock (_msgFrom, val', token) val _ -> empty : : Send State serverRespond nodeID snode = case snode of ResourceModifySucceeded lock client val' -> pure (buildReply client [1], ResourceIdle lock val') ResourceModifyFailed lock client val -> pure (buildReply client [0], ResourceIdle lock val) _ -> empty where buildReply to ans = Message { _msgTag = "Modify__Response", _msgFrom = nodeID, _msgTo = to, _msgBody = ans, _msgLabel = undefined } verifyToken :: Alternative f => Protlet f State verifyToken = RPC "Verify" clientStep serverStep where clientStep :: ClientStep State clientStep state = case state of ResourceVerifying lock (client, write, token) val -> pure (lock, [token], clientReceive lock client write val) _ -> empty clientReceive lock client write val [ans] = case ans of 0 -> ResourceModifyFailed lock client val _ -> ResourceModifySucceeded lock client write serverStep :: ServerStep State serverStep [token] state = case state of LockIdle _ -> pure ([0], state) LockHeld _ heldBy -> pure ([if heldBy == token then 1 else 0], state) _ -> empty initNetwork :: Alternative f => SpecNetwork f State initNetwork = initializeNetwork nodes protlets where nodes :: [(NodeID, [(NodeID, State)])] nodes = [ (0, [(0, ClientInit 2 3 42)]) , (1, [(0, ClientInit 2 3 99)]) , (2, [(0, LockIdle 0)]) , (3, [(0, ResourceIdle 2 0)]) ] protlets :: Alternative f => [(NodeID, [Protlet f State])] protlets = [(0, [acquire, modifyResource, verifyToken, release])]
8375541de90c78441d8de5ce92ebfcc18c0dcc3153a5d9d8dcc1db72ace4d413
manuel-serrano/hop
color.scm
;*=====================================================================*/ * serrano / prgm / project / hop/2.2.x / runtime / color.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Thu Feb 2 15:42:45 2006 * / * Last change : We d Nov 16 11:53:17 2011 ( serrano ) * / * Copyright : 2006 - 11 * / ;* ------------------------------------------------------------- */ ;* Simple color tools */ ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __hop_color (library multimedia) (export (color-lighter::bstring ::bstring #!optional (coef 1)) (color-darker::bstring ::bstring #!optional (coef 1)))) ;*---------------------------------------------------------------------*/ ;* change-luminance ... */ ;*---------------------------------------------------------------------*/ (define (change-luminance r::int g::int b::int coef::double) (multiple-value-bind (h s l) (rgb->hsl r g b) (let ((nl (minfx 100 (+fx l (inexact->exact (* l coef)))))) (multiple-value-bind (r g b) (hsl->rgb h s nl) (make-hex-color r g b))))) ;*---------------------------------------------------------------------*/ ;* color-lighter ... */ ;*---------------------------------------------------------------------*/ (define (color-lighter color #!optional (coef 1)) (with-handler (lambda (e) (if (isa? e &io-parse-error) color (raise e))) (multiple-value-bind (r g b) (parse-web-color color) (change-luminance r g b (/fl (fixnum->flonum coef) 10.))))) ;*---------------------------------------------------------------------*/ ;* color-darker ... */ ;*---------------------------------------------------------------------*/ (define (color-darker color #!optional (coef 1)) (with-handler (lambda (e) (if (isa? e &io-parse-error) color (raise e))) (multiple-value-bind (r g b) (parse-web-color color) (change-luminance r g b (negfl (/fl (fixnum->flonum coef) 10.))))))
null
https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/runtime/color.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ * Simple color tools */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * change-luminance ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * color-lighter ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * color-darker ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / hop/2.2.x / runtime / color.scm * / * Author : * / * Creation : Thu Feb 2 15:42:45 2006 * / * Last change : We d Nov 16 11:53:17 2011 ( serrano ) * / * Copyright : 2006 - 11 * / (module __hop_color (library multimedia) (export (color-lighter::bstring ::bstring #!optional (coef 1)) (color-darker::bstring ::bstring #!optional (coef 1)))) (define (change-luminance r::int g::int b::int coef::double) (multiple-value-bind (h s l) (rgb->hsl r g b) (let ((nl (minfx 100 (+fx l (inexact->exact (* l coef)))))) (multiple-value-bind (r g b) (hsl->rgb h s nl) (make-hex-color r g b))))) (define (color-lighter color #!optional (coef 1)) (with-handler (lambda (e) (if (isa? e &io-parse-error) color (raise e))) (multiple-value-bind (r g b) (parse-web-color color) (change-luminance r g b (/fl (fixnum->flonum coef) 10.))))) (define (color-darker color #!optional (coef 1)) (with-handler (lambda (e) (if (isa? e &io-parse-error) color (raise e))) (multiple-value-bind (r g b) (parse-web-color color) (change-luminance r g b (negfl (/fl (fixnum->flonum coef) 10.))))))
293087c97cbe488a22742aea03312f0c67adfdd48c1e6aed58d6113afeef6817
cartazio/tlaps
loc.mli
* loc.mli --- source locations * * * Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation * loc.mli --- source locations * * * Copyright (C) 2008-2010 INRIA and Microsoft Corporation *) (** Source locations *) (** A location represents a col in a source file *) type pt_ = { line : int ; bol : int ; col : int ; } type pt = Actual of pt_ | Dummy (** A location that is always invalid (but both = and == itself). *) val dummy : pt * The line number of the location , starting from 1 . Raises [ Failure " Loc.line " ] if the location is a dummy . "Loc.line"] if the location is a dummy. *) val line : pt -> int * The column number of the location , starting from 1 . Raises [ Failure " Loc.col " ] if the location is a dummy . [Failure "Loc.col"] if the location is a dummy. *) val column : pt -> int (** The character offset of a location in a file. Raises [Failure "Loc.point"] if the location is a dummy. *) val offset : pt -> int (** String representation of a location. The [file] argument is by default "<nofile>". *) val string_of_pt : ?file:string -> pt -> string (** The area of a locus is the space between [start] and [end], excluding both. *) type locus = { start : pt ; stop : pt ; file : string ; } (** left edge *) val left_of : locus -> locus (** right edge *) val right_of : locus -> locus (** A bogus locus *) val unknown : locus * Convert a [ Lexing.position ] to a [ locus ] of 0 width . val locus_of_position : Lexing.position -> locus * Merge two loci . Raises [ Failure " Loc.merge " ] if the loci are in different files . different files. *) val merge : locus -> locus -> locus * String representation of a locus . Capitalize the first word in the result iff [ cap ] is true ( the default ) . result iff [cap] is true (the default). *) val string_of_locus : ?cap:bool -> locus -> string (** String representation of a locus without filename. *) val string_of_locus_nofile : locus -> string (** Comparing loci *) val compare : locus -> locus -> int
null
https://raw.githubusercontent.com/cartazio/tlaps/562a34c066b636da7b921ae30fc5eacf83608280/src/loc.mli
ocaml
* Source locations * A location represents a col in a source file * A location that is always invalid (but both = and == itself). * The character offset of a location in a file. Raises [Failure "Loc.point"] if the location is a dummy. * String representation of a location. The [file] argument is by default "<nofile>". * The area of a locus is the space between [start] and [end], excluding both. * left edge * right edge * A bogus locus * String representation of a locus without filename. * Comparing loci
* loc.mli --- source locations * * * Copyright ( C ) 2008 - 2010 INRIA and Microsoft Corporation * loc.mli --- source locations * * * Copyright (C) 2008-2010 INRIA and Microsoft Corporation *) type pt_ = { line : int ; bol : int ; col : int ; } type pt = Actual of pt_ | Dummy val dummy : pt * The line number of the location , starting from 1 . Raises [ Failure " Loc.line " ] if the location is a dummy . "Loc.line"] if the location is a dummy. *) val line : pt -> int * The column number of the location , starting from 1 . Raises [ Failure " Loc.col " ] if the location is a dummy . [Failure "Loc.col"] if the location is a dummy. *) val column : pt -> int val offset : pt -> int val string_of_pt : ?file:string -> pt -> string type locus = { start : pt ; stop : pt ; file : string ; } val left_of : locus -> locus val right_of : locus -> locus val unknown : locus * Convert a [ Lexing.position ] to a [ locus ] of 0 width . val locus_of_position : Lexing.position -> locus * Merge two loci . Raises [ Failure " Loc.merge " ] if the loci are in different files . different files. *) val merge : locus -> locus -> locus * String representation of a locus . Capitalize the first word in the result iff [ cap ] is true ( the default ) . result iff [cap] is true (the default). *) val string_of_locus : ?cap:bool -> locus -> string val string_of_locus_nofile : locus -> string val compare : locus -> locus -> int
44033c0d03b6f970ed93c9a0fc6987ab5c893a8354f287b07688332f2492828f
nuvla/api-server
spec.cljc
(ns sixsq.nuvla.server.util.spec "Utilities that provide common spec definition patterns that aren't supported directly by the core spec functions and macros." (:require [clojure.set :as set] [clojure.spec.alpha :as s] [spec-tools.impl :as impl] [spec-tools.json-schema :as jsc] [spec-tools.parse :as st-parse] [spec-tools.visitor :as visitor])) (def ^:private all-ascii-chars (map str (map char (range 0 256)))) (defn regex-chars "Provides a list of ASCII characters that satisfy the regex pattern." [pattern] (set (filter #(re-matches pattern %) all-ascii-chars))) (defn merge-kw-lists "Merges two lists (or seqs) of namespaced keywords. The results will be a sorted vector with duplicates removed." [kws1 kws2] (vec (sort (set/union (set kws1) (set kws2))))) (defn merge-keys-specs "Merges the given clojure.spec/keys specs provided as a list of maps. All the arguments are eval'ed and must evaluate to map constants." [map-specs] (->> map-specs (map eval) (apply merge-with merge-kw-lists))) (defmacro only-keys "Creates a closed map definition where only the defined keys are permitted. The arguments must be literals, using the same function signature as clojure.spec/keys. (This implementation was provided on the clojure mailing list by Alistair Roche.)" [& {:keys [req req-un opt opt-un] :as args}] `(s/merge (s/keys ~@(apply concat (vec args))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?))) (defmacro only-keys-maps "Creates a closed map definition from one or more maps that contain key specifications as for clojure.spec/keys. All of the arguments are eval'ed, so they may be vars containing the definition(s). All of the arguments must evaluate to compile-time map constants." [& map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/keys ~@(apply concat (vec map-spec))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?)))) (defmacro constrained-map "Creates an open map spec using the supplied keys specs with the additional constraint that all unspecified entries must match the given key and value specs. The keys specs will be evaluated." [key-spec value-spec & map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/every (s/or :attrs (s/tuple ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?) :link (s/tuple ~key-spec ~value-spec))) (s/keys ~@(apply concat (vec map-spec)))))) ;; ;; spec parsing patches ;; (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys form options)) (defn transform-form [[spec-name & keys-specs]] (->> keys-specs (merge-keys-specs) (apply concat) (cons spec-name))) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys (transform-form form) options)) (defn transform-as-every [[spec-name key-spec value-spec & _]] [[spec-name key-spec value-spec]]) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/every (transform-as-every form) options)) ;; ;; patches for spec walking via visitor ;; (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys [spec accept options] (let [keys (impl/extract-keys (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/only-keys spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [spec accept options] (let [keys (impl/extract-keys (transform-form (impl/extract-form spec)))] (accept 'sixsq.nuvla.server.util.spec/only-keys-maps spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/constrained-map [spec accept options] (let [[_ inner-spec] (transform-as-every (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/constrained-map spec [(visitor/visit inner-spec accept options)] options))) ;; accept-spec monkey patches (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (jsc/accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_ spec children _] (let [{:keys [req req-un opt opt-un]} (impl/parse-keys (transform-form (impl/extract-form spec))) names-un (map name (concat req-un opt-un)) names (map impl/qualified-name (concat req opt)) required (map impl/qualified-name req) required-un (map name req-un) all-required (not-empty (concat required required-un))] (#'jsc/maybe-with-title (merge {:type "object" :properties (zipmap (concat names names-un) children)} (when all-required {:required (vec all-required)})) spec nil))) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_ spec children _] (#'jsc/maybe-with-title {:type "object", :additionalProperties (impl/unwrap children)} spec nil)) ;; patch transform of spec into ES mapping ;; (defn- spec-dispatch [dispatch _ _ _] dispatch) (defmulti accept-spec spec-dispatch :default ::default) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg))
null
https://raw.githubusercontent.com/nuvla/api-server/c11e45419af02b4bd514af10b640aa76c62072fe/code/src/sixsq/nuvla/server/util/spec.cljc
clojure
spec parsing patches patches for spec walking via visitor accept-spec monkey patches
(ns sixsq.nuvla.server.util.spec "Utilities that provide common spec definition patterns that aren't supported directly by the core spec functions and macros." (:require [clojure.set :as set] [clojure.spec.alpha :as s] [spec-tools.impl :as impl] [spec-tools.json-schema :as jsc] [spec-tools.parse :as st-parse] [spec-tools.visitor :as visitor])) (def ^:private all-ascii-chars (map str (map char (range 0 256)))) (defn regex-chars "Provides a list of ASCII characters that satisfy the regex pattern." [pattern] (set (filter #(re-matches pattern %) all-ascii-chars))) (defn merge-kw-lists "Merges two lists (or seqs) of namespaced keywords. The results will be a sorted vector with duplicates removed." [kws1 kws2] (vec (sort (set/union (set kws1) (set kws2))))) (defn merge-keys-specs "Merges the given clojure.spec/keys specs provided as a list of maps. All the arguments are eval'ed and must evaluate to map constants." [map-specs] (->> map-specs (map eval) (apply merge-with merge-kw-lists))) (defmacro only-keys "Creates a closed map definition where only the defined keys are permitted. The arguments must be literals, using the same function signature as clojure.spec/keys. (This implementation was provided on the clojure mailing list by Alistair Roche.)" [& {:keys [req req-un opt opt-un] :as args}] `(s/merge (s/keys ~@(apply concat (vec args))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?))) (defmacro only-keys-maps "Creates a closed map definition from one or more maps that contain key specifications as for clojure.spec/keys. All of the arguments are eval'ed, so they may be vars containing the definition(s). All of the arguments must evaluate to compile-time map constants." [& map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/keys ~@(apply concat (vec map-spec))) (s/map-of ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?)))) (defmacro constrained-map "Creates an open map spec using the supplied keys specs with the additional constraint that all unspecified entries must match the given key and value specs. The keys specs will be evaluated." [key-spec value-spec & map-specs] (let [{:keys [req req-un opt opt-un] :as map-spec} (merge-keys-specs map-specs)] `(s/merge (s/every (s/or :attrs (s/tuple ~(set (concat req (map (comp keyword name) req-un) opt (map (comp keyword name) opt-un))) any?) :link (s/tuple ~key-spec ~value-spec))) (s/keys ~@(apply concat (vec map-spec)))))) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys form options)) (defn transform-form [[spec-name & keys-specs]] (->> keys-specs (merge-keys-specs) (apply concat) (cons spec-name))) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/keys (transform-form form) options)) (defn transform-as-every [[spec-name key-spec value-spec & _]] [[spec-name key-spec value-spec]]) (defmethod st-parse/parse-form 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch form options] (st-parse/parse-form 'clojure.spec.alpha/every (transform-as-every form) options)) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys [spec accept options] (let [keys (impl/extract-keys (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/only-keys spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [spec accept options] (let [keys (impl/extract-keys (transform-form (impl/extract-form spec)))] (accept 'sixsq.nuvla.server.util.spec/only-keys-maps spec (mapv #(visitor/visit % accept options) keys) options))) (defmethod visitor/visit-spec 'sixsq.nuvla.server.util.spec/constrained-map [spec accept options] (let [[_ inner-spec] (transform-as-every (impl/extract-form spec))] (accept 'sixsq.nuvla.server.util.spec/constrained-map spec [(visitor/visit inner-spec accept options)] options))) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (jsc/accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_ spec children _] (let [{:keys [req req-un opt opt-un]} (impl/parse-keys (transform-form (impl/extract-form spec))) names-un (map name (concat req-un opt-un)) names (map impl/qualified-name (concat req opt)) required (map impl/qualified-name req) required-un (map name req-un) all-required (not-empty (concat required required-un))] (#'jsc/maybe-with-title (merge {:type "object" :properties (zipmap (concat names names-un) children)} (when all-required {:required (vec all-required)})) spec nil))) (defmethod jsc/accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_ spec children _] (#'jsc/maybe-with-title {:type "object", :additionalProperties (impl/unwrap children)} spec nil)) patch transform of spec into ES mapping (defn- spec-dispatch [dispatch _ _ _] dispatch) (defmulti accept-spec spec-dispatch :default ::default) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/only-keys-maps [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg)) (defmethod accept-spec 'sixsq.nuvla.server.util.spec/constrained-map [_dispatch spec children arg] (accept-spec 'clojure.spec.alpha/keys spec children arg))
f275e544b7701b72d93cdb20074cded42f12928a5da19be13e1fcec89a7e7d53
mathematical-systems/clml
ihmm.lisp
generalized sticky and blocked HDP - HMM (defpackage :nonparametric.ihmm (: nicknames : ihmm ) (:use :cl :hjs.util.meta :nonpara.stat :nonparametric.dpm :nonparametric.hdp :nonparametric.hdp-hmm :nonparametric.sticky-hdp-hmm :nonparametric.blocked-hdp-hmm) (:export :ihmm :ihmm-state :ihmm-state-uniform)) (in-package :nonparametric.ihmm) (defclass ihmm (blocked-hdp-hmm sticky-hdp-hmm) ((base-distribution :initform (make-instance 'ihmm-state-uniform)))) (defclass ihmm-state (blocked-hidden-state sticky-hidden-state) ()) (defclass ihmm-state-uniform (block-uniform sticky-state-uniform) ((cluster-class :initform 'ihmm-state))) (defmethod sampling-pi ((state ihmm-state) (dpm ihmm)) (declare (optimize (speed 3) (safety 0) (debug 0))) (let ((spi (state-pi state)) (states (dpm-clusters dpm)) (L (hdp-hmm-L dpm)) (p (dpm-p dpm)) (alpha (dpm-hyper dpm)) (table (cluster-dist-table state)) (before (sorted-before state))) (declare (type hash-table table) (type fixnum L) (type double-float alpha) (type vector before) (type (vector double-float) p spi)) (when (< (the fixnum (array-dimension before 0)) l) (adjust-array before l) (adjust-array spi l)) (setf (fill-pointer before) l) (setf (fill-pointer spi) l) (loop for i fixnum from 0 below L for s = (aref states i) do (setf (aref p i) (the double-float (+ (* alpha (the double-float (cluster-beta s))) (the double-float (+ (the double-float (if (eq state s) (sticky-kappa dpm) 0d0)) (the fixnum (gethash s table 0))))))) (setf (aref before i) s)) (dirichlet-random p p) ;; copy (loop for i fixnum from 0 below L do (setf (aref spi i) (aref p i)) ;; sort spi finally (sort spi #'(lambda (x y) (declare (type double-float x y)) (> x y)))) ;; sort before (sort before #'(lambda (x y) (declare (type fixnum x y)) (< x y)) :key #'(lambda (x) (position (aref p (position x states)) spi))) )) (defclass gauss-ihmm-state (ihmm-state gaussian-state) ()) (defclass gauss-ihmm (ihmm gauss-hdp-hmm) ((base-distribution :initform (make-instance 'ihmm-gaussian)))) (defclass ihmm-gaussian (ihmm-state-uniform state-gaussian) ((cluster-class :initform 'gauss-ihmm-state))) ;; for compare (defclass gauss-block-state (blocked-hidden-state gaussian-state) ()) (defclass gauss-block-hmm (blocked-hdp-hmm gauss-hdp-hmm) ((base-distribution :initform (make-instance 'block-gaussian)))) (defclass block-gaussian (block-uniform state-gaussian) ((cluster-class :initform 'gauss-block-state))) two type test (defun make-blocked-test (length states &optional (stds (map 'vector #'(lambda (x) (declare (ignore x)) 1d0) states))) (let ((trans (make-array length :element-type 'fixnum)) (ans (make-array length))) (loop for i from 0 below length for s = 0 then (case (random 100) (98 (ecase s (0 1) (1 2) (2 0))) (99 (ecase s (0 2) (1 0) (2 1))) (t s)) for d = (normal-random (aref states s) (aref stds s)) do (setf (aref trans i) s) (setf (aref ans i) (make-instance 'seq-point :data d))) (values trans (make-instance 'point-sequence :seq ans)))) (defun make-cyclic-test (length states &optional (stds (map 'vector #'(lambda (x) (declare (ignore x)) 1d0) states))) (let ((trans (make-array length :element-type 'fixnum)) (ans (make-array length))) (loop for i from 0 below length for s = 0 then (let ((r (random 100))) (if (> r 97) (let ((new (1+ s))) (if (= new (length states)) 0 new)) s)) for d = (normal-random (aref states s) (aref stds s)) do (setf (aref trans i) s) (setf (aref ans i) (make-instance 'seq-point :data d))) (values trans (make-instance 'point-sequence :seq ans))))
null
https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/nonparametric/ihmm.lisp
lisp
copy sort spi sort before for compare
generalized sticky and blocked HDP - HMM (defpackage :nonparametric.ihmm (: nicknames : ihmm ) (:use :cl :hjs.util.meta :nonpara.stat :nonparametric.dpm :nonparametric.hdp :nonparametric.hdp-hmm :nonparametric.sticky-hdp-hmm :nonparametric.blocked-hdp-hmm) (:export :ihmm :ihmm-state :ihmm-state-uniform)) (in-package :nonparametric.ihmm) (defclass ihmm (blocked-hdp-hmm sticky-hdp-hmm) ((base-distribution :initform (make-instance 'ihmm-state-uniform)))) (defclass ihmm-state (blocked-hidden-state sticky-hidden-state) ()) (defclass ihmm-state-uniform (block-uniform sticky-state-uniform) ((cluster-class :initform 'ihmm-state))) (defmethod sampling-pi ((state ihmm-state) (dpm ihmm)) (declare (optimize (speed 3) (safety 0) (debug 0))) (let ((spi (state-pi state)) (states (dpm-clusters dpm)) (L (hdp-hmm-L dpm)) (p (dpm-p dpm)) (alpha (dpm-hyper dpm)) (table (cluster-dist-table state)) (before (sorted-before state))) (declare (type hash-table table) (type fixnum L) (type double-float alpha) (type vector before) (type (vector double-float) p spi)) (when (< (the fixnum (array-dimension before 0)) l) (adjust-array before l) (adjust-array spi l)) (setf (fill-pointer before) l) (setf (fill-pointer spi) l) (loop for i fixnum from 0 below L for s = (aref states i) do (setf (aref p i) (the double-float (+ (* alpha (the double-float (cluster-beta s))) (the double-float (+ (the double-float (if (eq state s) (sticky-kappa dpm) 0d0)) (the fixnum (gethash s table 0))))))) (setf (aref before i) s)) (dirichlet-random p p) (loop for i fixnum from 0 below L do (setf (aref spi i) (aref p i)) finally (sort spi #'(lambda (x y) (declare (type double-float x y)) (> x y)))) (sort before #'(lambda (x y) (declare (type fixnum x y)) (< x y)) :key #'(lambda (x) (position (aref p (position x states)) spi))) )) (defclass gauss-ihmm-state (ihmm-state gaussian-state) ()) (defclass gauss-ihmm (ihmm gauss-hdp-hmm) ((base-distribution :initform (make-instance 'ihmm-gaussian)))) (defclass ihmm-gaussian (ihmm-state-uniform state-gaussian) ((cluster-class :initform 'gauss-ihmm-state))) (defclass gauss-block-state (blocked-hidden-state gaussian-state) ()) (defclass gauss-block-hmm (blocked-hdp-hmm gauss-hdp-hmm) ((base-distribution :initform (make-instance 'block-gaussian)))) (defclass block-gaussian (block-uniform state-gaussian) ((cluster-class :initform 'gauss-block-state))) two type test (defun make-blocked-test (length states &optional (stds (map 'vector #'(lambda (x) (declare (ignore x)) 1d0) states))) (let ((trans (make-array length :element-type 'fixnum)) (ans (make-array length))) (loop for i from 0 below length for s = 0 then (case (random 100) (98 (ecase s (0 1) (1 2) (2 0))) (99 (ecase s (0 2) (1 0) (2 1))) (t s)) for d = (normal-random (aref states s) (aref stds s)) do (setf (aref trans i) s) (setf (aref ans i) (make-instance 'seq-point :data d))) (values trans (make-instance 'point-sequence :seq ans)))) (defun make-cyclic-test (length states &optional (stds (map 'vector #'(lambda (x) (declare (ignore x)) 1d0) states))) (let ((trans (make-array length :element-type 'fixnum)) (ans (make-array length))) (loop for i from 0 below length for s = 0 then (let ((r (random 100))) (if (> r 97) (let ((new (1+ s))) (if (= new (length states)) 0 new)) s)) for d = (normal-random (aref states s) (aref stds s)) do (setf (aref trans i) s) (setf (aref ans i) (make-instance 'seq-point :data d))) (values trans (make-instance 'point-sequence :seq ans))))
2f30ae61f429bf6db2747bc8c9f9fc84e656fc9cc30e08418313853da731fbcf
smimram/saml
lang.ml
(** Internal representation of the language and operations to manipulate it (typechecking, reduction, etc.). *) open Extralib open Common module T = Type (** An expression. *) type t = { desc : desc; (** The expression. *) pos : pos; (** Position in source file. *) t : T.t; (** Type. *) } (** Contents of an expression. *) and desc = | Bool of bool | Int of int | Float of float | String of string | Var of string (** A variable. *) | Fun of pattern * t (** A function. *) | FFI of ffi | Let of pattern * t * t (** A variable declaration. *) | App of t * t | Seq of t * t | Tuple of t list | Meth of t * (string * t) (** A method. *) | Field of t * string (** A field. *) | Closure of environment * t (** A closure. *) | Cast of t * T.t (** Type casting. *) | Monad of string * (T.t -> T.t) * t (** Monad declaration : name, type, implementation. *) | Bind of T.monad_link * string * t * t (** A bind. *) and pattern = | PVar of string | PTuple of pattern list (** A tuple. *) and ffi = { ffi_name : string; ffi_itype : T.t; (** type of the input *) ffi_otype : T.t; (** type of the output *) ffi_eval : t -> t; (** evaluation *) } (** An environment. *) and environment = (string * t) list type expr = t let tenv = ref ([] : T.environment) let env = ref ([] : environment) (** Create an expression. *) let make ?(pos=dummy_pos) ?t e = let t = match t with | Some t -> t | None -> T.var max_int in { desc = e; pos; t } let var ?pos s = make ?pos (Var s) (* let free_var_name = let n = ref (-1) in fun () -> incr n; Printf.sprintf "#x%d" !n *) let args_name = "args" let args_pattern = PVar args_name let args ?pos () = var ?pos args_name let bool ?pos b = make ?pos (Bool b) let float ?pos x = make ?pos (Float x) let string ?pos x = make ?pos (String x) let fct ?pos args e = make ?pos (Fun (args, e)) let ufun ?pos e = fct ?pos (PTuple []) e let app ?pos f x = make ?pos (App (f, x)) let seq ?pos e1 e2 = make ?pos (Seq (e1, e2)) let letin ?pos pat def body = make ?pos (Let (pat, def, body)) let tuple ?pos l = match l with | [e] -> e | l -> make ?pos (Tuple l) let pair ?pos x y = tuple ?pos [x; y] let unit ?pos () = tuple ?pos [] let meth ?pos e lv = make ?pos (Meth (e,lv)) let rec meths ?pos e m = match m with | lv::m -> meth ?pos (meths ?pos e m) lv | [] -> e let record ?pos l = meths ?pos (unit ?pos ()) l (* module b = v a = u end is translated to a = u b = v (a=a, b=b) *) let modul ?pos decls = let rec aux e = function | (l,v)::m -> aux (letin ~pos:v.pos l v e) m | [] -> e in aux (record ?pos (List.map (function (PVar l,_) -> l, var l | _ -> failwith "pattern not yet supported in modules") decls)) decls let field ?pos e l = make ?pos (Field (e, l)) let cast ?pos e t = make ?pos (Cast (e,t)) let ffi ?pos name ?(eval=fun _ -> error "Not implemented: %s" name) a b = let f = FFI { ffi_name = name; ffi_itype = a; ffi_otype = b; ffi_eval = eval; } in make ?pos f let closure ?pos env t = make ?pos (Closure (env, t)) (** String representation of an expression. *) let rec to_string ~tab p e = let pa p s = if p then Printf.sprintf "(%s)" s else s in let tabs ?(tab=tab) () = String.make (2*tab) ' ' in let tabss () = tabs ~tab:(tab+1) () in match e.desc with | Var x -> x | Bool b -> string_of_bool b | Int n -> string_of_int n | Float f -> string_of_float f | String s -> Printf.sprintf "%S" s | FFI ffi -> Printf.sprintf "<%s>" ffi.ffi_name | Fun (pat, e) -> let pat = string_of_pattern ~tab pat in let e = to_string ~tab:(tab+1) false e in pa p (Printf.sprintf "fun %s ->%s%s" pat (if String.contains e '\n' then ("\n"^(tabs ~tab:(tab+1) ())) else " ") e) | Closure (_, e) -> Printf.sprintf "<closure>%s" (to_string ~tab true e) | App (e, a) -> let e = to_string ~tab true e in let a = to_string ~tab:(tab+1) true a in pa p (Printf.sprintf "%s %s" e a) | Seq (e1, e2) -> let e1 = to_string ~tab false e1 in let e2 = to_string ~tab false e2 in pa p (Printf.sprintf "%s%s\n%s%s" e1 (if !Config.Debug.Lang.show_seq then ";" else "") (tabs ()) e2) | Let (pat, def, body) -> let pat = string_of_pattern ~tab pat in let def = to_string ~tab:(tab+1) false def in let def = if String.contains def '\n' then Printf.sprintf "\n%s%s" (tabss ()) def else Printf.sprintf " %s " def in let body = to_string ~tab false body in if !Config.Debug.Lang.show_let then pa p (Printf.sprintf "let %s =%s%s\n%s%s" pat def (if String.contains def '\n' then "\n"^tabs()^"in" else "in") (tabs ()) body) else pa p (Printf.sprintf "%s =%s\n%s%s" pat def (tabs ()) body) | Tuple l -> let l = List.map (to_string ~tab false) l |> String.concat ", " in Printf.sprintf "(%s)" l | Meth (e,(l,v)) -> Printf.sprintf "(%s,%s=%s)" (to_string ~tab:(tab+1) false e) l (to_string ~tab:(tab+1) false v) | Field (e, l) -> Printf.sprintf "%s.%s" (to_string ~tab true e) l | Cast (e, t) -> Printf.sprintf "(%s : %s)" (to_string ~tab:(tab+1) false e) (T.to_string t) | Monad (s, t, v) -> pa p (Printf.sprintf "monad %s = %s with %s" s (T.to_string (t (T.var 0))) (to_string ~tab:(tab+1) false v)) | Bind (_, x, def, body) -> let def = to_string ~tab:(tab+1) false def in let body = to_string ~tab false body in pa p (Printf.sprintf "%s = !%s\n%s%s" x def (tabs ()) body) and string_of_pattern ~tab = function | PVar x -> x | PTuple l -> let l = List.map (string_of_pattern ~tab) l |> String.concat ", " in Printf.sprintf "(%s)" l let to_string e = to_string ~tab:0 false e let get_float t = match t.desc with | Float x -> x | _ -> error "Expected float but got %s" (to_string t) let get_string t = match t.desc with | String s -> s | _ -> assert false (** Free variables of a pattern. *) let rec pattern_variables = function | PVar x -> [x] | PTuple l -> List.fold_left (fun v p -> (pattern_variables p)@v) [] l * { 2 Type inference } (** Typing error. *) exception Typing of pos * string let type_error e s = Printf.ksprintf (fun s -> raise (Typing (e.pos, s))) s (** Check the type of an expression. *) let rec check level (env:T.environment) e = (* Printf.printf "check %s\n\n\n%!" (to_string e); *) Printf.printf " env : % s\n\n " ( String.concat_map " , " ( fun ( x,(_,t ) ) - > x ^ " : " ^ T.to_string t ) env . T.Env.t ) ; let (<:) e a = if not (T.( <: ) e.t a) then error "%s: %s has type %s but %s expected." (Common.string_of_pos e.pos) (to_string e) (T.to_string e.t) (T.to_string a) in let (>:) e a = if not (T.( <: ) a e.t) then error "%s: %s has type %s but %s expected." (Common.string_of_pos e.pos) (to_string e) (T.to_string e.t) (T.to_string a) in let rec type_of_pattern level env = function | PVar x -> let a = T.var level in let env = (x,a)::env in env, a | PTuple l -> let env, l = List.fold_map (type_of_pattern level) env l in env, T.tuple l in match e.desc with | Bool _ -> e >: T.bool () | Int _ -> e >: T.int () | Float _ -> e >: T.float () | String _ -> e >: T.string () | FFI f -> e >: T.instantiate level (T.arr f.ffi_itype f.ffi_otype) | Var x -> let t = try List.assoc x env with Not_found -> type_error e "Unbound variable %s." x in e >: T.instantiate level t | Seq (e1, e2) -> check level env e1; e1 <: T.unit (); check level env e2; e >: e2.t | Let (pat,def,body) -> check (level+1) env def; let env, a = type_of_pattern (level+1) env pat in def >: a; Printf.printf "let %s : %s\n%!" (string_of_pattern ~tab:0 pat) (T.to_string def.t); let env = the bound variables . (List.map (fun x -> let t = List.assoc x env in (* Printf.printf "generalize %s: %s\n%!" x (T.to_string t); *) T.generalize level t; (* Printf.printf "generalized : %s\n%!" (T.to_string t); *) x, t) (pattern_variables pat) )@env in check level env body; e >: body.t | Fun (pat,v) -> let env, a = type_of_pattern level env pat in check level env v; e >: T.arr a v.t | Closure _ -> assert false | App (f, v) -> let b = T.var level in check level env f; check level env v; f <: T.arr v.t b; e >: b | Tuple l -> List.iter (check level env) l; e >: T.tuple (List.map (fun v -> v.t) l) | Meth (u,(l,v)) -> check level env u; check level env v; e >: T.meth u.t (l, v.t) | Field (v, l) -> check level env v; let a = T.var level in let b = T.var level in v <: T.meth b (l, a); e >: a | Cast (u,a) -> check level env u; u <: a; e >: a | Monad (m, t, r) -> check level env r; let a = T.var level in let b = T.var level in let c = T.var level in r <: T.meths (T.var level) [ "return", T.arr a (t a); "bind", T.arr (T.tuple [t b; T.arr b (t c)]) (t c) ]; let m = T.monad m in e >: T.meths r.t [ "bind", T.arr (T.tuple [m b; T.arr b (m c)]) (m c); "return", T.arr a (m a); ] | Bind (m, x, def, body) -> let m a = T.make (T.Monad (m, a)) in let a = T.var level in let b = T.var level in check (level+1) env def; def <: m a; check level ((x,a)::env) body; body <: m b; e >: body.t let check t = check 0 !tenv t (** Evaluate a term to a value. *) let rec reduce env t = (* Printf.printf "reduce: %s\n\n%!" (to_string t); *) match t.desc with | Bool _ | Int _ | Float _ | String _ | FFI _ -> t | Var x -> (try List.assoc x env with Not_found -> error "Unbound variable during reduction: %s" x) | Fun _ -> make ~pos:t.pos (Closure (env, t)) | Closure (env, t) -> reduce env t | Let (pat, def, body) -> let def = reduce env def in let env = reduce_pattern env pat def in reduce env body | App (t, u) -> let u = reduce env u in let t = reduce env t in ( match t.desc with | Closure (env', {desc = Fun (pat, t) ; _}) -> let env'' = reduce_pattern [] pat u in let env' = env''@env' in let t = closure env' t in let t = letin args_pattern u t in reduce env t | FFI f -> f.ffi_eval u | _ -> error "Unexpected term during application: %s" (to_string t) ) | Seq (t, u) -> let _ = reduce env t in reduce env u | Meth (t,(l,v)) -> meth (reduce env t) (l, reduce env v) | Tuple l -> { t with desc = Tuple (List.map (reduce env) l) } | Field (t, l) -> let t = reduce env t in let rec aux t = match t.desc with | Meth (_,(l',v)) when l = l' -> v | Meth (t,(_,_)) -> aux t | _ -> assert false in aux t | Cast (u, _) -> reduce env u | Monad (_, _, e) -> reduce env e | Bind (m, x, t, u) -> let m = let rec aux = function | `Unknown -> error "unknown monad" | `Link m -> aux m | `Monad m -> m in aux !m in let m_name = m in let m = try List.assoc m env with Not_found -> error "Could not find monad %s" m in let m = match m.desc with | Monad (_, _, m) -> m | _ -> error "Monad expected for %s" m_name in let bind = field m "bind" in let e = app (app bind (fct (PVar x) t)) u in reduce env e and reduce_pattern env pat v = match pat, v.desc with | PVar x, _ -> (x,v)::env | PTuple p, Tuple l -> List.fold_left2 reduce_pattern env p l | _ -> assert false let reduce t = reduce !env t module Run = struct let fst t = match t.desc with | Tuple [a; _] -> a | _ -> assert false let snd t = match t.desc with | Tuple [_; b] -> b | _ -> assert false end
null
https://raw.githubusercontent.com/smimram/saml/6166a80decdf4ebb0da1d7dd74a9dd22cf65e3eb/src/lang.ml
ocaml
* Internal representation of the language and operations to manipulate it (typechecking, reduction, etc.). * An expression. * The expression. * Position in source file. * Type. * Contents of an expression. * A variable. * A function. * A variable declaration. * A method. * A field. * A closure. * Type casting. * Monad declaration : name, type, implementation. * A bind. * A tuple. * type of the input * type of the output * evaluation * An environment. * Create an expression. let free_var_name = let n = ref (-1) in fun () -> incr n; Printf.sprintf "#x%d" !n module b = v a = u end is translated to a = u b = v (a=a, b=b) * String representation of an expression. * Free variables of a pattern. * Typing error. * Check the type of an expression. Printf.printf "check %s\n\n\n%!" (to_string e); Printf.printf "generalize %s: %s\n%!" x (T.to_string t); Printf.printf "generalized : %s\n%!" (T.to_string t); * Evaluate a term to a value. Printf.printf "reduce: %s\n\n%!" (to_string t);
open Extralib open Common module T = Type type t = { } and desc = | Bool of bool | Int of int | Float of float | String of string | FFI of ffi | App of t * t | Seq of t * t | Tuple of t list and pattern = | PVar of string and ffi = { ffi_name : string; } and environment = (string * t) list type expr = t let tenv = ref ([] : T.environment) let env = ref ([] : environment) let make ?(pos=dummy_pos) ?t e = let t = match t with | Some t -> t | None -> T.var max_int in { desc = e; pos; t } let var ?pos s = make ?pos (Var s) let args_name = "args" let args_pattern = PVar args_name let args ?pos () = var ?pos args_name let bool ?pos b = make ?pos (Bool b) let float ?pos x = make ?pos (Float x) let string ?pos x = make ?pos (String x) let fct ?pos args e = make ?pos (Fun (args, e)) let ufun ?pos e = fct ?pos (PTuple []) e let app ?pos f x = make ?pos (App (f, x)) let seq ?pos e1 e2 = make ?pos (Seq (e1, e2)) let letin ?pos pat def body = make ?pos (Let (pat, def, body)) let tuple ?pos l = match l with | [e] -> e | l -> make ?pos (Tuple l) let pair ?pos x y = tuple ?pos [x; y] let unit ?pos () = tuple ?pos [] let meth ?pos e lv = make ?pos (Meth (e,lv)) let rec meths ?pos e m = match m with | lv::m -> meth ?pos (meths ?pos e m) lv | [] -> e let record ?pos l = meths ?pos (unit ?pos ()) l let modul ?pos decls = let rec aux e = function | (l,v)::m -> aux (letin ~pos:v.pos l v e) m | [] -> e in aux (record ?pos (List.map (function (PVar l,_) -> l, var l | _ -> failwith "pattern not yet supported in modules") decls)) decls let field ?pos e l = make ?pos (Field (e, l)) let cast ?pos e t = make ?pos (Cast (e,t)) let ffi ?pos name ?(eval=fun _ -> error "Not implemented: %s" name) a b = let f = FFI { ffi_name = name; ffi_itype = a; ffi_otype = b; ffi_eval = eval; } in make ?pos f let closure ?pos env t = make ?pos (Closure (env, t)) let rec to_string ~tab p e = let pa p s = if p then Printf.sprintf "(%s)" s else s in let tabs ?(tab=tab) () = String.make (2*tab) ' ' in let tabss () = tabs ~tab:(tab+1) () in match e.desc with | Var x -> x | Bool b -> string_of_bool b | Int n -> string_of_int n | Float f -> string_of_float f | String s -> Printf.sprintf "%S" s | FFI ffi -> Printf.sprintf "<%s>" ffi.ffi_name | Fun (pat, e) -> let pat = string_of_pattern ~tab pat in let e = to_string ~tab:(tab+1) false e in pa p (Printf.sprintf "fun %s ->%s%s" pat (if String.contains e '\n' then ("\n"^(tabs ~tab:(tab+1) ())) else " ") e) | Closure (_, e) -> Printf.sprintf "<closure>%s" (to_string ~tab true e) | App (e, a) -> let e = to_string ~tab true e in let a = to_string ~tab:(tab+1) true a in pa p (Printf.sprintf "%s %s" e a) | Seq (e1, e2) -> let e1 = to_string ~tab false e1 in let e2 = to_string ~tab false e2 in pa p (Printf.sprintf "%s%s\n%s%s" e1 (if !Config.Debug.Lang.show_seq then ";" else "") (tabs ()) e2) | Let (pat, def, body) -> let pat = string_of_pattern ~tab pat in let def = to_string ~tab:(tab+1) false def in let def = if String.contains def '\n' then Printf.sprintf "\n%s%s" (tabss ()) def else Printf.sprintf " %s " def in let body = to_string ~tab false body in if !Config.Debug.Lang.show_let then pa p (Printf.sprintf "let %s =%s%s\n%s%s" pat def (if String.contains def '\n' then "\n"^tabs()^"in" else "in") (tabs ()) body) else pa p (Printf.sprintf "%s =%s\n%s%s" pat def (tabs ()) body) | Tuple l -> let l = List.map (to_string ~tab false) l |> String.concat ", " in Printf.sprintf "(%s)" l | Meth (e,(l,v)) -> Printf.sprintf "(%s,%s=%s)" (to_string ~tab:(tab+1) false e) l (to_string ~tab:(tab+1) false v) | Field (e, l) -> Printf.sprintf "%s.%s" (to_string ~tab true e) l | Cast (e, t) -> Printf.sprintf "(%s : %s)" (to_string ~tab:(tab+1) false e) (T.to_string t) | Monad (s, t, v) -> pa p (Printf.sprintf "monad %s = %s with %s" s (T.to_string (t (T.var 0))) (to_string ~tab:(tab+1) false v)) | Bind (_, x, def, body) -> let def = to_string ~tab:(tab+1) false def in let body = to_string ~tab false body in pa p (Printf.sprintf "%s = !%s\n%s%s" x def (tabs ()) body) and string_of_pattern ~tab = function | PVar x -> x | PTuple l -> let l = List.map (string_of_pattern ~tab) l |> String.concat ", " in Printf.sprintf "(%s)" l let to_string e = to_string ~tab:0 false e let get_float t = match t.desc with | Float x -> x | _ -> error "Expected float but got %s" (to_string t) let get_string t = match t.desc with | String s -> s | _ -> assert false let rec pattern_variables = function | PVar x -> [x] | PTuple l -> List.fold_left (fun v p -> (pattern_variables p)@v) [] l * { 2 Type inference } exception Typing of pos * string let type_error e s = Printf.ksprintf (fun s -> raise (Typing (e.pos, s))) s let rec check level (env:T.environment) e = Printf.printf " env : % s\n\n " ( String.concat_map " , " ( fun ( x,(_,t ) ) - > x ^ " : " ^ T.to_string t ) env . T.Env.t ) ; let (<:) e a = if not (T.( <: ) e.t a) then error "%s: %s has type %s but %s expected." (Common.string_of_pos e.pos) (to_string e) (T.to_string e.t) (T.to_string a) in let (>:) e a = if not (T.( <: ) a e.t) then error "%s: %s has type %s but %s expected." (Common.string_of_pos e.pos) (to_string e) (T.to_string e.t) (T.to_string a) in let rec type_of_pattern level env = function | PVar x -> let a = T.var level in let env = (x,a)::env in env, a | PTuple l -> let env, l = List.fold_map (type_of_pattern level) env l in env, T.tuple l in match e.desc with | Bool _ -> e >: T.bool () | Int _ -> e >: T.int () | Float _ -> e >: T.float () | String _ -> e >: T.string () | FFI f -> e >: T.instantiate level (T.arr f.ffi_itype f.ffi_otype) | Var x -> let t = try List.assoc x env with Not_found -> type_error e "Unbound variable %s." x in e >: T.instantiate level t | Seq (e1, e2) -> check level env e1; e1 <: T.unit (); check level env e2; e >: e2.t | Let (pat,def,body) -> check (level+1) env def; let env, a = type_of_pattern (level+1) env pat in def >: a; Printf.printf "let %s : %s\n%!" (string_of_pattern ~tab:0 pat) (T.to_string def.t); let env = the bound variables . (List.map (fun x -> let t = List.assoc x env in T.generalize level t; x, t) (pattern_variables pat) )@env in check level env body; e >: body.t | Fun (pat,v) -> let env, a = type_of_pattern level env pat in check level env v; e >: T.arr a v.t | Closure _ -> assert false | App (f, v) -> let b = T.var level in check level env f; check level env v; f <: T.arr v.t b; e >: b | Tuple l -> List.iter (check level env) l; e >: T.tuple (List.map (fun v -> v.t) l) | Meth (u,(l,v)) -> check level env u; check level env v; e >: T.meth u.t (l, v.t) | Field (v, l) -> check level env v; let a = T.var level in let b = T.var level in v <: T.meth b (l, a); e >: a | Cast (u,a) -> check level env u; u <: a; e >: a | Monad (m, t, r) -> check level env r; let a = T.var level in let b = T.var level in let c = T.var level in r <: T.meths (T.var level) [ "return", T.arr a (t a); "bind", T.arr (T.tuple [t b; T.arr b (t c)]) (t c) ]; let m = T.monad m in e >: T.meths r.t [ "bind", T.arr (T.tuple [m b; T.arr b (m c)]) (m c); "return", T.arr a (m a); ] | Bind (m, x, def, body) -> let m a = T.make (T.Monad (m, a)) in let a = T.var level in let b = T.var level in check (level+1) env def; def <: m a; check level ((x,a)::env) body; body <: m b; e >: body.t let check t = check 0 !tenv t let rec reduce env t = match t.desc with | Bool _ | Int _ | Float _ | String _ | FFI _ -> t | Var x -> (try List.assoc x env with Not_found -> error "Unbound variable during reduction: %s" x) | Fun _ -> make ~pos:t.pos (Closure (env, t)) | Closure (env, t) -> reduce env t | Let (pat, def, body) -> let def = reduce env def in let env = reduce_pattern env pat def in reduce env body | App (t, u) -> let u = reduce env u in let t = reduce env t in ( match t.desc with | Closure (env', {desc = Fun (pat, t) ; _}) -> let env'' = reduce_pattern [] pat u in let env' = env''@env' in let t = closure env' t in let t = letin args_pattern u t in reduce env t | FFI f -> f.ffi_eval u | _ -> error "Unexpected term during application: %s" (to_string t) ) | Seq (t, u) -> let _ = reduce env t in reduce env u | Meth (t,(l,v)) -> meth (reduce env t) (l, reduce env v) | Tuple l -> { t with desc = Tuple (List.map (reduce env) l) } | Field (t, l) -> let t = reduce env t in let rec aux t = match t.desc with | Meth (_,(l',v)) when l = l' -> v | Meth (t,(_,_)) -> aux t | _ -> assert false in aux t | Cast (u, _) -> reduce env u | Monad (_, _, e) -> reduce env e | Bind (m, x, t, u) -> let m = let rec aux = function | `Unknown -> error "unknown monad" | `Link m -> aux m | `Monad m -> m in aux !m in let m_name = m in let m = try List.assoc m env with Not_found -> error "Could not find monad %s" m in let m = match m.desc with | Monad (_, _, m) -> m | _ -> error "Monad expected for %s" m_name in let bind = field m "bind" in let e = app (app bind (fct (PVar x) t)) u in reduce env e and reduce_pattern env pat v = match pat, v.desc with | PVar x, _ -> (x,v)::env | PTuple p, Tuple l -> List.fold_left2 reduce_pattern env p l | _ -> assert false let reduce t = reduce !env t module Run = struct let fst t = match t.desc with | Tuple [a; _] -> a | _ -> assert false let snd t = match t.desc with | Tuple [_; b] -> b | _ -> assert false end
c90c0a2839acca57a2bd66cd7aed5e4353db3dc9f67e7258feb730f70bc0601b
flowyourmoney/malli-ts
to_clj.cljs
(ns malli-ts.data-mapping.to-clj (:require [malli-ts.core :as-alias mts] [malli-ts.data-mapping :as mts-dm] [malli.core :as m] [cljs-bean.core :as b :refer [bean?]])) (defn unwrap [v] (when v (or (unchecked-get v "unwrap/clj") (when (bean? v) v)))) (deftype BeanContext [js<->clj-mapping mapping ^:mutable sub-cache] b/BeanContext (keywords? [_] true) (key->prop [_ key'] (let [s (get mapping key')] (set! sub-cache s) (if s (.-prop s) (name key')))) (prop->key [_ prop] (let [s (get mapping prop)] (set! sub-cache s) (if s (.-key s) (keyword prop)))) (transform [_ v prop key' nth'] (if-some [v (unwrap v)] v ;else (if-some [bean' (cond (object? v) true (array? v) false)] (let [sub-mapping (if (or nth' (not sub-cache)) mapping ;else (let [s (.-schema sub-cache)] (if-let [ref (::mts-dm/ref s)] (js<->clj-mapping ref) s))) bean-context (BeanContext. js<->clj-mapping sub-mapping nil)] (if bean' (b/Bean. nil v bean-context true nil nil nil) (b/ArrayVector. nil bean-context v nil))) ;else v)))) (defn ^:export to-clj ([v js<->clj-mapping] (if-some [v (unwrap v)] v ;else (if-some [bean' (cond (object? v) true (array? v) false)] (let [root (::mts-dm/root js<->clj-mapping) root (if-let [ref (::mts-dm/ref root)] (js<->clj-mapping ref) #_else root) bean-context (BeanContext. js<->clj-mapping root nil)] (if bean' (b/Bean. nil v bean-context true nil nil nil) (b/ArrayVector. nil bean-context v nil))) ;else v))) ([x registry schema & [mapping-options]] (let [s (m/schema [:schema {:registry registry} schema])] (to-clj x (mts-dm/clj<->js-mapping s mapping-options))))) (comment (let [order-items-schema [:vector [:map [:order/item {:optional true ::mts/clj<->js {:prop "orderItem" :fn-to nil :fn-from nil}} [:map [:order-item/id uuid?] [:order-item/type {::mts/clj<->js {:prop "type"}} string?] [:order-item/price [:map [:order-item/currency [:enum :EUR :USD :ZAR]] [:order-item/amount number?]]] [:order-item/test-dummy {::mts/clj<->js {:prop "TESTDummyXYZ"}} string?] [:order-item/related-items [:ref ::order-items] #_[:vector [:map [:related-item/how-is-related string? :related-item/order-item-id uuid?]]]]]] [:order/credit {:optional true} [:map [:order.credit/valid-for-timespan [:enum :milliseconds :seconds :minutes :hours :days]] [:order-credit/amount number?]]]]] order-schema [:map [:model-type [:= ::order]] [:order/id {::mts/clj<->js {:prop "orderId"}} string?] [:order/type {::mts/clj<->js {:prop "orderType"}} [:or keyword? string?]] #_[:order/items {:optional true ::mts/clj<->js {:prop "orderItems"}} [:ref ::order-items]] [:order/items {:optional true ::mts/clj<->js {:prop "orderItems"}} ::order-items] [:order/total-amount {:optional true ::mts/clj<->js {:prop "totalAmount"}} number?] [:order/user {::mts/clj<->js {:prop "user"} :optional true} [:map [:user/id {::mts/clj<->js {:prop "userId"}} string?] [:user/name {:optional true} string?]]]] r {::order-items order-items-schema} s (m/schema [:schema {:registry {::order-items order-items-schema}} order-schema]) clj-map (to-clj #js {"modelType" ::order "orderId" "2763yughjbh333" "orderType" "Sport Gear" "user" #js {"userId" "u678672" "name" "Kosie"} "orderItems" #js [#js {:orderItem #js {:type "some-test-order-item-type-1" :price #js {:currency :EUR :amount 22.3} :TESTDummyXYZ "TD-A1" :relatedItems #js [#js {:credit #js {:amount 676.30}}]}} #js {:orderItem #js {:type "some-test-order-item-type-2" :price #js {:currency :ZAR :amount 898} :TESTDummyXYZ "TD-B2"}}]} s)] #_{:js->clj-mapping (mts-dm/clj<->js-mapping s :prop) :clj->js-mapping (mts-dm/clj<->js-mapping s :key)} #_(-> clj-map :order/user :user/id) (get-in clj-map [:order/items 0 :order/item :order-item/related-items 0 :order/credit :order-credit/amount]) #_(get-in clj-map [:order/items 1 :order/item :order-item/price :order-item/currency])))
null
https://raw.githubusercontent.com/flowyourmoney/malli-ts/478b5dd190cbdc7a494c03e958ec65d53232441a/src/malli_ts/data_mapping/to_clj.cljs
clojure
else else else else else
(ns malli-ts.data-mapping.to-clj (:require [malli-ts.core :as-alias mts] [malli-ts.data-mapping :as mts-dm] [malli.core :as m] [cljs-bean.core :as b :refer [bean?]])) (defn unwrap [v] (when v (or (unchecked-get v "unwrap/clj") (when (bean? v) v)))) (deftype BeanContext [js<->clj-mapping mapping ^:mutable sub-cache] b/BeanContext (keywords? [_] true) (key->prop [_ key'] (let [s (get mapping key')] (set! sub-cache s) (if s (.-prop s) (name key')))) (prop->key [_ prop] (let [s (get mapping prop)] (set! sub-cache s) (if s (.-key s) (keyword prop)))) (transform [_ v prop key' nth'] (if-some [v (unwrap v)] v (if-some [bean' (cond (object? v) true (array? v) false)] (let [sub-mapping (if (or nth' (not sub-cache)) mapping (let [s (.-schema sub-cache)] (if-let [ref (::mts-dm/ref s)] (js<->clj-mapping ref) s))) bean-context (BeanContext. js<->clj-mapping sub-mapping nil)] (if bean' (b/Bean. nil v bean-context true nil nil nil) (b/ArrayVector. nil bean-context v nil))) v)))) (defn ^:export to-clj ([v js<->clj-mapping] (if-some [v (unwrap v)] v (if-some [bean' (cond (object? v) true (array? v) false)] (let [root (::mts-dm/root js<->clj-mapping) root (if-let [ref (::mts-dm/ref root)] (js<->clj-mapping ref) #_else root) bean-context (BeanContext. js<->clj-mapping root nil)] (if bean' (b/Bean. nil v bean-context true nil nil nil) (b/ArrayVector. nil bean-context v nil))) v))) ([x registry schema & [mapping-options]] (let [s (m/schema [:schema {:registry registry} schema])] (to-clj x (mts-dm/clj<->js-mapping s mapping-options))))) (comment (let [order-items-schema [:vector [:map [:order/item {:optional true ::mts/clj<->js {:prop "orderItem" :fn-to nil :fn-from nil}} [:map [:order-item/id uuid?] [:order-item/type {::mts/clj<->js {:prop "type"}} string?] [:order-item/price [:map [:order-item/currency [:enum :EUR :USD :ZAR]] [:order-item/amount number?]]] [:order-item/test-dummy {::mts/clj<->js {:prop "TESTDummyXYZ"}} string?] [:order-item/related-items [:ref ::order-items] #_[:vector [:map [:related-item/how-is-related string? :related-item/order-item-id uuid?]]]]]] [:order/credit {:optional true} [:map [:order.credit/valid-for-timespan [:enum :milliseconds :seconds :minutes :hours :days]] [:order-credit/amount number?]]]]] order-schema [:map [:model-type [:= ::order]] [:order/id {::mts/clj<->js {:prop "orderId"}} string?] [:order/type {::mts/clj<->js {:prop "orderType"}} [:or keyword? string?]] #_[:order/items {:optional true ::mts/clj<->js {:prop "orderItems"}} [:ref ::order-items]] [:order/items {:optional true ::mts/clj<->js {:prop "orderItems"}} ::order-items] [:order/total-amount {:optional true ::mts/clj<->js {:prop "totalAmount"}} number?] [:order/user {::mts/clj<->js {:prop "user"} :optional true} [:map [:user/id {::mts/clj<->js {:prop "userId"}} string?] [:user/name {:optional true} string?]]]] r {::order-items order-items-schema} s (m/schema [:schema {:registry {::order-items order-items-schema}} order-schema]) clj-map (to-clj #js {"modelType" ::order "orderId" "2763yughjbh333" "orderType" "Sport Gear" "user" #js {"userId" "u678672" "name" "Kosie"} "orderItems" #js [#js {:orderItem #js {:type "some-test-order-item-type-1" :price #js {:currency :EUR :amount 22.3} :TESTDummyXYZ "TD-A1" :relatedItems #js [#js {:credit #js {:amount 676.30}}]}} #js {:orderItem #js {:type "some-test-order-item-type-2" :price #js {:currency :ZAR :amount 898} :TESTDummyXYZ "TD-B2"}}]} s)] #_{:js->clj-mapping (mts-dm/clj<->js-mapping s :prop) :clj->js-mapping (mts-dm/clj<->js-mapping s :key)} #_(-> clj-map :order/user :user/id) (get-in clj-map [:order/items 0 :order/item :order-item/related-items 0 :order/credit :order-credit/amount]) #_(get-in clj-map [:order/items 1 :order/item :order-item/price :order-item/currency])))
19933aa3279b19dd0483a936ed333a79a5b1774a1450f7a6a13d735d8ddd4738
andrewthad/haskell-ip
IPv4TextVariableBuilder.hs
module IPv4TextVariableBuilder where import Net.Types (IPv4(..)) import Data.Text (Text) import Data.Monoid import Data.Word import Data.Bits import qualified Net.IPv4 as IPv4 import qualified Data.Text as Text import qualified Data.Text.Builder.Variable as VB encode :: IPv4 -> Text encode = VB.run variableBuilder variableBuilder :: VB.Builder IPv4 variableBuilder = VB.contramap (word8At 24) VB.word8 <> VB.staticCharBmp '.' <> VB.contramap (word8At 16) VB.word8 <> VB.staticCharBmp '.' <> VB.contramap (word8At 8) VB.word8 <> VB.staticCharBmp '.' <> VB.contramap (word8At 0) VB.word8 word8At :: Int -> IPv4 -> Word8 word8At i (IPv4 w) = fromIntegral (unsafeShiftR w i) # INLINE word8At #
null
https://raw.githubusercontent.com/andrewthad/haskell-ip/4782c5cb44aa6e04c9dbfb4c43909a07ff668216/test/IPv4TextVariableBuilder.hs
haskell
module IPv4TextVariableBuilder where import Net.Types (IPv4(..)) import Data.Text (Text) import Data.Monoid import Data.Word import Data.Bits import qualified Net.IPv4 as IPv4 import qualified Data.Text as Text import qualified Data.Text.Builder.Variable as VB encode :: IPv4 -> Text encode = VB.run variableBuilder variableBuilder :: VB.Builder IPv4 variableBuilder = VB.contramap (word8At 24) VB.word8 <> VB.staticCharBmp '.' <> VB.contramap (word8At 16) VB.word8 <> VB.staticCharBmp '.' <> VB.contramap (word8At 8) VB.word8 <> VB.staticCharBmp '.' <> VB.contramap (word8At 0) VB.word8 word8At :: Int -> IPv4 -> Word8 word8At i (IPv4 w) = fromIntegral (unsafeShiftR w i) # INLINE word8At #
745d73392b58cd72ae8b97edbf02483761c1d795a7ac98b982212a55e95e89cc
xhtmlboi/yocaml
validate.ml
type 'a t = ('a, Error.t Preface.Nonempty_list.t) Preface.Validation.t let valid x = Preface.Validation.Valid x let invalid x = Preface.Validation.Invalid x let error x = invalid (Preface.Nonempty_list.create x) let pp inner_pp = Preface.(Validation.pp inner_pp (Nonempty_list.pp Error.pp)) let equal inner_eq = Preface.(Validation.equal inner_eq (Nonempty_list.equal Error.equal)) ;; let to_try = function | Preface.Validation.Valid x -> Ok x | Preface.Validation.Invalid errs -> Error (Error.List errs) ;; let from_try = function | Ok x -> Preface.Validation.Valid x | Error err -> Preface.(Validation.Invalid (Nonempty_list.create err)) ;; module Error_list = Preface.Make.Semigroup.From_alt (Preface.Nonempty_list.Alt) (Error) module Functor = Preface.Validation.Functor (Error_list) module Applicative = Preface.Validation.Applicative (Error_list) module Selective = Preface.Validation.Selective (Error_list) module Monad = Preface.Validation.Monad (Error_list) module Alt = Preface.Validation.Alt (Error_list) module Infix = struct type nonrec 'a t = 'a t include (Alt.Infix : Preface.Specs.Alt.INFIX with type 'a t := 'a t) include ( Selective.Infix : Preface.Specs.Selective.INFIX with type 'a t := 'a t) include (Monad.Infix : Preface.Specs.Monad.INFIX with type 'a t := 'a t) end module Syntax = struct type nonrec 'a t = 'a t include ( Applicative.Syntax : Preface.Specs.Applicative.SYNTAX with type 'a t := 'a t) include (Monad.Syntax : Preface.Specs.Monad.SYNTAX with type 'a t := 'a t) end include (Infix : module type of Infix with type 'a t := 'a t) include (Syntax : module type of Syntax with type 'a t := 'a t)
null
https://raw.githubusercontent.com/xhtmlboi/yocaml/3d169cdaaec6f84f841b4212d232c1ee6f749b01/lib/yocaml/validate.ml
ocaml
type 'a t = ('a, Error.t Preface.Nonempty_list.t) Preface.Validation.t let valid x = Preface.Validation.Valid x let invalid x = Preface.Validation.Invalid x let error x = invalid (Preface.Nonempty_list.create x) let pp inner_pp = Preface.(Validation.pp inner_pp (Nonempty_list.pp Error.pp)) let equal inner_eq = Preface.(Validation.equal inner_eq (Nonempty_list.equal Error.equal)) ;; let to_try = function | Preface.Validation.Valid x -> Ok x | Preface.Validation.Invalid errs -> Error (Error.List errs) ;; let from_try = function | Ok x -> Preface.Validation.Valid x | Error err -> Preface.(Validation.Invalid (Nonempty_list.create err)) ;; module Error_list = Preface.Make.Semigroup.From_alt (Preface.Nonempty_list.Alt) (Error) module Functor = Preface.Validation.Functor (Error_list) module Applicative = Preface.Validation.Applicative (Error_list) module Selective = Preface.Validation.Selective (Error_list) module Monad = Preface.Validation.Monad (Error_list) module Alt = Preface.Validation.Alt (Error_list) module Infix = struct type nonrec 'a t = 'a t include (Alt.Infix : Preface.Specs.Alt.INFIX with type 'a t := 'a t) include ( Selective.Infix : Preface.Specs.Selective.INFIX with type 'a t := 'a t) include (Monad.Infix : Preface.Specs.Monad.INFIX with type 'a t := 'a t) end module Syntax = struct type nonrec 'a t = 'a t include ( Applicative.Syntax : Preface.Specs.Applicative.SYNTAX with type 'a t := 'a t) include (Monad.Syntax : Preface.Specs.Monad.SYNTAX with type 'a t := 'a t) end include (Infix : module type of Infix with type 'a t := 'a t) include (Syntax : module type of Syntax with type 'a t := 'a t)
10ad047e792ff8f3ce880d0a96e75238c5115aa97bf969e02ed35972f72e6da4
sgbj/MaximaSharp
brmbrg.lisp
;;; -*- Lisp -*- (defvar $brombergit 11) (defvar $brombergmin 0) 1.b-4 0.0b0 (defun fpscale (x m) (if (equal (car x) 0) x (list (car x) (+ (cadr x) m)))) (defun bfmeval3 (x1) (cond (($bfloatp (setq x1 ($bfloat (meval x1)))) (cdr x1)) (t (displa x1) (merror "bromberg: encountered a non-bigfloat.")))) (defun bqeval3 (f x) (cdr (funcall f (bcons x)))) (defun $bromberg (&rest l1) (or (= (length l1) 4) (= (length l1) 3) (merror "bromberg: wrong number of arguments.")) (let ((fun) (var) (a) (b) (x) ($bfloat t) ($float2bf t) (lim (cdr ($bfloat $brombergtol))) (limabs (cdr ($bfloat $brombergabs))) (tt (make-array $brombergit)) (rr (make-array $brombergit)) (zero (intofp 0)) (one (intofp 1)) (three (intofp 3))) (declare (special $bfloat $float2bf)) var = nil = = > first arg is function name (cond (var (setq var (cadr l1) fun (coerce-bfloat-fun (car l1) `((mlist) ,var)) l1 (cdr l1))) (t (setq fun (coerce-bfloat-fun (car l1))))) (setq a (bfmeval3 (cadr l1)) b (bfmeval3 (caddr l1)) x (fpdifference b a)) (setf (aref tt 0) (fpscale (fptimes* x (fpplus (bqeval3 fun b) (bqeval3 fun a))) -1)) (setf (aref rr 0) (fptimes* x (bqeval3 fun (fpscale (fpplus b a) -1)))) (do ((l 1 (1+ l)) (m 4 (* m 2)) (y) (z) (cerr)) ((= l $brombergit) (merror "bromberg: failed to converge.")) (setq y (intofp m) z (fpquotient x y)) (setf (aref tt l) (fpscale (fpplus (aref tt (1- l)) (aref rr (1- l))) -1)) (setf (aref rr l) zero) (do ((i 1 (+ i 2))) ((> i m)) (setf (aref rr l) (fpplus (bqeval3 fun (fpplus (fptimes* z (intofp i)) a)) (aref rr l)))) (setf (aref rr l) (fpscale (fptimes* z (aref rr l)) 1)) (setq y zero) (do ((k l (1- k))) ((zerop k)) (setq y (fpplus (fpscale y 2) three)) (setf (aref tt (1- k)) (fpplus (fpquotient (fpdifference (aref tt k) (aref tt (1- k))) y) (aref tt k))) (setf (aref rr (1- k)) (fpplus (fpquotient (fpdifference (aref rr k) (aref rr (1- k))) y) (aref rr k)))) (setq y (fpscale (fpplus (aref tt 0) (aref rr 0)) -1)) (when (and (or (not (fplessp limabs (setq cerr (fpabs (fpdifference (aref tt 0) (aref rr 0)))))) (not (fplessp lim (fpquotient cerr (cond ((equal y '(0 0)) one) (t (fpabs y))))))) (> l $brombergmin)) (return (bcons y))))))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/numeric/brmbrg.lisp
lisp
-*- Lisp -*-
(defvar $brombergit 11) (defvar $brombergmin 0) 1.b-4 0.0b0 (defun fpscale (x m) (if (equal (car x) 0) x (list (car x) (+ (cadr x) m)))) (defun bfmeval3 (x1) (cond (($bfloatp (setq x1 ($bfloat (meval x1)))) (cdr x1)) (t (displa x1) (merror "bromberg: encountered a non-bigfloat.")))) (defun bqeval3 (f x) (cdr (funcall f (bcons x)))) (defun $bromberg (&rest l1) (or (= (length l1) 4) (= (length l1) 3) (merror "bromberg: wrong number of arguments.")) (let ((fun) (var) (a) (b) (x) ($bfloat t) ($float2bf t) (lim (cdr ($bfloat $brombergtol))) (limabs (cdr ($bfloat $brombergabs))) (tt (make-array $brombergit)) (rr (make-array $brombergit)) (zero (intofp 0)) (one (intofp 1)) (three (intofp 3))) (declare (special $bfloat $float2bf)) var = nil = = > first arg is function name (cond (var (setq var (cadr l1) fun (coerce-bfloat-fun (car l1) `((mlist) ,var)) l1 (cdr l1))) (t (setq fun (coerce-bfloat-fun (car l1))))) (setq a (bfmeval3 (cadr l1)) b (bfmeval3 (caddr l1)) x (fpdifference b a)) (setf (aref tt 0) (fpscale (fptimes* x (fpplus (bqeval3 fun b) (bqeval3 fun a))) -1)) (setf (aref rr 0) (fptimes* x (bqeval3 fun (fpscale (fpplus b a) -1)))) (do ((l 1 (1+ l)) (m 4 (* m 2)) (y) (z) (cerr)) ((= l $brombergit) (merror "bromberg: failed to converge.")) (setq y (intofp m) z (fpquotient x y)) (setf (aref tt l) (fpscale (fpplus (aref tt (1- l)) (aref rr (1- l))) -1)) (setf (aref rr l) zero) (do ((i 1 (+ i 2))) ((> i m)) (setf (aref rr l) (fpplus (bqeval3 fun (fpplus (fptimes* z (intofp i)) a)) (aref rr l)))) (setf (aref rr l) (fpscale (fptimes* z (aref rr l)) 1)) (setq y zero) (do ((k l (1- k))) ((zerop k)) (setq y (fpplus (fpscale y 2) three)) (setf (aref tt (1- k)) (fpplus (fpquotient (fpdifference (aref tt k) (aref tt (1- k))) y) (aref tt k))) (setf (aref rr (1- k)) (fpplus (fpquotient (fpdifference (aref rr k) (aref rr (1- k))) y) (aref rr k)))) (setq y (fpscale (fpplus (aref tt 0) (aref rr 0)) -1)) (when (and (or (not (fplessp limabs (setq cerr (fpabs (fpdifference (aref tt 0) (aref rr 0)))))) (not (fplessp lim (fpquotient cerr (cond ((equal y '(0 0)) one) (t (fpabs y))))))) (> l $brombergmin)) (return (bcons y))))))
5417d33f83f8f2c1db5d9ff1168edba6ca311f2d1190ae90f302d22bdd8e9072
Carnap/Carnap
Util.hs
# LANGUAGE KindSignatures , GADTs , FlexibleContexts , MultiParamTypeClasses , FunctionalDependencies # module Carnap.Calculi.Util where import Data.Tree import Data.Map (Map) import Carnap.Core.Data.Types import Carnap.Core.Data.Classes import Carnap.Core.Unification.Unification import Carnap.Core.Unification.FirstOrder import Carnap.Core.Unification.Huet import Carnap.Core.Unification.ACUI import Carnap.Core.Unification.AU import Carnap.Languages.ClassicalSequent.Syntax import Control.Monad.State import Text.Parsec (ParseError) TODO eventually , Inference should be refactored into this together with one or more ND - specific classes ; also should probably be moved to a new --module class CoreInference r lex sem | r lex -> sem where corePremisesOf :: r -> [ClassicalSequentOver lex (Sequent sem)] corePremisesOf r = upperSequents (coreRuleOf r) coreConclusionOf :: r -> ClassicalSequentOver lex (Sequent sem) coreConclusionOf r = lowerSequent (coreRuleOf r) coreRuleOf :: r -> SequentRule lex sem coreRuleOf r = SequentRule (corePremisesOf r) (coreConclusionOf r) --local restrictions, based only on given substitutions coreRestriction :: r -> Maybe (Restriction lex) coreRestriction _ = Nothing class SpecifiedUnificationType r where unificationType :: r -> UnificationType unificationType _ = ACUIUnification data UnificationType = AssociativeUnification | ACUIUnification type Restriction lex = [Equation (ClassicalSequentOver lex)] -> Maybe String data ProofErrorMessage :: ((* -> *) -> * -> *) -> * where NoParse :: ParseError -> Int -> ProofErrorMessage lex NoUnify :: [[Equation (ClassicalSequentOver lex)]] -> Int -> ProofErrorMessage lex GenericError :: String -> Int -> ProofErrorMessage lex NoResult :: Int -> ProofErrorMessage lex --meant for blanks data RuntimeDeductionConfig lex sem = RuntimeDeductionConfig { derivedRules :: Map String (ClassicalSequentOver lex (Sequent sem)) , runtimeAxioms :: Map String [ClassicalSequentOver lex (Sequent sem)] , problemPremises :: Maybe [ClassicalSequentOver lex (Sequent sem)] } defaultRuntimeDeductionConfig = RuntimeDeductionConfig mempty mempty mempty data TreeFeedbackNode lex = Correct | Waiting | ProofData String | ProofError (ProofErrorMessage lex) type TreeFeedback lex = Tree (TreeFeedbackNode lex) lineNoOfError :: ProofErrorMessage lex -> Int lineNoOfError (NoParse _ n) = n lineNoOfError (NoUnify _ n) = n lineNoOfError (GenericError _ n) = n lineNoOfError (NoResult n) = n renumber :: Int -> ProofErrorMessage lex -> ProofErrorMessage lex renumber m (NoParse x n) = NoParse x m renumber m (NoUnify x n) = NoUnify x m renumber m (GenericError s n) = GenericError s m renumber m (NoResult n) = NoResult m fosolve :: ( FirstOrder (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) ) => [Equation (ClassicalSequentOver lex)] -> Either (ProofErrorMessage lex) [Equation (ClassicalSequentOver lex)] fosolve eqs = case evalState (foUnifySys (const False) eqs) (0 :: Int) of [] -> Left $ NoUnify [eqs] 0 [s] -> Right s homatch :: ( HigherOrder (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) ) => [Equation (ClassicalSequentOver lex)] -> Either (ProofErrorMessage lex) [[Equation (ClassicalSequentOver lex)]] homatch eqs = case evalState (huetMatchSys (const False) eqs) (0 :: Int) of [] -> Left $ NoUnify [eqs] 0 subs -> Right subs acuisolve :: ( ACUI (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) ) => [Equation (ClassicalSequentOver lex)] -> Either (ProofErrorMessage lex) [[Equation (ClassicalSequentOver lex)]] acuisolve eqs = case evalState (acuiUnifySys (const False) eqs) (0 :: Int) of [] -> Left $ NoUnify [eqs] 0 subs -> Right subs ausolve :: ( AU (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) ) => [Equation (ClassicalSequentOver lex)] -> Either (ProofErrorMessage lex) [[Equation (ClassicalSequentOver lex)]] ausolve eqs = case evalState (auMatchSys (const False) eqs) (0 :: Int) of [] -> Left $ NoUnify [eqs] 0 subs -> Right subs
null
https://raw.githubusercontent.com/Carnap/Carnap/1b54e377d1f7a08a3455fa626eef05aee186421a/Carnap/src/Carnap/Calculi/Util.hs
haskell
module local restrictions, based only on given substitutions meant for blanks
# LANGUAGE KindSignatures , GADTs , FlexibleContexts , MultiParamTypeClasses , FunctionalDependencies # module Carnap.Calculi.Util where import Data.Tree import Data.Map (Map) import Carnap.Core.Data.Types import Carnap.Core.Data.Classes import Carnap.Core.Unification.Unification import Carnap.Core.Unification.FirstOrder import Carnap.Core.Unification.Huet import Carnap.Core.Unification.ACUI import Carnap.Core.Unification.AU import Carnap.Languages.ClassicalSequent.Syntax import Control.Monad.State import Text.Parsec (ParseError) TODO eventually , Inference should be refactored into this together with one or more ND - specific classes ; also should probably be moved to a new class CoreInference r lex sem | r lex -> sem where corePremisesOf :: r -> [ClassicalSequentOver lex (Sequent sem)] corePremisesOf r = upperSequents (coreRuleOf r) coreConclusionOf :: r -> ClassicalSequentOver lex (Sequent sem) coreConclusionOf r = lowerSequent (coreRuleOf r) coreRuleOf :: r -> SequentRule lex sem coreRuleOf r = SequentRule (corePremisesOf r) (coreConclusionOf r) coreRestriction :: r -> Maybe (Restriction lex) coreRestriction _ = Nothing class SpecifiedUnificationType r where unificationType :: r -> UnificationType unificationType _ = ACUIUnification data UnificationType = AssociativeUnification | ACUIUnification type Restriction lex = [Equation (ClassicalSequentOver lex)] -> Maybe String data ProofErrorMessage :: ((* -> *) -> * -> *) -> * where NoParse :: ParseError -> Int -> ProofErrorMessage lex NoUnify :: [[Equation (ClassicalSequentOver lex)]] -> Int -> ProofErrorMessage lex GenericError :: String -> Int -> ProofErrorMessage lex data RuntimeDeductionConfig lex sem = RuntimeDeductionConfig { derivedRules :: Map String (ClassicalSequentOver lex (Sequent sem)) , runtimeAxioms :: Map String [ClassicalSequentOver lex (Sequent sem)] , problemPremises :: Maybe [ClassicalSequentOver lex (Sequent sem)] } defaultRuntimeDeductionConfig = RuntimeDeductionConfig mempty mempty mempty data TreeFeedbackNode lex = Correct | Waiting | ProofData String | ProofError (ProofErrorMessage lex) type TreeFeedback lex = Tree (TreeFeedbackNode lex) lineNoOfError :: ProofErrorMessage lex -> Int lineNoOfError (NoParse _ n) = n lineNoOfError (NoUnify _ n) = n lineNoOfError (GenericError _ n) = n lineNoOfError (NoResult n) = n renumber :: Int -> ProofErrorMessage lex -> ProofErrorMessage lex renumber m (NoParse x n) = NoParse x m renumber m (NoUnify x n) = NoUnify x m renumber m (GenericError s n) = GenericError s m renumber m (NoResult n) = NoResult m fosolve :: ( FirstOrder (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) ) => [Equation (ClassicalSequentOver lex)] -> Either (ProofErrorMessage lex) [Equation (ClassicalSequentOver lex)] fosolve eqs = case evalState (foUnifySys (const False) eqs) (0 :: Int) of [] -> Left $ NoUnify [eqs] 0 [s] -> Right s homatch :: ( HigherOrder (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) ) => [Equation (ClassicalSequentOver lex)] -> Either (ProofErrorMessage lex) [[Equation (ClassicalSequentOver lex)]] homatch eqs = case evalState (huetMatchSys (const False) eqs) (0 :: Int) of [] -> Left $ NoUnify [eqs] 0 subs -> Right subs acuisolve :: ( ACUI (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) ) => [Equation (ClassicalSequentOver lex)] -> Either (ProofErrorMessage lex) [[Equation (ClassicalSequentOver lex)]] acuisolve eqs = case evalState (acuiUnifySys (const False) eqs) (0 :: Int) of [] -> Left $ NoUnify [eqs] 0 subs -> Right subs ausolve :: ( AU (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) ) => [Equation (ClassicalSequentOver lex)] -> Either (ProofErrorMessage lex) [[Equation (ClassicalSequentOver lex)]] ausolve eqs = case evalState (auMatchSys (const False) eqs) (0 :: Int) of [] -> Left $ NoUnify [eqs] 0 subs -> Right subs
1bded2d31eebde2792698ae76874138b2769e739b58fd2121a22bd7e7c9d9ddf
nurpax/snaplet-sqlite-simple
Tests.hs
# LANGUAGE OverloadedStrings , ScopedTypeVariables # module Tests ( tests , testsDbInit) where ------------------------------------------------------------------------------ import Control.Error import Control.Monad.State as S import qualified Data.Aeson as A import qualified Data.ByteString.Char8 as BL import qualified Data.HashMap.Lazy as HM import qualified Data.Map as M import Data.Maybe import qualified Data.Text as T import Database.SQLite.Simple import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit hiding (Test, path) ------------------------------------------------------------------------------ import App import Snap.Snaplet import Snap.Snaplet.Auth import qualified Snap.Snaplet.SqliteSimple as SQ import qualified Snap.Test as ST import Snap.Snaplet.Test ------------------------------------------------------------------------------ tests :: Test tests = mutuallyExclusive $ testGroup "Snap.Snaplet.SqliteSimple" [ testInitDbEmpty , testCreateUserGood , testUpdateUser ] ------------------------------------------------------------------------------ testsDbInit :: Test testsDbInit = mutuallyExclusive $ testGroup "Snap.Snaplet.SqliteSimple" [ -- Empty db testInitDbEmpty , testCreateUserGood , testUpdateUser -- Create empty db with old schema + one user , testInitDbSchema0 , testCreateUserGood , testUpdateUser -- Create empty db, add user in old schema, then access it , testInitDbSchema0WithUser , testUpdateUser -- Create empty db, add user in old schema, then access it, and delete it , testInitDbSchema0 , testCreateUserGood , testDeleteUser -- Create empty db, perform some basic queries , testInitDbSchema0 , testQueries -- Login tests, these use some otherwise uncovered DB backend -- functions. , testInitDbSchema0WithUser , testLoginByRememberTokenKO , testLoginByRememberTokenOK , testLogoutOK , testCurrentUserKO , testCurrentUserOK ] dropTables :: Connection -> IO () dropTables conn = do execute_ conn "DROP TABLE IF EXISTS snap_auth_user" execute_ conn "DROP TABLE IF EXISTS snap_auth_user_version" Must be the first on the test list for basic database -- initialization (schema creation for snap_auth_user, etc.) testInitDbEmpty :: Test testInitDbEmpty = testCase "snaplet database init" go where go = do conn <- open "test.db" dropTables conn close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True initSchema0 :: Query initSchema0 = Query $ T.concat [ "CREATE TABLE snap_auth_user (uid INTEGER PRIMARY KEY," , "login text UNIQUE NOT NULL," , "password text," , "activated_at timestamp,suspended_at timestamp,remember_token text," , "login_count INTEGER NOT NULL,failed_login_count INTEGER NOT NULL," , "locked_out_until timestamp,current_login_at timestamp," , "last_login_at timestamp,current_login_ip text," , "last_login_ip text,created_at timestamp,updated_at timestamp);" ] addFooUserSchema0 :: Query addFooUserSchema0 = "INSERT INTO snap_auth_user VALUES(1,'foo',X'7368613235367C31327C39426E5255534356444B4E6A3553716345774E756E513D3D7C633534506C69614A42314E483562677143494651616732454C75444B684F37745A78655479456C4F6F356F3D',NULL,NULL,'2cc0caf41bd7387150cc1416ac38bccc36e64c11a8945f72298ea366ffa8fc97',0,0,NULL,'2012-11-28 21:59:15.150153','2012-11-28 21:59:15.109848',NULL, NULL, '2012-11-28 21:59:15.052817','2012-11-28 21:59:15.052817');" Must be the first on the test list for basic database -- initialization (schema creation for snap_auth_user, etc.) testInitDbSchema0 :: Test testInitDbSchema0 = testCase "init db with schema0" $ do conn <- open "test.db" dropTables conn execute_ conn initSchema0 close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True Initialize db schema to an empty schema0 and add a user ' foo ' . The expectation is that snaplet initialization needs to do schema -- migration for the tables and rows. testInitDbSchema0WithUser :: Test testInitDbSchema0WithUser = testCase "init + add foo user directly" $ do conn <- open "test.db" dropTables conn execute_ conn initSchema0 execute_ conn addFooUserSchema0 close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True ------------------------------------------------------------------------------ testCreateUserGood :: Test testCreateUserGood = testCase "createUser good params" assertGoodUser where assertGoodUser :: Assertion assertGoodUser = do let hdl = with auth $ createUser "foo" "foo" res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) checkUserFields res checkUserFields (Left _) = assertBool "createUser failed: Couldn't create a new user." False checkUserFields (Right u) = do assertEqual "login match" "foo" (userLogin u) assertEqual "login count" 0 (userLoginCount u) assertEqual "fail count" 0 (userFailedLoginCount u) assertEqual "local host ip" Nothing (userCurrentLoginIp u) assertEqual "local host ip" Nothing (userLastLoginIp u) assertEqual "locked until" Nothing (userLockedOutUntil u) assertEqual "empty email" Nothing (userEmail u) assertEqual "roles" [] (userRoles u) assertEqual "meta" HM.empty (userMeta u) ------------------------------------------------------------------------------ -- Create a user, modify it, persist it and load again, check fields ok. -- Must run after testCreateUserGood testUpdateUser :: Test testUpdateUser = testCase "createUser + update good params" assertGoodUser where assertGoodUser :: Assertion assertGoodUser = do let loginHdl = with auth $ loginByUsername "foo" (ClearText "foo") True res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) checkLoggedInUser res checkLoggedInUser (Left _) = assertBool "failed login" False checkLoggedInUser (Right u) = do assertEqual "login count" 1 (userLoginCount u) assertEqual "fail count" 0 (userFailedLoginCount u) assertEqual "locked until" Nothing (userLockedOutUntil u) assertEqual "local host ip" (Just "127.0.0.1") (userCurrentLoginIp u) assertEqual "no previous login" Nothing (userLastLoginIp u) let saveHdl = with auth $ saveUser (u { userLogin = "bar" , userRoles = roles , userMeta = meta }) res <- evalHandler Nothing (ST.get "" M.empty) saveHdl appInit either (assertFailure . show) checkUpdatedUser res roles = [Role $ BL.pack "Superman", Role $ BL.pack "Journalist"] meta = HM.fromList [ (T.pack "email-verified", A.toJSON $ T.pack "yes") , (T.pack "suppress-products", A.toJSON [T.pack "Kryptonite"]) ] checkUpdatedUser (Left _) = assertBool "failed saveUser" False checkUpdatedUser (Right u) = do assertEqual "login rename ok?" "bar" (userLogin u) assertEqual "login count" 1 (userLoginCount u) assertEqual "local host ip" (Just "127.0.0.1") (userCurrentLoginIp u) assertEqual "local host ip" Nothing (userLastLoginIp u) assertEqual "account roles" roles (userRoles u) assertEqual "account meta data" meta (userMeta u) let loginHdl = with auth $ loginByUsername "bar" (ClearText "foo") True res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) (assertBool "login as 'bar' ok?" . isRight) res ------------------------------------------------------------------------------ -- Test that deleting a user works. testDeleteUser :: Test testDeleteUser = testCase "delete a user" assertGoodUser where loginHdl = with auth $ loginByUsername "foo" (ClearText "foo") True assertGoodUser :: Assertion assertGoodUser = do res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) delUser res delUser (Left _) = assertBool "failed login" False delUser (Right u) = do let delHdl = with auth $ destroyUser u Right res <- evalHandler Nothing (ST.get "" M.empty) delHdl appInit res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) (assertBool "login as 'foo' should fail now" . isLeft) res ------------------------------------------------------------------------------ -- Query tests testQueries :: Test testQueries = testCase "basic queries" runTest where queries = do SQ.execute_ "CREATE TABLE foo (id INTEGER PRIMARY KEY, t TEXT)" SQ.execute "INSERT INTO foo (t) VALUES (?)" (Only ("bar" :: String)) [(a :: Int,b :: String)] <- SQ.query_ "SELECT id,t FROM foo" [Only (s :: String)] <- SQ.query "SELECT t FROM foo WHERE id = ?" (Only (1 :: Int)) withTop db . SQ.withSqlite $ \conn -> do a @=? 1 b @=? "bar" s @=? "bar" [Only (v :: Int)] <- query_ conn "SELECT 1+1" v @=? 2 runTest :: Assertion runTest = do r <- evalHandler Nothing (ST.get "" M.empty) queries appInit return () ------------------------------------------------------------------------------ testLoginByRememberTokenKO :: Test testLoginByRememberTokenKO = testCase "loginByRememberToken no token" assertion where assertion :: Assertion assertion = do let hdl = with auth loginByRememberToken res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isLeft) res failMsg = "loginByRememberToken: Expected to fail for the " ++ "absence of a token, but didn't." ------------------------------------------------------------------------------ testLoginByRememberTokenOK :: Test testLoginByRememberTokenOK = testCase "loginByRememberToken token" assertion where assertion :: Assertion assertion = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit case res of (Left e) -> assertFailure $ show e (Right res') -> assertBool failMsg $ isRight res' hdl :: Handler App App (Either AuthFailure AuthUser) hdl = with auth $ do res <- loginByUsername "foo" (ClearText "foo") True either (\e -> return (Left e)) (\_ -> loginByRememberToken) res failMsg = "loginByRememberToken: Expected to succeed but didn't." ------------------------------------------------------------------------------ assertLogout :: Handler App App (Maybe AuthUser) -> String -> Assertion assertLogout hdl failMsg = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isNothing) res testLogoutOK :: Test testLogoutOK = testCase "logout user logged in." $ assertLogout hdl failMsg where hdl :: Handler App App (Maybe AuthUser) hdl = with auth $ do loginByUsername "foo" (ClearText "foo") True logout mgr <- get return (activeUser mgr) failMsg = "logout: Expected to get Nothing as the active user, " ++ " but didn't." ------------------------------------------------------------------------------ testCurrentUserKO :: Test testCurrentUserKO = testCase "currentUser unsuccesful call" assertion where assertion :: Assertion assertion = do let hdl = with auth currentUser res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isNothing) res failMsg = "currentUser: Expected Nothing as the current user, " ++ " but didn't." ------------------------------------------------------------------------------ testCurrentUserOK :: Test testCurrentUserOK = testCase "successful currentUser call" assertion where assertion :: Assertion assertion = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isJust) res hdl :: Handler App App (Maybe AuthUser) hdl = with auth $ do res <- loginByUsername "foo" (ClearText "foo") True either (\_ -> return Nothing) (\_ -> currentUser) res failMsg = "currentUser: Expected to get the current user, " ++ " but didn't."
null
https://raw.githubusercontent.com/nurpax/snaplet-sqlite-simple/f19f0ff9018f3886544901bdacda133a42bc2476/test/Tests.hs
haskell
---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Empty db Create empty db with old schema + one user Create empty db, add user in old schema, then access it Create empty db, add user in old schema, then access it, and delete it Create empty db, perform some basic queries Login tests, these use some otherwise uncovered DB backend functions. initialization (schema creation for snap_auth_user, etc.) initialization (schema creation for snap_auth_user, etc.) migration for the tables and rows. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Create a user, modify it, persist it and load again, check fields ok. Must run after testCreateUserGood ---------------------------------------------------------------------------- Test that deleting a user works. ---------------------------------------------------------------------------- Query tests ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ----------------------------------------------------------------------------
# LANGUAGE OverloadedStrings , ScopedTypeVariables # module Tests ( tests , testsDbInit) where import Control.Error import Control.Monad.State as S import qualified Data.Aeson as A import qualified Data.ByteString.Char8 as BL import qualified Data.HashMap.Lazy as HM import qualified Data.Map as M import Data.Maybe import qualified Data.Text as T import Database.SQLite.Simple import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit hiding (Test, path) import App import Snap.Snaplet import Snap.Snaplet.Auth import qualified Snap.Snaplet.SqliteSimple as SQ import qualified Snap.Test as ST import Snap.Snaplet.Test tests :: Test tests = mutuallyExclusive $ testGroup "Snap.Snaplet.SqliteSimple" [ testInitDbEmpty , testCreateUserGood , testUpdateUser ] testsDbInit :: Test testsDbInit = mutuallyExclusive $ testGroup "Snap.Snaplet.SqliteSimple" testInitDbEmpty , testCreateUserGood , testUpdateUser , testInitDbSchema0 , testCreateUserGood , testUpdateUser , testInitDbSchema0WithUser , testUpdateUser , testInitDbSchema0 , testCreateUserGood , testDeleteUser , testInitDbSchema0 , testQueries , testInitDbSchema0WithUser , testLoginByRememberTokenKO , testLoginByRememberTokenOK , testLogoutOK , testCurrentUserKO , testCurrentUserOK ] dropTables :: Connection -> IO () dropTables conn = do execute_ conn "DROP TABLE IF EXISTS snap_auth_user" execute_ conn "DROP TABLE IF EXISTS snap_auth_user_version" Must be the first on the test list for basic database testInitDbEmpty :: Test testInitDbEmpty = testCase "snaplet database init" go where go = do conn <- open "test.db" dropTables conn close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True initSchema0 :: Query initSchema0 = Query $ T.concat [ "CREATE TABLE snap_auth_user (uid INTEGER PRIMARY KEY," , "login text UNIQUE NOT NULL," , "password text," , "activated_at timestamp,suspended_at timestamp,remember_token text," , "login_count INTEGER NOT NULL,failed_login_count INTEGER NOT NULL," , "locked_out_until timestamp,current_login_at timestamp," , "last_login_at timestamp,current_login_ip text," , "last_login_ip text,created_at timestamp,updated_at timestamp);" ] addFooUserSchema0 :: Query addFooUserSchema0 = "INSERT INTO snap_auth_user VALUES(1,'foo',X'7368613235367C31327C39426E5255534356444B4E6A3553716345774E756E513D3D7C633534506C69614A42314E483562677143494651616732454C75444B684F37745A78655479456C4F6F356F3D',NULL,NULL,'2cc0caf41bd7387150cc1416ac38bccc36e64c11a8945f72298ea366ffa8fc97',0,0,NULL,'2012-11-28 21:59:15.150153','2012-11-28 21:59:15.109848',NULL, NULL, '2012-11-28 21:59:15.052817','2012-11-28 21:59:15.052817');" Must be the first on the test list for basic database testInitDbSchema0 :: Test testInitDbSchema0 = testCase "init db with schema0" $ do conn <- open "test.db" dropTables conn execute_ conn initSchema0 close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True Initialize db schema to an empty schema0 and add a user ' foo ' . The expectation is that snaplet initialization needs to do schema testInitDbSchema0WithUser :: Test testInitDbSchema0WithUser = testCase "init + add foo user directly" $ do conn <- open "test.db" dropTables conn execute_ conn initSchema0 execute_ conn addFooUserSchema0 close conn (_, _handler, _doCleanup) <- runSnaplet Nothing appInit assertBool "init ok" True testCreateUserGood :: Test testCreateUserGood = testCase "createUser good params" assertGoodUser where assertGoodUser :: Assertion assertGoodUser = do let hdl = with auth $ createUser "foo" "foo" res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) checkUserFields res checkUserFields (Left _) = assertBool "createUser failed: Couldn't create a new user." False checkUserFields (Right u) = do assertEqual "login match" "foo" (userLogin u) assertEqual "login count" 0 (userLoginCount u) assertEqual "fail count" 0 (userFailedLoginCount u) assertEqual "local host ip" Nothing (userCurrentLoginIp u) assertEqual "local host ip" Nothing (userLastLoginIp u) assertEqual "locked until" Nothing (userLockedOutUntil u) assertEqual "empty email" Nothing (userEmail u) assertEqual "roles" [] (userRoles u) assertEqual "meta" HM.empty (userMeta u) testUpdateUser :: Test testUpdateUser = testCase "createUser + update good params" assertGoodUser where assertGoodUser :: Assertion assertGoodUser = do let loginHdl = with auth $ loginByUsername "foo" (ClearText "foo") True res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) checkLoggedInUser res checkLoggedInUser (Left _) = assertBool "failed login" False checkLoggedInUser (Right u) = do assertEqual "login count" 1 (userLoginCount u) assertEqual "fail count" 0 (userFailedLoginCount u) assertEqual "locked until" Nothing (userLockedOutUntil u) assertEqual "local host ip" (Just "127.0.0.1") (userCurrentLoginIp u) assertEqual "no previous login" Nothing (userLastLoginIp u) let saveHdl = with auth $ saveUser (u { userLogin = "bar" , userRoles = roles , userMeta = meta }) res <- evalHandler Nothing (ST.get "" M.empty) saveHdl appInit either (assertFailure . show) checkUpdatedUser res roles = [Role $ BL.pack "Superman", Role $ BL.pack "Journalist"] meta = HM.fromList [ (T.pack "email-verified", A.toJSON $ T.pack "yes") , (T.pack "suppress-products", A.toJSON [T.pack "Kryptonite"]) ] checkUpdatedUser (Left _) = assertBool "failed saveUser" False checkUpdatedUser (Right u) = do assertEqual "login rename ok?" "bar" (userLogin u) assertEqual "login count" 1 (userLoginCount u) assertEqual "local host ip" (Just "127.0.0.1") (userCurrentLoginIp u) assertEqual "local host ip" Nothing (userLastLoginIp u) assertEqual "account roles" roles (userRoles u) assertEqual "account meta data" meta (userMeta u) let loginHdl = with auth $ loginByUsername "bar" (ClearText "foo") True res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) (assertBool "login as 'bar' ok?" . isRight) res testDeleteUser :: Test testDeleteUser = testCase "delete a user" assertGoodUser where loginHdl = with auth $ loginByUsername "foo" (ClearText "foo") True assertGoodUser :: Assertion assertGoodUser = do res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) delUser res delUser (Left _) = assertBool "failed login" False delUser (Right u) = do let delHdl = with auth $ destroyUser u Right res <- evalHandler Nothing (ST.get "" M.empty) delHdl appInit res <- evalHandler Nothing (ST.get "" M.empty) loginHdl appInit either (assertFailure . show) (assertBool "login as 'foo' should fail now" . isLeft) res testQueries :: Test testQueries = testCase "basic queries" runTest where queries = do SQ.execute_ "CREATE TABLE foo (id INTEGER PRIMARY KEY, t TEXT)" SQ.execute "INSERT INTO foo (t) VALUES (?)" (Only ("bar" :: String)) [(a :: Int,b :: String)] <- SQ.query_ "SELECT id,t FROM foo" [Only (s :: String)] <- SQ.query "SELECT t FROM foo WHERE id = ?" (Only (1 :: Int)) withTop db . SQ.withSqlite $ \conn -> do a @=? 1 b @=? "bar" s @=? "bar" [Only (v :: Int)] <- query_ conn "SELECT 1+1" v @=? 2 runTest :: Assertion runTest = do r <- evalHandler Nothing (ST.get "" M.empty) queries appInit return () testLoginByRememberTokenKO :: Test testLoginByRememberTokenKO = testCase "loginByRememberToken no token" assertion where assertion :: Assertion assertion = do let hdl = with auth loginByRememberToken res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isLeft) res failMsg = "loginByRememberToken: Expected to fail for the " ++ "absence of a token, but didn't." testLoginByRememberTokenOK :: Test testLoginByRememberTokenOK = testCase "loginByRememberToken token" assertion where assertion :: Assertion assertion = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit case res of (Left e) -> assertFailure $ show e (Right res') -> assertBool failMsg $ isRight res' hdl :: Handler App App (Either AuthFailure AuthUser) hdl = with auth $ do res <- loginByUsername "foo" (ClearText "foo") True either (\e -> return (Left e)) (\_ -> loginByRememberToken) res failMsg = "loginByRememberToken: Expected to succeed but didn't." assertLogout :: Handler App App (Maybe AuthUser) -> String -> Assertion assertLogout hdl failMsg = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isNothing) res testLogoutOK :: Test testLogoutOK = testCase "logout user logged in." $ assertLogout hdl failMsg where hdl :: Handler App App (Maybe AuthUser) hdl = with auth $ do loginByUsername "foo" (ClearText "foo") True logout mgr <- get return (activeUser mgr) failMsg = "logout: Expected to get Nothing as the active user, " ++ " but didn't." testCurrentUserKO :: Test testCurrentUserKO = testCase "currentUser unsuccesful call" assertion where assertion :: Assertion assertion = do let hdl = with auth currentUser res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isNothing) res failMsg = "currentUser: Expected Nothing as the current user, " ++ " but didn't." testCurrentUserOK :: Test testCurrentUserOK = testCase "successful currentUser call" assertion where assertion :: Assertion assertion = do res <- evalHandler Nothing (ST.get "" M.empty) hdl appInit either (assertFailure . show) (assertBool failMsg . isJust) res hdl :: Handler App App (Maybe AuthUser) hdl = with auth $ do res <- loginByUsername "foo" (ClearText "foo") True either (\_ -> return Nothing) (\_ -> currentUser) res failMsg = "currentUser: Expected to get the current user, " ++ " but didn't."
a3ba0ee6fcdf93710e56751981e1e3de3bc0f7940819fc91ff5c2cb4ede6b9bc
exoscale/clojure-kubernetes-client
v1_local_object_reference.clj
(ns clojure-kubernetes-client.specs.v1-local-object-reference (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] ) (:import (java.io File))) (declare v1-local-object-reference-data v1-local-object-reference) (def v1-local-object-reference-data { (ds/opt :name) string? }) (def v1-local-object-reference (ds/spec {:name ::v1-local-object-reference :spec v1-local-object-reference-data}))
null
https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_local_object_reference.clj
clojure
(ns clojure-kubernetes-client.specs.v1-local-object-reference (:require [clojure.spec.alpha :as s] [spec-tools.data-spec :as ds] ) (:import (java.io File))) (declare v1-local-object-reference-data v1-local-object-reference) (def v1-local-object-reference-data { (ds/opt :name) string? }) (def v1-local-object-reference (ds/spec {:name ::v1-local-object-reference :spec v1-local-object-reference-data}))
c10b2d39657f0a78cfbd1b0006de9bced3004fb2ca14bb16745ec7d0638c83fb
dcastro/haskell-flatbuffers
Generated.hs
# LANGUAGE TemplateHaskell # module Examples.Generated where import FlatBuffers ( defaultOptions, mkFlatBuffers ) $(mkFlatBuffers "test/Examples/schema.fbs" defaultOptions) $(mkFlatBuffers "test/Examples/vector_of_unions.fbs" defaultOptions)
null
https://raw.githubusercontent.com/dcastro/haskell-flatbuffers/cea6a75109de109ae906741ee73cbb0f356a8e0d/test/Examples/Generated.hs
haskell
# LANGUAGE TemplateHaskell # module Examples.Generated where import FlatBuffers ( defaultOptions, mkFlatBuffers ) $(mkFlatBuffers "test/Examples/schema.fbs" defaultOptions) $(mkFlatBuffers "test/Examples/vector_of_unions.fbs" defaultOptions)
3b94fcf12fd964ee56148a54e2bbc36c03683039de8da84d7ddb351d0354bbbd
haskell/haskell-language-server
PunShadowing.expected.hs
data Bar = Bar { ax :: Int, bax :: Bool } bar :: () -> Bar -> Int bar ax Bar {ax = n, bax} = _w0
null
https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/PunShadowing.expected.hs
haskell
data Bar = Bar { ax :: Int, bax :: Bool } bar :: () -> Bar -> Int bar ax Bar {ax = n, bax} = _w0
31a6a0336187ddc68728bdaedff931f9efdc1c54e3e923fdcf82bd66919c84b3
metaocaml/ber-metaocaml
pr9019.ml
(* TEST * expect *) # 9012 by type ab = A | B module M : sig type mab = A | B type _ t = AB : ab t | MAB : mab t val ab : mab t end = struct type mab = ab = A | B type _ t = AB : ab t | MAB : mab t let ab = AB end [%%expect{| type ab = A | B module M : sig type mab = A | B type _ t = AB : ab t | MAB : mab t val ab : mab t end |}] open M let f (type x) (t1 : x t) (t2 : x t) (x : x) = match t1, t2, x with | AB, AB, A -> 1 | MAB, _, A -> 2 | _, AB, B -> 3 | _, MAB, B -> 4 [%%expect{| Lines 4-8, characters 2-18: 4 | ..match t1, t2, x with 5 | | AB, AB, A -> 1 6 | | MAB, _, A -> 2 7 | | _, AB, B -> 3 8 | | _, MAB, B -> 4 Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: (AB, MAB, A) val f : 'x M.t -> 'x M.t -> 'x -> int = <fun> |}] let () = ignore (f M.ab MAB A) [%%expect{| Exception: Match_failure ("", 4, 2). |}] (* variant *) type _ ab = A | B module M : sig type _ mab type _ t = AB : unit ab t | MAB : unit mab t val ab : unit mab t val a : 'a mab val b : 'a mab end = struct type 'a mab = 'a ab = A | B type _ t = AB : unit ab t | MAB : unit mab t let ab = AB let a = A let b = B end;; [%%expect{| type _ ab = A | B module M : sig type _ mab type _ t = AB : unit ab t | MAB : unit mab t val ab : unit mab t val a : 'a mab val b : 'a mab end |}] open M The second clause is n't redundant let f (type x) (t1 : x t) (t2 : x t) (x : x) = match t1, t2, x with | AB, AB, A -> 1 | _, AB, A -> 2 | _, AB, B -> 3 | _, MAB, _ -> 4;; [%%expect{| val f : 'x M.t -> 'x M.t -> 'x -> int = <fun> |}] the answer should n't be 3 let x = f MAB M.ab M.a;; [%%expect{| val x : int = 2 |}] (* using records *) type ab = { a : int } module M : sig type mab = { a : int } type _ t = AB : ab t | MAB : mab t val a : mab val ab : mab t end = struct type mab = ab = { a : int } type _ t = AB : ab t | MAB : mab t let a = { a = 42 } let ab = AB end;; [%%expect{| type ab = { a : int; } module M : sig type mab = { a : int; } type _ t = AB : ab t | MAB : mab t val a : mab val ab : mab t end |}] open M let f (type x) (t1 : x t) (t2 : x t) (x : x) = match t1, t2, x with | AB, AB, { a = _ } -> 1 | MAB, _, { a = _ } -> 2 | _, AB, { a = _ } -> 3 | _, MAB, { a = _ } -> 4;; [%%expect{| Line 7, characters 4-22: 7 | | _, AB, { a = _ } -> 3 ^^^^^^^^^^^^^^^^^^ Warning 11: this match case is unused. val f : 'x M.t -> 'x M.t -> 'x -> int = <fun> |}] let p = f M.ab MAB { a = 42 };; [%%expect{| val p : int = 4 |}] # 9019 by type _ a_or_b = A_or_B : [< `A of string | `B of int] a_or_b type _ a = | A : [> `A of string] a | Not_A : _ a let f (type x) (a : x a) (a_or_b : x a_or_b) (x : x) = match a, a_or_b, x with | Not_A, A_or_B, `B i -> print_int i | _, A_or_B, `A s -> print_string s [%%expect{| type _ a_or_b = A_or_B : [< `A of string | `B of int ] a_or_b type _ a = A : [> `A of string ] a | Not_A : 'a a Lines 9-11, characters 2-37: 9 | ..match a, a_or_b, x with 10 | | Not_A, A_or_B, `B i -> print_int i 11 | | _, A_or_B, `A s -> print_string s Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: (A, A_or_B, `B _) val f : 'x a -> 'x a_or_b -> 'x -> unit = <fun> |}] let segfault = f A A_or_B (`B 0) [%%expect{| Exception: Match_failure ("", 9, 2). |}] (* Another example *) type (_, _) b = | A : ([< `A ], 'a) b | B : ([< `B of 'a], 'a) b type _ ty = | String_option : string option ty let f (type x) (type y) (b : (x, y ty) b) (x : x) (y : y) = match b, x, y with | B, `B String_option, Some s -> print_string s | A, `A, _ -> () [%%expect{| type (_, _) b = A : ([< `A ], 'a) b | B : ([< `B of 'a ], 'a) b type _ ty = String_option : string option ty Lines 9-11, characters 2-18: 9 | ..match b, x, y with 10 | | B, `B String_option, Some s -> print_string s 11 | | A, `A, _ -> () Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: (B, `B String_option, None) val f : ('x, 'y ty) b -> 'x -> 'y -> unit = <fun> |}] let segfault = f B (`B String_option) None [%%expect{| Exception: Match_failure ("", 9, 2). |}] (* More polymorphic variants *) type 'a a = private [< `A of 'a];; let f (x : _ a) = match x with `A None -> ();; [%%expect{| type 'a a = private [< `A of 'a ] Line 2, characters 18-44: 2 | let f (x : _ a) = match x with `A None -> ();; ^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `A (Some _) val f : 'a option a -> unit = <fun> |}] let f (x : [> `A] a) = match x with `A `B -> ();; [%%expect{| Line 1, characters 23-47: 1 | let f (x : [> `A] a) = match x with `A `B -> ();; ^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `A `A val f : [< `A | `B > `A ] a -> unit = <fun> |}]
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-gadts/pr9019.ml
ocaml
TEST * expect variant using records Another example More polymorphic variants
# 9012 by type ab = A | B module M : sig type mab = A | B type _ t = AB : ab t | MAB : mab t val ab : mab t end = struct type mab = ab = A | B type _ t = AB : ab t | MAB : mab t let ab = AB end [%%expect{| type ab = A | B module M : sig type mab = A | B type _ t = AB : ab t | MAB : mab t val ab : mab t end |}] open M let f (type x) (t1 : x t) (t2 : x t) (x : x) = match t1, t2, x with | AB, AB, A -> 1 | MAB, _, A -> 2 | _, AB, B -> 3 | _, MAB, B -> 4 [%%expect{| Lines 4-8, characters 2-18: 4 | ..match t1, t2, x with 5 | | AB, AB, A -> 1 6 | | MAB, _, A -> 2 7 | | _, AB, B -> 3 8 | | _, MAB, B -> 4 Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: (AB, MAB, A) val f : 'x M.t -> 'x M.t -> 'x -> int = <fun> |}] let () = ignore (f M.ab MAB A) [%%expect{| Exception: Match_failure ("", 4, 2). |}] type _ ab = A | B module M : sig type _ mab type _ t = AB : unit ab t | MAB : unit mab t val ab : unit mab t val a : 'a mab val b : 'a mab end = struct type 'a mab = 'a ab = A | B type _ t = AB : unit ab t | MAB : unit mab t let ab = AB let a = A let b = B end;; [%%expect{| type _ ab = A | B module M : sig type _ mab type _ t = AB : unit ab t | MAB : unit mab t val ab : unit mab t val a : 'a mab val b : 'a mab end |}] open M The second clause is n't redundant let f (type x) (t1 : x t) (t2 : x t) (x : x) = match t1, t2, x with | AB, AB, A -> 1 | _, AB, A -> 2 | _, AB, B -> 3 | _, MAB, _ -> 4;; [%%expect{| val f : 'x M.t -> 'x M.t -> 'x -> int = <fun> |}] the answer should n't be 3 let x = f MAB M.ab M.a;; [%%expect{| val x : int = 2 |}] type ab = { a : int } module M : sig type mab = { a : int } type _ t = AB : ab t | MAB : mab t val a : mab val ab : mab t end = struct type mab = ab = { a : int } type _ t = AB : ab t | MAB : mab t let a = { a = 42 } let ab = AB end;; [%%expect{| type ab = { a : int; } module M : sig type mab = { a : int; } type _ t = AB : ab t | MAB : mab t val a : mab val ab : mab t end |}] open M let f (type x) (t1 : x t) (t2 : x t) (x : x) = match t1, t2, x with | AB, AB, { a = _ } -> 1 | MAB, _, { a = _ } -> 2 | _, AB, { a = _ } -> 3 | _, MAB, { a = _ } -> 4;; [%%expect{| Line 7, characters 4-22: 7 | | _, AB, { a = _ } -> 3 ^^^^^^^^^^^^^^^^^^ Warning 11: this match case is unused. val f : 'x M.t -> 'x M.t -> 'x -> int = <fun> |}] let p = f M.ab MAB { a = 42 };; [%%expect{| val p : int = 4 |}] # 9019 by type _ a_or_b = A_or_B : [< `A of string | `B of int] a_or_b type _ a = | A : [> `A of string] a | Not_A : _ a let f (type x) (a : x a) (a_or_b : x a_or_b) (x : x) = match a, a_or_b, x with | Not_A, A_or_B, `B i -> print_int i | _, A_or_B, `A s -> print_string s [%%expect{| type _ a_or_b = A_or_B : [< `A of string | `B of int ] a_or_b type _ a = A : [> `A of string ] a | Not_A : 'a a Lines 9-11, characters 2-37: 9 | ..match a, a_or_b, x with 10 | | Not_A, A_or_B, `B i -> print_int i 11 | | _, A_or_B, `A s -> print_string s Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: (A, A_or_B, `B _) val f : 'x a -> 'x a_or_b -> 'x -> unit = <fun> |}] let segfault = f A A_or_B (`B 0) [%%expect{| Exception: Match_failure ("", 9, 2). |}] type (_, _) b = | A : ([< `A ], 'a) b | B : ([< `B of 'a], 'a) b type _ ty = | String_option : string option ty let f (type x) (type y) (b : (x, y ty) b) (x : x) (y : y) = match b, x, y with | B, `B String_option, Some s -> print_string s | A, `A, _ -> () [%%expect{| type (_, _) b = A : ([< `A ], 'a) b | B : ([< `B of 'a ], 'a) b type _ ty = String_option : string option ty Lines 9-11, characters 2-18: 9 | ..match b, x, y with 10 | | B, `B String_option, Some s -> print_string s 11 | | A, `A, _ -> () Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: (B, `B String_option, None) val f : ('x, 'y ty) b -> 'x -> 'y -> unit = <fun> |}] let segfault = f B (`B String_option) None [%%expect{| Exception: Match_failure ("", 9, 2). |}] type 'a a = private [< `A of 'a];; let f (x : _ a) = match x with `A None -> ();; [%%expect{| type 'a a = private [< `A of 'a ] Line 2, characters 18-44: 2 | let f (x : _ a) = match x with `A None -> ();; ^^^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `A (Some _) val f : 'a option a -> unit = <fun> |}] let f (x : [> `A] a) = match x with `A `B -> ();; [%%expect{| Line 1, characters 23-47: 1 | let f (x : [> `A] a) = match x with `A `B -> ();; ^^^^^^^^^^^^^^^^^^^^^^^^ Warning 8: this pattern-matching is not exhaustive. Here is an example of a case that is not matched: `A `A val f : [< `A | `B > `A ] a -> unit = <fun> |}]
e2993e690a0b00d920cfe741dda59b6278bd70b752498aefe9a9a19a5a4c7276
returntocorp/semgrep
Src_file.ml
(* Keep a copy of the source input, suitable for returning source code from ranges of locations. *) open Printf type source = File of string | Stdin | String | Channel (* The contents of the source document. *) type t = { source : source; contents : string } let source x = x.source let show_source = function | File s -> s | Stdin -> "<stdin>" | String -> "<string>" | Channel -> "<channel>" let source_string x = x |> source |> show_source let contents x = x.contents let length x = String.length x.contents let replace_contents x f = { x with contents = f x.contents } let of_string ?(source = String) contents = { source; contents } let partial_input max_len ic = let buf = Bytes.create max_len in let rec read pos remaining = if remaining > 0 then let n_read = input ic buf pos remaining in if n_read > 0 then read (pos + n_read) (remaining - n_read) else pos else pos in let len = read 0 max_len in Bytes.sub_string buf 0 len let get_channel_length ic = try Some (in_channel_length ic) with | _ -> None let input_all_from_nonseekable_channel ic = let buf = Buffer.create 10000 in try while true do bprintf buf "%s\n" (input_line ic) done; assert false with | End_of_file -> Buffer.contents buf let of_channel ?(source = Channel) ?max_len ic = let contents = match max_len with | None -> ( match get_channel_length ic with | None -> input_all_from_nonseekable_channel ic | Some len -> really_input_string ic len) | Some max_len -> partial_input max_len ic in { source; contents } let of_stdin ?(source = Stdin) () = of_channel ~source stdin let of_file ?source ?max_len file = let source = match source with | None -> File file | Some x -> x in (* This needs to work on named pipes such as those created by bash with so-called "process substitution" (for those, 'in_channel_length' returns but then we can't read the file again). It's convenient for testing using the spacegrep command line: $ spacegrep hello <(echo 'hello') *) let contents = Common.read_file ?max_len file in { source; contents } let to_lexbuf x = Lexing.from_string x.contents (* Find the index (position from the beginning of the string) right after the end of the current line. *) let rec find_end_of_line s i = if i >= String.length s then i else match s.[i] with | '\n' -> i + 1 | _ -> find_end_of_line s (i + 1) (* Remove the trailing newline character if there is one. *) let remove_trailing_newline s = match s with | "" -> "" | s -> let len = String.length s in if s.[len - 1] = '\n' then String.sub s 0 (len - 1) (* nosem *) else s (* Add a trailing newline character if the last character isn't a newline (or there is no last character). *) let ensure_newline s = match s with | "" -> "" | s -> if s.[String.length s - 1] <> '\n' then s ^ "\n" else s let insert_line_prefix prefix s = if prefix = "" then s else if s = "" then s else let buf = Buffer.create (2 * String.length s) in Buffer.add_string buf prefix; let len = String.length s in for i = 0 to len - 1 do let c = s.[i] in Buffer.add_char buf c; if c = '\n' && i < len - 1 then Buffer.add_string buf prefix done; Buffer.contents buf let insert_highlight highlight s start end_ = let len = String.length s in if start < 0 || end_ > len || start > end_ then s else let buf = Buffer.create (2 * len) in for i = 0 to start - 1 do Buffer.add_char buf s.[i] done; let pos = ref start in for i = start to end_ - 1 do match s.[i] with | '\n' -> Buffer.add_string buf (highlight (String.sub s !pos (i - !pos))); Buffer.add_char buf '\n'; pos := i + 1 | _ -> () done; Buffer.add_string buf (highlight (String.sub s !pos (end_ - !pos))); for i = end_ to len - 1 do Buffer.add_char buf s.[i] done; Buffer.contents buf Same as String.sub but shrink the requested range to a valid range if needed . Same as String.sub but shrink the requested range to a valid range if needed. *) let safe_string_sub s orig_start orig_len = let s_len = String.length s in let orig_end = orig_start + orig_len in let start = min s_len (max 0 orig_start) in let end_ = min s_len (max 0 orig_end) in let len = max 0 (end_ - start) in String.sub s start len let region_of_pos_range x start_pos end_pos = let open Lexing in safe_string_sub x.contents start_pos.pos_cnum (end_pos.pos_cnum - start_pos.pos_cnum) let region_of_loc_range x (start_pos, _) (_, end_pos) = region_of_pos_range x start_pos end_pos let lines_of_pos_range ?(force_trailing_newline = true) ?highlight ?(line_prefix = "") x start_pos end_pos = let s = x.contents in let open Lexing in let start = start_pos.pos_bol in let match_start = start_pos.pos_cnum in assert (match_start >= start); let end_ = find_end_of_line s end_pos.pos_bol in let match_end = end_pos.pos_cnum in assert (match_end <= end_); let lines = let s = safe_string_sub s start (end_ - start) in if force_trailing_newline then ensure_newline s else s in let with_highlight = match highlight with | None -> lines | Some highlight -> insert_highlight highlight lines (match_start - start) (match_end - start) in insert_line_prefix line_prefix with_highlight let lines_of_loc_range ?force_trailing_newline ?highlight ?line_prefix x (start_pos, _) (_, end_pos) = lines_of_pos_range ?force_trailing_newline ?highlight ?line_prefix x start_pos end_pos let list_lines_of_pos_range ?highlight ?line_prefix x start_pos end_pos = let s = lines_of_pos_range ~force_trailing_newline:false ?highlight ?line_prefix x start_pos end_pos in remove_trailing_newline s |> String.split_on_char '\n' let list_lines_of_loc_range ?highlight ?line_prefix x (start_pos, _) (_, end_pos) = list_lines_of_pos_range ?highlight ?line_prefix x start_pos end_pos
null
https://raw.githubusercontent.com/returntocorp/semgrep/6e182e59a3d7cb8d3c837032dd2fc51091098c10/libs/spacegrep/src/lib/Src_file.ml
ocaml
Keep a copy of the source input, suitable for returning source code from ranges of locations. The contents of the source document. This needs to work on named pipes such as those created by bash with so-called "process substitution" (for those, 'in_channel_length' returns but then we can't read the file again). It's convenient for testing using the spacegrep command line: $ spacegrep hello <(echo 'hello') Find the index (position from the beginning of the string) right after the end of the current line. Remove the trailing newline character if there is one. nosem Add a trailing newline character if the last character isn't a newline (or there is no last character).
open Printf type source = File of string | Stdin | String | Channel type t = { source : source; contents : string } let source x = x.source let show_source = function | File s -> s | Stdin -> "<stdin>" | String -> "<string>" | Channel -> "<channel>" let source_string x = x |> source |> show_source let contents x = x.contents let length x = String.length x.contents let replace_contents x f = { x with contents = f x.contents } let of_string ?(source = String) contents = { source; contents } let partial_input max_len ic = let buf = Bytes.create max_len in let rec read pos remaining = if remaining > 0 then let n_read = input ic buf pos remaining in if n_read > 0 then read (pos + n_read) (remaining - n_read) else pos else pos in let len = read 0 max_len in Bytes.sub_string buf 0 len let get_channel_length ic = try Some (in_channel_length ic) with | _ -> None let input_all_from_nonseekable_channel ic = let buf = Buffer.create 10000 in try while true do bprintf buf "%s\n" (input_line ic) done; assert false with | End_of_file -> Buffer.contents buf let of_channel ?(source = Channel) ?max_len ic = let contents = match max_len with | None -> ( match get_channel_length ic with | None -> input_all_from_nonseekable_channel ic | Some len -> really_input_string ic len) | Some max_len -> partial_input max_len ic in { source; contents } let of_stdin ?(source = Stdin) () = of_channel ~source stdin let of_file ?source ?max_len file = let source = match source with | None -> File file | Some x -> x in let contents = Common.read_file ?max_len file in { source; contents } let to_lexbuf x = Lexing.from_string x.contents let rec find_end_of_line s i = if i >= String.length s then i else match s.[i] with | '\n' -> i + 1 | _ -> find_end_of_line s (i + 1) let remove_trailing_newline s = match s with | "" -> "" | s -> let len = String.length s in let ensure_newline s = match s with | "" -> "" | s -> if s.[String.length s - 1] <> '\n' then s ^ "\n" else s let insert_line_prefix prefix s = if prefix = "" then s else if s = "" then s else let buf = Buffer.create (2 * String.length s) in Buffer.add_string buf prefix; let len = String.length s in for i = 0 to len - 1 do let c = s.[i] in Buffer.add_char buf c; if c = '\n' && i < len - 1 then Buffer.add_string buf prefix done; Buffer.contents buf let insert_highlight highlight s start end_ = let len = String.length s in if start < 0 || end_ > len || start > end_ then s else let buf = Buffer.create (2 * len) in for i = 0 to start - 1 do Buffer.add_char buf s.[i] done; let pos = ref start in for i = start to end_ - 1 do match s.[i] with | '\n' -> Buffer.add_string buf (highlight (String.sub s !pos (i - !pos))); Buffer.add_char buf '\n'; pos := i + 1 | _ -> () done; Buffer.add_string buf (highlight (String.sub s !pos (end_ - !pos))); for i = end_ to len - 1 do Buffer.add_char buf s.[i] done; Buffer.contents buf Same as String.sub but shrink the requested range to a valid range if needed . Same as String.sub but shrink the requested range to a valid range if needed. *) let safe_string_sub s orig_start orig_len = let s_len = String.length s in let orig_end = orig_start + orig_len in let start = min s_len (max 0 orig_start) in let end_ = min s_len (max 0 orig_end) in let len = max 0 (end_ - start) in String.sub s start len let region_of_pos_range x start_pos end_pos = let open Lexing in safe_string_sub x.contents start_pos.pos_cnum (end_pos.pos_cnum - start_pos.pos_cnum) let region_of_loc_range x (start_pos, _) (_, end_pos) = region_of_pos_range x start_pos end_pos let lines_of_pos_range ?(force_trailing_newline = true) ?highlight ?(line_prefix = "") x start_pos end_pos = let s = x.contents in let open Lexing in let start = start_pos.pos_bol in let match_start = start_pos.pos_cnum in assert (match_start >= start); let end_ = find_end_of_line s end_pos.pos_bol in let match_end = end_pos.pos_cnum in assert (match_end <= end_); let lines = let s = safe_string_sub s start (end_ - start) in if force_trailing_newline then ensure_newline s else s in let with_highlight = match highlight with | None -> lines | Some highlight -> insert_highlight highlight lines (match_start - start) (match_end - start) in insert_line_prefix line_prefix with_highlight let lines_of_loc_range ?force_trailing_newline ?highlight ?line_prefix x (start_pos, _) (_, end_pos) = lines_of_pos_range ?force_trailing_newline ?highlight ?line_prefix x start_pos end_pos let list_lines_of_pos_range ?highlight ?line_prefix x start_pos end_pos = let s = lines_of_pos_range ~force_trailing_newline:false ?highlight ?line_prefix x start_pos end_pos in remove_trailing_newline s |> String.split_on_char '\n' let list_lines_of_loc_range ?highlight ?line_prefix x (start_pos, _) (_, end_pos) = list_lines_of_pos_range ?highlight ?line_prefix x start_pos end_pos
3447aa37095f029aaa23109f9f92fc6871e1f9b1de4f988b23039bfa703091b7
uxbox/uxbox-old
db.cljs
(ns uxbox.data.db (:require [datascript :as d] [uxbox.data.schema :as sch])) (defn create [] (let [conn (d/create-conn sch/schema)] conn)) (defn restore! [conn storage] ;; todo: handle diverging schemas, per-user storage key? (when-let [old-db (get storage ::datoms)] (reset! conn old-db))) (defn persist-to! [conn storage] (d/listen! conn ::persitence (fn [_] (assoc! storage ::datoms @conn)))) (defn init! [conn storage] (restore! conn storage) (persist-to! conn storage))
null
https://raw.githubusercontent.com/uxbox/uxbox-old/9c3c3c406a6c629717cfc40e3da2f96df3bdebf7/src/frontend/uxbox/data/db.cljs
clojure
todo: handle diverging schemas, per-user storage key?
(ns uxbox.data.db (:require [datascript :as d] [uxbox.data.schema :as sch])) (defn create [] (let [conn (d/create-conn sch/schema)] conn)) (defn restore! [conn storage] (when-let [old-db (get storage ::datoms)] (reset! conn old-db))) (defn persist-to! [conn storage] (d/listen! conn ::persitence (fn [_] (assoc! storage ::datoms @conn)))) (defn init! [conn storage] (restore! conn storage) (persist-to! conn storage))
9f60d0ff022b0bd0d68be8291850e454d4f0abc8d255b21771f8fe3abf5b64f7
ocaml-batteries-team/batteries-included
batDeque.mli
* Deque -- functional double - ended queues * Copyright ( C ) 2011 Batteries Included Development Team * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Deque -- functional double-ended queues * Copyright (C) 2011 Batteries Included Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (** Functional double-ended queues *) type +'a dq (** The type of double-ended queues *) type 'a t = 'a dq (** A synonym for convenience *) include BatEnum.Enumerable with type 'a enumerable = 'a t include BatInterfaces.Mappable with type 'a mappable = 'a t val size : 'a dq -> int * [ size dq ] is the number of elements in the [ dq ] . ) (** {6 Construction} *) val empty : 'a dq (** The empty deque. *) val cons : 'a -> 'a dq -> 'a dq * [ cons x dq ] adds [ x ] to the front of [ dq ] . ) val snoc : 'a dq -> 'a -> 'a dq * [ snoc x dq ] adds [ x ] to the rear of [ dq ] . ) (** {6 Deconstruction} *) val front : 'a dq -> ('a * 'a dq) option (** [front dq] returns [Some (x, dq')] iff [x] is at the front of [dq] and [dq'] is the rest of [dq] excluding [x], and [None] if [dq] has no elements. O(1) amortized, O(n) worst case *) val rear : 'a dq -> ('a dq * 'a) option (** [rear dq] returns [Some (dq', x)] iff [x] is at the rear of [dq] and [dq'] is the rest of [dq] excluding [x], and [None] if [dq] has no elements. O(1) amortized, O(n) worst case *) * { 6 Basic operations } val eq : ?eq:('a -> 'a -> bool) -> 'a dq -> 'a dq -> bool * [ eq dq1 dq2 ] is true if [ dq1 ] and [ dq2 ] have the same sequence of elements . A custom function can be optionally provided with the [ eq ] parameter ( default is { ! Pervasives.(= ) } ) . @since 2.2.0 of elements. A custom function can be optionally provided with the [eq] parameter (default is {!Pervasives.(=)}). @since 2.2.0 *) val rev : 'a dq -> 'a dq * [ rev dq ] reverses [ dq ] . ) val is_empty : 'a dq -> bool (** [is_empty dq] returns [true] iff [dq] has no elements. O(1) *) val at : ?backwards:bool -> 'a dq -> int -> 'a option * [ at ~backwards dq k ] returns the [ k]th element of [ dq ] , from the front if [ backwards ] is false , and from the rear if [ backwards ] is true . By default , [ backwards = false ] . O(n ) the front if [backwards] is false, and from the rear if [backwards] is true. By default, [backwards = false]. O(n) *) val map : ('a -> 'b) -> 'a dq -> 'b dq (** [map f dq] returns a deque where every element [x] of [dq] has been replaced with [f x]. O(n) *) val mapi : (int -> 'a -> 'b) -> 'a dq -> 'b dq * [ mapi f dq ] returns a deque where every element [ x ] of [ dq ] has been replaced with [ f n x ] , where [ n ] is the position of [ x ] from the front of [ dq ] . O(n ) been replaced with [f n x], where [n] is the position of [x] from the front of [dq]. O(n) *) val iter : ('a -> unit) -> 'a dq -> unit (** [iter f dq] calls [f x] on each element [x] of [dq]. O(n) *) val iteri : (int -> 'a -> unit) -> 'a dq -> unit * [ iteri f dq ] calls [ f n x ] on each element [ x ] of [ dq ] . The first argument to [ f ] is the position of the element from the front of [ dq ] . O(n ) argument to [f] is the position of the element from the front of [dq]. O(n) *) val find : ?backwards:bool -> ('a -> bool) -> 'a dq -> (int * 'a) option * [ find ~backwards f dq ] returns [ Some ( n , x ) ] if [ x ] at position [ n ] is such that [ f x ] is true , or [ None ] if there is no such element . The position [ n ] is from the rear if [ backwards ] is true , and from the front if [ backwards ] is [ false ] . By default , [ backwards ] is [ false ] . O(n ) [n] is such that [f x] is true, or [None] if there is no such element. The position [n] is from the rear if [backwards] is true, and from the front if [backwards] is [false]. By default, [backwards] is [false]. O(n) *) val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a dq -> 'acc * [ fold_left f acc dq ] is equivalent to [ List.fold_left f acc ( to_list dq ) ] , but more efficient . O(n ) (to_list dq)], but more efficient. O(n) *) val fold_right : ('a -> 'acc -> 'acc) -> 'a dq -> 'acc -> 'acc * [ fold_right f dq acc ] is equivalent to [ List.fold_right f ( to_list dq ) acc ] , but more efficient . O(n ) (to_list dq) acc], but more efficient. O(n) *) val append : 'a dq -> 'a dq -> 'a dq (** [append dq1 dq2] represents the concatenateion of [dq1] and [dq2]. O(min(m, n))*) val append_list : 'a dq -> 'a list -> 'a dq (** [append_list dq l] is equivalent to [append dq (of_list l)], but more efficient. O(min(m, n)) *) val prepend_list : 'a list -> 'a dq -> 'a dq (** [prepend_list l dq] is equivalent to [append (of_list l) dq], but more efficient. O(min(m, n)) *) val rotate_forward : 'a dq -> 'a dq * A cyclic shift of deque elements from rear to front by one position . As a result , the front element becomes the rear element . Time : O(1 ) amortized , O(n ) worst - case . @since 2.3.0 As a result, the front element becomes the rear element. Time: O(1) amortized, O(n) worst-case. @since 2.3.0 *) val rotate_backward : 'a dq -> 'a dq * A cyclic shift of deque elements from front to rear by one position . As a result , the rear element becomes the front element . Time : O(1 ) amortized , O(n ) worst - case . @since 2.3.0 As a result, the rear element becomes the front element. Time: O(1) amortized, O(n) worst-case. @since 2.3.0 *) * { 6 Transformation } val of_list : 'a list -> 'a dq (** [of_list l] is a deque representation of the elements of [l]. O(n) *) val to_list : 'a dq -> 'a list (** [to_list dq] is a list representation of the elements of [dq]. O(n) *) val of_enum : 'a BatEnum.t -> 'a dq (** [of_enum e] is a deque representation of the elements of [e]. Consumes the enumeration [e]. O(n) *) val enum : 'a dq -> 'a BatEnum.t (** [enum dq] is an enumeration of the elements of [dq] from the front to the rear. This function is O(1), but generating each element of the enumeration is amortized O(1), and O(n) worst case. *) * { 6 Printing } val print : ?first:string -> ?last:string -> ?sep:string -> ('a, 'b) BatIO.printer -> ('a dq, 'b) BatIO.printer (** Print the contents of the deque. O(n) *) (**/**) val invariants : _ t -> unit (**/**)
null
https://raw.githubusercontent.com/ocaml-batteries-team/batteries-included/f143ef5ec583d87d538b8f06f06d046d64555e90/src/batDeque.mli
ocaml
* Functional double-ended queues * The type of double-ended queues * A synonym for convenience * {6 Construction} * The empty deque. * {6 Deconstruction} * [front dq] returns [Some (x, dq')] iff [x] is at the front of [dq] and [dq'] is the rest of [dq] excluding [x], and [None] if [dq] has no elements. O(1) amortized, O(n) worst case * [rear dq] returns [Some (dq', x)] iff [x] is at the rear of [dq] and [dq'] is the rest of [dq] excluding [x], and [None] if [dq] has no elements. O(1) amortized, O(n) worst case * [is_empty dq] returns [true] iff [dq] has no elements. O(1) * [map f dq] returns a deque where every element [x] of [dq] has been replaced with [f x]. O(n) * [iter f dq] calls [f x] on each element [x] of [dq]. O(n) * [append dq1 dq2] represents the concatenateion of [dq1] and [dq2]. O(min(m, n)) * [append_list dq l] is equivalent to [append dq (of_list l)], but more efficient. O(min(m, n)) * [prepend_list l dq] is equivalent to [append (of_list l) dq], but more efficient. O(min(m, n)) * [of_list l] is a deque representation of the elements of [l]. O(n) * [to_list dq] is a list representation of the elements of [dq]. O(n) * [of_enum e] is a deque representation of the elements of [e]. Consumes the enumeration [e]. O(n) * [enum dq] is an enumeration of the elements of [dq] from the front to the rear. This function is O(1), but generating each element of the enumeration is amortized O(1), and O(n) worst case. * Print the contents of the deque. O(n) */* */*
* Deque -- functional double - ended queues * Copyright ( C ) 2011 Batteries Included Development Team * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Deque -- functional double-ended queues * Copyright (C) 2011 Batteries Included Development Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) type +'a dq type 'a t = 'a dq include BatEnum.Enumerable with type 'a enumerable = 'a t include BatInterfaces.Mappable with type 'a mappable = 'a t val size : 'a dq -> int * [ size dq ] is the number of elements in the [ dq ] . ) val empty : 'a dq val cons : 'a -> 'a dq -> 'a dq * [ cons x dq ] adds [ x ] to the front of [ dq ] . ) val snoc : 'a dq -> 'a -> 'a dq * [ snoc x dq ] adds [ x ] to the rear of [ dq ] . ) val front : 'a dq -> ('a * 'a dq) option val rear : 'a dq -> ('a dq * 'a) option * { 6 Basic operations } val eq : ?eq:('a -> 'a -> bool) -> 'a dq -> 'a dq -> bool * [ eq dq1 dq2 ] is true if [ dq1 ] and [ dq2 ] have the same sequence of elements . A custom function can be optionally provided with the [ eq ] parameter ( default is { ! Pervasives.(= ) } ) . @since 2.2.0 of elements. A custom function can be optionally provided with the [eq] parameter (default is {!Pervasives.(=)}). @since 2.2.0 *) val rev : 'a dq -> 'a dq * [ rev dq ] reverses [ dq ] . ) val is_empty : 'a dq -> bool val at : ?backwards:bool -> 'a dq -> int -> 'a option * [ at ~backwards dq k ] returns the [ k]th element of [ dq ] , from the front if [ backwards ] is false , and from the rear if [ backwards ] is true . By default , [ backwards = false ] . O(n ) the front if [backwards] is false, and from the rear if [backwards] is true. By default, [backwards = false]. O(n) *) val map : ('a -> 'b) -> 'a dq -> 'b dq val mapi : (int -> 'a -> 'b) -> 'a dq -> 'b dq * [ mapi f dq ] returns a deque where every element [ x ] of [ dq ] has been replaced with [ f n x ] , where [ n ] is the position of [ x ] from the front of [ dq ] . O(n ) been replaced with [f n x], where [n] is the position of [x] from the front of [dq]. O(n) *) val iter : ('a -> unit) -> 'a dq -> unit val iteri : (int -> 'a -> unit) -> 'a dq -> unit * [ iteri f dq ] calls [ f n x ] on each element [ x ] of [ dq ] . The first argument to [ f ] is the position of the element from the front of [ dq ] . O(n ) argument to [f] is the position of the element from the front of [dq]. O(n) *) val find : ?backwards:bool -> ('a -> bool) -> 'a dq -> (int * 'a) option * [ find ~backwards f dq ] returns [ Some ( n , x ) ] if [ x ] at position [ n ] is such that [ f x ] is true , or [ None ] if there is no such element . The position [ n ] is from the rear if [ backwards ] is true , and from the front if [ backwards ] is [ false ] . By default , [ backwards ] is [ false ] . O(n ) [n] is such that [f x] is true, or [None] if there is no such element. The position [n] is from the rear if [backwards] is true, and from the front if [backwards] is [false]. By default, [backwards] is [false]. O(n) *) val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a dq -> 'acc * [ fold_left f acc dq ] is equivalent to [ List.fold_left f acc ( to_list dq ) ] , but more efficient . O(n ) (to_list dq)], but more efficient. O(n) *) val fold_right : ('a -> 'acc -> 'acc) -> 'a dq -> 'acc -> 'acc * [ fold_right f dq acc ] is equivalent to [ List.fold_right f ( to_list dq ) acc ] , but more efficient . O(n ) (to_list dq) acc], but more efficient. O(n) *) val append : 'a dq -> 'a dq -> 'a dq val append_list : 'a dq -> 'a list -> 'a dq val prepend_list : 'a list -> 'a dq -> 'a dq val rotate_forward : 'a dq -> 'a dq * A cyclic shift of deque elements from rear to front by one position . As a result , the front element becomes the rear element . Time : O(1 ) amortized , O(n ) worst - case . @since 2.3.0 As a result, the front element becomes the rear element. Time: O(1) amortized, O(n) worst-case. @since 2.3.0 *) val rotate_backward : 'a dq -> 'a dq * A cyclic shift of deque elements from front to rear by one position . As a result , the rear element becomes the front element . Time : O(1 ) amortized , O(n ) worst - case . @since 2.3.0 As a result, the rear element becomes the front element. Time: O(1) amortized, O(n) worst-case. @since 2.3.0 *) * { 6 Transformation } val of_list : 'a list -> 'a dq val to_list : 'a dq -> 'a list val of_enum : 'a BatEnum.t -> 'a dq val enum : 'a dq -> 'a BatEnum.t * { 6 Printing } val print : ?first:string -> ?last:string -> ?sep:string -> ('a, 'b) BatIO.printer -> ('a dq, 'b) BatIO.printer val invariants : _ t -> unit
05939e14ffe6926f63eeffa762f005dff25f1e15c8232a6547e5b89d78a3b322
replikativ/datalog-parser
proto.cljc
(ns datalog.parser.impl.proto) #?(:clj (set! *warn-on-reflection* true)) (defprotocol ITraversable (-collect [_ pred acc]) (-collect-vars [_ acc]) (-postwalk [_ f])) (defprotocol Traversable (-traversable? [_])) (defprotocol IFindVars (-find-vars [this])) (defprotocol IFindElements (find-elements [this])) (extend-type #?(:clj Object :cljs object) Traversable (-traversable? [_] false)) (extend-type nil Traversable (-traversable? [_] false))
null
https://raw.githubusercontent.com/replikativ/datalog-parser/597b6a04fb9d1f5931a40566058620e422a77532/src/datalog/parser/impl/proto.cljc
clojure
(ns datalog.parser.impl.proto) #?(:clj (set! *warn-on-reflection* true)) (defprotocol ITraversable (-collect [_ pred acc]) (-collect-vars [_ acc]) (-postwalk [_ f])) (defprotocol Traversable (-traversable? [_])) (defprotocol IFindVars (-find-vars [this])) (defprotocol IFindElements (find-elements [this])) (extend-type #?(:clj Object :cljs object) Traversable (-traversable? [_] false)) (extend-type nil Traversable (-traversable? [_] false))
200e9b73db3630c510fd4ed969c289e16fe4de399d43b52b5ec68b6ebdee29c9
chanshunli/wechat-clj
core.clj
(ns wechat-clj.public.core (:require [clj-http.client :as client] [cheshire.core :as cjson])) (defn invoke-wx-api-with-cfg-by-get "微信调用接口辅助函数get" [cmd form-params] (let [wx-api-url (format "-bin/%s" cmd) get-data {:accept :json :query-params form-params}] (let [resp (client/get wx-api-url get-data)] (cjson/parse-string (:body resp))))) (defn invoke-wx-api-with-cfg "微信调用接口辅助函数 cmd 为接口名,如 menu/create form-params 为map 返回json解析的map" [access-token cmd form-params] (let [wx-api-url (format "-bin/%s?access_token=%s" cmd access-token) post-data {:form-params form-params :content-type :json}] (let [resp (client/post wx-api-url post-data)] (cjson/parse-string (:body resp))))) (defn get-wxuser-list [access-token] (-> (invoke-wx-api-with-cfg access-token "user/get" {}) (get "data") (get "openid"))) (defn get-wxuser-info [{:keys [openid access-token]}] (invoke-wx-api-with-cfg-by-get "user/info" {:access_token access-token :openid openid :lang "zh_CN"})) (defn print-all-wx-user [access-token] (doseq [openid (get-wxuser-list access-token)] (prn (get-wxuser-info {:openid openid :access-token access-token})))) (comment (get-wxuser-list "official-account-token") (get-wxuser-info {:openid "opb8V1Q7oNvSjfQ-tCdasdas321321" :access-token "official-account-token"}) (print-all-wx-user "official-account-token"))
null
https://raw.githubusercontent.com/chanshunli/wechat-clj/145a99825669b743a09a8565fa1301d90480c91b/src/clj/wechat_clj/public/core.clj
clojure
(ns wechat-clj.public.core (:require [clj-http.client :as client] [cheshire.core :as cjson])) (defn invoke-wx-api-with-cfg-by-get "微信调用接口辅助函数get" [cmd form-params] (let [wx-api-url (format "-bin/%s" cmd) get-data {:accept :json :query-params form-params}] (let [resp (client/get wx-api-url get-data)] (cjson/parse-string (:body resp))))) (defn invoke-wx-api-with-cfg "微信调用接口辅助函数 cmd 为接口名,如 menu/create form-params 为map 返回json解析的map" [access-token cmd form-params] (let [wx-api-url (format "-bin/%s?access_token=%s" cmd access-token) post-data {:form-params form-params :content-type :json}] (let [resp (client/post wx-api-url post-data)] (cjson/parse-string (:body resp))))) (defn get-wxuser-list [access-token] (-> (invoke-wx-api-with-cfg access-token "user/get" {}) (get "data") (get "openid"))) (defn get-wxuser-info [{:keys [openid access-token]}] (invoke-wx-api-with-cfg-by-get "user/info" {:access_token access-token :openid openid :lang "zh_CN"})) (defn print-all-wx-user [access-token] (doseq [openid (get-wxuser-list access-token)] (prn (get-wxuser-info {:openid openid :access-token access-token})))) (comment (get-wxuser-list "official-account-token") (get-wxuser-info {:openid "opb8V1Q7oNvSjfQ-tCdasdas321321" :access-token "official-account-token"}) (print-all-wx-user "official-account-token"))
c51035b38a0a352524b697788399826c49f9d1e3208f3345b9e4de154c504437
binsec/haunted
taint.ml
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) exception Elements_of_top type t = | Top | Tainted | NotTainted | Bot let universe = Top let empty = Bot let of_bounds _ = Top let elements abs = match abs with | Bot -> [] | Tainted | NotTainted | Top -> raise Elements_of_top let pp ppf = function | Top -> Format.fprintf ppf "Top" | Tainted -> Format.fprintf ppf "Tainted" | NotTainted -> Format.fprintf ppf "Untainted" | Bot -> Format.fprintf ppf "Bot" let to_string abs = Format.fprintf Format.str_formatter "%a" pp abs; Format.flush_str_formatter () let is_empty abs = match abs with | Bot -> true | Tainted | NotTainted | Top -> false let singleton bv = match bv with | `Undef _ -> Tainted | _ -> NotTainted let contains abs1 abs2 = match abs1, abs2 with | Top, _ -> true | _, Bot -> true | _, _ -> false let equal abs1 abs2 = (contains abs1 abs2) && (contains abs2 abs1) let join abs1 abs2 = match abs1,abs2 with | a, Bot -> a | Bot, a -> a | Tainted, Tainted -> Tainted | NotTainted, NotTainted -> NotTainted | _, _ -> Top let widen abs1 abs2 _thresholds = match abs1,abs2 with | a, Bot -> a | Bot, a -> a | Tainted, Tainted -> Tainted | NotTainted, NotTainted -> NotTainted | _, _ -> Top let meet abs1 abs2 = match abs1, abs2 with | Top, a -> a | a, Top -> a | Tainted, Tainted -> Tainted | NotTainted, NotTainted -> NotTainted | _, _ -> Bot let neg abs = abs let lognot abs = abs let binop abs1 abs2 = match abs1, abs2 with | Tainted, _ -> Tainted | _, Tainted -> Tainted | Top, _ -> Top | _, Top -> Top | NotTainted, _ -> NotTainted | _, NotTainted -> NotTainted | Bot, Bot -> Bot let concat abs1 abs2 = binop abs1 abs2 let add abs1 abs2 = binop abs1 abs2 let sub abs1 abs2 = binop abs1 abs2 let max _abs = failwith "taint.ml: max of taint" let mul abs1 abs2 = binop abs1 abs2 let power abs1 abs2 = binop abs1 abs2 let udiv abs1 abs2 = binop abs1 abs2 let sdiv abs1 abs2 = binop abs1 abs2 let restrict abs _of1 _of2 = abs let umod abs1 abs2 = binop abs1 abs2 let smod abs1 abs2 = binop abs1 abs2 let logor abs1 abs2 = binop abs1 abs2 let logand abs1 abs2 = binop abs1 abs2 let logxor abs1 abs2 = binop abs1 abs2 let lshift abs1 abs2 = binop abs1 abs2 let rshiftU abs1 abs2 = binop abs1 abs2 let rshiftS abs1 abs2 = binop abs1 abs2 let rotate_left abs1 abs2 = binop abs1 abs2 let rotate_right abs1 abs2 = binop abs1 abs2 let extension abs _ = abs let signed_extension abs _ = abs let eq abs1 abs2 = binop abs1 abs2 let diff abs1 abs2 = binop abs1 abs2 let leqU abs1 abs2 = binop abs1 abs2 let ltU abs1 abs2 = binop abs1 abs2 let geqU abs1 abs2 = binop abs1 abs2 let gtU abs1 abs2 = binop abs1 abs2 let leqS abs1 abs2 = binop abs1 abs2 let ltS abs1 abs2 = binop abs1 abs2 let geqS abs1 abs2 = binop abs1 abs2 let gtS abs1 abs2 = binop abs1 abs2 let guard _ abs1 abs2 = abs1, abs2 let is_true abs _ _ = match abs with | Bot -> Basic_types.Ternary.False | _ -> Basic_types.Ternary.Unknown let to_smt _ _ = failwith "to_smt not yet implemented un Kset.ml" let smt_refine _ _ = failwith "not yet implemented!"
null
https://raw.githubusercontent.com/binsec/haunted/7ffc5f4072950fe138f53fe953ace98fff181c73/src/static/ai/domains/taint.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. ************************************************************************
This file is part of BINSEC . Copyright ( C ) 2016 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . exception Elements_of_top type t = | Top | Tainted | NotTainted | Bot let universe = Top let empty = Bot let of_bounds _ = Top let elements abs = match abs with | Bot -> [] | Tainted | NotTainted | Top -> raise Elements_of_top let pp ppf = function | Top -> Format.fprintf ppf "Top" | Tainted -> Format.fprintf ppf "Tainted" | NotTainted -> Format.fprintf ppf "Untainted" | Bot -> Format.fprintf ppf "Bot" let to_string abs = Format.fprintf Format.str_formatter "%a" pp abs; Format.flush_str_formatter () let is_empty abs = match abs with | Bot -> true | Tainted | NotTainted | Top -> false let singleton bv = match bv with | `Undef _ -> Tainted | _ -> NotTainted let contains abs1 abs2 = match abs1, abs2 with | Top, _ -> true | _, Bot -> true | _, _ -> false let equal abs1 abs2 = (contains abs1 abs2) && (contains abs2 abs1) let join abs1 abs2 = match abs1,abs2 with | a, Bot -> a | Bot, a -> a | Tainted, Tainted -> Tainted | NotTainted, NotTainted -> NotTainted | _, _ -> Top let widen abs1 abs2 _thresholds = match abs1,abs2 with | a, Bot -> a | Bot, a -> a | Tainted, Tainted -> Tainted | NotTainted, NotTainted -> NotTainted | _, _ -> Top let meet abs1 abs2 = match abs1, abs2 with | Top, a -> a | a, Top -> a | Tainted, Tainted -> Tainted | NotTainted, NotTainted -> NotTainted | _, _ -> Bot let neg abs = abs let lognot abs = abs let binop abs1 abs2 = match abs1, abs2 with | Tainted, _ -> Tainted | _, Tainted -> Tainted | Top, _ -> Top | _, Top -> Top | NotTainted, _ -> NotTainted | _, NotTainted -> NotTainted | Bot, Bot -> Bot let concat abs1 abs2 = binop abs1 abs2 let add abs1 abs2 = binop abs1 abs2 let sub abs1 abs2 = binop abs1 abs2 let max _abs = failwith "taint.ml: max of taint" let mul abs1 abs2 = binop abs1 abs2 let power abs1 abs2 = binop abs1 abs2 let udiv abs1 abs2 = binop abs1 abs2 let sdiv abs1 abs2 = binop abs1 abs2 let restrict abs _of1 _of2 = abs let umod abs1 abs2 = binop abs1 abs2 let smod abs1 abs2 = binop abs1 abs2 let logor abs1 abs2 = binop abs1 abs2 let logand abs1 abs2 = binop abs1 abs2 let logxor abs1 abs2 = binop abs1 abs2 let lshift abs1 abs2 = binop abs1 abs2 let rshiftU abs1 abs2 = binop abs1 abs2 let rshiftS abs1 abs2 = binop abs1 abs2 let rotate_left abs1 abs2 = binop abs1 abs2 let rotate_right abs1 abs2 = binop abs1 abs2 let extension abs _ = abs let signed_extension abs _ = abs let eq abs1 abs2 = binop abs1 abs2 let diff abs1 abs2 = binop abs1 abs2 let leqU abs1 abs2 = binop abs1 abs2 let ltU abs1 abs2 = binop abs1 abs2 let geqU abs1 abs2 = binop abs1 abs2 let gtU abs1 abs2 = binop abs1 abs2 let leqS abs1 abs2 = binop abs1 abs2 let ltS abs1 abs2 = binop abs1 abs2 let geqS abs1 abs2 = binop abs1 abs2 let gtS abs1 abs2 = binop abs1 abs2 let guard _ abs1 abs2 = abs1, abs2 let is_true abs _ _ = match abs with | Bot -> Basic_types.Ternary.False | _ -> Basic_types.Ternary.Unknown let to_smt _ _ = failwith "to_smt not yet implemented un Kset.ml" let smt_refine _ _ = failwith "not yet implemented!"
3903ff982f1f20c6cf1f4bff4a3194adc09561f437358e5be80850b6e6a07562
0install/0install
test_qdom.ml
Copyright ( C ) 2013 , the README file for details , or visit . * See the README file for details, or visit . *) open Support open OUnit module Q = Support.Qdom let assert_str_equal = Fake_system.assert_str_equal let parse_simple s = `String (0, s) |> Xmlm.make_input |> Q.parse_input None let parse s1 = let xml1 = parse_simple s1 in let s2 = Q.to_utf8 xml1 in let xml2 = parse_simple s2 in if Q.compare_nodes ~ignore_whitespace:false xml1 xml2 <> 0 then Safe_exn.failf "XML changed after saving and reloading!\n%s\n%s" s1 s2; Fake_system.assert_str_equal s2 (Q.to_utf8 xml2); xml1 let suite = "qdom">::: [ "simple">:: (fun () -> let root = parse "<?xml version=\"1.0\"?><root/>" in Q.Empty.check_tag "root" root; assert_equal (Some "root") (Q.Empty.tag root); assert_str_equal "" (Q.simple_content root); ); "text">:: (fun () -> let root = parse "<?xml version=\"1.0\"?><root> Hi </root>" in assert_str_equal " Hi " root.Q.last_text_inside; assert_equal [] root.Q.child_nodes; let root = parse "<?xml version='1.0'?><root>A <b>bold</b> move.</root>" in assert_str_equal " move." root.Q.last_text_inside; assert (Str.string_match (Str.regexp "^<\\?xml .*\\?>\n<root>A <b>bold</b> move.</root>") (Q.to_utf8 root) 0); ); "ns">:: (fun () -> let root = parse "<?xml version='1.0'?><x:root xmlns:x=''/>" in assert_equal ("", "root") root.Q.tag; assert_str_equal "" (Q.simple_content root); assert_equal [] root.Q.child_nodes; let root = parse "<?xml version='1.0'?><x:root xmlns:x='' x:y='foo'/>" in assert_equal ("", "root") root.Q.tag; assert_equal "foo" (Q.AttrMap.get ("", "y") root.Q.attrs |> Fake_system.expect); (* Add a default-ns node to a non-default document *) let other = parse "<imported xmlns='/'/>" in let combined = {root with Q.child_nodes = [other]} |> Q.to_utf8 |> parse in assert_equal ("", "root") combined.Q.tag; assert_equal ("/", "imported") (List.hd combined.Q.child_nodes).Q.tag; (* Add a default-ns node to a default-ns document *) let root = parse "<root xmlns='/'/>" in let other = parse "<imported xmlns='/'/>" in let combined = {root with Q.child_nodes = [other]} |> Q.to_utf8 |> parse in assert_equal ("/", "root") combined.Q.tag; assert_equal ("/", "imported") (List.hd combined.Q.child_nodes).Q.tag; ); "attrs">:: (fun () -> let root = parse "<?xml version='1.0'?><root x:foo='bar' bar='baz' xmlns:x=''/>" in root.Q.attrs |> Q.AttrMap.get ("", "foo") |> assert_equal (Some "bar"); root.Q.attrs |> Q.AttrMap.get ("", "bar") |> assert_equal (Some "baz"); ); "nested">:: (fun () -> let root = parse "<?xml version='1.0'?><root><name>Bob</name><age>3</age></root>" in assert_str_equal "" root.Q.last_text_inside; let open Q in match root.child_nodes with | [ { tag = ("", "name"); last_text_inside = "Bob"; child_nodes = []; _ }; { tag = ("", "age"); last_text_inside = "3"; child_nodes = []; _ }; ] -> () | _ -> assert false ); ]
null
https://raw.githubusercontent.com/0install/0install/22eebdbe51a9f46cda29eed3e9e02e37e36b2d18/src/tests/test_qdom.ml
ocaml
Add a default-ns node to a non-default document Add a default-ns node to a default-ns document
Copyright ( C ) 2013 , the README file for details , or visit . * See the README file for details, or visit . *) open Support open OUnit module Q = Support.Qdom let assert_str_equal = Fake_system.assert_str_equal let parse_simple s = `String (0, s) |> Xmlm.make_input |> Q.parse_input None let parse s1 = let xml1 = parse_simple s1 in let s2 = Q.to_utf8 xml1 in let xml2 = parse_simple s2 in if Q.compare_nodes ~ignore_whitespace:false xml1 xml2 <> 0 then Safe_exn.failf "XML changed after saving and reloading!\n%s\n%s" s1 s2; Fake_system.assert_str_equal s2 (Q.to_utf8 xml2); xml1 let suite = "qdom">::: [ "simple">:: (fun () -> let root = parse "<?xml version=\"1.0\"?><root/>" in Q.Empty.check_tag "root" root; assert_equal (Some "root") (Q.Empty.tag root); assert_str_equal "" (Q.simple_content root); ); "text">:: (fun () -> let root = parse "<?xml version=\"1.0\"?><root> Hi </root>" in assert_str_equal " Hi " root.Q.last_text_inside; assert_equal [] root.Q.child_nodes; let root = parse "<?xml version='1.0'?><root>A <b>bold</b> move.</root>" in assert_str_equal " move." root.Q.last_text_inside; assert (Str.string_match (Str.regexp "^<\\?xml .*\\?>\n<root>A <b>bold</b> move.</root>") (Q.to_utf8 root) 0); ); "ns">:: (fun () -> let root = parse "<?xml version='1.0'?><x:root xmlns:x=''/>" in assert_equal ("", "root") root.Q.tag; assert_str_equal "" (Q.simple_content root); assert_equal [] root.Q.child_nodes; let root = parse "<?xml version='1.0'?><x:root xmlns:x='' x:y='foo'/>" in assert_equal ("", "root") root.Q.tag; assert_equal "foo" (Q.AttrMap.get ("", "y") root.Q.attrs |> Fake_system.expect); let other = parse "<imported xmlns='/'/>" in let combined = {root with Q.child_nodes = [other]} |> Q.to_utf8 |> parse in assert_equal ("", "root") combined.Q.tag; assert_equal ("/", "imported") (List.hd combined.Q.child_nodes).Q.tag; let root = parse "<root xmlns='/'/>" in let other = parse "<imported xmlns='/'/>" in let combined = {root with Q.child_nodes = [other]} |> Q.to_utf8 |> parse in assert_equal ("/", "root") combined.Q.tag; assert_equal ("/", "imported") (List.hd combined.Q.child_nodes).Q.tag; ); "attrs">:: (fun () -> let root = parse "<?xml version='1.0'?><root x:foo='bar' bar='baz' xmlns:x=''/>" in root.Q.attrs |> Q.AttrMap.get ("", "foo") |> assert_equal (Some "bar"); root.Q.attrs |> Q.AttrMap.get ("", "bar") |> assert_equal (Some "baz"); ); "nested">:: (fun () -> let root = parse "<?xml version='1.0'?><root><name>Bob</name><age>3</age></root>" in assert_str_equal "" root.Q.last_text_inside; let open Q in match root.child_nodes with | [ { tag = ("", "name"); last_text_inside = "Bob"; child_nodes = []; _ }; { tag = ("", "age"); last_text_inside = "3"; child_nodes = []; _ }; ] -> () | _ -> assert false ); ]
ef1a7128c6b3da0a1be64d8217fc65d511c3022a7eac3e9f10d80721bb33b112
PLTools/GT
test037.ml
type 'a t1 = [`A | `B of 'a] [@@deriving gt ~show ~gmap] type 'a t2 = [`C | `D of 'a] [@@deriving gt ~show ~gmap] type 'a t = ['a t1 | 'a t2] [@@deriving gt ~show ~gmap] let _ = let a = `B (`B `A) in let rec mapt1 x = GT.fix0 (fun self -> GT.transform(t1) (new gmap_t1 self self) ()) x in let rec show1 x = GT.fix0 (fun self -> GT.transform(t1) (new show_t1 self self) ()) x in Printf.printf "a=%s, map a=%s\n" (show1 a) (show1 (mapt1 a)); let b = `D (`D `C) in let rec mapt2 x = GT.fix0 (fun self -> GT.transform(t2) (new gmap_t2 self self) ()) x in let rec show2 x = GT.fix0 (fun self -> GT.transform(t2) (new show_t2 self self) ()) x in Printf.printf "b=%s, map b=%s\n" (show2 b) (show2 (mapt2 b)); let c = `D (`B (`D `A)) in let rec mapt x = GT.fix0 (fun self -> GT.transform(t) (new gmap_t self self) ()) x in let rec show x = GT.fix0 (fun self -> GT.transform(t) (new show_t self self) ()) x in Printf.printf "c=%s, map c=%s\n" (show c) (show (mapt c))
null
https://raw.githubusercontent.com/PLTools/GT/62d1a424a3336f2317ba67e447a9ff09d179b583/regression_ppx/test037.ml
ocaml
type 'a t1 = [`A | `B of 'a] [@@deriving gt ~show ~gmap] type 'a t2 = [`C | `D of 'a] [@@deriving gt ~show ~gmap] type 'a t = ['a t1 | 'a t2] [@@deriving gt ~show ~gmap] let _ = let a = `B (`B `A) in let rec mapt1 x = GT.fix0 (fun self -> GT.transform(t1) (new gmap_t1 self self) ()) x in let rec show1 x = GT.fix0 (fun self -> GT.transform(t1) (new show_t1 self self) ()) x in Printf.printf "a=%s, map a=%s\n" (show1 a) (show1 (mapt1 a)); let b = `D (`D `C) in let rec mapt2 x = GT.fix0 (fun self -> GT.transform(t2) (new gmap_t2 self self) ()) x in let rec show2 x = GT.fix0 (fun self -> GT.transform(t2) (new show_t2 self self) ()) x in Printf.printf "b=%s, map b=%s\n" (show2 b) (show2 (mapt2 b)); let c = `D (`B (`D `A)) in let rec mapt x = GT.fix0 (fun self -> GT.transform(t) (new gmap_t self self) ()) x in let rec show x = GT.fix0 (fun self -> GT.transform(t) (new show_t self self) ()) x in Printf.printf "c=%s, map c=%s\n" (show c) (show (mapt c))
ddb9c99655c5f31dcd3f87c58a15b3a6bb9360cc9d3591d3250ef9c421b4cf9d
LLazarek/mutate
low-level.rkt
#lang racket/base (require "low-level/define.rkt" "low-level/primitives.rkt" "low-level/mutators.rkt") (provide (all-from-out "low-level/define.rkt") (all-from-out "low-level/primitives.rkt") (all-from-out "low-level/mutators.rkt"))
null
https://raw.githubusercontent.com/LLazarek/mutate/297eae74e1969e21ee24382a63165af37631690a/mutate-lib/low-level.rkt
racket
#lang racket/base (require "low-level/define.rkt" "low-level/primitives.rkt" "low-level/mutators.rkt") (provide (all-from-out "low-level/define.rkt") (all-from-out "low-level/primitives.rkt") (all-from-out "low-level/mutators.rkt"))
dba9d4544f1d878561131817756d23a3422bedd1dde5c139df12a6c549bce890
agentm/project-m36
DataFrame.hs
# LANGUAGE DeriveGeneric , DerivingVia # {- A dataframe is a strongly-typed, ordered list of named tuples. A dataframe differs from a relation in that its tuples are ordered.-} module ProjectM36.DataFrame where import ProjectM36.Base import ProjectM36.Attribute as A hiding (drop) import ProjectM36.Error import qualified ProjectM36.Relation as R import ProjectM36.Relation.Show.Term import qualified ProjectM36.Relation.Show.HTML as RelHTML import ProjectM36.DataTypes.Sorting import ProjectM36.AtomType import ProjectM36.Atom import qualified Data.Vector as V import GHC.Generics import qualified Data.List as L import qualified Data.Set as S import Data.Maybe import qualified Data.Text as T import Control.Arrow import Control.Monad (unless) #if __GLASGOW_HASKELL__ < 804 import Data.Monoid #endif data AttributeOrderExpr = AttributeOrderExpr AttributeName Order deriving (Show, Generic) data AttributeOrder = AttributeOrder AttributeName Order deriving (Show, Generic) data Order = AscendingOrder | DescendingOrder deriving (Eq, Show, Generic) ascending :: T.Text ascending = "⬆" descending :: T.Text descending = "⬇" arbitrary :: T.Text arbitrary = "↕" data DataFrame = DataFrame { orders :: [AttributeOrder], attributes :: Attributes, tuples :: [DataFrameTuple] } deriving (Show, Generic) data DataFrameTuple = DataFrameTuple Attributes (V.Vector Atom) deriving (Eq, Show, Generic) sortDataFrameBy :: [AttributeOrder] -> DataFrame -> Either RelationalError DataFrame sortDataFrameBy attrOrders frame = do attrs <- mapM (\(AttributeOrder nam _) -> A.attributeForName nam (attributes frame)) attrOrders mapM_ (\attr -> unless (isSortableAtomType (atomType attr)) $ Left (AttributeNotSortableError attr)) attrs pure $ DataFrame attrOrders (attributes frame) (sortTuplesBy (compareTupleByAttributeOrders attrOrders) (tuples frame)) sortTuplesBy :: (DataFrameTuple -> DataFrameTuple -> Ordering) -> [DataFrameTuple] -> [DataFrameTuple] sortTuplesBy = L.sortBy compareTupleByAttributeOrders :: [AttributeOrder] -> DataFrameTuple -> DataFrameTuple -> Ordering compareTupleByAttributeOrders attributeOrders tup1 tup2 = let compare' (AttributeOrder attr order) = if order == DescendingOrder then compareTupleByOneAttributeName attr tup2 tup1 else compareTupleByOneAttributeName attr tup1 tup2 res = map compare' attributeOrders in fromMaybe EQ (L.find (/= EQ) res) compareTupleByOneAttributeName :: AttributeName -> DataFrameTuple -> DataFrameTuple -> Ordering compareTupleByOneAttributeName attr tuple1 tuple2 = let eAtom1 = atomForAttributeName attr tuple1 eAtom2 = atomForAttributeName attr tuple2 in case eAtom1 of Left err -> error (show err) Right atom1 -> case eAtom2 of Left err -> error (show err) Right atom2 -> compareAtoms atom1 atom2 atomForAttributeName :: AttributeName -> DataFrameTuple -> Either RelationalError Atom atomForAttributeName attrName (DataFrameTuple tupAttrs tupVec) = case V.findIndex (\attr -> attributeName attr == attrName) (attributesVec tupAttrs) of Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName)) Just index -> case tupVec V.!? index of Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName)) Just atom -> Right atom take' :: Integer -> DataFrame -> DataFrame take' n df = df { tuples = take (fromInteger n) (tuples df) } drop' :: Integer -> DataFrame -> DataFrame drop' n df = df { tuples = drop (fromInteger n) (tuples df) } toDataFrame :: Relation -> DataFrame toDataFrame (Relation attrs (RelationTupleSet tuples')) = DataFrame [] attrs (map (\(RelationTuple tupAttrs tupVec) -> DataFrameTuple tupAttrs tupVec) tuples') fromDataFrame :: DataFrame -> Either RelationalError Relation fromDataFrame df = R.mkRelation (attributes df) (RelationTupleSet tuples') where tuples' = map (\(DataFrameTuple attrs' tupVec) -> RelationTuple attrs' tupVec) (tuples df) showDataFrame :: DataFrame -> T.Text showDataFrame = renderTable . dataFrameAsTable --terminal display dataFrameAsTable :: DataFrame -> Table dataFrameAsTable df = (header, body) where oAttrNames = orderedAttributeNames (attributes df) oAttrs = orderedAttributes (attributes df) header = "DF" : map dfPrettyAttribute oAttrs dfPrettyAttribute attr = prettyAttribute attr <> case L.find (\(AttributeOrder nam _) -> nam == attributeName attr) (orders df) of Nothing -> arbitrary Just (AttributeOrder _ AscendingOrder) -> ascending Just (AttributeOrder _ DescendingOrder) -> descending body = snd (L.foldl' tupleFolder (1 :: Int,[]) (tuples df)) tupleFolder (count, acc) tuple = (count + 1, acc ++ [T.pack (show count) : map (\attrName -> case atomForAttributeName attrName tuple of Left _ -> "?" Right atom -> showAtom 0 atom ) oAttrNames]) -- | A Relation can be converted to a DataFrame for sorting, limits, and offsets. data DataFrameExpr = DataFrameExpr { convertExpr :: RelationalExpr, orderExprs :: [AttributeOrderExpr], offset :: Maybe Integer, limit :: Maybe Integer } deriving (Show, Generic) dataFrameAsHTML :: DataFrame -> T.Text -- web browsers don't display tables with empty cells or empty headers, so we have to insert some placeholders- it's not technically the same, but looks as expected in the browser dataFrameAsHTML df | length (tuples df) == 1 && A.null (attributes df) = style <> tablestart <> "<tr><th></th></tr>" <> "<tr><td></td></tr>" <> tablefooter <> "</table>" | L.null (tuples df) && A.null (attributes df) = style <> tablestart <> "<tr><th></th></tr>" <> tablefooter <> "</table>" | otherwise = style <> tablestart <> attributesAsHTML (attributes df) (orders df) <> tuplesAsHTML (tuples df) <> tablefooter <> "</table>" where cardinality = T.pack (show (length (tuples df))) style = "<style>.pm36dataframe {empty-cells: show;} .pm36dataframe tbody td, .pm36relation th { border: 1px solid black;}</style>" tablefooter = "<tfoot><tr><td colspan=\"100%\">" <> cardinality <> " tuples</td></tr></tfoot>" tablestart = "<table class=\"pm36dataframe\"\">" tuplesAsHTML :: [DataFrameTuple] -> T.Text tuplesAsHTML = foldr folder "" where folder tuple acc = acc <> tupleAsHTML tuple tupleAssocs :: DataFrameTuple -> [(AttributeName, Atom)] tupleAssocs (DataFrameTuple attrs tupVec) = V.toList $ V.map (first attributeName) (V.zip (attributesVec attrs) tupVec) tupleAsHTML :: DataFrameTuple -> T.Text tupleAsHTML tuple = "<tr>" <> T.concat (L.map tupleFrag (tupleAssocs tuple)) <> "</tr>" where tupleFrag tup = "<td>" <> atomAsHTML (snd tup) <> "</td>" atomAsHTML (RelationAtom rel) = RelHTML.relationAsHTML rel atomAsHTML (TextAtom t) = "&quot;" <> t <> "&quot;" atomAsHTML atom = atomToText atom attributesAsHTML :: Attributes -> [AttributeOrder] -> T.Text attributesAsHTML attrs orders' = "<tr>" <> T.concat (map oneAttrHTML (A.toList attrs)) <> "</tr>" where oneAttrHTML attr = "<th>" <> prettyAttribute attr <> ordering (attributeName attr) <> "</th>" ordering attrName = " " <> case L.find (\(AttributeOrder nam _) -> nam == attrName) orders' of Nothing -> "(arb)" Just (AttributeOrder _ AscendingOrder) -> "(asc)" Just (AttributeOrder _ DescendingOrder) -> "(desc)"
null
https://raw.githubusercontent.com/agentm/project-m36/d05dec56f6a4884f10c49d30efd1db45b7db3a48/src/lib/ProjectM36/DataFrame.hs
haskell
A dataframe is a strongly-typed, ordered list of named tuples. A dataframe differs from a relation in that its tuples are ordered. terminal display | A Relation can be converted to a DataFrame for sorting, limits, and offsets. web browsers don't display tables with empty cells or empty headers, so we have to insert some placeholders- it's not technically the same, but looks as expected in the browser
# LANGUAGE DeriveGeneric , DerivingVia # module ProjectM36.DataFrame where import ProjectM36.Base import ProjectM36.Attribute as A hiding (drop) import ProjectM36.Error import qualified ProjectM36.Relation as R import ProjectM36.Relation.Show.Term import qualified ProjectM36.Relation.Show.HTML as RelHTML import ProjectM36.DataTypes.Sorting import ProjectM36.AtomType import ProjectM36.Atom import qualified Data.Vector as V import GHC.Generics import qualified Data.List as L import qualified Data.Set as S import Data.Maybe import qualified Data.Text as T import Control.Arrow import Control.Monad (unless) #if __GLASGOW_HASKELL__ < 804 import Data.Monoid #endif data AttributeOrderExpr = AttributeOrderExpr AttributeName Order deriving (Show, Generic) data AttributeOrder = AttributeOrder AttributeName Order deriving (Show, Generic) data Order = AscendingOrder | DescendingOrder deriving (Eq, Show, Generic) ascending :: T.Text ascending = "⬆" descending :: T.Text descending = "⬇" arbitrary :: T.Text arbitrary = "↕" data DataFrame = DataFrame { orders :: [AttributeOrder], attributes :: Attributes, tuples :: [DataFrameTuple] } deriving (Show, Generic) data DataFrameTuple = DataFrameTuple Attributes (V.Vector Atom) deriving (Eq, Show, Generic) sortDataFrameBy :: [AttributeOrder] -> DataFrame -> Either RelationalError DataFrame sortDataFrameBy attrOrders frame = do attrs <- mapM (\(AttributeOrder nam _) -> A.attributeForName nam (attributes frame)) attrOrders mapM_ (\attr -> unless (isSortableAtomType (atomType attr)) $ Left (AttributeNotSortableError attr)) attrs pure $ DataFrame attrOrders (attributes frame) (sortTuplesBy (compareTupleByAttributeOrders attrOrders) (tuples frame)) sortTuplesBy :: (DataFrameTuple -> DataFrameTuple -> Ordering) -> [DataFrameTuple] -> [DataFrameTuple] sortTuplesBy = L.sortBy compareTupleByAttributeOrders :: [AttributeOrder] -> DataFrameTuple -> DataFrameTuple -> Ordering compareTupleByAttributeOrders attributeOrders tup1 tup2 = let compare' (AttributeOrder attr order) = if order == DescendingOrder then compareTupleByOneAttributeName attr tup2 tup1 else compareTupleByOneAttributeName attr tup1 tup2 res = map compare' attributeOrders in fromMaybe EQ (L.find (/= EQ) res) compareTupleByOneAttributeName :: AttributeName -> DataFrameTuple -> DataFrameTuple -> Ordering compareTupleByOneAttributeName attr tuple1 tuple2 = let eAtom1 = atomForAttributeName attr tuple1 eAtom2 = atomForAttributeName attr tuple2 in case eAtom1 of Left err -> error (show err) Right atom1 -> case eAtom2 of Left err -> error (show err) Right atom2 -> compareAtoms atom1 atom2 atomForAttributeName :: AttributeName -> DataFrameTuple -> Either RelationalError Atom atomForAttributeName attrName (DataFrameTuple tupAttrs tupVec) = case V.findIndex (\attr -> attributeName attr == attrName) (attributesVec tupAttrs) of Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName)) Just index -> case tupVec V.!? index of Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName)) Just atom -> Right atom take' :: Integer -> DataFrame -> DataFrame take' n df = df { tuples = take (fromInteger n) (tuples df) } drop' :: Integer -> DataFrame -> DataFrame drop' n df = df { tuples = drop (fromInteger n) (tuples df) } toDataFrame :: Relation -> DataFrame toDataFrame (Relation attrs (RelationTupleSet tuples')) = DataFrame [] attrs (map (\(RelationTuple tupAttrs tupVec) -> DataFrameTuple tupAttrs tupVec) tuples') fromDataFrame :: DataFrame -> Either RelationalError Relation fromDataFrame df = R.mkRelation (attributes df) (RelationTupleSet tuples') where tuples' = map (\(DataFrameTuple attrs' tupVec) -> RelationTuple attrs' tupVec) (tuples df) showDataFrame :: DataFrame -> T.Text showDataFrame = renderTable . dataFrameAsTable dataFrameAsTable :: DataFrame -> Table dataFrameAsTable df = (header, body) where oAttrNames = orderedAttributeNames (attributes df) oAttrs = orderedAttributes (attributes df) header = "DF" : map dfPrettyAttribute oAttrs dfPrettyAttribute attr = prettyAttribute attr <> case L.find (\(AttributeOrder nam _) -> nam == attributeName attr) (orders df) of Nothing -> arbitrary Just (AttributeOrder _ AscendingOrder) -> ascending Just (AttributeOrder _ DescendingOrder) -> descending body = snd (L.foldl' tupleFolder (1 :: Int,[]) (tuples df)) tupleFolder (count, acc) tuple = (count + 1, acc ++ [T.pack (show count) : map (\attrName -> case atomForAttributeName attrName tuple of Left _ -> "?" Right atom -> showAtom 0 atom ) oAttrNames]) data DataFrameExpr = DataFrameExpr { convertExpr :: RelationalExpr, orderExprs :: [AttributeOrderExpr], offset :: Maybe Integer, limit :: Maybe Integer } deriving (Show, Generic) dataFrameAsHTML :: DataFrame -> T.Text dataFrameAsHTML df | length (tuples df) == 1 && A.null (attributes df) = style <> tablestart <> "<tr><th></th></tr>" <> "<tr><td></td></tr>" <> tablefooter <> "</table>" | L.null (tuples df) && A.null (attributes df) = style <> tablestart <> "<tr><th></th></tr>" <> tablefooter <> "</table>" | otherwise = style <> tablestart <> attributesAsHTML (attributes df) (orders df) <> tuplesAsHTML (tuples df) <> tablefooter <> "</table>" where cardinality = T.pack (show (length (tuples df))) style = "<style>.pm36dataframe {empty-cells: show;} .pm36dataframe tbody td, .pm36relation th { border: 1px solid black;}</style>" tablefooter = "<tfoot><tr><td colspan=\"100%\">" <> cardinality <> " tuples</td></tr></tfoot>" tablestart = "<table class=\"pm36dataframe\"\">" tuplesAsHTML :: [DataFrameTuple] -> T.Text tuplesAsHTML = foldr folder "" where folder tuple acc = acc <> tupleAsHTML tuple tupleAssocs :: DataFrameTuple -> [(AttributeName, Atom)] tupleAssocs (DataFrameTuple attrs tupVec) = V.toList $ V.map (first attributeName) (V.zip (attributesVec attrs) tupVec) tupleAsHTML :: DataFrameTuple -> T.Text tupleAsHTML tuple = "<tr>" <> T.concat (L.map tupleFrag (tupleAssocs tuple)) <> "</tr>" where tupleFrag tup = "<td>" <> atomAsHTML (snd tup) <> "</td>" atomAsHTML (RelationAtom rel) = RelHTML.relationAsHTML rel atomAsHTML (TextAtom t) = "&quot;" <> t <> "&quot;" atomAsHTML atom = atomToText atom attributesAsHTML :: Attributes -> [AttributeOrder] -> T.Text attributesAsHTML attrs orders' = "<tr>" <> T.concat (map oneAttrHTML (A.toList attrs)) <> "</tr>" where oneAttrHTML attr = "<th>" <> prettyAttribute attr <> ordering (attributeName attr) <> "</th>" ordering attrName = " " <> case L.find (\(AttributeOrder nam _) -> nam == attrName) orders' of Nothing -> "(arb)" Just (AttributeOrder _ AscendingOrder) -> "(asc)" Just (AttributeOrder _ DescendingOrder) -> "(desc)"
2239ca142f5d789635e50143664d0382a7999c1f6773c54c35a3a54dd4bd07cd
Drup/adtr
types.ml
open Syntax type error = | Unbound_type of Name.t | Unbound_type_variable of Name.t | Bad_constructor of name * Syntax.type_expr | No_constructor of Syntax.type_expr exception Error of error let error e = raise @@ Error e let prepare_error = function | Error (Unbound_type_variable n) -> Some (Report.errorf "The type variable %a is unbounded" Name.pp n) | Error (Unbound_type n) -> Some (Report.errorf "The type constructor %a is unbounded" Name.pp n) | Error (Bad_constructor (n, ty)) -> Some (Report.errorf "The data constructor %s doesn't belong to the type %a." n Printer.types ty) | Error (No_constructor ty) -> Some (Report.errorf "The type %a doesn't have any constructors." Printer.types ty) | _ -> None let () = Report.register_report_of_exn prepare_error let rec equal ty1 ty2 = match ty1, ty2 with | TInt, TInt -> true | TVar a, TVar b -> String.equal a b | TConstructor { constructor = c1 ; arguments = a1 }, TConstructor { constructor = c2 ; arguments = a2} -> String.equal c1 c2 && CCList.equal equal a1 a2 | _, _ -> false let is_scalar ty = match ty with | TInt -> true | TConstructor _ | TFun _ -> false | TVar _ -> assert false module Env = struct type t = Syntax.type_declaration Name.Map.t let empty = Name.Map.empty let add = Name.Map.add let get n e : type_declaration = match Name.Map.get n e with | None -> error @@ Unbound_type n | Some v -> v end module Subst = struct type t = type_expr Name.Map.t let empty = Name.Map.empty let var subst n = match Name.Map.get n subst with | None -> error @@ Unbound_type_variable n | Some v -> v let rec type_expr subst ty = match ty with | TVar n -> var subst n | TInt -> TInt | TFun (args, ret) -> let args = List.map (type_expr subst) args in let ret = type_expr subst ret in TFun (args, ret) | TConstructor { constructor; arguments } -> let arguments = List.map (type_expr subst) arguments in TConstructor { constructor; arguments } end let rec get_definition_with_subst tyenv subst ty = match ty with | TInt | TFun _ -> error @@ No_constructor ty | TVar name -> let ty = Subst.var subst name in get_definition_with_subst tyenv subst ty | TConstructor { constructor = type_name ; arguments } -> let { name = _ ; parameters ; definition } = Env.get type_name tyenv in let subst = let f e name ty = Name.Map.add name ty e in List.fold_left2 f subst parameters arguments in begin match definition with | Sum constrs -> let f { constructor ; arguments } = List.mapi (fun pos ty -> constructor, {Field. pos; ty = Subst.type_expr subst ty}) arguments in CCList.flat_map f constrs end let get_definition tyenv ty = get_definition_with_subst tyenv Subst.empty ty let instantiate_data_constructor tyenv constructor ty = match ty with | TVar _ -> assert false | TInt | TFun _ -> error @@ Bad_constructor (constructor, ty) | TConstructor { constructor = type_name ; arguments } -> let { name = _ ; parameters ; definition } = Env.get type_name tyenv in let subst = let f e name ty = Name.Map.add name ty e in List.fold_left2 f Subst.empty parameters arguments in begin match definition with | Sum constrs -> match CCList.find_opt (fun x -> x.constructor = constructor) constrs with | None -> error @@ Bad_constructor (constructor, ty) | Some { constructor = _ ; arguments } -> List.map (Subst.type_expr subst) arguments end let complement tyenv ty0 (fields0 : Field.t) = let rec aux prev_ty curr_fields = function | [] -> [], [] | {Field. ty; pos} as f :: path -> let all_fields = get_definition tyenv prev_ty in let compl_paths = CCList.sort_uniq ~cmp:Stdlib.compare @@ CCList.filter_map (fun (_constr',f') -> if f = f' then None else Some (Field.(curr_fields +/ f'), f'.ty)) all_fields in let curr_fields', compl_paths' = aux ty Field.(curr_fields +/ f) path in curr_fields :: curr_fields', compl_paths @ compl_paths' in aux ty0 Field.empty fields0
null
https://raw.githubusercontent.com/Drup/adtr/a2d1cb8473522a52e475fd1261892cf363f215aa/src/types.ml
ocaml
open Syntax type error = | Unbound_type of Name.t | Unbound_type_variable of Name.t | Bad_constructor of name * Syntax.type_expr | No_constructor of Syntax.type_expr exception Error of error let error e = raise @@ Error e let prepare_error = function | Error (Unbound_type_variable n) -> Some (Report.errorf "The type variable %a is unbounded" Name.pp n) | Error (Unbound_type n) -> Some (Report.errorf "The type constructor %a is unbounded" Name.pp n) | Error (Bad_constructor (n, ty)) -> Some (Report.errorf "The data constructor %s doesn't belong to the type %a." n Printer.types ty) | Error (No_constructor ty) -> Some (Report.errorf "The type %a doesn't have any constructors." Printer.types ty) | _ -> None let () = Report.register_report_of_exn prepare_error let rec equal ty1 ty2 = match ty1, ty2 with | TInt, TInt -> true | TVar a, TVar b -> String.equal a b | TConstructor { constructor = c1 ; arguments = a1 }, TConstructor { constructor = c2 ; arguments = a2} -> String.equal c1 c2 && CCList.equal equal a1 a2 | _, _ -> false let is_scalar ty = match ty with | TInt -> true | TConstructor _ | TFun _ -> false | TVar _ -> assert false module Env = struct type t = Syntax.type_declaration Name.Map.t let empty = Name.Map.empty let add = Name.Map.add let get n e : type_declaration = match Name.Map.get n e with | None -> error @@ Unbound_type n | Some v -> v end module Subst = struct type t = type_expr Name.Map.t let empty = Name.Map.empty let var subst n = match Name.Map.get n subst with | None -> error @@ Unbound_type_variable n | Some v -> v let rec type_expr subst ty = match ty with | TVar n -> var subst n | TInt -> TInt | TFun (args, ret) -> let args = List.map (type_expr subst) args in let ret = type_expr subst ret in TFun (args, ret) | TConstructor { constructor; arguments } -> let arguments = List.map (type_expr subst) arguments in TConstructor { constructor; arguments } end let rec get_definition_with_subst tyenv subst ty = match ty with | TInt | TFun _ -> error @@ No_constructor ty | TVar name -> let ty = Subst.var subst name in get_definition_with_subst tyenv subst ty | TConstructor { constructor = type_name ; arguments } -> let { name = _ ; parameters ; definition } = Env.get type_name tyenv in let subst = let f e name ty = Name.Map.add name ty e in List.fold_left2 f subst parameters arguments in begin match definition with | Sum constrs -> let f { constructor ; arguments } = List.mapi (fun pos ty -> constructor, {Field. pos; ty = Subst.type_expr subst ty}) arguments in CCList.flat_map f constrs end let get_definition tyenv ty = get_definition_with_subst tyenv Subst.empty ty let instantiate_data_constructor tyenv constructor ty = match ty with | TVar _ -> assert false | TInt | TFun _ -> error @@ Bad_constructor (constructor, ty) | TConstructor { constructor = type_name ; arguments } -> let { name = _ ; parameters ; definition } = Env.get type_name tyenv in let subst = let f e name ty = Name.Map.add name ty e in List.fold_left2 f Subst.empty parameters arguments in begin match definition with | Sum constrs -> match CCList.find_opt (fun x -> x.constructor = constructor) constrs with | None -> error @@ Bad_constructor (constructor, ty) | Some { constructor = _ ; arguments } -> List.map (Subst.type_expr subst) arguments end let complement tyenv ty0 (fields0 : Field.t) = let rec aux prev_ty curr_fields = function | [] -> [], [] | {Field. ty; pos} as f :: path -> let all_fields = get_definition tyenv prev_ty in let compl_paths = CCList.sort_uniq ~cmp:Stdlib.compare @@ CCList.filter_map (fun (_constr',f') -> if f = f' then None else Some (Field.(curr_fields +/ f'), f'.ty)) all_fields in let curr_fields', compl_paths' = aux ty Field.(curr_fields +/ f) path in curr_fields :: curr_fields', compl_paths @ compl_paths' in aux ty0 Field.empty fields0
6f71e79eaf1cb7ee5d445dff1dc8af40fbe2b5899d6ff362b146c78d09a4e07d
winny-/aoc
imm-eq-8.rkt
#lang reader "reader-p2.rkt" 3,3,1108,-1,8,3,4,3,99
null
https://raw.githubusercontent.com/winny-/aoc/d508caae19899dcab57ac665ef5d1a05b0a90c0c/2019/day05/programs/imm-eq-8.rkt
racket
#lang reader "reader-p2.rkt" 3,3,1108,-1,8,3,4,3,99
e647ce0b98f07a3fe9d515e787a2792693c4c4bf06563fe76135a36329242c6a
lexi-lambda/megaparsack
contract.rkt
#lang racket/base (require data/applicative data/monad megaparsack megaparsack/text racket/list racket/contract rackunit rackunit/spec) (describe "parser/c" (it "signals a contract violation on invalid input tokens" (define exn (with-handlers ([exn:fail? values]) (parse (char/p #\a) (list (syntax-box #f (srcloc #f #f #f #f #f)))))) (check-pred exn:fail:contract:blame? exn) (define blame (exn:fail:contract:blame-object exn)) (check-equal? (blame-contract blame) '(-> char? (parser/c char? char?))) (check-pred blame-swapped? blame) (check-equal? (first (blame-context blame)) "the input to")) (it "signals a contract violation on invalid results" (define/contract foo/p (parser/c any/c string?) (do void/p (pure #f))) (define exn (with-handlers ([exn:fail? values]) (parse foo/p '()))) (check-pred exn:fail:contract:blame? exn) (define blame (exn:fail:contract:blame-object exn)) (check-equal? (blame-contract blame) '(parser/c any/c string?)) (check-pred blame-original? blame) (check-equal? (first (blame-context blame)) "the result of")))
null
https://raw.githubusercontent.com/lexi-lambda/megaparsack/86cd7bca381e1c58458f26080fa4ed73cf64d67e/megaparsack-test/tests/megaparsack/contract.rkt
racket
#lang racket/base (require data/applicative data/monad megaparsack megaparsack/text racket/list racket/contract rackunit rackunit/spec) (describe "parser/c" (it "signals a contract violation on invalid input tokens" (define exn (with-handlers ([exn:fail? values]) (parse (char/p #\a) (list (syntax-box #f (srcloc #f #f #f #f #f)))))) (check-pred exn:fail:contract:blame? exn) (define blame (exn:fail:contract:blame-object exn)) (check-equal? (blame-contract blame) '(-> char? (parser/c char? char?))) (check-pred blame-swapped? blame) (check-equal? (first (blame-context blame)) "the input to")) (it "signals a contract violation on invalid results" (define/contract foo/p (parser/c any/c string?) (do void/p (pure #f))) (define exn (with-handlers ([exn:fail? values]) (parse foo/p '()))) (check-pred exn:fail:contract:blame? exn) (define blame (exn:fail:contract:blame-object exn)) (check-equal? (blame-contract blame) '(parser/c any/c string?)) (check-pred blame-original? blame) (check-equal? (first (blame-context blame)) "the result of")))
4e2e238590398e20a3b57eb804bf5b14fc71d58cd8b732b776cfe27da51cf9f6
dnsimple/erldns-admin
erldns_admin_zone_control_handler.erl
Copyright ( c ) 2012 - 2019 , DNSimple Corporation %% %% Permission to use, copy, modify, and/or distribute this software for any %% purpose with or without fee is hereby granted, provided that the above %% copyright notice and this permission notice appear in all copies. %% THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. %% @doc Cowboy handler that handles Admin API requests to /zones/:name/:action %% %% Currently no actions are supported. -module(erldns_admin_zone_control_handler). -export([init/2]). -export([content_types_provided/2, is_authorized/2]). -export([to_html/2, to_json/2, to_text/2]). -behaviour(cowboy_rest). -include_lib("dns_erlang/include/dns.hrl"). -include_lib("erldns/include/erldns.hrl"). init(Req, State) -> {cowboy_rest, Req, State}. content_types_provided(Req, State) -> {[ {<<"text/html">>, to_html}, {<<"text/plain">>, to_text}, {<<"application/json">>, to_json} ], Req, State}. is_authorized(Req, State) -> erldns_admin:is_authorized(Req, State). to_html(Req, State) -> {<<"erldns admin">>, Req, State}. to_text(Req, State) -> {<<"erldns admin">>, Req, State}. to_json(Req, State) -> Name = cowboy_req:binding(zone_name, Req), Action = cowboy_req:binding(action, Req), case Action of _ -> lager:debug("Unsupported action: ~p (name: ~p)", [Action, Name]), {jsx:encode([]), Req, State} end.
null
https://raw.githubusercontent.com/dnsimple/erldns-admin/37ad199c5a71ea3605a2e43f7c3847f51521516d/src/erldns_admin_zone_control_handler.erl
erlang
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. @doc Cowboy handler that handles Admin API requests to /zones/:name/:action Currently no actions are supported.
Copyright ( c ) 2012 - 2019 , DNSimple Corporation THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN -module(erldns_admin_zone_control_handler). -export([init/2]). -export([content_types_provided/2, is_authorized/2]). -export([to_html/2, to_json/2, to_text/2]). -behaviour(cowboy_rest). -include_lib("dns_erlang/include/dns.hrl"). -include_lib("erldns/include/erldns.hrl"). init(Req, State) -> {cowboy_rest, Req, State}. content_types_provided(Req, State) -> {[ {<<"text/html">>, to_html}, {<<"text/plain">>, to_text}, {<<"application/json">>, to_json} ], Req, State}. is_authorized(Req, State) -> erldns_admin:is_authorized(Req, State). to_html(Req, State) -> {<<"erldns admin">>, Req, State}. to_text(Req, State) -> {<<"erldns admin">>, Req, State}. to_json(Req, State) -> Name = cowboy_req:binding(zone_name, Req), Action = cowboy_req:binding(action, Req), case Action of _ -> lager:debug("Unsupported action: ~p (name: ~p)", [Action, Name]), {jsx:encode([]), Req, State} end.
94120cd2982e7d176e32eb89789523fe6f396ba594dc00ce199cf45ae743c9f5
ewestern/geos
Prepared.hs
module Data.Geometry.Geos.Raw.Prepared ( PreparedGeometry(..) , withPreparedGeometry , prepare , contains , containsProperly , coveredBy , covers , crosses , disjoint , intersects , overlaps , touches , within ) where import Data.Geometry.Geos.Raw.Internal import Data.Geometry.Geos.Raw.Base import qualified Data.Geometry.Geos.Raw.Geometry as RG import Foreign.Marshal.Utils import Foreign hiding ( throwIf ) import Foreign.C.Types newtype PreparedGeometry = PreparedGeometry { unPreparedGeometry :: ForeignPtr GEOSPreparedGeometry } deriving (Show, Eq) withPreparedGeometry :: PreparedGeometry -> (Ptr GEOSPreparedGeometry -> IO a) -> IO a withPreparedGeometry (PreparedGeometry g) = withForeignPtr g prepare :: RG.Geometry a => a -> Geos PreparedGeometry prepare g = withGeos $ \h -> do g' <- RG.withGeometry g $ \gp -> geos_Prepare h gp fp <- newForeignPtrEnv geos_PreparedGeomDestroy h g' return $ PreparedGeometry fp queryPrepared :: RG.Geometry a => ( GEOSContextHandle_t -> Ptr GEOSPreparedGeometry -> Ptr GEOSGeometry -> IO CChar ) -> String -> PreparedGeometry -> a -> Geos Bool queryPrepared f s pg g = do b <- throwIf (2 ==) (mkErrorMessage s) $ withGeos $ \h -> RG.withGeometry g $ \gp -> withPreparedGeometry pg $ flip (f h) gp return . toBool $ b contains :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool contains = queryPrepared geos_PreparedContains "contains" containsProperly :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool containsProperly = queryPrepared geos_PreparedContainsProperly "containsProperly" coveredBy :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool coveredBy = queryPrepared geos_PreparedCoveredBy "coveredBy" covers :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool covers = queryPrepared geos_PreparedCovers "covers" crosses :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool crosses = queryPrepared geos_PreparedCrosses "crosses" disjoint :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool disjoint = queryPrepared geos_PreparedDisjoint "disjoint" intersects :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool intersects = queryPrepared geos_PreparedIntersects "intersects" overlaps :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool overlaps = queryPrepared geos_PreparedOverlaps "overlaps" touches :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool touches = queryPrepared geos_PreparedTouches "touches" within :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool within = queryPrepared geos_PreparedWithin "within"
null
https://raw.githubusercontent.com/ewestern/geos/3568c3449efe180bd89959c9247d4667137662b6/src/Data/Geometry/Geos/Raw/Prepared.hs
haskell
module Data.Geometry.Geos.Raw.Prepared ( PreparedGeometry(..) , withPreparedGeometry , prepare , contains , containsProperly , coveredBy , covers , crosses , disjoint , intersects , overlaps , touches , within ) where import Data.Geometry.Geos.Raw.Internal import Data.Geometry.Geos.Raw.Base import qualified Data.Geometry.Geos.Raw.Geometry as RG import Foreign.Marshal.Utils import Foreign hiding ( throwIf ) import Foreign.C.Types newtype PreparedGeometry = PreparedGeometry { unPreparedGeometry :: ForeignPtr GEOSPreparedGeometry } deriving (Show, Eq) withPreparedGeometry :: PreparedGeometry -> (Ptr GEOSPreparedGeometry -> IO a) -> IO a withPreparedGeometry (PreparedGeometry g) = withForeignPtr g prepare :: RG.Geometry a => a -> Geos PreparedGeometry prepare g = withGeos $ \h -> do g' <- RG.withGeometry g $ \gp -> geos_Prepare h gp fp <- newForeignPtrEnv geos_PreparedGeomDestroy h g' return $ PreparedGeometry fp queryPrepared :: RG.Geometry a => ( GEOSContextHandle_t -> Ptr GEOSPreparedGeometry -> Ptr GEOSGeometry -> IO CChar ) -> String -> PreparedGeometry -> a -> Geos Bool queryPrepared f s pg g = do b <- throwIf (2 ==) (mkErrorMessage s) $ withGeos $ \h -> RG.withGeometry g $ \gp -> withPreparedGeometry pg $ flip (f h) gp return . toBool $ b contains :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool contains = queryPrepared geos_PreparedContains "contains" containsProperly :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool containsProperly = queryPrepared geos_PreparedContainsProperly "containsProperly" coveredBy :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool coveredBy = queryPrepared geos_PreparedCoveredBy "coveredBy" covers :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool covers = queryPrepared geos_PreparedCovers "covers" crosses :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool crosses = queryPrepared geos_PreparedCrosses "crosses" disjoint :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool disjoint = queryPrepared geos_PreparedDisjoint "disjoint" intersects :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool intersects = queryPrepared geos_PreparedIntersects "intersects" overlaps :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool overlaps = queryPrepared geos_PreparedOverlaps "overlaps" touches :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool touches = queryPrepared geos_PreparedTouches "touches" within :: RG.Geometry a => PreparedGeometry -> a -> Geos Bool within = queryPrepared geos_PreparedWithin "within"
9e3fcc610b5b96bc4a5643a0ab7dfef5c252b4872959aab7a2b65dee4ddab15a
GillianPlatform/Gillian
valueTranslation.ml
open Compcert module Literal = Gillian.Gil_syntax.Literal open CConstants let true_name id = let str = Camlcoq.extern_atom id in if str.[0] = '$' then Prefix.uvar ^ String.sub str 1 (String.length str - 1) else str let z_of_int z = Camlcoq.Z.of_sint (Z.to_int z) let int_of_z z = Z.of_int (Camlcoq.Z.to_int z) let string_of_chunk = Chunk.to_string let chunk_of_string = Chunk.of_string let loc_name_of_block block = let int_block = Camlcoq.P.to_int block in let string_block = string_of_int int_block in Prefix.loc ^ string_block let block_of_loc_name loc_name = let size_int = String.length loc_name - 2 in let string_block = String.sub loc_name 2 size_int in let int_block = int_of_string string_block in Camlcoq.P.of_int int_block let compcert_size_of_gil = z_of_int let gil_size_of_compcert = int_of_z let compcert_of_gil gil_value = let open Literal in let open Values in match gil_value with | Undefined -> Vundef | LList [ String typ; Int ocaml_int ] when String.equal typ VTypes.int_type -> let coq_int = z_of_int ocaml_int in Vint coq_int | LList [ String typ; Num ocaml_float ] when String.equal typ VTypes.float_type -> let coq_float = Camlcoq.coqfloat_of_camlfloat ocaml_float in Vfloat coq_float | LList [ String typ; Num ocaml_float ] when String.equal typ VTypes.single_type -> let coq_float = Camlcoq.coqfloat_of_camlfloat ocaml_float in Vsingle coq_float | LList [ String typ; Int ocaml_int ] when String.equal typ VTypes.long_type -> let coq_int = z_of_int ocaml_int in Vlong coq_int | LList [ Loc loc; Int ocaml_ofs ] -> let block = block_of_loc_name loc in let ptrofs = z_of_int ocaml_ofs in Vptr (block, ptrofs) | _ -> failwith (Format.asprintf "Invalid serialization of value : %a" pp gil_value) let gil_of_compcert compcert_value = let open Literal in let open Values in match compcert_value with | Vundef -> Undefined | Vint i -> let ocaml_int = int_of_z i in LList [ String VTypes.int_type; Int ocaml_int ] | Vfloat f -> let ocaml_float = Camlcoq.camlfloat_of_coqfloat f in LList [ String VTypes.float_type; Num ocaml_float ] | Vsingle f32 -> let ocaml_float = Camlcoq.camlfloat_of_coqfloat32 f32 in LList [ String VTypes.single_type; Num ocaml_float ] | Vlong i64 -> let ocaml_int = int_of_z i64 in LList [ String VTypes.long_type; Int ocaml_int ] | Vptr (block, ptrofs) -> let loc = loc_name_of_block block in let ocaml_ofs = int_of_z ptrofs in LList [ Loc loc; Int ocaml_ofs ] let string_of_permission perm = let open Compcert.Memtype in match perm with | Freeable -> "Freeable" | Writable -> "Writable" | Readable -> "Readable" | Nonempty -> "Nonempty" let permission_of_string str = let open Compcert.Memtype in match str with | "Freeable" -> Freeable | "Writable" -> Writable | "Readable" -> Readable | "Nonempty" -> Nonempty | _ -> failwith ("Unkown permission : " ^ str) let permission_opt_of_string str = try Some (permission_of_string str) with Failure _ -> if String.equal "None" str then None else failwith ("Unkown optional permission : " ^ str) let string_of_permission_opt p_opt = match p_opt with | None -> "None" | Some p -> string_of_permission p let compcert_block_of_gil gil_block = let open Gillian.Gil_syntax.Literal in match gil_block with | LList [ Loc l; Int low; Int high ] -> ((block_of_loc_name l, z_of_int low), z_of_int high) | _ -> failwith (Format.asprintf "Invalid block to free : %a" pp gil_block) let gil_init_data init_data = let open Literal in let oint n = Int (int_of_z n) in let open Compcert.AST in match init_data with | Init_int8 n -> LList [ String "int8"; oint n ] | Init_int16 n -> LList [ String "int16"; oint n ] | Init_int32 n -> LList [ String "int32"; oint n ] | Init_int64 n -> LList [ String "int64"; oint n ] | Init_float32 n -> LList [ String "float32"; Num (Camlcoq.camlfloat_of_coqfloat32 n) ] | Init_float64 n -> LList [ String "float64"; Num (Camlcoq.camlfloat_of_coqfloat n) ] | Init_space n -> LList [ String "space"; oint n ] | Init_addrof (sym, ofs) -> LList [ String "addrof"; String (true_name sym); oint ofs ]
null
https://raw.githubusercontent.com/GillianPlatform/Gillian/21ba7e6ee56277bbf06eb3a79be4b87f3224bc11/Gillian-C/lib/valueTranslation.ml
ocaml
open Compcert module Literal = Gillian.Gil_syntax.Literal open CConstants let true_name id = let str = Camlcoq.extern_atom id in if str.[0] = '$' then Prefix.uvar ^ String.sub str 1 (String.length str - 1) else str let z_of_int z = Camlcoq.Z.of_sint (Z.to_int z) let int_of_z z = Z.of_int (Camlcoq.Z.to_int z) let string_of_chunk = Chunk.to_string let chunk_of_string = Chunk.of_string let loc_name_of_block block = let int_block = Camlcoq.P.to_int block in let string_block = string_of_int int_block in Prefix.loc ^ string_block let block_of_loc_name loc_name = let size_int = String.length loc_name - 2 in let string_block = String.sub loc_name 2 size_int in let int_block = int_of_string string_block in Camlcoq.P.of_int int_block let compcert_size_of_gil = z_of_int let gil_size_of_compcert = int_of_z let compcert_of_gil gil_value = let open Literal in let open Values in match gil_value with | Undefined -> Vundef | LList [ String typ; Int ocaml_int ] when String.equal typ VTypes.int_type -> let coq_int = z_of_int ocaml_int in Vint coq_int | LList [ String typ; Num ocaml_float ] when String.equal typ VTypes.float_type -> let coq_float = Camlcoq.coqfloat_of_camlfloat ocaml_float in Vfloat coq_float | LList [ String typ; Num ocaml_float ] when String.equal typ VTypes.single_type -> let coq_float = Camlcoq.coqfloat_of_camlfloat ocaml_float in Vsingle coq_float | LList [ String typ; Int ocaml_int ] when String.equal typ VTypes.long_type -> let coq_int = z_of_int ocaml_int in Vlong coq_int | LList [ Loc loc; Int ocaml_ofs ] -> let block = block_of_loc_name loc in let ptrofs = z_of_int ocaml_ofs in Vptr (block, ptrofs) | _ -> failwith (Format.asprintf "Invalid serialization of value : %a" pp gil_value) let gil_of_compcert compcert_value = let open Literal in let open Values in match compcert_value with | Vundef -> Undefined | Vint i -> let ocaml_int = int_of_z i in LList [ String VTypes.int_type; Int ocaml_int ] | Vfloat f -> let ocaml_float = Camlcoq.camlfloat_of_coqfloat f in LList [ String VTypes.float_type; Num ocaml_float ] | Vsingle f32 -> let ocaml_float = Camlcoq.camlfloat_of_coqfloat32 f32 in LList [ String VTypes.single_type; Num ocaml_float ] | Vlong i64 -> let ocaml_int = int_of_z i64 in LList [ String VTypes.long_type; Int ocaml_int ] | Vptr (block, ptrofs) -> let loc = loc_name_of_block block in let ocaml_ofs = int_of_z ptrofs in LList [ Loc loc; Int ocaml_ofs ] let string_of_permission perm = let open Compcert.Memtype in match perm with | Freeable -> "Freeable" | Writable -> "Writable" | Readable -> "Readable" | Nonempty -> "Nonempty" let permission_of_string str = let open Compcert.Memtype in match str with | "Freeable" -> Freeable | "Writable" -> Writable | "Readable" -> Readable | "Nonempty" -> Nonempty | _ -> failwith ("Unkown permission : " ^ str) let permission_opt_of_string str = try Some (permission_of_string str) with Failure _ -> if String.equal "None" str then None else failwith ("Unkown optional permission : " ^ str) let string_of_permission_opt p_opt = match p_opt with | None -> "None" | Some p -> string_of_permission p let compcert_block_of_gil gil_block = let open Gillian.Gil_syntax.Literal in match gil_block with | LList [ Loc l; Int low; Int high ] -> ((block_of_loc_name l, z_of_int low), z_of_int high) | _ -> failwith (Format.asprintf "Invalid block to free : %a" pp gil_block) let gil_init_data init_data = let open Literal in let oint n = Int (int_of_z n) in let open Compcert.AST in match init_data with | Init_int8 n -> LList [ String "int8"; oint n ] | Init_int16 n -> LList [ String "int16"; oint n ] | Init_int32 n -> LList [ String "int32"; oint n ] | Init_int64 n -> LList [ String "int64"; oint n ] | Init_float32 n -> LList [ String "float32"; Num (Camlcoq.camlfloat_of_coqfloat32 n) ] | Init_float64 n -> LList [ String "float64"; Num (Camlcoq.camlfloat_of_coqfloat n) ] | Init_space n -> LList [ String "space"; oint n ] | Init_addrof (sym, ofs) -> LList [ String "addrof"; String (true_name sym); oint ofs ]
51a64a40918235caa831686dbcb3196aa5ec3a5b86eaf972b76dd1d2fcb3de3c
RefactoringTools/HaRe
OldSyntaxRec.hs
module OldSyntaxRec where import SyntaxRec -- For backward compatibility: type HsPat = HsPatI HsName type HsType = HsTypeI HsName type HsExp = HsExpI HsName type HsDecl = HsDeclI HsName type HsModuleR = HsModuleRI HsName type BaseDecl = BaseDeclI HsName type BaseExp = BaseExpI HsName type BasePat = BasePatI HsName type BaseType = BaseTypeI HsName type HsModuleRI i = HsModuleI i [HsDeclI i] type HsStmtR = HsStmt HsExp HsPat [HsDecl] type HsAltR = HsAlt HsExp HsPat [HsDecl]
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/base/syntax/OldSyntaxRec.hs
haskell
For backward compatibility:
module OldSyntaxRec where import SyntaxRec type HsPat = HsPatI HsName type HsType = HsTypeI HsName type HsExp = HsExpI HsName type HsDecl = HsDeclI HsName type HsModuleR = HsModuleRI HsName type BaseDecl = BaseDeclI HsName type BaseExp = BaseExpI HsName type BasePat = BasePatI HsName type BaseType = BaseTypeI HsName type HsModuleRI i = HsModuleI i [HsDeclI i] type HsStmtR = HsStmt HsExp HsPat [HsDecl] type HsAltR = HsAlt HsExp HsPat [HsDecl]
a162595810edcf0c367864ca6b40e86b4fb7f967ea6ed6a3c23a8c82a4d9b355
puppetlabs/puppetdb
queue.clj
(ns puppetlabs.puppetdb.testutils.queue (:require [me.raynes.fs :refer [delete-dir]] [puppetlabs.stockpile.queue :as stock] [puppetlabs.puppetdb.nio :refer [get-path]] [puppetlabs.puppetdb.testutils.nio :refer [create-temp-dir]] [puppetlabs.puppetdb.queue :as q] [puppetlabs.puppetdb.cheshire :as json] [puppetlabs.puppetdb.time :refer [now]] [puppetlabs.kitchensink.core :as ks])) (defmacro with-stockpile [queue-sym & body] `(let [ns-str# (str (ns-name ~*ns*)) queue-dir# (-> (get-path "target" ns-str#) (create-temp-dir "stk") (.resolve "q") str) ~queue-sym (stock/create queue-dir#)] (try ~@body (finally (delete-dir queue-dir#))))) (defprotocol CoerceToStream (-coerce-to-stream [x] "Converts the given input to the input stream that stockpile requires")) (extend-protocol CoerceToStream java.io.InputStream (-coerce-to-stream [x] x) String (-coerce-to-stream [x] (java.io.ByteArrayInputStream. (.getBytes x "UTF-8"))) clojure.lang.IEditableCollection (-coerce-to-stream [x] (let [baos (java.io.ByteArrayOutputStream.)] (with-open [osw (java.io.OutputStreamWriter. baos java.nio.charset.StandardCharsets/UTF_8)] (json/generate-stream x osw)) (.close baos) (-> baos .toByteArray java.io.ByteArrayInputStream.)))) (defn coerce-to-stream [x] (-coerce-to-stream x)) (defn catalog->command-req [version {:keys [certname name] :as catalog}] (q/create-command-req "replace catalog" version (or certname name) (ks/timestamp (now)) "" identity (coerce-to-stream catalog))) (defn catalog-inputs->command-req [version {:keys [certname name] :as catalog-inputs}] (q/create-command-req "replace catalog inputs" version (or certname name) (ks/timestamp (now)) "" identity (coerce-to-stream catalog-inputs))) (defn facts->command-req [version {:keys [certname name] :as facts}] (q/create-command-req "replace facts" version (or certname name) (ks/timestamp (now)) "" identity (coerce-to-stream facts))) (defn deactivate->command-req [version {:keys [certname] :as command}] (q/create-command-req "deactivate node" version (case version 3 certname 2 (json/parse-string command) 1 (json/parse-string (json/parse-string command))) (ks/timestamp (now)) "" identity (coerce-to-stream command))) (defn report->command-req [version {:keys [certname name] :as command}] (q/create-command-req "store report" version (or certname name) (ks/timestamp (now)) "" identity (coerce-to-stream command)))
null
https://raw.githubusercontent.com/puppetlabs/puppetdb/b3d6d10555561657150fa70b6d1e609fba9c0eda/test/puppetlabs/puppetdb/testutils/queue.clj
clojure
(ns puppetlabs.puppetdb.testutils.queue (:require [me.raynes.fs :refer [delete-dir]] [puppetlabs.stockpile.queue :as stock] [puppetlabs.puppetdb.nio :refer [get-path]] [puppetlabs.puppetdb.testutils.nio :refer [create-temp-dir]] [puppetlabs.puppetdb.queue :as q] [puppetlabs.puppetdb.cheshire :as json] [puppetlabs.puppetdb.time :refer [now]] [puppetlabs.kitchensink.core :as ks])) (defmacro with-stockpile [queue-sym & body] `(let [ns-str# (str (ns-name ~*ns*)) queue-dir# (-> (get-path "target" ns-str#) (create-temp-dir "stk") (.resolve "q") str) ~queue-sym (stock/create queue-dir#)] (try ~@body (finally (delete-dir queue-dir#))))) (defprotocol CoerceToStream (-coerce-to-stream [x] "Converts the given input to the input stream that stockpile requires")) (extend-protocol CoerceToStream java.io.InputStream (-coerce-to-stream [x] x) String (-coerce-to-stream [x] (java.io.ByteArrayInputStream. (.getBytes x "UTF-8"))) clojure.lang.IEditableCollection (-coerce-to-stream [x] (let [baos (java.io.ByteArrayOutputStream.)] (with-open [osw (java.io.OutputStreamWriter. baos java.nio.charset.StandardCharsets/UTF_8)] (json/generate-stream x osw)) (.close baos) (-> baos .toByteArray java.io.ByteArrayInputStream.)))) (defn coerce-to-stream [x] (-coerce-to-stream x)) (defn catalog->command-req [version {:keys [certname name] :as catalog}] (q/create-command-req "replace catalog" version (or certname name) (ks/timestamp (now)) "" identity (coerce-to-stream catalog))) (defn catalog-inputs->command-req [version {:keys [certname name] :as catalog-inputs}] (q/create-command-req "replace catalog inputs" version (or certname name) (ks/timestamp (now)) "" identity (coerce-to-stream catalog-inputs))) (defn facts->command-req [version {:keys [certname name] :as facts}] (q/create-command-req "replace facts" version (or certname name) (ks/timestamp (now)) "" identity (coerce-to-stream facts))) (defn deactivate->command-req [version {:keys [certname] :as command}] (q/create-command-req "deactivate node" version (case version 3 certname 2 (json/parse-string command) 1 (json/parse-string (json/parse-string command))) (ks/timestamp (now)) "" identity (coerce-to-stream command))) (defn report->command-req [version {:keys [certname name] :as command}] (q/create-command-req "store report" version (or certname name) (ks/timestamp (now)) "" identity (coerce-to-stream command)))
b6d9edcf1f8294ef114bc965cc3ff67126d4994557606f84232dc31bd1f9282f
plewto/Cadejo
keymode.clj
(println "--> cadejo.midi.keymode") (ns cadejo.midi.keymode) (defprotocol Keymode "Defines performance keymode interface. See mono-mode and poly-mode for concrete implementations." (set-parent! [this performance] "Sets parent performance for this keymode.") (reset [this] "Set all notes off and reset all internal values to a known initial state.") (key-down [this event] "Handle MIDI note-on events.") (key-up [this event] "Handle MIDI note-off events") (trace! [this flag] "Enable diagnostic tracing of j]key on/off events") (dump [this depth] [this]))
null
https://raw.githubusercontent.com/plewto/Cadejo/2a98610ce1f5fe01dce5f28d986a38c86677fd67/src/cadejo/midi/keymode.clj
clojure
(println "--> cadejo.midi.keymode") (ns cadejo.midi.keymode) (defprotocol Keymode "Defines performance keymode interface. See mono-mode and poly-mode for concrete implementations." (set-parent! [this performance] "Sets parent performance for this keymode.") (reset [this] "Set all notes off and reset all internal values to a known initial state.") (key-down [this event] "Handle MIDI note-on events.") (key-up [this event] "Handle MIDI note-off events") (trace! [this flag] "Enable diagnostic tracing of j]key on/off events") (dump [this depth] [this]))