_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 |
|---|---|---|---|---|---|---|---|---|
e1c1e961a2a2b4881bd71e2679005c26068fea08d966e54154a2e537d72dcf5e | huangjs/cl | zlog.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':simple-array)
;;; (:array-slicing nil) (:declare-common nil)
;;; (:float-format double-float))
(in-package :slatec)
(let ((dpi 3.141592653589793) (dhpi 1.5707963267948966))
(declare (type (double-float) dpi dhpi))
(defun zlog (ar ai br bi ierr)
(declare (type (f2cl-lib:integer4) ierr) (type (double-float) bi br ai ar))
(prog ((zm 0.0) (dtheta 0.0))
(declare (type (double-float) dtheta zm))
(setf ierr 0)
(if (= ar 0.0) (go label10))
(if (= ai 0.0) (go label20))
(setf dtheta (f2cl-lib:datan (/ ai ar)))
(if (<= dtheta 0.0) (go label40))
(if (< ar 0.0) (setf dtheta (- dtheta dpi)))
(go label50)
label10
(if (= ai 0.0) (go label60))
(setf bi dhpi)
(setf br (f2cl-lib:flog (abs ai)))
(if (< ai 0.0) (setf bi (- bi)))
(go end_label)
label20
(if (> ar 0.0) (go label30))
(setf br (f2cl-lib:flog (abs ar)))
(setf bi dpi)
(go end_label)
label30
(setf br (f2cl-lib:flog ar))
(setf bi 0.0)
(go end_label)
label40
(if (< ar 0.0) (setf dtheta (+ dtheta dpi)))
label50
(setf zm (coerce (realpart (zabs ar ai)) 'double-float))
(setf br (f2cl-lib:flog zm))
(setf bi dtheta)
(go end_label)
label60
(setf ierr 1)
(go end_label)
end_label
(return (values nil nil br bi ierr)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zlog fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((double-float) (double-float) (double-float)
(double-float) (fortran-to-lisp::integer4))
:return-values '(nil nil fortran-to-lisp::br fortran-to-lisp::bi
fortran-to-lisp::ierr)
:calls '(fortran-to-lisp::zabs))))
| null | https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/src/numerical/slatec/zlog.lisp | lisp | Compiled by f2cl version:
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':simple-array)
(:array-slicing nil) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
(in-package :slatec)
(let ((dpi 3.141592653589793) (dhpi 1.5707963267948966))
(declare (type (double-float) dpi dhpi))
(defun zlog (ar ai br bi ierr)
(declare (type (f2cl-lib:integer4) ierr) (type (double-float) bi br ai ar))
(prog ((zm 0.0) (dtheta 0.0))
(declare (type (double-float) dtheta zm))
(setf ierr 0)
(if (= ar 0.0) (go label10))
(if (= ai 0.0) (go label20))
(setf dtheta (f2cl-lib:datan (/ ai ar)))
(if (<= dtheta 0.0) (go label40))
(if (< ar 0.0) (setf dtheta (- dtheta dpi)))
(go label50)
label10
(if (= ai 0.0) (go label60))
(setf bi dhpi)
(setf br (f2cl-lib:flog (abs ai)))
(if (< ai 0.0) (setf bi (- bi)))
(go end_label)
label20
(if (> ar 0.0) (go label30))
(setf br (f2cl-lib:flog (abs ar)))
(setf bi dpi)
(go end_label)
label30
(setf br (f2cl-lib:flog ar))
(setf bi 0.0)
(go end_label)
label40
(if (< ar 0.0) (setf dtheta (+ dtheta dpi)))
label50
(setf zm (coerce (realpart (zabs ar ai)) 'double-float))
(setf br (f2cl-lib:flog zm))
(setf bi dtheta)
(go end_label)
label60
(setf ierr 1)
(go end_label)
end_label
(return (values nil nil br bi ierr)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zlog fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((double-float) (double-float) (double-float)
(double-float) (fortran-to-lisp::integer4))
:return-values '(nil nil fortran-to-lisp::br fortran-to-lisp::bi
fortran-to-lisp::ierr)
:calls '(fortran-to-lisp::zabs))))
|
59b92678cafa569831d406d7ba9efdcdf98c2c1f75291a9040ca0aed37772a0f | namin/biohacker | condef.lisp | ;;; -*- Mode: Lisp; Syntax: Common-lisp; -*-
;;;; Sample constraints for TCON interpreter.
Last edited 1/29/93 , by KDF
Copyright ( c ) 1988 - 1993 , , Northwestern University ,
and , the Xerox Corporation .
;;; All rights reserved.
;;; See the file legal.txt for a paragraph stating scope of permission
;;; and disclaimer of warranty. The above copyright notice and that
;;; paragraph must be included in any separate copy of this file.
(in-package :COMMON-LISP-USER)
(constraint adder ((a1 cell) (a2 cell) (sum cell))
(formulae (sum (a1 a2) (+ a1 a2))
(a1 (sum a2) (- sum a2))
(a2 (sum a1) (- sum a1))))
(constraint multiplier ((m1 cell) (m2 cell) (product cell))
(formulae (product (m1) (if (nearly-zero? m1) 0.0 :DISMISS))
(product (m2) (if (nearly-zero? m2) 0.0 :DISMISS))
(product (m1 m2) (cond ((or (nearly-zero? m1)
(nearly-zero? m2))
:DISMISS)
(t (* m1 m2))))
(m1 (product m2) (if (nearly-zero? m2)
(if (nearly-zero? product)
:DISMISS
:LOSE)
(/ product m2)))
(m2 (product m1) (if (nearly-zero? m1)
(if (nearly-zero? product)
:DISMISS
:LOSE)
(/ product m1)))))
(constraint sign ((in cell) (out cell))
(formulae (out (in) (if (nearly-zero? in) 0.0
(signum in)))
(in (out) (if (= 0.0 out) 0.0 :DISMISS))))
(constraint magnitude ((in cell) (out cell))
(formulae (out (in) (if (nearly-zero? in) 0.0
(abs in)))
(in (out) (if (= 0.0 out)
0.0 :DISMISS))))
(constraint sign-magnitude ((number cell) (sign cell)
(magnitude cell)
(s sign) (m magnitude)
(prod multiplier))
(== (>> sign) (>> out s))
(== (>> magnitude) (>> out m))
(== (>> number) (>> in s))
(== (>> number) (>> in m))
;Use multiplier constraint
(== (>> number) (>> product prod))
(== (>> sign) (>> m1 prod))
(== (>> magnitude) (>> m2 prod)))
;;;; Temperature conversion (a classic)
(constraint F-to-C ((degF cell) (degC cell)
(sum adder)(m multiplier))
(== (>> degF) (>> sum sum))
(Constant (>> a1 sum) 32)
(== (>> a2 sum) (>> product m))
(== (>> degC) (>> m1 m))
(Constant (>> m2 m) (float (/ 9 5))))
;;;; Primitive boolean constraints.
(constraint inverter ((in cell) (out cell))
(formulae (in (out) (not out))
(out (in) (not in))))
(constraint implication ((antecedent cell) (consequent cell))
(formulae (consequent (antecedent)
(cond (antecedent 'T) (t :DISMISS)))
(antecedent (consequent)
(cond (consequent :DISMISS) (t 'NIL)))))
(constraint or-gate ((in1 cell) (in2 cell) (out cell))
(formulae (out (in1 in2) (or in1 in2))
(out (in1) (cond (in1 t) (t :DISMISS)))
(out (in2) (cond (in2 t) (t :DISMISS)))
(in1 (out in2) (cond ((not in2) out)
(t :DISMISS)))
(in2 (out in1) (cond ((not in1) out)
(t :DISMISS)))))
(constraint and-gate ((in1 cell) (in2 cell) (out cell))
(formulae (out (in1 in2) (and in1 in2))
(out (in1) (cond (in1 :DISMISS)
(t nil)))
(out (in2) (cond (in2 :DISMISS)
(t nil)))
(in1 (out in2) (cond (in2 out)
(T :DISMISS)))
(in2 (out in1) (cond (in1 out)
(t :DISMISS)))))
(constraint relay ((in1 cell) (in2 cell) (out cell)
(control cell))
(formulae (in1 (out control) (cond (control out)
(t :DISMISS)))
(in2 (out control) (cond (control :DISMISS)
(t out)))
(out (in1 control) (cond (control in1)
(t :DISMISS)))
(out (in2 control) (cond (control :DISMISS)
(t in2)))))
| null | https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/BPS/tcon/condef.lisp | lisp | -*- Mode: Lisp; Syntax: Common-lisp; -*-
Sample constraints for TCON interpreter.
All rights reserved.
See the file legal.txt for a paragraph stating scope of permission
and disclaimer of warranty. The above copyright notice and that
paragraph must be included in any separate copy of this file.
Use multiplier constraint
Temperature conversion (a classic)
Primitive boolean constraints. |
Last edited 1/29/93 , by KDF
Copyright ( c ) 1988 - 1993 , , Northwestern University ,
and , the Xerox Corporation .
(in-package :COMMON-LISP-USER)
(constraint adder ((a1 cell) (a2 cell) (sum cell))
(formulae (sum (a1 a2) (+ a1 a2))
(a1 (sum a2) (- sum a2))
(a2 (sum a1) (- sum a1))))
(constraint multiplier ((m1 cell) (m2 cell) (product cell))
(formulae (product (m1) (if (nearly-zero? m1) 0.0 :DISMISS))
(product (m2) (if (nearly-zero? m2) 0.0 :DISMISS))
(product (m1 m2) (cond ((or (nearly-zero? m1)
(nearly-zero? m2))
:DISMISS)
(t (* m1 m2))))
(m1 (product m2) (if (nearly-zero? m2)
(if (nearly-zero? product)
:DISMISS
:LOSE)
(/ product m2)))
(m2 (product m1) (if (nearly-zero? m1)
(if (nearly-zero? product)
:DISMISS
:LOSE)
(/ product m1)))))
(constraint sign ((in cell) (out cell))
(formulae (out (in) (if (nearly-zero? in) 0.0
(signum in)))
(in (out) (if (= 0.0 out) 0.0 :DISMISS))))
(constraint magnitude ((in cell) (out cell))
(formulae (out (in) (if (nearly-zero? in) 0.0
(abs in)))
(in (out) (if (= 0.0 out)
0.0 :DISMISS))))
(constraint sign-magnitude ((number cell) (sign cell)
(magnitude cell)
(s sign) (m magnitude)
(prod multiplier))
(== (>> sign) (>> out s))
(== (>> magnitude) (>> out m))
(== (>> number) (>> in s))
(== (>> number) (>> in m))
(== (>> number) (>> product prod))
(== (>> sign) (>> m1 prod))
(== (>> magnitude) (>> m2 prod)))
(constraint F-to-C ((degF cell) (degC cell)
(sum adder)(m multiplier))
(== (>> degF) (>> sum sum))
(Constant (>> a1 sum) 32)
(== (>> a2 sum) (>> product m))
(== (>> degC) (>> m1 m))
(Constant (>> m2 m) (float (/ 9 5))))
(constraint inverter ((in cell) (out cell))
(formulae (in (out) (not out))
(out (in) (not in))))
(constraint implication ((antecedent cell) (consequent cell))
(formulae (consequent (antecedent)
(cond (antecedent 'T) (t :DISMISS)))
(antecedent (consequent)
(cond (consequent :DISMISS) (t 'NIL)))))
(constraint or-gate ((in1 cell) (in2 cell) (out cell))
(formulae (out (in1 in2) (or in1 in2))
(out (in1) (cond (in1 t) (t :DISMISS)))
(out (in2) (cond (in2 t) (t :DISMISS)))
(in1 (out in2) (cond ((not in2) out)
(t :DISMISS)))
(in2 (out in1) (cond ((not in1) out)
(t :DISMISS)))))
(constraint and-gate ((in1 cell) (in2 cell) (out cell))
(formulae (out (in1 in2) (and in1 in2))
(out (in1) (cond (in1 :DISMISS)
(t nil)))
(out (in2) (cond (in2 :DISMISS)
(t nil)))
(in1 (out in2) (cond (in2 out)
(T :DISMISS)))
(in2 (out in1) (cond (in1 out)
(t :DISMISS)))))
(constraint relay ((in1 cell) (in2 cell) (out cell)
(control cell))
(formulae (in1 (out control) (cond (control out)
(t :DISMISS)))
(in2 (out control) (cond (control :DISMISS)
(t out)))
(out (in1 control) (cond (control in1)
(t :DISMISS)))
(out (in2 control) (cond (control :DISMISS)
(t in2)))))
|
20e579d86e48733f198a00ac3f43f17aa68929bb0e18396e0b0abee3f3154486 | ohua-dev/ohua-core | Passes.hs | -- |
-- Module : $Header$
-- Description : Passes over algorithm language terms to ensure certain invariants
Copyright : ( c ) 2017 . All Rights Reserved .
-- License : EPL-1.0
Maintainer : ,
-- Stability : experimental
-- Portability : portable
--
-- This module implements a set of passes over ALang which perform
-- various tasks. The most important function is `normalize`, which
-- transforms an arbitrary ALang expression either into the normal
-- form of a sequence of let bindings which are invocations of
-- stateful functions on local or environment variables finalised by a
-- local binding as a return value.
This source code is licensed under the terms described in the associated LICENSE.TXT file
# LANGUAGE CPP #
{-# LANGUAGE ExplicitForAll #-}
# LANGUAGE ScopedTypeVariables #
module Ohua.ALang.Passes where
import Ohua.Prelude
import Control.Comonad (extract)
import Control.Monad.RWS.Lazy (evalRWST)
import Control.Monad.Writer (listen, runWriter, tell)
import Data.Functor.Foldable
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import Ohua.ALang.Lang
import Ohua.ALang.PPrint
import Ohua.ALang.Passes.If
import Ohua.ALang.Passes.Seq
import Ohua.ALang.Passes.Smap
import Ohua.ALang.Passes.Unit
import qualified Ohua.ALang.Refs as Refs
import Ohua.Stage
runCorePasses :: MonadOhua m => Expression -> m Expression
runCorePasses expr = do
let exprE = mkUnitFunctionsExplicit expr
stage "unit-transformation" exprE
smapE <- smapRewrite exprE
-- traceM $ "after 'smap' pass:\n" <> (show $ prettyExpr smapE)
stage "smap-transformation" smapE
ifE <- ifRewrite smapE
traceM $ " after ' if ' pass:\n " < > ( show $ prettyExpr ifE )
stage "conditionals-transformation" ifE
seqE <- seqRewrite ifE
traceM $ " after ' seq ' pass:\n " < > ( show $ prettyExpr seqE )
stage "seq-transformation" seqE
return seqE
-- | Inline all references to lambdas.
Aka ` let f = ( \a - > E ) in f N ` - > ` ( \a - > E ) N `
inlineLambdaRefs :: MonadOhua m => Expression -> m Expression
inlineLambdaRefs = flip runReaderT mempty . para go
where
go (LetF b (Lambda _ _, l) (_, body)) =
l >>= \l' -> local (HM.insert b l') body
go (VarF bnd) = asks (fromMaybe (Var bnd) . HM.lookup bnd)
go e = embed <$> traverse snd e
-- | Reduce lambdas by simulating application
Aka ` ( \a - > E ) N ` - > ` let a = N in E `
-- Assumes lambda refs have been inlined
inlineLambda :: Expression -> Expression
inlineLambda =
cata $ \case
e@(ApplyF func argument) ->
case func of
Lambda assignment body -> Let assignment argument body
Apply _ _ -> reduceLetCWith f func
where f (Lambda assignment body) =
Let assignment argument body
f v0 = Apply v0 argument
_ -> embed e
e -> embed e
-- recursively performs the substitution
--
-- let x = (let y = M in A) in E[x] -> let y = M in let x = A in E[x]
reduceLetA :: Expression -> Expression
reduceLetA =
\case
Let assign (Let assign2 val expr3) expr ->
Let assign2 val $ reduceLetA $ Let assign expr3 expr
e -> e
reduceLetCWith :: (Expression -> Expression) -> Expression -> Expression
reduceLetCWith f =
\case
Apply (Let assign val expr) argument ->
Let assign val $ reduceLetCWith f $ Apply expr argument
e -> f e
reduceLetC :: Expression -> Expression
reduceLetC = reduceLetCWith id
reduceAppArgument :: Expression -> Expression
reduceAppArgument =
\case
Apply function (Let assign val expr) ->
Let assign val $ reduceApplication $ Apply function expr
e -> e
-- recursively performs the substitution
--
-- (let x = M in A) N -> let x = M in A N
--
-- and then
--
-- A (let x = M in N) -> let x = M in A N
reduceApplication :: Expression -> Expression
reduceApplication = reduceLetCWith reduceAppArgument
-- | Lift all nested lets to the top level
-- Aka `let x = let y = E in N in M` -> `let y = E in let x = N in M`
-- and `(let x = E in F) a` -> `let x = E in F a`
letLift :: Expression -> Expression
letLift =
cata $ \e ->
let f =
case e of
LetF _ _ _ -> reduceLetA
ApplyF _ _ -> reduceApplication
_ -> id
in f $ embed e
-- -- | Inline all direct reassignments.
-- -- Aka `let x = E in let y = x in y` -> `let x = E in x`
inlineReassignments :: Expression -> Expression
inlineReassignments = flip runReader HM.empty . cata go
where
go (LetF bnd val body) =
val >>= \v ->
let requestReplace = local (HM.insert bnd v) body
in case v of
Var {} -> requestReplace
Lit {} -> requestReplace
_ -> Let bnd v <$> body
go (VarF val) = asks (fromMaybe (Var val) . HM.lookup val)
go e = embed <$> sequence e
-- | Transforms the final expression into a let expression with the result variable as body.
-- Aka `let x = E in some/sf a` -> `let x = E in let y = some/sf a in y`
--
-- EDIT: Now also does the same for any residual lambdas
ensureFinalLet :: MonadOhua m => Expression -> m Expression
ensureFinalLet = ensureFinalLetInLambdas >=> ensureFinalLet'
-- | Transforms the final expression into a let expression with the result variable as body.
ensureFinalLet' :: MonadOhua m => Expression -> m Expression
ensureFinalLet' =
para $ \case
LetF b (oldV, _) (_, recB) -> Let b oldV <$> recB -- Recurse only into let body, not the bound value
any
| isVarOrLambdaF any -> embed <$> traverse snd any -- Don't rebind a lambda or var. Continue or terminate
Rebind anything else
newBnd <- generateBinding
pure $ Let newBnd (embed $ fmap fst any) (Var newBnd)
where
isVarOrLambdaF =
\case
VarF _ -> True
LambdaF {} -> True
_ -> False
| Obsolete , will be removed soon . Replaced by ` ensureFinalLet ' `
ensureFinalLet'' :: MonadOhua m => Expression -> m Expression
ensureFinalLet'' (Let a e b) = Let a e <$> ensureFinalLet' b
ensureFinalLet'' v@(Var _) = return v
I 'm not 100 % sure about this case , perhaps this ought to be in
-- `ensureFinalLetInLambdas` instead
ensureFinalLet'' (Lambda b body) = Lambda b <$> ensureFinalLet' body
ensureFinalLet'' a = do
newBnd <- generateBinding
return $ Let newBnd a (Var newBnd)
ensureFinalLetInLambdas :: MonadOhua m => Expression -> m Expression
ensureFinalLetInLambdas =
cata $ \case
LambdaF bnd body -> Lambda bnd <$> (ensureFinalLet' =<< body)
a -> embed <$> sequence a
ensureAtLeastOneCall :: (Monad m, MonadGenBnd m) => Expression -> m Expression
ensureAtLeastOneCall e@(Var _) = do
newBnd <- generateBinding
pure $ Let newBnd (PureFunction Refs.id Nothing `Apply` e) $ Var newBnd
ensureAtLeastOneCall e = cata f e
where
f (LambdaF bnd body) =
body >>= \case
v@(Var _) -> do
newBnd <- generateBinding
pure $
Lambda bnd $
Let newBnd (PureFunction Refs.id Nothing `Apply` v) $
Var newBnd
eInner -> pure $ Lambda bnd eInner
f eInner = embed <$> sequence eInner
-- | Removes bindings that are never used.
-- This is actually not safe becuase sfn invocations may have side effects
-- and therefore cannot be removed.
-- Assumes ssa for simplicity
removeUnusedBindings :: Expression -> Expression
removeUnusedBindings = fst . runWriter . cata go
where
go (VarF val) = tell (HS.singleton val) >> return (Var val)
go (LetF b val body) = do
(inner, used) <- listen body
if not $ b `HS.member` used
then return inner
else do
val' <- val
pure $ Let b val' inner
go e = embed <$> sequence e
newtype MonoidCombineHashMap k v =
MonoidCombineHashMap (HashMap k v)
deriving (Show, Eq, Ord)
instance (Semigroup v, Eq k, Hashable k) =>
Semigroup (MonoidCombineHashMap k v) where
MonoidCombineHashMap m1 <> MonoidCombineHashMap m2 =
MonoidCombineHashMap $ HM.unionWith (<>) m1 m2
instance (Semigroup v, Eq k, Hashable k) =>
Monoid (MonoidCombineHashMap k v) where
mempty = MonoidCombineHashMap mempty
data WasTouched
= No
| Yes
deriving (Show, Eq, Ord)
instance Semigroup WasTouched where
(<>) = max
instance Monoid WasTouched where
mempty = No
type TouchMap = MonoidCombineHashMap Binding (WasTouched, WasTouched)
wasTouchedAsFunction :: Binding -> TouchMap
wasTouchedAsFunction bnd = MonoidCombineHashMap $ HM.singleton bnd (Yes, No)
wasTouchedAsValue :: Binding -> TouchMap
wasTouchedAsValue bnd = MonoidCombineHashMap $ HM.singleton bnd (No, Yes)
lookupTouchState :: Binding -> TouchMap -> (WasTouched, WasTouched)
lookupTouchState bnd (MonoidCombineHashMap m) =
fromMaybe mempty $ HM.lookup bnd m
-- | Reduce curried expressions. aka `let f = some/sf a in f b`
becomes ` some / sf a b ` . It both inlines the curried function and
-- removes the binding site. Recursively calls it self and therefore
handles redefinitions as well . It only substitutes vars in the
-- function positions of apply's hence it may produce an expression
-- with undefined local bindings. It is recommended therefore to
-- check this with 'noUndefinedBindings'. If an undefined binding is
-- left behind which indicates the source expression was not
-- fulfilling all its invariants.
removeCurrying ::
forall m. MonadError Error m
=> Expression
-> m Expression
removeCurrying e = fst <$> evalRWST (para inlinePartials e) mempty ()
where
inlinePartials (LetF bnd (_, val) (_, body)) = do
val' <- val
(body', touched) <- listen $ local (HM.insert bnd val') body
case lookupTouchState bnd touched of
(Yes, Yes) ->
throwErrorDebugS $
"Binding was used as function and value " <> show bnd
(Yes, _) -> pure body'
_ -> pure $ Let bnd val' body'
inlinePartials (ApplyF (Var bnd, _) (_, arg)) = do
tell $ wasTouchedAsFunction bnd
val <- asks (HM.lookup bnd)
Apply <$>
(maybe
(failWith $ "No suitable value found for binding " <> show bnd)
pure
val) <*>
arg
inlinePartials (VarF bnd) = tell (wasTouchedAsValue bnd) >> pure (Var bnd)
inlinePartials innerExpr = embed <$> traverse snd innerExpr
-- | Ensures the expression is a sequence of let statements terminated
-- with a local variable.
hasFinalLet :: MonadOhua m => Expression -> m ()
hasFinalLet =
cata $ \case
LetF _ _ body -> body
VarF {} -> return ()
_ -> failWith "Final value is not a var"
-- | Ensures all of the optionally provided stateful function ids are unique.
noDuplicateIds :: MonadError Error m => Expression -> m ()
noDuplicateIds = flip evalStateT mempty . cata go
where
go (PureFunctionF _ (Just funid)) = do
isMember <- gets (HS.member funid)
when isMember $ failWith $ "Duplicate id " <> show funid
modify (HS.insert funid)
go e = sequence_ e
-- | Checks that no apply to a local variable is performed. This is a
-- simple check and it will pass on complex expressions even if they
-- would reduce to an apply to a local variable.
applyToPureFunction :: MonadOhua m => Expression -> m ()
applyToPureFunction =
para $ \case
ApplyF (Var bnd, _) _ ->
failWith $ "Illegal Apply to local var " <> show bnd
e -> sequence_ $ fmap snd e
-- | Checks that all local bindings are defined before use.
Scoped . Aka bindings are only visible in their respective scopes .
-- Hence the expression does not need to be in SSA form.
noUndefinedBindings :: MonadOhua m => Expression -> m ()
noUndefinedBindings = flip runReaderT mempty . cata go
where
go (LetF b val body) = val >> registerBinding b body
go (VarF bnd) = do
isDefined <- asks (HS.member bnd)
unless isDefined $ failWith $ "Not in scope " <> show bnd
go (LambdaF b body) = registerBinding b body
go e = sequence_ e
registerBinding = local . HS.insert
checkProgramValidity :: MonadOhua m => Expression -> m ()
checkProgramValidity e = do
hasFinalLet e
noDuplicateIds e
applyToPureFunction e
noUndefinedBindings e
| Lifts something like @if ( f x ) a b@ to @let x0 = f x in if
liftApplyToApply :: MonadOhua m => Expression -> m Expression
liftApplyToApply =
lrPrewalkExprM $ \case
Apply fn arg@(Apply _ _) -> do
bnd <- generateBinding
return $ Let bnd arg $ Apply fn (Var bnd)
a -> return a
normalizeBind : : ( MonadError Error m , ) = > Expression - > m Expression
-- normalizeBind =
-- rewriteM $ \case
BindState e2 e1@(PureFunction _ _ ) - >
-- case e2 of
-- Var _ -> pure Nothing
-- Lit _ -> pure Nothing
-- _ ->
-- generateBinding >>= \b ->
pure $ Just $ Let b e2 ( BindState ( Var b ) e1 )
BindState _ _ - > throwError " State bind target must be a pure function reference "
-- _ -> pure Nothing
dumpNormalizeDebug = False
putStrLnND :: (Print str, MonadIO m) => str -> m ()
putStrLnND =
if dumpNormalizeDebug
then putStrLn
else const $ return ()
printND :: (Show a, MonadIO m) => a -> m ()
printND =
if dumpNormalizeDebug
then print
else const $ return ()
-- The canonical composition of the above transformations to create a
-- program with the invariants we expect.
normalize :: MonadOhua m => Expression -> m Expression
normalize e =
reduceLambdas (letLift e) >>=
(\a ->
putStrLnND ("Reduced lamdas" :: Text) >> printND (pretty a) >> return a) >>=
return . inlineReassignments >>=
removeCurrying >>=
(\a ->
putStrLnND ("Removed Currying" :: Text) >> printND (pretty a) >>
return a) >>=
liftApplyToApply >>=
(\a -> putStrLnND ("App to App" :: Text) >> printND (pretty a) >> return a) .
letLift >>=
ensureFinalLet . inlineReassignments >>=
ensureAtLeastOneCall
-- we repeat this step until a fix point is reached.
-- this is necessary as lambdas may be input to lambdas,
-- which means after inlining them we may be able again to
-- inline a ref and then inline the lambda.
I doubt this will ever do more than two or three iterations ,
-- but to make sure it accepts every valid program this is necessary.
where
reduceLambdas expr = do
res <- letLift . inlineLambda <$> inlineLambdaRefs expr
if res == expr
then return res
else reduceLambdas res
letLift ( Let ( Let ) expr4 ) = letLift $ Let $ Let expr4
-- letLift (Let assign v@(Var _) expr) = Let assign v $ letLift expr
letLift ( Let assign expr ) =
-- case letLift val of
-- v'@(Let _ _ _) -> letLift $ Let assign v' expr
-- _ -> Let assign v' $ letLift expr
-- letLift e@(Var _) = e
-- letLift (Apply v@(Var _) argument) = Apply v (letLift argument)
-- letLift (Apply (Let assign expr function) argument) = letLift $ Let assign expr $ Apply function argument
-- letLift (Apply function argument) =
-- case letLift argument of
| null | https://raw.githubusercontent.com/ohua-dev/ohua-core/978fa3369922f86cc3fc474d5f2c554cc87fd60a/core/src/Ohua/ALang/Passes.hs | haskell | |
Module : $Header$
Description : Passes over algorithm language terms to ensure certain invariants
License : EPL-1.0
Stability : experimental
Portability : portable
This module implements a set of passes over ALang which perform
various tasks. The most important function is `normalize`, which
transforms an arbitrary ALang expression either into the normal
form of a sequence of let bindings which are invocations of
stateful functions on local or environment variables finalised by a
local binding as a return value.
# LANGUAGE ExplicitForAll #
traceM $ "after 'smap' pass:\n" <> (show $ prettyExpr smapE)
| Inline all references to lambdas.
| Reduce lambdas by simulating application
Assumes lambda refs have been inlined
recursively performs the substitution
let x = (let y = M in A) in E[x] -> let y = M in let x = A in E[x]
recursively performs the substitution
(let x = M in A) N -> let x = M in A N
and then
A (let x = M in N) -> let x = M in A N
| Lift all nested lets to the top level
Aka `let x = let y = E in N in M` -> `let y = E in let x = N in M`
and `(let x = E in F) a` -> `let x = E in F a`
-- | Inline all direct reassignments.
-- Aka `let x = E in let y = x in y` -> `let x = E in x`
| Transforms the final expression into a let expression with the result variable as body.
Aka `let x = E in some/sf a` -> `let x = E in let y = some/sf a in y`
EDIT: Now also does the same for any residual lambdas
| Transforms the final expression into a let expression with the result variable as body.
Recurse only into let body, not the bound value
Don't rebind a lambda or var. Continue or terminate
`ensureFinalLetInLambdas` instead
| Removes bindings that are never used.
This is actually not safe becuase sfn invocations may have side effects
and therefore cannot be removed.
Assumes ssa for simplicity
| Reduce curried expressions. aka `let f = some/sf a in f b`
removes the binding site. Recursively calls it self and therefore
function positions of apply's hence it may produce an expression
with undefined local bindings. It is recommended therefore to
check this with 'noUndefinedBindings'. If an undefined binding is
left behind which indicates the source expression was not
fulfilling all its invariants.
| Ensures the expression is a sequence of let statements terminated
with a local variable.
| Ensures all of the optionally provided stateful function ids are unique.
| Checks that no apply to a local variable is performed. This is a
simple check and it will pass on complex expressions even if they
would reduce to an apply to a local variable.
| Checks that all local bindings are defined before use.
Hence the expression does not need to be in SSA form.
normalizeBind =
rewriteM $ \case
case e2 of
Var _ -> pure Nothing
Lit _ -> pure Nothing
_ ->
generateBinding >>= \b ->
_ -> pure Nothing
The canonical composition of the above transformations to create a
program with the invariants we expect.
we repeat this step until a fix point is reached.
this is necessary as lambdas may be input to lambdas,
which means after inlining them we may be able again to
inline a ref and then inline the lambda.
but to make sure it accepts every valid program this is necessary.
letLift (Let assign v@(Var _) expr) = Let assign v $ letLift expr
case letLift val of
v'@(Let _ _ _) -> letLift $ Let assign v' expr
_ -> Let assign v' $ letLift expr
letLift e@(Var _) = e
letLift (Apply v@(Var _) argument) = Apply v (letLift argument)
letLift (Apply (Let assign expr function) argument) = letLift $ Let assign expr $ Apply function argument
letLift (Apply function argument) =
case letLift argument of | Copyright : ( c ) 2017 . All Rights Reserved .
Maintainer : ,
This source code is licensed under the terms described in the associated LICENSE.TXT file
# LANGUAGE CPP #
# LANGUAGE ScopedTypeVariables #
module Ohua.ALang.Passes where
import Ohua.Prelude
import Control.Comonad (extract)
import Control.Monad.RWS.Lazy (evalRWST)
import Control.Monad.Writer (listen, runWriter, tell)
import Data.Functor.Foldable
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import Ohua.ALang.Lang
import Ohua.ALang.PPrint
import Ohua.ALang.Passes.If
import Ohua.ALang.Passes.Seq
import Ohua.ALang.Passes.Smap
import Ohua.ALang.Passes.Unit
import qualified Ohua.ALang.Refs as Refs
import Ohua.Stage
runCorePasses :: MonadOhua m => Expression -> m Expression
runCorePasses expr = do
let exprE = mkUnitFunctionsExplicit expr
stage "unit-transformation" exprE
smapE <- smapRewrite exprE
stage "smap-transformation" smapE
ifE <- ifRewrite smapE
traceM $ " after ' if ' pass:\n " < > ( show $ prettyExpr ifE )
stage "conditionals-transformation" ifE
seqE <- seqRewrite ifE
traceM $ " after ' seq ' pass:\n " < > ( show $ prettyExpr seqE )
stage "seq-transformation" seqE
return seqE
Aka ` let f = ( \a - > E ) in f N ` - > ` ( \a - > E ) N `
inlineLambdaRefs :: MonadOhua m => Expression -> m Expression
inlineLambdaRefs = flip runReaderT mempty . para go
where
go (LetF b (Lambda _ _, l) (_, body)) =
l >>= \l' -> local (HM.insert b l') body
go (VarF bnd) = asks (fromMaybe (Var bnd) . HM.lookup bnd)
go e = embed <$> traverse snd e
Aka ` ( \a - > E ) N ` - > ` let a = N in E `
inlineLambda :: Expression -> Expression
inlineLambda =
cata $ \case
e@(ApplyF func argument) ->
case func of
Lambda assignment body -> Let assignment argument body
Apply _ _ -> reduceLetCWith f func
where f (Lambda assignment body) =
Let assignment argument body
f v0 = Apply v0 argument
_ -> embed e
e -> embed e
reduceLetA :: Expression -> Expression
reduceLetA =
\case
Let assign (Let assign2 val expr3) expr ->
Let assign2 val $ reduceLetA $ Let assign expr3 expr
e -> e
reduceLetCWith :: (Expression -> Expression) -> Expression -> Expression
reduceLetCWith f =
\case
Apply (Let assign val expr) argument ->
Let assign val $ reduceLetCWith f $ Apply expr argument
e -> f e
reduceLetC :: Expression -> Expression
reduceLetC = reduceLetCWith id
reduceAppArgument :: Expression -> Expression
reduceAppArgument =
\case
Apply function (Let assign val expr) ->
Let assign val $ reduceApplication $ Apply function expr
e -> e
reduceApplication :: Expression -> Expression
reduceApplication = reduceLetCWith reduceAppArgument
letLift :: Expression -> Expression
letLift =
cata $ \e ->
let f =
case e of
LetF _ _ _ -> reduceLetA
ApplyF _ _ -> reduceApplication
_ -> id
in f $ embed e
inlineReassignments :: Expression -> Expression
inlineReassignments = flip runReader HM.empty . cata go
where
go (LetF bnd val body) =
val >>= \v ->
let requestReplace = local (HM.insert bnd v) body
in case v of
Var {} -> requestReplace
Lit {} -> requestReplace
_ -> Let bnd v <$> body
go (VarF val) = asks (fromMaybe (Var val) . HM.lookup val)
go e = embed <$> sequence e
ensureFinalLet :: MonadOhua m => Expression -> m Expression
ensureFinalLet = ensureFinalLetInLambdas >=> ensureFinalLet'
ensureFinalLet' :: MonadOhua m => Expression -> m Expression
ensureFinalLet' =
para $ \case
any
Rebind anything else
newBnd <- generateBinding
pure $ Let newBnd (embed $ fmap fst any) (Var newBnd)
where
isVarOrLambdaF =
\case
VarF _ -> True
LambdaF {} -> True
_ -> False
| Obsolete , will be removed soon . Replaced by ` ensureFinalLet ' `
ensureFinalLet'' :: MonadOhua m => Expression -> m Expression
ensureFinalLet'' (Let a e b) = Let a e <$> ensureFinalLet' b
ensureFinalLet'' v@(Var _) = return v
I 'm not 100 % sure about this case , perhaps this ought to be in
ensureFinalLet'' (Lambda b body) = Lambda b <$> ensureFinalLet' body
ensureFinalLet'' a = do
newBnd <- generateBinding
return $ Let newBnd a (Var newBnd)
ensureFinalLetInLambdas :: MonadOhua m => Expression -> m Expression
ensureFinalLetInLambdas =
cata $ \case
LambdaF bnd body -> Lambda bnd <$> (ensureFinalLet' =<< body)
a -> embed <$> sequence a
ensureAtLeastOneCall :: (Monad m, MonadGenBnd m) => Expression -> m Expression
ensureAtLeastOneCall e@(Var _) = do
newBnd <- generateBinding
pure $ Let newBnd (PureFunction Refs.id Nothing `Apply` e) $ Var newBnd
ensureAtLeastOneCall e = cata f e
where
f (LambdaF bnd body) =
body >>= \case
v@(Var _) -> do
newBnd <- generateBinding
pure $
Lambda bnd $
Let newBnd (PureFunction Refs.id Nothing `Apply` v) $
Var newBnd
eInner -> pure $ Lambda bnd eInner
f eInner = embed <$> sequence eInner
removeUnusedBindings :: Expression -> Expression
removeUnusedBindings = fst . runWriter . cata go
where
go (VarF val) = tell (HS.singleton val) >> return (Var val)
go (LetF b val body) = do
(inner, used) <- listen body
if not $ b `HS.member` used
then return inner
else do
val' <- val
pure $ Let b val' inner
go e = embed <$> sequence e
newtype MonoidCombineHashMap k v =
MonoidCombineHashMap (HashMap k v)
deriving (Show, Eq, Ord)
instance (Semigroup v, Eq k, Hashable k) =>
Semigroup (MonoidCombineHashMap k v) where
MonoidCombineHashMap m1 <> MonoidCombineHashMap m2 =
MonoidCombineHashMap $ HM.unionWith (<>) m1 m2
instance (Semigroup v, Eq k, Hashable k) =>
Monoid (MonoidCombineHashMap k v) where
mempty = MonoidCombineHashMap mempty
data WasTouched
= No
| Yes
deriving (Show, Eq, Ord)
instance Semigroup WasTouched where
(<>) = max
instance Monoid WasTouched where
mempty = No
type TouchMap = MonoidCombineHashMap Binding (WasTouched, WasTouched)
wasTouchedAsFunction :: Binding -> TouchMap
wasTouchedAsFunction bnd = MonoidCombineHashMap $ HM.singleton bnd (Yes, No)
wasTouchedAsValue :: Binding -> TouchMap
wasTouchedAsValue bnd = MonoidCombineHashMap $ HM.singleton bnd (No, Yes)
lookupTouchState :: Binding -> TouchMap -> (WasTouched, WasTouched)
lookupTouchState bnd (MonoidCombineHashMap m) =
fromMaybe mempty $ HM.lookup bnd m
becomes ` some / sf a b ` . It both inlines the curried function and
handles redefinitions as well . It only substitutes vars in the
removeCurrying ::
forall m. MonadError Error m
=> Expression
-> m Expression
removeCurrying e = fst <$> evalRWST (para inlinePartials e) mempty ()
where
inlinePartials (LetF bnd (_, val) (_, body)) = do
val' <- val
(body', touched) <- listen $ local (HM.insert bnd val') body
case lookupTouchState bnd touched of
(Yes, Yes) ->
throwErrorDebugS $
"Binding was used as function and value " <> show bnd
(Yes, _) -> pure body'
_ -> pure $ Let bnd val' body'
inlinePartials (ApplyF (Var bnd, _) (_, arg)) = do
tell $ wasTouchedAsFunction bnd
val <- asks (HM.lookup bnd)
Apply <$>
(maybe
(failWith $ "No suitable value found for binding " <> show bnd)
pure
val) <*>
arg
inlinePartials (VarF bnd) = tell (wasTouchedAsValue bnd) >> pure (Var bnd)
inlinePartials innerExpr = embed <$> traverse snd innerExpr
hasFinalLet :: MonadOhua m => Expression -> m ()
hasFinalLet =
cata $ \case
LetF _ _ body -> body
VarF {} -> return ()
_ -> failWith "Final value is not a var"
noDuplicateIds :: MonadError Error m => Expression -> m ()
noDuplicateIds = flip evalStateT mempty . cata go
where
go (PureFunctionF _ (Just funid)) = do
isMember <- gets (HS.member funid)
when isMember $ failWith $ "Duplicate id " <> show funid
modify (HS.insert funid)
go e = sequence_ e
applyToPureFunction :: MonadOhua m => Expression -> m ()
applyToPureFunction =
para $ \case
ApplyF (Var bnd, _) _ ->
failWith $ "Illegal Apply to local var " <> show bnd
e -> sequence_ $ fmap snd e
Scoped . Aka bindings are only visible in their respective scopes .
noUndefinedBindings :: MonadOhua m => Expression -> m ()
noUndefinedBindings = flip runReaderT mempty . cata go
where
go (LetF b val body) = val >> registerBinding b body
go (VarF bnd) = do
isDefined <- asks (HS.member bnd)
unless isDefined $ failWith $ "Not in scope " <> show bnd
go (LambdaF b body) = registerBinding b body
go e = sequence_ e
registerBinding = local . HS.insert
checkProgramValidity :: MonadOhua m => Expression -> m ()
checkProgramValidity e = do
hasFinalLet e
noDuplicateIds e
applyToPureFunction e
noUndefinedBindings e
| Lifts something like @if ( f x ) a b@ to @let x0 = f x in if
liftApplyToApply :: MonadOhua m => Expression -> m Expression
liftApplyToApply =
lrPrewalkExprM $ \case
Apply fn arg@(Apply _ _) -> do
bnd <- generateBinding
return $ Let bnd arg $ Apply fn (Var bnd)
a -> return a
normalizeBind : : ( MonadError Error m , ) = > Expression - > m Expression
BindState e2 e1@(PureFunction _ _ ) - >
pure $ Just $ Let b e2 ( BindState ( Var b ) e1 )
BindState _ _ - > throwError " State bind target must be a pure function reference "
dumpNormalizeDebug = False
putStrLnND :: (Print str, MonadIO m) => str -> m ()
putStrLnND =
if dumpNormalizeDebug
then putStrLn
else const $ return ()
printND :: (Show a, MonadIO m) => a -> m ()
printND =
if dumpNormalizeDebug
then print
else const $ return ()
normalize :: MonadOhua m => Expression -> m Expression
normalize e =
reduceLambdas (letLift e) >>=
(\a ->
putStrLnND ("Reduced lamdas" :: Text) >> printND (pretty a) >> return a) >>=
return . inlineReassignments >>=
removeCurrying >>=
(\a ->
putStrLnND ("Removed Currying" :: Text) >> printND (pretty a) >>
return a) >>=
liftApplyToApply >>=
(\a -> putStrLnND ("App to App" :: Text) >> printND (pretty a) >> return a) .
letLift >>=
ensureFinalLet . inlineReassignments >>=
ensureAtLeastOneCall
I doubt this will ever do more than two or three iterations ,
where
reduceLambdas expr = do
res <- letLift . inlineLambda <$> inlineLambdaRefs expr
if res == expr
then return res
else reduceLambdas res
letLift ( Let ( Let ) expr4 ) = letLift $ Let $ Let expr4
letLift ( Let assign expr ) =
|
ad49569e7d17aff8b3dc6a5f34bfa6e3b1baa1f9178187c084e48655913920f7 | tezos/tezos-mirror | interpreter_model.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
let ns = Namespace.make Registration_helpers.ns "interpreter"
let fv s = Free_variable.of_namespace (ns s)
(* ------------------------------------------------------------------------- *)
let trace_error expected given =
let open Interpreter_workload in
let exp = string_of_instr_or_cont expected in
let given = string_of_instr_or_cont given in
let msg =
Format.asprintf
"Interpreter_model: trace error, expected %s, given %s"
exp
given
in
Stdlib.failwith msg
let arity_error instr expected given =
let open Interpreter_workload in
let s = string_of_instr_or_cont instr in
let msg =
Format.asprintf
"Interpreter_model: arity error (%s), expected %d, given %a"
s
expected
Interpreter_workload.pp_args
given
in
Stdlib.failwith msg
(* ------------------------------------------------------------------------- *)
let model_0 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = []} -> if name = instr then () else trace_error instr name
| {args; _} -> arity_error instr 0 args)
~model
let model_1 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = [{name = _; arg}]} ->
if name = instr then (arg, ()) else trace_error instr name
| {args; _} -> arity_error instr 1 args)
~model
let model_2 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = [{name = _; arg = x}; {name = _; arg = y}]} ->
if name = instr then (x, (y, ())) else trace_error instr name
| {args; _} -> arity_error instr 2 args)
~model
let model_3 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {
name;
args = [{name = _; arg = x}; {name = _; arg = y}; {name = _; arg = z}];
} ->
if name = instr then (x, (y, (z, ()))) else trace_error instr name
| {args; _} -> arity_error instr 3 args)
~model
let model_4 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {
name;
args =
[
{name = _; arg = w};
{name = _; arg = x};
{name = _; arg = y};
{name = _; arg = z};
];
} ->
if name = instr then (w, (x, (y, (z, ()))))
else trace_error instr name
| {args; _} -> arity_error instr 4 args)
~model
let sf = Format.asprintf
let division_cost name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
let name = ns name
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
Note that [ q ] is guaranteed to be non - negative because we use
saturated subtraction . When [ size1 < size2 ] , the model evaluates to
[ const ] as expected .
saturated subtraction. When [size1 < size2], the model evaluates to
[const] as expected. *)
let_ ~name:"q" (sat_sub size1 size2) @@ fun q ->
(free ~name:coeff * q * size2) + free ~name:const
end
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let addlogadd name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
let name = ns name
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
let_ ~name:"a" (size1 + size2) @@ fun a ->
(free ~name:coeff * (a * log2 (int 1 + a))) + free ~name:const
end
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
(* Some instructions are oveloaded (eg COMPARE). In order to generate distinct
models at different types, we must specialize these models. The [specialization]
parameter acts as a mangling scheme to produce distinct models. *)
let name_of_instr_or_cont ?specialization instr_or_cont =
let spec = Option.fold ~none:"" ~some:(fun s -> "_" ^ s) specialization in
Interpreter_workload.string_of_instr_or_cont instr_or_cont ^ spec
module Models = struct
let const1_model name =
(* For constant-time instructions *)
Model.unknown_const1 ~name:(ns name) ~const:(fv (sf "%s_const" name))
let affine_model name =
(* For instructions with cost function
[\lambda size. const + coeff * size] *)
Model.affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let break_model name break =
Model.breakdown
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~break
let break_model_2 name break1 break2 =
Model.breakdown2
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~coeff3:(fv (sf "%s_coeff3" name))
~break1
~break2
let break_model_2_const name break1 break2 =
Model.breakdown2_const
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~coeff3:(fv (sf "%s_coeff3" name))
~const:(fv (sf "%s_const" name))
~break1
~break2
let nlogm_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * size1 log2(size2 ) ]
[\lambda size1. \lambda size2. const + coeff * size1 log2(size2)] *)
Model.nlogm
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let concat_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_total_bytes" name))
~coeff2:(fv (sf "%s_list_length" name))
let concat_pair_model name =
Model.linear_sum
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let linear_max_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * max(size1,size2 ) ]
[\lambda size1. \lambda size2. const + coeff * max(size1,size2)] *)
Model.linear_max
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let linear_min_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * min(size1,size2 ) ]
[\lambda size1. \lambda size2. const + coeff * min(size1,size2)] *)
Model.linear_min
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let pack_model name =
Model.trilinear
~name:(ns name)
~coeff1:(fv (sf "%s_micheline_nodes" name))
~coeff2:(fv (sf "%s_micheline_int_bytes" name))
~coeff3:(fv (sf "%s_micheline_string_bytes" name))
let open_chest_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_log_time_coeff" name)) * size1)
+ (free ~name:(fv (sf "%s_plaintext_coeff" name)) * size2)
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let verify_update_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_inputs" name))
~coeff2:(fv (sf "%s_ouputs" name))
let list_enter_body_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size_xs" @@ fun size_xs ->
lam ~name:"size_ys" @@ fun size_ys ->
if_
(eq size_xs (int 0))
(free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_coeff" name)) * size_ys))
(free ~name:(fv (sf "%s_iter" name)))
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let branching_model ~case_0 ~case_1 name =
let module M = struct
type arg_type = int * unit
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size
let arity = Model.arity_1
let model =
lam ~name:"size" @@ fun size ->
if_
(eq size (int 0))
(free ~name:(fv (sf "%s_%s" name case_0)))
(free ~name:(fv (sf "%s_%s" name case_1)))
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * unit)
let empty_branch_model name =
branching_model ~case_0:"empty" ~case_1:"nonempty" name
let apply_model name = branching_model ~case_0:"lam" ~case_1:"lamrec" name
let join_tickets_model name =
let module M = struct
type arg_type = int * (int * (int * (int * unit)))
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size -> size -> size
let arity = Model.Succ_arity Model.arity_3
let model =
lam ~name:"content_size_x" @@ fun content_size_x ->
lam ~name:"content_size_y" @@ fun content_size_y ->
lam ~name:"amount_size_x" @@ fun amount_size_x ->
lam ~name:"amount_size_y" @@ fun amount_size_y ->
free ~name:(fv (sf "%s_const" name))
+ free ~name:(fv (sf "%s_compare_coeff" name))
* min content_size_x content_size_y
+ free ~name:(fv (sf "%s_add_coeff" name))
* max amount_size_x amount_size_y
end
let name = ns name
end in
(module M : Model.Model_impl
with type arg_type = int * (int * (int * (int * unit))))
let lsl_bytes_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_bytes" name))
~coeff2:(fv (sf "%s_shift" name))
let lsr_bytes_model name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
Note that [ q ] is guaranteed to be non - negative because we use
saturated subtraction . When [ size1 < size2 ] , the model evaluates to
[ const ] as expected .
saturated subtraction. When [size1 < size2], the model evaluates to
[const] as expected. *)
let_ ~name:"q" (sat_sub size1 (size2 * float 0.125)) @@ fun q ->
free ~name:const + (free ~name:coeff * q)
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
end
let ir_model ?specialization instr_or_cont =
let open Interpreter_workload in
let open Models in
let name = name_of_instr_or_cont ?specialization instr_or_cont in
match instr_or_cont with
| Instr_name instr -> (
match instr with
| N_IDrop | N_IDup | N_ISwap | N_IConst | N_ICons_pair | N_ICar | N_ICdr
| N_ICons_some | N_ICons_none | N_IIf_none | N_IOpt_map | N_ILeft
| N_IRight | N_IIf_left | N_ICons_list | N_INil | N_IIf_cons
| N_IEmpty_set | N_IEmpty_map | N_IEmpty_big_map | N_IOr | N_IAnd | N_IXor
| N_INot | N_IIf | N_ILoop | N_ILoop_left | N_IDip | N_IExec | N_IView
| N_ILambda | N_IFailwith | N_IAddress | N_ICreate_contract
| N_ISet_delegate | N_INow | N_IMin_block_time | N_IBalance | N_IHash_key
| N_IUnpack | N_ISource | N_ISender | N_ISelf | N_IAmount | N_IChainId
| N_ILevel | N_ISelf_address | N_INever | N_IUnpair | N_IVoting_power
| N_ITotal_voting_power | N_IList_size | N_ISet_size | N_IMap_size
| N_ISapling_empty_state ->
model_0 instr_or_cont (const1_model name)
| N_ISet_mem | N_ISet_update | N_IMap_mem | N_IMap_get | N_IMap_update
| N_IBig_map_mem | N_IBig_map_get | N_IBig_map_update
| N_IMap_get_and_update | N_IBig_map_get_and_update ->
model_2 instr_or_cont (nlogm_model name)
| N_IConcat_string -> model_2 instr_or_cont (concat_model name)
| N_IConcat_string_pair -> model_2 instr_or_cont (concat_pair_model name)
| N_ISlice_string -> model_1 instr_or_cont (affine_model name)
| N_IString_size -> model_0 instr_or_cont (const1_model name)
| N_IConcat_bytes -> model_2 instr_or_cont (concat_model name)
| N_IConcat_bytes_pair -> model_2 instr_or_cont (concat_pair_model name)
| N_ISlice_bytes -> model_1 instr_or_cont (affine_model name)
| N_IBytes_size -> model_0 instr_or_cont (const1_model name)
| N_IOr_bytes -> model_2 instr_or_cont (linear_max_model name)
| N_IAnd_bytes -> model_2 instr_or_cont (linear_min_model name)
| N_IXor_bytes -> model_2 instr_or_cont (linear_max_model name)
| N_INot_bytes -> model_1 instr_or_cont (affine_model name)
| N_ILsl_bytes -> model_2 instr_or_cont (lsl_bytes_model name)
| N_ILsr_bytes -> model_2 instr_or_cont (lsr_bytes_model name)
| N_IBytes_nat -> model_1 instr_or_cont (affine_model name)
| N_INat_bytes -> model_1 instr_or_cont (affine_model name)
| N_IBytes_int -> model_1 instr_or_cont (affine_model name)
| N_IInt_bytes -> model_1 instr_or_cont (affine_model name)
| N_IAdd_seconds_to_timestamp | N_IAdd_timestamp_to_seconds
| N_ISub_timestamp_seconds | N_IDiff_timestamps ->
model_2 instr_or_cont (linear_max_model name)
| N_IAdd_tez | N_ISub_tez | N_ISub_tez_legacy | N_IEdiv_tez ->
model_0 instr_or_cont (const1_model name)
| N_IMul_teznat | N_IMul_nattez ->
model_1 instr_or_cont (affine_model name)
| N_IEdiv_teznat -> model_2 instr_or_cont (division_cost name)
| N_IIs_nat -> model_0 instr_or_cont (const1_model name)
| N_INeg -> model_1 instr_or_cont (affine_model name)
| N_IAbs_int -> model_1 instr_or_cont (affine_model name)
| N_IInt_nat -> model_0 instr_or_cont (const1_model name)
| N_IAdd_int -> model_2 instr_or_cont (linear_max_model name)
| N_IAdd_nat -> model_2 instr_or_cont (linear_max_model name)
| N_ISub_int -> model_2 instr_or_cont (linear_max_model name)
| N_IMul_int -> model_2 instr_or_cont (addlogadd name)
| N_IMul_nat -> model_2 instr_or_cont (addlogadd name)
| N_IEdiv_int -> model_2 instr_or_cont (division_cost name)
| N_IEdiv_nat -> model_2 instr_or_cont (division_cost name)
| N_ILsl_nat -> model_1 instr_or_cont (affine_model name)
| N_ILsr_nat -> model_1 instr_or_cont (affine_model name)
| N_IOr_nat -> model_2 instr_or_cont (linear_max_model name)
| N_IAnd_nat -> model_2 instr_or_cont (linear_min_model name)
| N_IAnd_int_nat -> model_2 instr_or_cont (linear_min_model name)
| N_IXor_nat -> model_2 instr_or_cont (linear_max_model name)
| N_INot_int -> model_1 instr_or_cont (affine_model name)
| N_ICompare -> model_2 instr_or_cont (linear_min_model name)
| N_IEq | N_INeq | N_ILt | N_IGt | N_ILe | N_IGe ->
model_0 instr_or_cont (const1_model name)
| N_IPack -> model_3 instr_or_cont (pack_model name)
| N_IBlake2b | N_ISha256 | N_ISha512 | N_IKeccak | N_ISha3 ->
model_1 instr_or_cont (affine_model name)
| N_ICheck_signature_ed25519 | N_ICheck_signature_secp256k1
| N_ICheck_signature_p256 | N_ICheck_signature_bls ->
model_1 instr_or_cont (affine_model name)
| N_IContract | N_ITransfer_tokens | N_IImplicit_account ->
model_0 instr_or_cont (const1_model name)
The following two instructions are expected to have an affine model . However ,
we observe 3 affine parts , on [ 0;300 ] , [ 300;400 ] and [ 400;\inf [ .
we observe 3 affine parts, on [0;300], [300;400] and [400;\inf[. *)
| N_IDupN -> model_1 instr_or_cont (break_model_2 name 300 400)
| N_IDropN -> model_1 instr_or_cont (break_model_2_const name 300 400)
| N_IDig | N_IDug | N_IDipN -> model_1 instr_or_cont (affine_model name)
| N_IAdd_bls12_381_g1 | N_IAdd_bls12_381_g2 | N_IAdd_bls12_381_fr
| N_IMul_bls12_381_g1 | N_IMul_bls12_381_g2 | N_IMul_bls12_381_fr
| N_INeg_bls12_381_g1 | N_INeg_bls12_381_g2 | N_INeg_bls12_381_fr
| N_IInt_bls12_381_z_fr ->
model_0 instr_or_cont (const1_model name)
| N_IMul_bls12_381_fr_z | N_IMul_bls12_381_z_fr
| N_IPairing_check_bls12_381 ->
model_1 instr_or_cont (affine_model name)
| N_IComb_get | N_IComb | N_IComb_set | N_IUncomb ->
model_1 instr_or_cont (affine_model name)
| N_ITicket | N_IRead_ticket -> model_0 instr_or_cont (const1_model name)
| N_ISplit_ticket -> model_2 instr_or_cont (linear_max_model name)
| N_IJoin_tickets -> model_4 instr_or_cont (join_tickets_model name)
| N_ISapling_verify_update ->
model_2 instr_or_cont (verify_update_model name)
| N_IList_map -> model_0 instr_or_cont (const1_model name)
| N_IList_iter -> model_0 instr_or_cont (const1_model name)
| N_IIter -> model_0 instr_or_cont (const1_model name)
| N_IMap_map -> model_1 instr_or_cont (affine_model name)
| N_IMap_iter -> model_1 instr_or_cont (affine_model name)
| N_ISet_iter -> model_1 instr_or_cont (affine_model name)
| N_IHalt -> model_0 instr_or_cont (const1_model name)
| N_IApply -> model_1 instr_or_cont (apply_model name)
| N_ILog -> model_0 instr_or_cont (const1_model name)
| N_IOpen_chest -> model_2 instr_or_cont (open_chest_model name)
| N_IEmit -> model_0 instr_or_cont (const1_model name))
| Cont_name cont -> (
match cont with
| N_KNil -> model_0 instr_or_cont (const1_model name)
| N_KCons -> model_0 instr_or_cont (const1_model name)
| N_KReturn -> model_0 instr_or_cont (const1_model name)
| N_KView_exit -> model_0 instr_or_cont (const1_model name)
| N_KMap_head -> model_0 instr_or_cont (const1_model name)
| N_KUndip -> model_0 instr_or_cont (const1_model name)
| N_KLoop_in -> model_0 instr_or_cont (const1_model name)
| N_KLoop_in_left -> model_0 instr_or_cont (const1_model name)
| N_KIter -> model_1 instr_or_cont (empty_branch_model name)
| N_KList_enter_body -> model_2 instr_or_cont (list_enter_body_model name)
| N_KList_exit_body -> model_0 instr_or_cont (const1_model name)
| N_KMap_enter_body -> model_1 instr_or_cont (empty_branch_model name)
| N_KMap_exit_body -> model_2 instr_or_cont (nlogm_model name)
| N_KLog -> model_0 instr_or_cont (const1_model name))
let amplification_loop_iteration = fv "amplification_loop_iteration"
let amplification_loop_model =
Model.make
~conv:(fun iterations -> (iterations, ()))
~model:(Model.linear ~name:(ns "amp") ~coeff:amplification_loop_iteration)
(* The following model stitches together the per-instruction models and
adds a term corresponding to the latency induced by the timer itself. *)
let interpreter_model ?amplification sub_model =
Model.make_aggregated
~model:(fun trace ->
let module Def (X : Costlang.S) = struct
type t = X.size X.repr
let applied =
let initial =
match amplification with
| None -> X.int 0
| Some amplification_factor ->
let (module Amplification_applied) =
Model.apply amplification_loop_model amplification_factor
in
let module Amplification_result = Amplification_applied (X) in
Amplification_result.applied
in
List.fold_left
(fun (acc : X.size X.repr) instr_trace ->
let (module Applied_instr) =
Model.apply
(ir_model instr_trace.Interpreter_workload.name)
instr_trace
in
let module R = Applied_instr (X) in
X.(acc + R.applied))
initial
trace
end in
((module Def) : Model.applied))
~sub_models:[sub_model]
let make_model ?amplification instr_name =
(* When generating code, we don't want to consider the terms specific to
Lwt and to the timer latency. Also, we restrict to single instructions. *)
let ir_model =
match ir_model instr_name with
| Aggregate _ -> assert false
| Abstract {model; _} -> Model.Model model
in
[("interpreter", interpreter_model ?amplification ir_model)]
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/cdc7a4382ef6dfcd6c73f86d9a29b829b33d18d4/src/proto_016_PtMumbai/lib_benchmarks_proto/interpreter_model.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Some instructions are oveloaded (eg COMPARE). In order to generate distinct
models at different types, we must specialize these models. The [specialization]
parameter acts as a mangling scheme to produce distinct models.
For constant-time instructions
For instructions with cost function
[\lambda size. const + coeff * size]
The following model stitches together the per-instruction models and
adds a term corresponding to the latency induced by the timer itself.
When generating code, we don't want to consider the terms specific to
Lwt and to the timer latency. Also, we restrict to single instructions. | Copyright ( c ) 2021 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
let ns = Namespace.make Registration_helpers.ns "interpreter"
let fv s = Free_variable.of_namespace (ns s)
let trace_error expected given =
let open Interpreter_workload in
let exp = string_of_instr_or_cont expected in
let given = string_of_instr_or_cont given in
let msg =
Format.asprintf
"Interpreter_model: trace error, expected %s, given %s"
exp
given
in
Stdlib.failwith msg
let arity_error instr expected given =
let open Interpreter_workload in
let s = string_of_instr_or_cont instr in
let msg =
Format.asprintf
"Interpreter_model: arity error (%s), expected %d, given %a"
s
expected
Interpreter_workload.pp_args
given
in
Stdlib.failwith msg
let model_0 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = []} -> if name = instr then () else trace_error instr name
| {args; _} -> arity_error instr 0 args)
~model
let model_1 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = [{name = _; arg}]} ->
if name = instr then (arg, ()) else trace_error instr name
| {args; _} -> arity_error instr 1 args)
~model
let model_2 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = [{name = _; arg = x}; {name = _; arg = y}]} ->
if name = instr then (x, (y, ())) else trace_error instr name
| {args; _} -> arity_error instr 2 args)
~model
let model_3 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {
name;
args = [{name = _; arg = x}; {name = _; arg = y}; {name = _; arg = z}];
} ->
if name = instr then (x, (y, (z, ()))) else trace_error instr name
| {args; _} -> arity_error instr 3 args)
~model
let model_4 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {
name;
args =
[
{name = _; arg = w};
{name = _; arg = x};
{name = _; arg = y};
{name = _; arg = z};
];
} ->
if name = instr then (w, (x, (y, (z, ()))))
else trace_error instr name
| {args; _} -> arity_error instr 4 args)
~model
let sf = Format.asprintf
let division_cost name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
let name = ns name
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
Note that [ q ] is guaranteed to be non - negative because we use
saturated subtraction . When [ size1 < size2 ] , the model evaluates to
[ const ] as expected .
saturated subtraction. When [size1 < size2], the model evaluates to
[const] as expected. *)
let_ ~name:"q" (sat_sub size1 size2) @@ fun q ->
(free ~name:coeff * q * size2) + free ~name:const
end
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let addlogadd name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
let name = ns name
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
let_ ~name:"a" (size1 + size2) @@ fun a ->
(free ~name:coeff * (a * log2 (int 1 + a))) + free ~name:const
end
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let name_of_instr_or_cont ?specialization instr_or_cont =
let spec = Option.fold ~none:"" ~some:(fun s -> "_" ^ s) specialization in
Interpreter_workload.string_of_instr_or_cont instr_or_cont ^ spec
module Models = struct
let const1_model name =
Model.unknown_const1 ~name:(ns name) ~const:(fv (sf "%s_const" name))
let affine_model name =
Model.affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let break_model name break =
Model.breakdown
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~break
let break_model_2 name break1 break2 =
Model.breakdown2
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~coeff3:(fv (sf "%s_coeff3" name))
~break1
~break2
let break_model_2_const name break1 break2 =
Model.breakdown2_const
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~coeff3:(fv (sf "%s_coeff3" name))
~const:(fv (sf "%s_const" name))
~break1
~break2
let nlogm_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * size1 log2(size2 ) ]
[\lambda size1. \lambda size2. const + coeff * size1 log2(size2)] *)
Model.nlogm
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let concat_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_total_bytes" name))
~coeff2:(fv (sf "%s_list_length" name))
let concat_pair_model name =
Model.linear_sum
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let linear_max_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * max(size1,size2 ) ]
[\lambda size1. \lambda size2. const + coeff * max(size1,size2)] *)
Model.linear_max
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let linear_min_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * min(size1,size2 ) ]
[\lambda size1. \lambda size2. const + coeff * min(size1,size2)] *)
Model.linear_min
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let pack_model name =
Model.trilinear
~name:(ns name)
~coeff1:(fv (sf "%s_micheline_nodes" name))
~coeff2:(fv (sf "%s_micheline_int_bytes" name))
~coeff3:(fv (sf "%s_micheline_string_bytes" name))
let open_chest_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_log_time_coeff" name)) * size1)
+ (free ~name:(fv (sf "%s_plaintext_coeff" name)) * size2)
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let verify_update_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_inputs" name))
~coeff2:(fv (sf "%s_ouputs" name))
let list_enter_body_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size_xs" @@ fun size_xs ->
lam ~name:"size_ys" @@ fun size_ys ->
if_
(eq size_xs (int 0))
(free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_coeff" name)) * size_ys))
(free ~name:(fv (sf "%s_iter" name)))
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let branching_model ~case_0 ~case_1 name =
let module M = struct
type arg_type = int * unit
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size
let arity = Model.arity_1
let model =
lam ~name:"size" @@ fun size ->
if_
(eq size (int 0))
(free ~name:(fv (sf "%s_%s" name case_0)))
(free ~name:(fv (sf "%s_%s" name case_1)))
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * unit)
let empty_branch_model name =
branching_model ~case_0:"empty" ~case_1:"nonempty" name
let apply_model name = branching_model ~case_0:"lam" ~case_1:"lamrec" name
let join_tickets_model name =
let module M = struct
type arg_type = int * (int * (int * (int * unit)))
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size -> size -> size
let arity = Model.Succ_arity Model.arity_3
let model =
lam ~name:"content_size_x" @@ fun content_size_x ->
lam ~name:"content_size_y" @@ fun content_size_y ->
lam ~name:"amount_size_x" @@ fun amount_size_x ->
lam ~name:"amount_size_y" @@ fun amount_size_y ->
free ~name:(fv (sf "%s_const" name))
+ free ~name:(fv (sf "%s_compare_coeff" name))
* min content_size_x content_size_y
+ free ~name:(fv (sf "%s_add_coeff" name))
* max amount_size_x amount_size_y
end
let name = ns name
end in
(module M : Model.Model_impl
with type arg_type = int * (int * (int * (int * unit))))
let lsl_bytes_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_bytes" name))
~coeff2:(fv (sf "%s_shift" name))
let lsr_bytes_model name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
Note that [ q ] is guaranteed to be non - negative because we use
saturated subtraction . When [ size1 < size2 ] , the model evaluates to
[ const ] as expected .
saturated subtraction. When [size1 < size2], the model evaluates to
[const] as expected. *)
let_ ~name:"q" (sat_sub size1 (size2 * float 0.125)) @@ fun q ->
free ~name:const + (free ~name:coeff * q)
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
end
let ir_model ?specialization instr_or_cont =
let open Interpreter_workload in
let open Models in
let name = name_of_instr_or_cont ?specialization instr_or_cont in
match instr_or_cont with
| Instr_name instr -> (
match instr with
| N_IDrop | N_IDup | N_ISwap | N_IConst | N_ICons_pair | N_ICar | N_ICdr
| N_ICons_some | N_ICons_none | N_IIf_none | N_IOpt_map | N_ILeft
| N_IRight | N_IIf_left | N_ICons_list | N_INil | N_IIf_cons
| N_IEmpty_set | N_IEmpty_map | N_IEmpty_big_map | N_IOr | N_IAnd | N_IXor
| N_INot | N_IIf | N_ILoop | N_ILoop_left | N_IDip | N_IExec | N_IView
| N_ILambda | N_IFailwith | N_IAddress | N_ICreate_contract
| N_ISet_delegate | N_INow | N_IMin_block_time | N_IBalance | N_IHash_key
| N_IUnpack | N_ISource | N_ISender | N_ISelf | N_IAmount | N_IChainId
| N_ILevel | N_ISelf_address | N_INever | N_IUnpair | N_IVoting_power
| N_ITotal_voting_power | N_IList_size | N_ISet_size | N_IMap_size
| N_ISapling_empty_state ->
model_0 instr_or_cont (const1_model name)
| N_ISet_mem | N_ISet_update | N_IMap_mem | N_IMap_get | N_IMap_update
| N_IBig_map_mem | N_IBig_map_get | N_IBig_map_update
| N_IMap_get_and_update | N_IBig_map_get_and_update ->
model_2 instr_or_cont (nlogm_model name)
| N_IConcat_string -> model_2 instr_or_cont (concat_model name)
| N_IConcat_string_pair -> model_2 instr_or_cont (concat_pair_model name)
| N_ISlice_string -> model_1 instr_or_cont (affine_model name)
| N_IString_size -> model_0 instr_or_cont (const1_model name)
| N_IConcat_bytes -> model_2 instr_or_cont (concat_model name)
| N_IConcat_bytes_pair -> model_2 instr_or_cont (concat_pair_model name)
| N_ISlice_bytes -> model_1 instr_or_cont (affine_model name)
| N_IBytes_size -> model_0 instr_or_cont (const1_model name)
| N_IOr_bytes -> model_2 instr_or_cont (linear_max_model name)
| N_IAnd_bytes -> model_2 instr_or_cont (linear_min_model name)
| N_IXor_bytes -> model_2 instr_or_cont (linear_max_model name)
| N_INot_bytes -> model_1 instr_or_cont (affine_model name)
| N_ILsl_bytes -> model_2 instr_or_cont (lsl_bytes_model name)
| N_ILsr_bytes -> model_2 instr_or_cont (lsr_bytes_model name)
| N_IBytes_nat -> model_1 instr_or_cont (affine_model name)
| N_INat_bytes -> model_1 instr_or_cont (affine_model name)
| N_IBytes_int -> model_1 instr_or_cont (affine_model name)
| N_IInt_bytes -> model_1 instr_or_cont (affine_model name)
| N_IAdd_seconds_to_timestamp | N_IAdd_timestamp_to_seconds
| N_ISub_timestamp_seconds | N_IDiff_timestamps ->
model_2 instr_or_cont (linear_max_model name)
| N_IAdd_tez | N_ISub_tez | N_ISub_tez_legacy | N_IEdiv_tez ->
model_0 instr_or_cont (const1_model name)
| N_IMul_teznat | N_IMul_nattez ->
model_1 instr_or_cont (affine_model name)
| N_IEdiv_teznat -> model_2 instr_or_cont (division_cost name)
| N_IIs_nat -> model_0 instr_or_cont (const1_model name)
| N_INeg -> model_1 instr_or_cont (affine_model name)
| N_IAbs_int -> model_1 instr_or_cont (affine_model name)
| N_IInt_nat -> model_0 instr_or_cont (const1_model name)
| N_IAdd_int -> model_2 instr_or_cont (linear_max_model name)
| N_IAdd_nat -> model_2 instr_or_cont (linear_max_model name)
| N_ISub_int -> model_2 instr_or_cont (linear_max_model name)
| N_IMul_int -> model_2 instr_or_cont (addlogadd name)
| N_IMul_nat -> model_2 instr_or_cont (addlogadd name)
| N_IEdiv_int -> model_2 instr_or_cont (division_cost name)
| N_IEdiv_nat -> model_2 instr_or_cont (division_cost name)
| N_ILsl_nat -> model_1 instr_or_cont (affine_model name)
| N_ILsr_nat -> model_1 instr_or_cont (affine_model name)
| N_IOr_nat -> model_2 instr_or_cont (linear_max_model name)
| N_IAnd_nat -> model_2 instr_or_cont (linear_min_model name)
| N_IAnd_int_nat -> model_2 instr_or_cont (linear_min_model name)
| N_IXor_nat -> model_2 instr_or_cont (linear_max_model name)
| N_INot_int -> model_1 instr_or_cont (affine_model name)
| N_ICompare -> model_2 instr_or_cont (linear_min_model name)
| N_IEq | N_INeq | N_ILt | N_IGt | N_ILe | N_IGe ->
model_0 instr_or_cont (const1_model name)
| N_IPack -> model_3 instr_or_cont (pack_model name)
| N_IBlake2b | N_ISha256 | N_ISha512 | N_IKeccak | N_ISha3 ->
model_1 instr_or_cont (affine_model name)
| N_ICheck_signature_ed25519 | N_ICheck_signature_secp256k1
| N_ICheck_signature_p256 | N_ICheck_signature_bls ->
model_1 instr_or_cont (affine_model name)
| N_IContract | N_ITransfer_tokens | N_IImplicit_account ->
model_0 instr_or_cont (const1_model name)
The following two instructions are expected to have an affine model . However ,
we observe 3 affine parts , on [ 0;300 ] , [ 300;400 ] and [ 400;\inf [ .
we observe 3 affine parts, on [0;300], [300;400] and [400;\inf[. *)
| N_IDupN -> model_1 instr_or_cont (break_model_2 name 300 400)
| N_IDropN -> model_1 instr_or_cont (break_model_2_const name 300 400)
| N_IDig | N_IDug | N_IDipN -> model_1 instr_or_cont (affine_model name)
| N_IAdd_bls12_381_g1 | N_IAdd_bls12_381_g2 | N_IAdd_bls12_381_fr
| N_IMul_bls12_381_g1 | N_IMul_bls12_381_g2 | N_IMul_bls12_381_fr
| N_INeg_bls12_381_g1 | N_INeg_bls12_381_g2 | N_INeg_bls12_381_fr
| N_IInt_bls12_381_z_fr ->
model_0 instr_or_cont (const1_model name)
| N_IMul_bls12_381_fr_z | N_IMul_bls12_381_z_fr
| N_IPairing_check_bls12_381 ->
model_1 instr_or_cont (affine_model name)
| N_IComb_get | N_IComb | N_IComb_set | N_IUncomb ->
model_1 instr_or_cont (affine_model name)
| N_ITicket | N_IRead_ticket -> model_0 instr_or_cont (const1_model name)
| N_ISplit_ticket -> model_2 instr_or_cont (linear_max_model name)
| N_IJoin_tickets -> model_4 instr_or_cont (join_tickets_model name)
| N_ISapling_verify_update ->
model_2 instr_or_cont (verify_update_model name)
| N_IList_map -> model_0 instr_or_cont (const1_model name)
| N_IList_iter -> model_0 instr_or_cont (const1_model name)
| N_IIter -> model_0 instr_or_cont (const1_model name)
| N_IMap_map -> model_1 instr_or_cont (affine_model name)
| N_IMap_iter -> model_1 instr_or_cont (affine_model name)
| N_ISet_iter -> model_1 instr_or_cont (affine_model name)
| N_IHalt -> model_0 instr_or_cont (const1_model name)
| N_IApply -> model_1 instr_or_cont (apply_model name)
| N_ILog -> model_0 instr_or_cont (const1_model name)
| N_IOpen_chest -> model_2 instr_or_cont (open_chest_model name)
| N_IEmit -> model_0 instr_or_cont (const1_model name))
| Cont_name cont -> (
match cont with
| N_KNil -> model_0 instr_or_cont (const1_model name)
| N_KCons -> model_0 instr_or_cont (const1_model name)
| N_KReturn -> model_0 instr_or_cont (const1_model name)
| N_KView_exit -> model_0 instr_or_cont (const1_model name)
| N_KMap_head -> model_0 instr_or_cont (const1_model name)
| N_KUndip -> model_0 instr_or_cont (const1_model name)
| N_KLoop_in -> model_0 instr_or_cont (const1_model name)
| N_KLoop_in_left -> model_0 instr_or_cont (const1_model name)
| N_KIter -> model_1 instr_or_cont (empty_branch_model name)
| N_KList_enter_body -> model_2 instr_or_cont (list_enter_body_model name)
| N_KList_exit_body -> model_0 instr_or_cont (const1_model name)
| N_KMap_enter_body -> model_1 instr_or_cont (empty_branch_model name)
| N_KMap_exit_body -> model_2 instr_or_cont (nlogm_model name)
| N_KLog -> model_0 instr_or_cont (const1_model name))
let amplification_loop_iteration = fv "amplification_loop_iteration"
let amplification_loop_model =
Model.make
~conv:(fun iterations -> (iterations, ()))
~model:(Model.linear ~name:(ns "amp") ~coeff:amplification_loop_iteration)
let interpreter_model ?amplification sub_model =
Model.make_aggregated
~model:(fun trace ->
let module Def (X : Costlang.S) = struct
type t = X.size X.repr
let applied =
let initial =
match amplification with
| None -> X.int 0
| Some amplification_factor ->
let (module Amplification_applied) =
Model.apply amplification_loop_model amplification_factor
in
let module Amplification_result = Amplification_applied (X) in
Amplification_result.applied
in
List.fold_left
(fun (acc : X.size X.repr) instr_trace ->
let (module Applied_instr) =
Model.apply
(ir_model instr_trace.Interpreter_workload.name)
instr_trace
in
let module R = Applied_instr (X) in
X.(acc + R.applied))
initial
trace
end in
((module Def) : Model.applied))
~sub_models:[sub_model]
let make_model ?amplification instr_name =
let ir_model =
match ir_model instr_name with
| Aggregate _ -> assert false
| Abstract {model; _} -> Model.Model model
in
[("interpreter", interpreter_model ?amplification ir_model)]
|
17f10ad93035498416c55172171fc4eb9312487cab454301b34502acb29d5d8a | Bogdanp/racket-component | system.rkt | #lang racket/base
(require (for-syntax racket/base
racket/syntax
syntax/parse)
racket/contract/base
racket/match
"component.rkt"
"dependency.rkt")
(provide
(for-syntax component)
define-system
(contract-out
[make-system (-> system-spec/c system?)]
[current-system (parameter/c (or/c false/c system?))]
[system? (-> any/c boolean?)]
[system-start (-> system? void?)]
[system-stop (-> system? void?)]
[system-ref (case->
(-> symbol? any/c)
(-> system? symbol? any/c))]
[system-get (case->
(-> symbol? any/c)
(-> system? symbol? any/c))]
[system-replace (-> system? symbol? any/c system?)]
[system->dot (-> system? string?)]
[system->png (-> system? path-string? boolean?)]))
(define-logger system)
(define system-spec/c
(listof (or/c
(list/c symbol? any/c)
(list/c symbol? (listof symbol?) any/c))))
(struct system (dependencies factories components))
(define current-system
(make-parameter #f))
(begin-for-syntax
(define-syntax-class component
(pattern (name:id e:expr)
#:with spec #'(list 'name (list) e))
(pattern (name:id (dep-name:id ...) e:expr)
#:with spec #'(list 'name (list 'dep-name ...) e))))
(define-syntax (define-system stx)
(syntax-parse stx
[(_ id:id component:component ...+)
#:with full-id (format-id #'id "~a-system" #'id)
#'(define full-id (make-system (list component.spec ...)))]))
(define (make-system spec)
(define-values (factories dependencies)
(for/fold ([factories (hash)]
[dependencies (make-dependency-graph)])
([definition spec])
(match definition
[(list id e)
(values (hash-set factories id e) dependencies)]
[(list id dep-ids e)
(values (hash-set factories id e)
(for/fold ([dependencies dependencies])
([dep-id dep-ids])
(depend dependencies id dep-id)))]
[_
(error 'make-system "bad component definition ~a" definition)])))
(system dependencies factories (make-hasheq)))
(define (system-start s)
(log-system-debug "starting system")
(parameterize ([current-system s])
(for/fold ([started-ids null] #:result (void))
([id (starting-order (system-dependencies s))])
(with-handlers ([(λ (_) #t)
(λ (e)
(log-system-warning "~a failed to start; stopping components started so far" id)
(for ([id (in-list started-ids)])
(hash-set! (system-components s) id (stop-component s id)))
(raise e))])
(begin0 (cons id started-ids)
(hash-set! (system-components s) id (start-component s id)))))))
(define (start-component s id)
(log-system-debug "starting component ~a" id)
(define factory (hash-ref (system-factories s) id))
(define dependencies (direct-dependencies (system-dependencies s) id))
(define a-component (apply factory (for/list ([id (in-list dependencies)])
(system-ref s id))))
(if (component? a-component)
(component-start a-component)
a-component))
(define (system-stop s)
(log-system-debug "stopping system")
(for ([id (stopping-order (system-dependencies s))])
(hash-set! (system-components s) id (stop-component s id))))
(define (stop-component s id)
(log-system-debug "stopping component ~a" id)
(define a-component (system-ref s id))
(if (component? a-component)
(component-stop a-component)
a-component))
(define system-ref
(case-lambda
[(id)
(system-ref (current-system) id)]
[(s id)
(define components (system-components s))
(hash-ref components id (lambda ()
(raise-argument-error 'system-ref "a declared component" id)))]))
(define system-get system-ref) ;; backwards-compat
(define (system-replace s id factory)
(define factories (system-factories s))
(unless (hash-has-key? factories id)
(raise-argument-error 'system-ref "a declared component" id))
(struct-copy system s
[components (make-hash)]
[factories (hash-set factories id factory)]))
(define (system->dot s)
(dependency-graph->dot (system-dependencies s)))
(define (system->png s output-path)
(dependency-graph->png (system-dependencies s) output-path))
| null | https://raw.githubusercontent.com/Bogdanp/racket-component/1d0b73fd482e8ae9388336a1357e5afdb4b6c612/component-lib/component/private/system.rkt | racket | backwards-compat | #lang racket/base
(require (for-syntax racket/base
racket/syntax
syntax/parse)
racket/contract/base
racket/match
"component.rkt"
"dependency.rkt")
(provide
(for-syntax component)
define-system
(contract-out
[make-system (-> system-spec/c system?)]
[current-system (parameter/c (or/c false/c system?))]
[system? (-> any/c boolean?)]
[system-start (-> system? void?)]
[system-stop (-> system? void?)]
[system-ref (case->
(-> symbol? any/c)
(-> system? symbol? any/c))]
[system-get (case->
(-> symbol? any/c)
(-> system? symbol? any/c))]
[system-replace (-> system? symbol? any/c system?)]
[system->dot (-> system? string?)]
[system->png (-> system? path-string? boolean?)]))
(define-logger system)
(define system-spec/c
(listof (or/c
(list/c symbol? any/c)
(list/c symbol? (listof symbol?) any/c))))
(struct system (dependencies factories components))
(define current-system
(make-parameter #f))
(begin-for-syntax
(define-syntax-class component
(pattern (name:id e:expr)
#:with spec #'(list 'name (list) e))
(pattern (name:id (dep-name:id ...) e:expr)
#:with spec #'(list 'name (list 'dep-name ...) e))))
(define-syntax (define-system stx)
(syntax-parse stx
[(_ id:id component:component ...+)
#:with full-id (format-id #'id "~a-system" #'id)
#'(define full-id (make-system (list component.spec ...)))]))
(define (make-system spec)
(define-values (factories dependencies)
(for/fold ([factories (hash)]
[dependencies (make-dependency-graph)])
([definition spec])
(match definition
[(list id e)
(values (hash-set factories id e) dependencies)]
[(list id dep-ids e)
(values (hash-set factories id e)
(for/fold ([dependencies dependencies])
([dep-id dep-ids])
(depend dependencies id dep-id)))]
[_
(error 'make-system "bad component definition ~a" definition)])))
(system dependencies factories (make-hasheq)))
(define (system-start s)
(log-system-debug "starting system")
(parameterize ([current-system s])
(for/fold ([started-ids null] #:result (void))
([id (starting-order (system-dependencies s))])
(with-handlers ([(λ (_) #t)
(λ (e)
(log-system-warning "~a failed to start; stopping components started so far" id)
(for ([id (in-list started-ids)])
(hash-set! (system-components s) id (stop-component s id)))
(raise e))])
(begin0 (cons id started-ids)
(hash-set! (system-components s) id (start-component s id)))))))
(define (start-component s id)
(log-system-debug "starting component ~a" id)
(define factory (hash-ref (system-factories s) id))
(define dependencies (direct-dependencies (system-dependencies s) id))
(define a-component (apply factory (for/list ([id (in-list dependencies)])
(system-ref s id))))
(if (component? a-component)
(component-start a-component)
a-component))
(define (system-stop s)
(log-system-debug "stopping system")
(for ([id (stopping-order (system-dependencies s))])
(hash-set! (system-components s) id (stop-component s id))))
(define (stop-component s id)
(log-system-debug "stopping component ~a" id)
(define a-component (system-ref s id))
(if (component? a-component)
(component-stop a-component)
a-component))
(define system-ref
(case-lambda
[(id)
(system-ref (current-system) id)]
[(s id)
(define components (system-components s))
(hash-ref components id (lambda ()
(raise-argument-error 'system-ref "a declared component" id)))]))
(define (system-replace s id factory)
(define factories (system-factories s))
(unless (hash-has-key? factories id)
(raise-argument-error 'system-ref "a declared component" id))
(struct-copy system s
[components (make-hash)]
[factories (hash-set factories id factory)]))
(define (system->dot s)
(dependency-graph->dot (system-dependencies s)))
(define (system->png s output-path)
(dependency-graph->png (system-dependencies s) output-path))
|
ba65b71a4f205d2c70556db965cf455ef2e9f224bf1388dcd67290c1bc882f2d | philnguyen/soft-contract | member.rkt | #lang racket
(require soft-contract/fake-contract)
(define (member x l)
(if (empty? l) empty
(if (equal? x (car l)) l (member x (cdr l)))))
(provide/contract
[member (any/c (listof any/c) . -> . (listof any/c))])
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/programs/safe/softy/member.rkt | racket | #lang racket
(require soft-contract/fake-contract)
(define (member x l)
(if (empty? l) empty
(if (equal? x (car l)) l (member x (cdr l)))))
(provide/contract
[member (any/c (listof any/c) . -> . (listof any/c))])
| |
c4717164382b923622adc7b504500715b8e5b5fa5407f30a7dcbe5025194f720 | nibbula/yew | who-cmds.lisp | ;;;
who-cmds.lisp - Commands for who .
;;;
(in-package :who)
(defun who-user-name-list ()
(append (los-util:user-name-list) (list "am" "i")))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass lish-user::arg-who-user (lish-user::arg-user)
()
(:default-initargs
:choice-func #'who-user-name-list)
(:documentation "User name.")))
(lish:defcommand who
((show-dead boolean :short-arg #\d
:help "True to show dead processes.")
(all boolean :short-arg #\a
:help "True to show all processes, not only user processes.")
(tty string :long-arg "tty"
:help "Terminal to exclusively report on.")
(file pathname :short-arg #\f
:help "Name of a file to use as the database.")
(users who-user :repeating t :help "Users to report on."))
"Who is on."
(when (equalp users '("am" "i"))
(setf users (list (user-name))
tty (file-handle-terminal-name 0)))
(setf lish:*output*
(who :users users :show-dead show-dead :all all :tty tty :file file)))
(lish:defcommand lastlogin
((show-history boolean :short-arg #\h :help "True to show login history.")
(users user :repeating t :help "User to show the last login for."))
"Show users' last login."
;; @@@ There should be an option where it tries to figure out durations
;; for sessions and booted times, like the "last" command.
(setf lish:*output*
(who :users users :all t
:file (cond
(show-history
(default-utmpx-file +UTXDB-LOG+))
(t
;; @@@ I can't be bothered to do this correctly now.
#+linux (default-utmpx-file +UTXDB-LOG+)
#-linux (default-utmpx-file +UTXDB-LASTLOGIN+))))))
(lish:defcommand uptime
((pretty boolean :short-arg #\p
:help "True to show in a long drawn-out format, mostly for gloating.")
(show-since boolean :short-arg #\s
:help "True to show the time the system has been up since."))
"Show how long the system has been running."
(print-uptime :pretty pretty :show-since show-since))
(lish:defcommand w
((no-header boolean :short-arg #\h :help "True to omit the header.")
(long boolean :short-arg #\l :help "True show the longer output.")
(users user :repeating t :help "Users to show."))
"Show who's doing what."
(setf lish:*output* (who-what :users users :no-header no-header :long long)))
;; End
| null | https://raw.githubusercontent.com/nibbula/yew/a62473dae637fb33a92aa75f260bf77b34cdbcfd/los/who-cmds.lisp | lisp |
@@@ There should be an option where it tries to figure out durations
for sessions and booted times, like the "last" command.
@@@ I can't be bothered to do this correctly now.
End | who-cmds.lisp - Commands for who .
(in-package :who)
(defun who-user-name-list ()
(append (los-util:user-name-list) (list "am" "i")))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass lish-user::arg-who-user (lish-user::arg-user)
()
(:default-initargs
:choice-func #'who-user-name-list)
(:documentation "User name.")))
(lish:defcommand who
((show-dead boolean :short-arg #\d
:help "True to show dead processes.")
(all boolean :short-arg #\a
:help "True to show all processes, not only user processes.")
(tty string :long-arg "tty"
:help "Terminal to exclusively report on.")
(file pathname :short-arg #\f
:help "Name of a file to use as the database.")
(users who-user :repeating t :help "Users to report on."))
"Who is on."
(when (equalp users '("am" "i"))
(setf users (list (user-name))
tty (file-handle-terminal-name 0)))
(setf lish:*output*
(who :users users :show-dead show-dead :all all :tty tty :file file)))
(lish:defcommand lastlogin
((show-history boolean :short-arg #\h :help "True to show login history.")
(users user :repeating t :help "User to show the last login for."))
"Show users' last login."
(setf lish:*output*
(who :users users :all t
:file (cond
(show-history
(default-utmpx-file +UTXDB-LOG+))
(t
#+linux (default-utmpx-file +UTXDB-LOG+)
#-linux (default-utmpx-file +UTXDB-LASTLOGIN+))))))
(lish:defcommand uptime
((pretty boolean :short-arg #\p
:help "True to show in a long drawn-out format, mostly for gloating.")
(show-since boolean :short-arg #\s
:help "True to show the time the system has been up since."))
"Show how long the system has been running."
(print-uptime :pretty pretty :show-since show-since))
(lish:defcommand w
((no-header boolean :short-arg #\h :help "True to omit the header.")
(long boolean :short-arg #\l :help "True show the longer output.")
(users user :repeating t :help "Users to show."))
"Show who's doing what."
(setf lish:*output* (who-what :users users :no-header no-header :long long)))
|
8a2e0532b6076a995e4b630ca58407ddec7141773f9a7f564073dd6ac26d889d | samrushing/irken-compiler | hpack.scm | ;; -*- Mode: Irken -*-
;; RFC 7541
;; XXX need to support SETTINGS_MAX_HEADER_LIST_SIZE
;; in order to defend against an 'hpack bomb'.
(define (H a b)
(:tuple a b))
(define *static-table*
#((H "" "")
(H ":authority" "")
(H ":method" "GET")
(H ":method" "POST")
(H ":path" "/")
(H ":path" "/index.html")
(H ":scheme" "http")
(H ":scheme" "https")
(H ":status" "200")
(H ":status" "204")
(H ":status" "206")
(H ":status" "304")
(H ":status" "400")
(H ":status" "404")
(H ":status" "500")
(H "accept-charset" "")
(H "accept-encoding" "gzip, deflate")
(H "accept-language" "")
(H "accept-ranges" "")
(H "accept" "")
(H "access-control-allow-origin" "")
(H "age" "")
(H "allow" "")
(H "authorization" "")
(H "cache-control" "")
(H "content-disposition" "")
(H "content-encoding" "")
(H "content-language" "")
(H "content-length" "")
(H "content-location" "")
(H "content-range" "")
(H "content-type" "")
(H "cookie" "")
(H "date" "")
(H "etag" "")
(H "expect" "")
(H "expires" "")
(H "from" "")
(H "host" "")
(H "if-match" "")
(H "if-modified-since" "")
(H "if-none-match" "")
(H "if-range" "")
(H "if-unmodified-since" "")
(H "last-modified" "")
(H "link" "")
(H "location" "")
(H "max-forwards" "")
(H "proxy-authenticate" "")
(H "proxy-authorization" "")
(H "range" "")
(H "referer" "")
(H "refresh" "")
(H "retry-after" "")
(H "server" "")
(H "set-cookie" "")
(H "strict-transport-security" "")
(H "transfer-encoding" "")
(H "user-agent" "")
(H "vary" "")
(H "via" "")
(H "www-authenticate" "")
))
(define nstatic 62)
(assert (= nstatic (vector-length *static-table*)))
;; a map from header-pair to index in the static table.
(define *static-map*
(let ((m (tree/empty)))
(for-range i nstatic
(tree/insert! m magic-cmp *static-table*[i] i))
m))
;; XXX investigate: this is supposed to be a 'canonical' huffman
;; encoding, which is supposed to have a very compact representation,
;; where each entry consists of 'key', 'bits'.
;;
(define huffman-table-ascii
(string-append
".....3031.3261..6365.696f...7374..2025.2d2e...2f33.3435..3637.38"
"39.....3d41.5f62..6466.6768...6c6d.6e70..7275..3a42.4344.....454"
"6.4748..494a.4b4c...4d4e.4f50..5152.5354....5556.5759..6a6b.7176"
"...7778.797a...262a.2c3b..585a...2122.2829..3f.272b..7c.233e...0"
"024.405b..5d7e..5e7d..3c60.7b....5cc3.d0.8082...83a2.b8c2..e0e2."
".99a1.a7ac.....b0b1.b3d1..d8d9.e3e5...e6.8184..8586.8892...9a9c."
"a0a3..a4a9.aaad.....b2b5.b9ba..bbbd.bec4...c6e4.e8e9...0187.898a"
"..8b8c.8d8f.....9395.9697..989b.9d9e...a5a6.a8ae..afb4.b6b7....b"
"cbf.c5e7..ef.098e..9091.949f....abce.d7e1..eced..c7cf.eaeb.....c"
"0c1.c8c9..cacd.d2d5...dadb.eef0..f2f3.ff.cbcc.....d3d4.d6dd..ded"
"f.f1f4...f5f6.f7f8..fafb.fcfd....fe.0203..0405.0607...080b.0c0e."
".0f10.1112....1314.1517..1819.1a1b...1c1d.1e1f..7fdc.f9..0a0d.16Z"))
(datatype hufftree
(:node hufftree hufftree)
(:leaf int)
)
;; this should go somewhere else
(define hexdig->int
#\0 -> 0
#\1 -> 1
#\2 -> 2
#\3 -> 3
#\4 -> 4
#\5 -> 5
#\6 -> 6
#\7 -> 7
#\8 -> 8
#\9 -> 9
#\a -> 10
#\b -> 11
#\c -> 12
#\d -> 13
#\e -> 14
#\f -> 15
x -> (raise (:BadHexDigit))
)
(define (2hex->int s pos)
(logior
(<< (hexdig->int (string-ref s pos)) 4)
(hexdig->int (string-ref s (+ pos 1)))))
(define (ascii->tree s pos)
(let recur ()
(match (string-ref s pos) with
#\. -> (begin
(set! pos (+ 1 pos))
(hufftree:node (recur) (recur)))
#\Z -> (hufftree:leaf 256)
_ -> (let ((r (hufftree:leaf (2hex->int s pos))))
(set! pos (+ pos 2))
r)
)))
(define huffman-table (ascii->tree huffman-table-ascii 0))
(define huffman-map
(let ((m (make-vector 257 (:pair 0 0))))
(let loop ((t huffman-table)
(n 0)
(bits 0))
(match t with
(hufftree:leaf val)
-> (set! m[val] (:pair n bits))
(hufftree:node L R)
-> (begin
(loop L (logior 0 (<< n 1)) (+ bits 1))
(loop R (logior 1 (<< n 1)) (+ bits 1)))
))
m))
(define masks
(let ((v (make-vector 9 0)))
(for-range i 8
(set! v[(+ i 1)] (- (<< 1 (+ 1 i)) 1))
)
v))
(define (huffman-encode s)
(let ((data '())
(left 8)
(byte 0))
(define (emit-byte)
(push! data (int->char byte))
(set! left 8)
(set! byte 0))
(define (emit n bits)
(while (> bits 0)
(let ((slice (min left bits))
(shift (- bits slice)))
(set! byte (<< byte slice))
(set! byte (logior byte (logand (>> n shift) masks[slice])))
(dec! bits slice)
(dec! left slice)
(when (= left 0) (emit-byte))
)))
(define (encode s)
(for-string ch s
(match huffman-map[(char->int ch)] with
(:pair n bits)
-> (emit n bits))))
(define (done)
(if (< left 8)
(emit #xffffffff left))
(list->string (reverse data)))
(encode s)
(done)
))
(define (huffman-decode s pos nbytes)
(let ((r '())
(bits (* nbytes 8))
(bpos -1)
(byte 0))
(define (get-bit)
(when (< bpos 0) (next-byte))
(let ((set? (= 1 (logand 1 (>> byte bpos)))))
(dec! bpos)
(dec! bits)
set?
))
(define (next-byte)
(set! byte (char->int (string-ref s pos)))
(inc! pos)
(set! bpos 7)
)
;; note: after the last encoded character, there may be remaining
;; bits, we have no way of knowing ahead of time if they encode a
;; character, so we have to peel them off (i.e., we descend
partway down the tree toward ` EOS ` )
shortest code is 5 bits .
(let loop ((t huffman-table))
(match t with
(hufftree:leaf val) -> (push! r (int->char val))
(hufftree:node L R) -> (if (> bits 0) (loop (if (get-bit) R L)))
)))
(list->string (reverse r))
))
;; api for dynamic table:
;; get
;; set
;; get-index
count of one name
;; set-size
OK , how about this : we use two maps , just like cmap .
;; fwd, rev. Then we have a 'clock'. when you put something
;; in, you store its clock. To reference it, you pull it out
;; by clock - index.
;; to insert an entry,
;; we store it in fwd as (key,val) -> clock
;; rev as clock -> (key, val)
;;
(define (make-dynamic-table max-size)
(let ((fwd (tree/empty))
(rev (tree/empty))
(clock 0)
(size 0))
(define (entry-size name val)
(+ 32 (string-length name) (string-length val)))
(define (evict-one)
(let (((index key) (tree/min rev))
((name val) key)
(esize (entry-size name val)))
;;(printf "evicting " (int esize) " bytes.\n")
(tree/delete! fwd magic-cmp key)
(tree/delete! rev int-cmp index)
(dec! size esize)
))
(define (dump)
(printf "table " (int clock) " {\n")
(for-map index pair rev
(let (((name val) pair))
(printf (int index) "/" (int (- clock index 1)) " " name ": " val "\n")))
(printf "}\n")
)
(define (set name val)
(let ((key (:tuple name val))
(esize (entry-size name val)))
(while (> (+ size esize) max-size)
(evict-one))
(tree/insert! fwd magic-cmp key clock)
(tree/insert! rev int-cmp clock key)
(inc! clock)
(inc! size esize)
;;(dump)
))
(define (get index)
;;(printf "get " (int index) " nstatic " (int nstatic) "\n")
(if (< index nstatic)
*static-table*[index]
(let ((index0 (- index nstatic))
(index1 (- clock index0 1)))
( printf " clock " ( int clock ) " index0 " ( int index0 ) " index1 " ( int ) " \n " )
(match (tree/member rev int-cmp index1) with
(maybe:yes pair) -> pair
(maybe:no) -> (raise (:Hpack/BadIndex index))
))))
(define (set-size new-max-size)
;;(printf "set-size " (int new-max-size) "\n")
(set! max-size new-max-size)
(while (> size max-size)
(evict-one)))
;; -------------------------------------------
;; everything below is to support `get-index`
;; -------------------------------------------
(define (lookup-static name val)
(tree/member *static-map* magic-cmp (:tuple name val)))
(define (lookup-dynamic name val)
(tree/member fwd magic-cmp (:tuple name val)))
;; return a list of entries with `name`.
(define (name-range map name)
(let ((range '()))
(tree/range
map magic-cmp
(:tuple name "") (:tuple name "\xff")
(lambda (k v) (push! range (:tuple k v))))
(reverse range)))
(define (lookup-name-only map name)
(match (name-range map name) with
;; XXX possible optimization: choose the most recent index,
;; which will remain in the table longer.
() -> (maybe:no)
((:tuple key index) . _) -> (maybe:yes index)
))
;; how many entries do we have under this name?
(define (nvals name)
(length (name-range fwd name)))
(define (get-static-index name val)
(match (lookup-static name val) with
(maybe:yes index) -> (:tuple (maybe:yes index) #t)
(maybe:no)
-> (:tuple (lookup-name-only *static-map* name) #f)
))
(define (get-dynamic-index name val)
(match (lookup-dynamic name val) with
(maybe:yes index) -> (:tuple (maybe:yes index) #t)
(maybe:no)
-> (:tuple (lookup-name-only fwd name) #f)
))
;; adjust dynamic index to reflect
1 ) offset after static table
2 ) our clock - based indexing scheme .
(define adjust
(maybe:yes index) -> (maybe:yes (+ nstatic (- clock index 1)))
no -> no
)
(define (get-index name val)
(match (get-static-index name val) with
;; both present static
(:tuple probe0 #t) -> (:tuple probe0 #t)
(:tuple probe0 #f)
-> (let (((probe1 both1) (get-dynamic-index name val)))
( printf " get - index both1= " ( ) " " )
( printn ( list ) )
(cond (both1
;; both present in dynamic
(:tuple (adjust probe1) #t))
((maybe? probe0)
;; name only, prefer static
(:tuple probe0 #f))
((maybe? probe1)
;; name only in dynamic
(:tuple (adjust probe1) #f))
(else
;; nothing in either table
(:tuple (maybe:no) #f)))
)))
{get=get set=set set-size=set-size get-index=get-index nvals=nvals}
))
one function , ' unpack ' . so we probably do n't need a record .
(define (hpack/decoder)
(let ((data "")
(pos -1)
(byte 0)
(stop 0)
(table (make-dynamic-table 4096)))
(define (forward n)
(inc! pos n)
(if (< pos stop)
(set! byte (char->int (string-ref data pos)))))
(define (next-byte)
(forward 1))
(define (get-integer nbits)
(let ((mask masks[nbits])
(r (logand mask byte)))
(cond ((= r mask) ;; more octets
(set! r 0)
;; note: little-endian encoding!
(let loop ((m 0)) ;; XXX length check
(next-byte)
(set! r (logior r (<< (logand #x7f byte) m)))
(if (not (= 0 (logand #x80 byte)))
(loop (+ m 7))))
(next-byte)
(+ r mask))
(else
(next-byte)
r))))
(define (get-pair0 index)
;;(printf "get-pair0 " (int index) "\n")
(let ((name (if (= index 0)
(get-literal)
(match (table.get index) with
(:tuple name1 _) -> name1))))
(:tuple name (get-literal))
))
(define (get-literal)
(let ((huffman? (= (logand #x80 byte) #x80))
(len (get-integer 7))
(r (if huffman?
(huffman-decode data pos len)
(substring data pos (+ pos len)))))
(forward len)
;;(printf " --> " (string r) "\n")
r))
(define (get-header)
;;(printf "get-header byte = " (hex byte) "\n")
(cond ((= 1 (>> byte 7))
;; index name and value
(let ((index (get-integer 7)))
( printf " 7 " ( int index ) " \n " )
(table.get index)))
((= 1 (>> byte 6))
;; literal with incremental indexing
(let ((index (get-integer 6))
(key (get-pair0 index))
((name val) key))
( printf " 6 " ( int index ) " name " name " " ( string ) " \n " )
(table.set name val)
key))
((< (>> byte 4) 2)
;; literal without indexing
(let ((never (= 1 (>> byte 4)))
(index (get-integer 4)))
( printf " 4 " ( int index ) " \n " )
(get-pair0 index)))
(else
(raise (:Hpack/BadHeaderCode byte)))))
(define (unpack s)
(let ((r '()))
(set! data s)
(set! pos -1)
(set! stop (string-length data))
(next-byte)
(while (< pos stop)
(cond ((= 1 (>> byte 5))
(table.set-size (get-integer 5)))
(else
(let ((r0 (get-header)))
(push! r r0)))))
(reverse r)))
unpack
))
;; does h2 allow specifying a standard size before-hand?
(define (hpack/encoder)
(let ((table (make-dynamic-table 4096))
(max-vals 5)
(data '()) ;; XXX use a buffer object
(never (set/empty)))
(define (emit byte)
(push! data (int->char byte)))
(define (emit-string s)
(for-string ch s
(push! data ch)))
(define (emit-integer n0 bits n1)
(let ((mask masks[bits]))
(cond ((< n1 mask)
(emit (logior n1 (<< n0 bits))))
(else
(emit (logior mask (<< n0 bits)))
(dec! n1 mask)
encode the remaining bits 7 at a time ...
(while (>= n1 #x80)
(emit (logior (logand n1 #x7f) #x80))
(set! n1 (>> n1 7)))
;; and any leftover (or 0).
(emit n1)))))
(define (emit-literal s0)
(let ((len0 (string-length s0))
(s1 (huffman-encode s0))
(len1 (string-length s1)))
(cond ((>= len1 len0)
oops , not - friendly
(emit-integer 0 7 len0)
(emit-string s0))
(else
(emit-integer 1 7 len1)
(emit-string s1)))))
(define (emit-header name val)
;;(printf "emit-header " name " " val "\n")
(cond ((set/member? never string-compare name)
;; literal name & value: never index
;;(printf "*** never " name " " val "\n")
(emit-integer 1 4 0)
(emit-literal name)
(emit-literal val))
(else
(match (table.get-index name val) with
(:tuple (maybe:yes index) #t)
-> (begin
;;(printf "*** both index " (int index) "\n")
(emit-integer 1 7 index)
)
(:tuple (maybe:yes index) #f)
-> (cond ((>= (table.nvals name) max-vals)
;; a header like `date`, which varies.
( printf " * * * ! index " ( int index ) " " ( string ) " \n " )
(emit-integer 0 4 index)
(emit-literal val))
(else
;; index name, literal value.
( printf " * * * index " ( int index ) " " ( string ) " \n " )
(table.set name val)
(emit-integer 1 6 index)
(emit-literal val)))
(:tuple (maybe:no) _)
-> (begin
;; index literal name & value
;;(printf "*** new " name " " val "\n")
(table.set name val)
(emit-integer 1 6 0)
(emit-literal name)
(emit-literal val))
))))
(define (pack headers)
;; rfc7540 8.1.2.1 Pseudo-Header Fields
;; requires that pseudo-headers precede normal headers.
(let ((pseudo '())
(normal '()))
(for-list header headers
(match header with
(:tuple name val)
-> (if (eq? (string-ref name 0) #\:)
(push! pseudo header)
(push! normal header))))
(for-list header (append (reverse pseudo) (reverse normal))
(match header with
(:tuple name val)
-> (emit-header name val)))
(let ((r (list->string (reverse data))))
(set! data '())
r)))
pack
))
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/doom/http/hpack.scm | scheme | -*- Mode: Irken -*-
RFC 7541
XXX need to support SETTINGS_MAX_HEADER_LIST_SIZE
in order to defend against an 'hpack bomb'.
a map from header-pair to index in the static table.
XXX investigate: this is supposed to be a 'canonical' huffman
encoding, which is supposed to have a very compact representation,
where each entry consists of 'key', 'bits'.
this should go somewhere else
note: after the last encoded character, there may be remaining
bits, we have no way of knowing ahead of time if they encode a
character, so we have to peel them off (i.e., we descend
api for dynamic table:
get
set
get-index
set-size
fwd, rev. Then we have a 'clock'. when you put something
in, you store its clock. To reference it, you pull it out
by clock - index.
to insert an entry,
we store it in fwd as (key,val) -> clock
rev as clock -> (key, val)
(printf "evicting " (int esize) " bytes.\n")
(dump)
(printf "get " (int index) " nstatic " (int nstatic) "\n")
(printf "set-size " (int new-max-size) "\n")
-------------------------------------------
everything below is to support `get-index`
-------------------------------------------
return a list of entries with `name`.
XXX possible optimization: choose the most recent index,
which will remain in the table longer.
how many entries do we have under this name?
adjust dynamic index to reflect
both present static
both present in dynamic
name only, prefer static
name only in dynamic
nothing in either table
more octets
note: little-endian encoding!
XXX length check
(printf "get-pair0 " (int index) "\n")
(printf " --> " (string r) "\n")
(printf "get-header byte = " (hex byte) "\n")
index name and value
literal with incremental indexing
literal without indexing
does h2 allow specifying a standard size before-hand?
XXX use a buffer object
and any leftover (or 0).
(printf "emit-header " name " " val "\n")
literal name & value: never index
(printf "*** never " name " " val "\n")
(printf "*** both index " (int index) "\n")
a header like `date`, which varies.
index name, literal value.
index literal name & value
(printf "*** new " name " " val "\n")
rfc7540 8.1.2.1 Pseudo-Header Fields
requires that pseudo-headers precede normal headers. |
(define (H a b)
(:tuple a b))
(define *static-table*
#((H "" "")
(H ":authority" "")
(H ":method" "GET")
(H ":method" "POST")
(H ":path" "/")
(H ":path" "/index.html")
(H ":scheme" "http")
(H ":scheme" "https")
(H ":status" "200")
(H ":status" "204")
(H ":status" "206")
(H ":status" "304")
(H ":status" "400")
(H ":status" "404")
(H ":status" "500")
(H "accept-charset" "")
(H "accept-encoding" "gzip, deflate")
(H "accept-language" "")
(H "accept-ranges" "")
(H "accept" "")
(H "access-control-allow-origin" "")
(H "age" "")
(H "allow" "")
(H "authorization" "")
(H "cache-control" "")
(H "content-disposition" "")
(H "content-encoding" "")
(H "content-language" "")
(H "content-length" "")
(H "content-location" "")
(H "content-range" "")
(H "content-type" "")
(H "cookie" "")
(H "date" "")
(H "etag" "")
(H "expect" "")
(H "expires" "")
(H "from" "")
(H "host" "")
(H "if-match" "")
(H "if-modified-since" "")
(H "if-none-match" "")
(H "if-range" "")
(H "if-unmodified-since" "")
(H "last-modified" "")
(H "link" "")
(H "location" "")
(H "max-forwards" "")
(H "proxy-authenticate" "")
(H "proxy-authorization" "")
(H "range" "")
(H "referer" "")
(H "refresh" "")
(H "retry-after" "")
(H "server" "")
(H "set-cookie" "")
(H "strict-transport-security" "")
(H "transfer-encoding" "")
(H "user-agent" "")
(H "vary" "")
(H "via" "")
(H "www-authenticate" "")
))
(define nstatic 62)
(assert (= nstatic (vector-length *static-table*)))
(define *static-map*
(let ((m (tree/empty)))
(for-range i nstatic
(tree/insert! m magic-cmp *static-table*[i] i))
m))
(define huffman-table-ascii
(string-append
".....3031.3261..6365.696f...7374..2025.2d2e...2f33.3435..3637.38"
"39.....3d41.5f62..6466.6768...6c6d.6e70..7275..3a42.4344.....454"
"6.4748..494a.4b4c...4d4e.4f50..5152.5354....5556.5759..6a6b.7176"
"...7778.797a...262a.2c3b..585a...2122.2829..3f.272b..7c.233e...0"
"024.405b..5d7e..5e7d..3c60.7b....5cc3.d0.8082...83a2.b8c2..e0e2."
".99a1.a7ac.....b0b1.b3d1..d8d9.e3e5...e6.8184..8586.8892...9a9c."
"a0a3..a4a9.aaad.....b2b5.b9ba..bbbd.bec4...c6e4.e8e9...0187.898a"
"..8b8c.8d8f.....9395.9697..989b.9d9e...a5a6.a8ae..afb4.b6b7....b"
"cbf.c5e7..ef.098e..9091.949f....abce.d7e1..eced..c7cf.eaeb.....c"
"0c1.c8c9..cacd.d2d5...dadb.eef0..f2f3.ff.cbcc.....d3d4.d6dd..ded"
"f.f1f4...f5f6.f7f8..fafb.fcfd....fe.0203..0405.0607...080b.0c0e."
".0f10.1112....1314.1517..1819.1a1b...1c1d.1e1f..7fdc.f9..0a0d.16Z"))
(datatype hufftree
(:node hufftree hufftree)
(:leaf int)
)
(define hexdig->int
#\0 -> 0
#\1 -> 1
#\2 -> 2
#\3 -> 3
#\4 -> 4
#\5 -> 5
#\6 -> 6
#\7 -> 7
#\8 -> 8
#\9 -> 9
#\a -> 10
#\b -> 11
#\c -> 12
#\d -> 13
#\e -> 14
#\f -> 15
x -> (raise (:BadHexDigit))
)
(define (2hex->int s pos)
(logior
(<< (hexdig->int (string-ref s pos)) 4)
(hexdig->int (string-ref s (+ pos 1)))))
(define (ascii->tree s pos)
(let recur ()
(match (string-ref s pos) with
#\. -> (begin
(set! pos (+ 1 pos))
(hufftree:node (recur) (recur)))
#\Z -> (hufftree:leaf 256)
_ -> (let ((r (hufftree:leaf (2hex->int s pos))))
(set! pos (+ pos 2))
r)
)))
(define huffman-table (ascii->tree huffman-table-ascii 0))
(define huffman-map
(let ((m (make-vector 257 (:pair 0 0))))
(let loop ((t huffman-table)
(n 0)
(bits 0))
(match t with
(hufftree:leaf val)
-> (set! m[val] (:pair n bits))
(hufftree:node L R)
-> (begin
(loop L (logior 0 (<< n 1)) (+ bits 1))
(loop R (logior 1 (<< n 1)) (+ bits 1)))
))
m))
(define masks
(let ((v (make-vector 9 0)))
(for-range i 8
(set! v[(+ i 1)] (- (<< 1 (+ 1 i)) 1))
)
v))
(define (huffman-encode s)
(let ((data '())
(left 8)
(byte 0))
(define (emit-byte)
(push! data (int->char byte))
(set! left 8)
(set! byte 0))
(define (emit n bits)
(while (> bits 0)
(let ((slice (min left bits))
(shift (- bits slice)))
(set! byte (<< byte slice))
(set! byte (logior byte (logand (>> n shift) masks[slice])))
(dec! bits slice)
(dec! left slice)
(when (= left 0) (emit-byte))
)))
(define (encode s)
(for-string ch s
(match huffman-map[(char->int ch)] with
(:pair n bits)
-> (emit n bits))))
(define (done)
(if (< left 8)
(emit #xffffffff left))
(list->string (reverse data)))
(encode s)
(done)
))
(define (huffman-decode s pos nbytes)
(let ((r '())
(bits (* nbytes 8))
(bpos -1)
(byte 0))
(define (get-bit)
(when (< bpos 0) (next-byte))
(let ((set? (= 1 (logand 1 (>> byte bpos)))))
(dec! bpos)
(dec! bits)
set?
))
(define (next-byte)
(set! byte (char->int (string-ref s pos)))
(inc! pos)
(set! bpos 7)
)
partway down the tree toward ` EOS ` )
shortest code is 5 bits .
(let loop ((t huffman-table))
(match t with
(hufftree:leaf val) -> (push! r (int->char val))
(hufftree:node L R) -> (if (> bits 0) (loop (if (get-bit) R L)))
)))
(list->string (reverse r))
))
count of one name
OK , how about this : we use two maps , just like cmap .
(define (make-dynamic-table max-size)
(let ((fwd (tree/empty))
(rev (tree/empty))
(clock 0)
(size 0))
(define (entry-size name val)
(+ 32 (string-length name) (string-length val)))
(define (evict-one)
(let (((index key) (tree/min rev))
((name val) key)
(esize (entry-size name val)))
(tree/delete! fwd magic-cmp key)
(tree/delete! rev int-cmp index)
(dec! size esize)
))
(define (dump)
(printf "table " (int clock) " {\n")
(for-map index pair rev
(let (((name val) pair))
(printf (int index) "/" (int (- clock index 1)) " " name ": " val "\n")))
(printf "}\n")
)
(define (set name val)
(let ((key (:tuple name val))
(esize (entry-size name val)))
(while (> (+ size esize) max-size)
(evict-one))
(tree/insert! fwd magic-cmp key clock)
(tree/insert! rev int-cmp clock key)
(inc! clock)
(inc! size esize)
))
(define (get index)
(if (< index nstatic)
*static-table*[index]
(let ((index0 (- index nstatic))
(index1 (- clock index0 1)))
( printf " clock " ( int clock ) " index0 " ( int index0 ) " index1 " ( int ) " \n " )
(match (tree/member rev int-cmp index1) with
(maybe:yes pair) -> pair
(maybe:no) -> (raise (:Hpack/BadIndex index))
))))
(define (set-size new-max-size)
(set! max-size new-max-size)
(while (> size max-size)
(evict-one)))
(define (lookup-static name val)
(tree/member *static-map* magic-cmp (:tuple name val)))
(define (lookup-dynamic name val)
(tree/member fwd magic-cmp (:tuple name val)))
(define (name-range map name)
(let ((range '()))
(tree/range
map magic-cmp
(:tuple name "") (:tuple name "\xff")
(lambda (k v) (push! range (:tuple k v))))
(reverse range)))
(define (lookup-name-only map name)
(match (name-range map name) with
() -> (maybe:no)
((:tuple key index) . _) -> (maybe:yes index)
))
(define (nvals name)
(length (name-range fwd name)))
(define (get-static-index name val)
(match (lookup-static name val) with
(maybe:yes index) -> (:tuple (maybe:yes index) #t)
(maybe:no)
-> (:tuple (lookup-name-only *static-map* name) #f)
))
(define (get-dynamic-index name val)
(match (lookup-dynamic name val) with
(maybe:yes index) -> (:tuple (maybe:yes index) #t)
(maybe:no)
-> (:tuple (lookup-name-only fwd name) #f)
))
1 ) offset after static table
2 ) our clock - based indexing scheme .
(define adjust
(maybe:yes index) -> (maybe:yes (+ nstatic (- clock index 1)))
no -> no
)
(define (get-index name val)
(match (get-static-index name val) with
(:tuple probe0 #t) -> (:tuple probe0 #t)
(:tuple probe0 #f)
-> (let (((probe1 both1) (get-dynamic-index name val)))
( printf " get - index both1= " ( ) " " )
( printn ( list ) )
(cond (both1
(:tuple (adjust probe1) #t))
((maybe? probe0)
(:tuple probe0 #f))
((maybe? probe1)
(:tuple (adjust probe1) #f))
(else
(:tuple (maybe:no) #f)))
)))
{get=get set=set set-size=set-size get-index=get-index nvals=nvals}
))
one function , ' unpack ' . so we probably do n't need a record .
(define (hpack/decoder)
(let ((data "")
(pos -1)
(byte 0)
(stop 0)
(table (make-dynamic-table 4096)))
(define (forward n)
(inc! pos n)
(if (< pos stop)
(set! byte (char->int (string-ref data pos)))))
(define (next-byte)
(forward 1))
(define (get-integer nbits)
(let ((mask masks[nbits])
(r (logand mask byte)))
(set! r 0)
(next-byte)
(set! r (logior r (<< (logand #x7f byte) m)))
(if (not (= 0 (logand #x80 byte)))
(loop (+ m 7))))
(next-byte)
(+ r mask))
(else
(next-byte)
r))))
(define (get-pair0 index)
(let ((name (if (= index 0)
(get-literal)
(match (table.get index) with
(:tuple name1 _) -> name1))))
(:tuple name (get-literal))
))
(define (get-literal)
(let ((huffman? (= (logand #x80 byte) #x80))
(len (get-integer 7))
(r (if huffman?
(huffman-decode data pos len)
(substring data pos (+ pos len)))))
(forward len)
r))
(define (get-header)
(cond ((= 1 (>> byte 7))
(let ((index (get-integer 7)))
( printf " 7 " ( int index ) " \n " )
(table.get index)))
((= 1 (>> byte 6))
(let ((index (get-integer 6))
(key (get-pair0 index))
((name val) key))
( printf " 6 " ( int index ) " name " name " " ( string ) " \n " )
(table.set name val)
key))
((< (>> byte 4) 2)
(let ((never (= 1 (>> byte 4)))
(index (get-integer 4)))
( printf " 4 " ( int index ) " \n " )
(get-pair0 index)))
(else
(raise (:Hpack/BadHeaderCode byte)))))
(define (unpack s)
(let ((r '()))
(set! data s)
(set! pos -1)
(set! stop (string-length data))
(next-byte)
(while (< pos stop)
(cond ((= 1 (>> byte 5))
(table.set-size (get-integer 5)))
(else
(let ((r0 (get-header)))
(push! r r0)))))
(reverse r)))
unpack
))
(define (hpack/encoder)
(let ((table (make-dynamic-table 4096))
(max-vals 5)
(never (set/empty)))
(define (emit byte)
(push! data (int->char byte)))
(define (emit-string s)
(for-string ch s
(push! data ch)))
(define (emit-integer n0 bits n1)
(let ((mask masks[bits]))
(cond ((< n1 mask)
(emit (logior n1 (<< n0 bits))))
(else
(emit (logior mask (<< n0 bits)))
(dec! n1 mask)
encode the remaining bits 7 at a time ...
(while (>= n1 #x80)
(emit (logior (logand n1 #x7f) #x80))
(set! n1 (>> n1 7)))
(emit n1)))))
(define (emit-literal s0)
(let ((len0 (string-length s0))
(s1 (huffman-encode s0))
(len1 (string-length s1)))
(cond ((>= len1 len0)
oops , not - friendly
(emit-integer 0 7 len0)
(emit-string s0))
(else
(emit-integer 1 7 len1)
(emit-string s1)))))
(define (emit-header name val)
(cond ((set/member? never string-compare name)
(emit-integer 1 4 0)
(emit-literal name)
(emit-literal val))
(else
(match (table.get-index name val) with
(:tuple (maybe:yes index) #t)
-> (begin
(emit-integer 1 7 index)
)
(:tuple (maybe:yes index) #f)
-> (cond ((>= (table.nvals name) max-vals)
( printf " * * * ! index " ( int index ) " " ( string ) " \n " )
(emit-integer 0 4 index)
(emit-literal val))
(else
( printf " * * * index " ( int index ) " " ( string ) " \n " )
(table.set name val)
(emit-integer 1 6 index)
(emit-literal val)))
(:tuple (maybe:no) _)
-> (begin
(table.set name val)
(emit-integer 1 6 0)
(emit-literal name)
(emit-literal val))
))))
(define (pack headers)
(let ((pseudo '())
(normal '()))
(for-list header headers
(match header with
(:tuple name val)
-> (if (eq? (string-ref name 0) #\:)
(push! pseudo header)
(push! normal header))))
(for-list header (append (reverse pseudo) (reverse normal))
(match header with
(:tuple name val)
-> (emit-header name val)))
(let ((r (list->string (reverse data))))
(set! data '())
r)))
pack
))
|
72a330632d0e051a32ffa53473d340b12a5747f6215bc4a4f6444e1769739c05 | GaloisInc/cryptol | RunLexer.hs | -- |
-- Module : Main
Copyright : ( c ) 2013 - 2016 Galois , Inc.
-- License : BSD3
-- Maintainer :
-- Stability : provisional
-- Portability : portable
import Cryptol.Parser.Lexer
import Cryptol.Parser.PP
main :: IO ()
main = interact (unlines . map (show . pp) . fst . primLexer)
| null | https://raw.githubusercontent.com/GaloisInc/cryptol/8cca24568ad499f06032c2e4eaa7dfd4c542efb6/tests/parser/RunLexer.hs | haskell | |
Module : Main
License : BSD3
Maintainer :
Stability : provisional
Portability : portable | Copyright : ( c ) 2013 - 2016 Galois , Inc.
import Cryptol.Parser.Lexer
import Cryptol.Parser.PP
main :: IO ()
main = interact (unlines . map (show . pp) . fst . primLexer)
|
59b2a367766a825ea2a520557aa9d7dd2a4e61888fdb3758723fef89b1f63db5 | birthevdb/Latent-Effect-and-Handlers | Reader.hs | {-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeOperators #
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE FlexibleContexts #
module Effects.Reader where
import General
data Reading r :: * -> (* -> *) -> * where
Local :: (r -> r) -> Reading r a (OneSub a)
Ask :: Reading r r NoSub
hRead :: Functor l
=> r
-> Tree (Reading r :++: σ) l (l a)
-> Tree σ l (l a)
hRead r (Leaf x) = Leaf x
hRead r (Node (Inl' (Local f)) l st k) = hRead (f r) (st One l) >>= hRead r . k
hRead r (Node (Inl' Ask) l _ k) = hRead r (k (r <$ l))
hRead r (Node (Inr' op) l st k) =
Node op l (\ c2 -> hRead r . st c2) (hRead r . k)
local :: forall r σ a. (Reading r :<<: σ) => (r -> r) -> Tree σ Id a -> Tree σ Id a
local f t = oneSubNode (Local f) t
ask :: (Reading r :<<: σ) => Tree σ Id r
ask = noSubNode Ask
| null | https://raw.githubusercontent.com/birthevdb/Latent-Effect-and-Handlers/398167aa3a18572afa1ecc9ecdd6b37c97495f90/Effects/Reader.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE GADTs # | # LANGUAGE TypeOperators #
# LANGUAGE KindSignatures #
# LANGUAGE FlexibleContexts #
module Effects.Reader where
import General
data Reading r :: * -> (* -> *) -> * where
Local :: (r -> r) -> Reading r a (OneSub a)
Ask :: Reading r r NoSub
hRead :: Functor l
=> r
-> Tree (Reading r :++: σ) l (l a)
-> Tree σ l (l a)
hRead r (Leaf x) = Leaf x
hRead r (Node (Inl' (Local f)) l st k) = hRead (f r) (st One l) >>= hRead r . k
hRead r (Node (Inl' Ask) l _ k) = hRead r (k (r <$ l))
hRead r (Node (Inr' op) l st k) =
Node op l (\ c2 -> hRead r . st c2) (hRead r . k)
local :: forall r σ a. (Reading r :<<: σ) => (r -> r) -> Tree σ Id a -> Tree σ Id a
local f t = oneSubNode (Local f) t
ask :: (Reading r :<<: σ) => Tree σ Id r
ask = noSubNode Ask
|
7badb05fc455c00e6710f8182684b288bad957667aa3e0d054be140cd8afcd08 | fortytools/holumbus | Grammar.hs | -- ----------------------------------------------------------------------------
|
Module : Holumbus . Query . Language . Grammar
Copyright : Copyright ( C ) 2007 , 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.2
The Holumbus query language definition .
The specific syntax of any query language can be designed independently
by creating appropriate parsers . Also see " Holumbus . Query . Language . " .
Module : Holumbus.Query.Language.Grammar
Copyright : Copyright (C) 2007, 2008 Timo B. Huebel
License : MIT
Maintainer : Timo B. Huebel ()
Stability : experimental
Portability: portable
Version : 0.2
The Holumbus query language definition.
The specific syntax of any query language can be designed independently
by creating appropriate parsers. Also see "Holumbus.Query.Language.Parser".
-}
-- ----------------------------------------------------------------------------
module Holumbus.Query.Language.Grammar
(
-- * Query data types
Query (Word, Phrase, CaseWord, CasePhrase, FuzzyWord, Specifier, Negation, BinQuery)
, BinOp (And, Or, But)
-- * Optimizing
, optimize
, checkWith
, extractTerms
)
where
import Data.Char
import Data.List
import Data.Binary
import Control.Monad
import Holumbus.Index.Common (Context)
-- | The query language.
data Query = Word String -- ^ Single case-insensitive word.
| Phrase String -- ^ Single case-insensitive phrase.
| CaseWord String -- ^ Single case-sensitive word.
| CasePhrase String -- ^ Single case-sensitive phrase.
| FuzzyWord String -- ^ Single fuzzy word.
| Specifier [Context] Query -- ^ Restrict query to a list of contexts.
| Negation Query -- ^ Negate the query.
^ Combine two queries through a binary operation .
deriving (Eq, Show)
-- | A binary operation.
data BinOp = And -- ^ Intersect two queries.
^ Union two queries .
^ Filter a query by another , @q1 BUT q2@ is equivalent to @q1 AND NOT q2@.
deriving (Eq, Show)
instance Binary Query where
put (Word s) = put (0 :: Word8) >> put s
put (Phrase s) = put (1 :: Word8) >> put s
put (CaseWord s) = put (2 :: Word8) >> put s
put (CasePhrase s) = put (3 :: Word8) >> put s
put (FuzzyWord s) = put (4 :: Word8) >> put s
put (Specifier c q) = put (5 :: Word8) >> put c >> put q
put (Negation q) = put (6 :: Word8) >> put q
put (BinQuery o q1 q2) = put (7 :: Word8) >> put o >> put q1 >> put q2
get = do tag <- getWord8
case tag of
0 -> liftM Word get
1 -> liftM Phrase get
2 -> liftM CaseWord get
3 -> liftM CasePhrase get
4 -> liftM FuzzyWord get
5 -> liftM2 Specifier get get
6 -> liftM Negation get
7 -> liftM3 BinQuery get get get
_ -> fail "Error while decoding Query"
instance Binary BinOp where
put And = put (0 :: Word8)
put Or = put (1 :: Word8)
put But = put (2 :: Word8)
get = do tag <- getWord8
case tag of
0 -> return And
1 -> return Or
2 -> return But
_ -> fail "Error while decoding BinOp"
| Transforms all @(BinQuery And q1 where one of @q1@ or @q2@ is a @Negation@ into
-- @BinQuery Filter q1 q2@ or @BinQuery Filter q2 q1@ respectively.
optimize :: Query -> Query
optimize q@(BinQuery And (Word q1) (Word q2)) =
if (map toLower q1) `isPrefixOf` (map toLower q2) then Word q2 else
if (map toLower q2) `isPrefixOf` (map toLower q1) then Word q1 else q
optimize q@(BinQuery And (CaseWord q1) (CaseWord q2)) =
if q1 `isPrefixOf` q2 then CaseWord q2 else
if q2 `isPrefixOf` q1 then CaseWord q1 else q
optimize q@(BinQuery Or (Word q1) (Word q2)) =
if (map toLower q1) `isPrefixOf` (map toLower q2) then Word q1 else
if (map toLower q2) `isPrefixOf` (map toLower q1) then Word q2 else q
optimize q@(BinQuery Or (CaseWord q1) (CaseWord q2)) =
if q1 `isPrefixOf` q2 then CaseWord q1 else
if q2 `isPrefixOf` q1 then CaseWord q2 else q
optimize (BinQuery And q1 (Negation q2)) = BinQuery But (optimize q1) (optimize q2)
optimize (BinQuery And (Negation q1) q2) = BinQuery But (optimize q2) (optimize q1)
optimize (BinQuery And q1 q2) = BinQuery And (optimize q1) (optimize q2)
optimize (BinQuery Or q1 q2) = BinQuery Or (optimize q1) (optimize q2)
optimize (BinQuery But q1 q2) = BinQuery But (optimize q1) (optimize q2)
optimize (Negation q) = Negation (optimize q)
optimize (Specifier cs q) = Specifier cs (optimize q)
optimize q = q
-- | Check if the query arguments comply with some custom predicate.
checkWith :: (String -> Bool) -> Query -> Bool
checkWith f (Word s) = f s
checkWith f (Phrase s) = f s
checkWith f (CaseWord s) = f s
checkWith f (CasePhrase s) = f s
checkWith f (FuzzyWord s) = f s
checkWith f (Negation q) = checkWith f q
checkWith f (BinQuery _ q1 q2) = (checkWith f q1) && (checkWith f q2)
checkWith f (Specifier _ q) = checkWith f q
-- | Returns a list of all terms in the query.
extractTerms :: Query -> [String]
extractTerms (Word s) = [s]
extractTerms (CaseWord s) = [s]
extractTerms (FuzzyWord s) = [s]
extractTerms (Specifier _ q) = extractTerms q
extractTerms (Negation q) = extractTerms q
extractTerms (BinQuery _ q1 q2) = (extractTerms q1) ++ (extractTerms q2)
extractTerms _ = []
| null | https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/searchengine/source/Holumbus/Query/Language/Grammar.hs | haskell | ----------------------------------------------------------------------------
----------------------------------------------------------------------------
* Query data types
* Optimizing
| The query language.
^ Single case-insensitive word.
^ Single case-insensitive phrase.
^ Single case-sensitive word.
^ Single case-sensitive phrase.
^ Single fuzzy word.
^ Restrict query to a list of contexts.
^ Negate the query.
| A binary operation.
^ Intersect two queries.
@BinQuery Filter q1 q2@ or @BinQuery Filter q2 q1@ respectively.
| Check if the query arguments comply with some custom predicate.
| Returns a list of all terms in the query. |
|
Module : Holumbus . Query . Language . Grammar
Copyright : Copyright ( C ) 2007 , 2008
License : MIT
Maintainer : ( )
Stability : experimental
Portability : portable
Version : 0.2
The Holumbus query language definition .
The specific syntax of any query language can be designed independently
by creating appropriate parsers . Also see " Holumbus . Query . Language . " .
Module : Holumbus.Query.Language.Grammar
Copyright : Copyright (C) 2007, 2008 Timo B. Huebel
License : MIT
Maintainer : Timo B. Huebel ()
Stability : experimental
Portability: portable
Version : 0.2
The Holumbus query language definition.
The specific syntax of any query language can be designed independently
by creating appropriate parsers. Also see "Holumbus.Query.Language.Parser".
-}
module Holumbus.Query.Language.Grammar
(
Query (Word, Phrase, CaseWord, CasePhrase, FuzzyWord, Specifier, Negation, BinQuery)
, BinOp (And, Or, But)
, optimize
, checkWith
, extractTerms
)
where
import Data.Char
import Data.List
import Data.Binary
import Control.Monad
import Holumbus.Index.Common (Context)
^ Combine two queries through a binary operation .
deriving (Eq, Show)
^ Union two queries .
^ Filter a query by another , @q1 BUT q2@ is equivalent to @q1 AND NOT q2@.
deriving (Eq, Show)
instance Binary Query where
put (Word s) = put (0 :: Word8) >> put s
put (Phrase s) = put (1 :: Word8) >> put s
put (CaseWord s) = put (2 :: Word8) >> put s
put (CasePhrase s) = put (3 :: Word8) >> put s
put (FuzzyWord s) = put (4 :: Word8) >> put s
put (Specifier c q) = put (5 :: Word8) >> put c >> put q
put (Negation q) = put (6 :: Word8) >> put q
put (BinQuery o q1 q2) = put (7 :: Word8) >> put o >> put q1 >> put q2
get = do tag <- getWord8
case tag of
0 -> liftM Word get
1 -> liftM Phrase get
2 -> liftM CaseWord get
3 -> liftM CasePhrase get
4 -> liftM FuzzyWord get
5 -> liftM2 Specifier get get
6 -> liftM Negation get
7 -> liftM3 BinQuery get get get
_ -> fail "Error while decoding Query"
instance Binary BinOp where
put And = put (0 :: Word8)
put Or = put (1 :: Word8)
put But = put (2 :: Word8)
get = do tag <- getWord8
case tag of
0 -> return And
1 -> return Or
2 -> return But
_ -> fail "Error while decoding BinOp"
| Transforms all @(BinQuery And q1 where one of @q1@ or @q2@ is a @Negation@ into
optimize :: Query -> Query
optimize q@(BinQuery And (Word q1) (Word q2)) =
if (map toLower q1) `isPrefixOf` (map toLower q2) then Word q2 else
if (map toLower q2) `isPrefixOf` (map toLower q1) then Word q1 else q
optimize q@(BinQuery And (CaseWord q1) (CaseWord q2)) =
if q1 `isPrefixOf` q2 then CaseWord q2 else
if q2 `isPrefixOf` q1 then CaseWord q1 else q
optimize q@(BinQuery Or (Word q1) (Word q2)) =
if (map toLower q1) `isPrefixOf` (map toLower q2) then Word q1 else
if (map toLower q2) `isPrefixOf` (map toLower q1) then Word q2 else q
optimize q@(BinQuery Or (CaseWord q1) (CaseWord q2)) =
if q1 `isPrefixOf` q2 then CaseWord q1 else
if q2 `isPrefixOf` q1 then CaseWord q2 else q
optimize (BinQuery And q1 (Negation q2)) = BinQuery But (optimize q1) (optimize q2)
optimize (BinQuery And (Negation q1) q2) = BinQuery But (optimize q2) (optimize q1)
optimize (BinQuery And q1 q2) = BinQuery And (optimize q1) (optimize q2)
optimize (BinQuery Or q1 q2) = BinQuery Or (optimize q1) (optimize q2)
optimize (BinQuery But q1 q2) = BinQuery But (optimize q1) (optimize q2)
optimize (Negation q) = Negation (optimize q)
optimize (Specifier cs q) = Specifier cs (optimize q)
optimize q = q
checkWith :: (String -> Bool) -> Query -> Bool
checkWith f (Word s) = f s
checkWith f (Phrase s) = f s
checkWith f (CaseWord s) = f s
checkWith f (CasePhrase s) = f s
checkWith f (FuzzyWord s) = f s
checkWith f (Negation q) = checkWith f q
checkWith f (BinQuery _ q1 q2) = (checkWith f q1) && (checkWith f q2)
checkWith f (Specifier _ q) = checkWith f q
extractTerms :: Query -> [String]
extractTerms (Word s) = [s]
extractTerms (CaseWord s) = [s]
extractTerms (FuzzyWord s) = [s]
extractTerms (Specifier _ q) = extractTerms q
extractTerms (Negation q) = extractTerms q
extractTerms (BinQuery _ q1 q2) = (extractTerms q1) ++ (extractTerms q2)
extractTerms _ = []
|
50d2716cca7b9ffca5e0e8ce0817e4a01ae0eaf01a34a42f7b0bc1723e5a9e90 | ocsigen/js_of_ocaml | test.ml | (* TEST
*)
let is_nan2 (x, y) = Float.is_nan x && Float.is_nan y
type test = True of (unit -> bool)
| False of (unit -> bool)
| Equal of ((unit -> float) * float)
| Pair of ((unit -> float * float) * (float * float))
let cases = [
( 1, True (fun () -> Float.is_finite 1.));
( 2, True (fun () -> Float.is_finite Float.pi));
( 3, False(fun () -> Float.is_finite Float.infinity));
( 4, False(fun () -> Float.is_finite Float.nan));
( 5, True (fun () -> Float.is_infinite Float.infinity));
( 6, False(fun () -> Float.is_infinite 1.));
( 7, False(fun () -> Float.is_infinite Float.nan));
( 8, True (fun () -> Float.is_nan Float.nan));
( 9, False(fun () -> Float.is_nan 1.));
(10, False(fun () -> Float.is_nan neg_infinity));
(11, True (fun () -> Float.is_integer 1.));
(12, True (fun () -> Float.is_integer (-1e10)));
(13, False(fun () -> Float.is_integer 1.5));
(14, False(fun () -> Float.is_integer Float.infinity));
(15, False(fun () -> Float.is_integer Float.nan));
(16, Equal((fun () -> Float.trunc 1.5), 1.));
(17, Equal((fun () -> Float.trunc (-1.5)), -1.));
(18, Equal(Float.((fun () -> trunc infinity), infinity)));
(19, Equal(Float.(((fun () -> trunc neg_infinity), neg_infinity))));
(20, True (fun () -> Float.(is_nan(trunc nan))));
(21, Equal((fun () -> Float.round 0.5), 1.));
(* tie resolve differently *)
( 22 , Equal((fun ( ) - > Float.round ( -0.5 ) ) , -1 . ) ) ;
(23, Equal((fun () -> Float.round 1.5), 2.));
(* tie resolve differently *)
( 24 , Equal((fun ( ) - > Float.round ( -1.5 ) ) , -2 . ) ) ;
x + 0.5 rounds to x + . 1 .
Equal((fun () -> Float.round x), x));
(26, Equal((fun () -> Float.round (Float.next_after 0.5 0.)), 0.));
(27, Equal(Float.((fun () -> round infinity), infinity)));
(28, Equal(Float.((fun () -> round neg_infinity), neg_infinity)));
(29, True (fun () -> Float.(is_nan(round nan))));
(30, Equal((fun () -> Float.next_after 0x1.FFFFFFFFFFFFFp-2 1.), 0.5));
(31, Equal((fun () -> Float.next_after 0x1.FFFFFFFFFFFFFp-2 0.), 0x1.FFFFFFFFFFFFEp-2));
(32, Equal(Float.((fun () -> next_after 0x1.FFFFFFFFFFFFFp-2 infinity), 0.5)));
(33, Equal(Float.((fun () -> next_after 0x1.FFFFFFFFFFFFFp-2 neg_infinity), 0x1.FFFFFFFFFFFFEp-2)));
(34, Equal((fun () -> Float.next_after 1. 1.), 1.));
(35, True (fun () -> Float.(is_nan(next_after nan 1.))));
(36, True (fun () -> Float.(is_nan(next_after 3. nan))));
(37, Equal(Float.((fun () -> succ 0x1.FFFFFFFFFFFFFp-2), 0.5)));
(38, Equal(Float.((fun () -> pred 0.5), 0x1.FFFFFFFFFFFFFp-2)));
(39, True (Float.(fun () -> succ 0. > 0.)));
(40, True (Float.(fun () -> pred 0. < 0.)));
(41, Equal(Float.((fun () -> succ max_float), infinity)));
(42, Equal(Float.((fun () -> pred (-. max_float)), neg_infinity)));
(43, True (Float.(fun () -> succ 0. < min_float)));
(44, Equal(Float.((fun () -> succ infinity), infinity)));
(45, Equal(Float.((fun () -> pred neg_infinity), neg_infinity)));
(46, True (Float.(fun () -> is_nan(succ nan))));
(47, True (Float.(fun () -> is_nan(pred nan))));
(48, False(fun () -> Float.sign_bit 1.));
(49, True (fun () -> Float.sign_bit (-1.)));
(50, False(fun () -> Float.sign_bit 0.));
(51, True (fun () -> Float.sign_bit (-0.)));
(52, False(fun () -> Float.sign_bit infinity));
(53, True (fun () -> Float.sign_bit neg_infinity));
(54, Equal((fun () -> Float.min 1. 2.), 1.));
(55, Equal((fun () -> Float.min 2. 1.), 1.));
(56, True (fun () -> Float.(is_nan(min 1. nan))));
(57, True (fun () -> Float.(is_nan(min nan 2.))));
(58, True (fun () -> Float.(is_nan(min nan nan))));
(59, Equal((fun () -> 1. /. Float.min (-0.) (+0.)), neg_infinity));
(60, Equal((fun () -> 1. /. Float.min (+0.) (-0.)), neg_infinity));
(61, Equal((fun () -> Float.max 1. 2.), 2.));
(62, Equal((fun () -> Float.max 2. 1.), 2.));
(63, True (fun () -> Float.(is_nan(max 1. nan))));
(64, True (fun () -> Float.(is_nan(max nan 2.))));
(65, True (fun () -> Float.(is_nan(max nan nan))));
(66, Equal((fun () -> 1. /. Float.max (-0.) (+0.)), infinity));
(67, Equal((fun () -> 1. /. Float.max (+0.) (-0.)), infinity));
(68, Pair ((fun () -> Float.min_max 1. 2.), (1., 2.)));
(69, Pair ((fun () -> Float.min_max 2. 1.), (1., 2.)));
(70, True (fun () -> Float.(is_nan2(min_max 1. nan))));
(71, True (fun () -> Float.(is_nan2(min_max nan 2.))));
(72, True (fun () -> Float.(is_nan2(min_max nan nan))));
(73, Pair ((fun () -> let x, y = Float.min_max (-0.) (+0.) in
(1. /. x, 1. /. y)), (neg_infinity, infinity)));
(74, Pair ((fun () -> let x, y = Float.min_max (+0.) (-0.) in
(1. /. x, 1. /. y)), (neg_infinity, infinity)));
(75, Equal((fun () -> Float.min_num 1. 2.), 1.));
(76, Equal(Float.((fun () -> min_num 1. nan), 1.)));
(77, Equal(Float.((fun () -> min_num nan 2.), 2.)));
(78, True (fun () -> Float.(is_nan(min_num nan nan))));
(79, Equal((fun () -> 1. /. Float.min_num (-0.) (+0.)), neg_infinity));
(80, Equal((fun () -> 1. /. Float.min_num (+0.) (-0.)), neg_infinity));
(81, Equal((fun () -> Float.max_num 1. 2.), 2.));
(82, Equal(Float.((fun () -> max_num 1. nan), 1.)));
(83, Equal(Float.((fun () -> max_num nan 2.), 2.)));
(84, True (fun () -> Float.(is_nan(max_num nan nan))));
(85, Equal((fun () -> 1. /. Float.max_num (-0.) (+0.)), infinity));
(86, Equal((fun () -> 1. /. Float.max_num (+0.) (-0.)), infinity));
(87, Pair ((fun () -> Float.min_max_num 1. 2.), (1., 2.)));
(88, Pair ((fun () -> Float.min_max_num 2. 1.), (1., 2.)));
(89, Pair ((fun () -> Float.min_max_num 1. nan), (1., 1.)));
(90, Pair ((fun () -> Float.min_max_num nan 1.), (1., 1.)));
(91, True (fun () -> Float.(is_nan2(min_max_num nan nan))));
(92, Pair ((fun () -> let x, y = Float.min_max_num (-0.) (+0.) in
(1. /. x, 1. /. y)), (neg_infinity, infinity)));
(93, Pair ((fun () -> let x, y = Float.min_max_num (+0.) (-0.) in
(1. /. x, 1. /. y)), (neg_infinity, infinity)));
]
let () =
let f (n, test) =
match test with
| True p ->
Printf.printf "%03d: %s\n%!" n (if p () then "OK" else "FAIL")
| False p ->
Printf.printf "%03d: %s\n%!" n (if p () then "FAIL" else "OK")
| Equal (f, result) ->
let v = f () in
if v = result then
Printf.printf "%03d: OK\n%!" n
else
Printf.printf "%03d: FAIL (%h returned instead of %h)\n%!" n v result
| Pair (f, ((l', r') as result)) ->
let (l, r) as v = f () in
if v = result then
Printf.printf "%03d: OK\n%!" n
else
Printf.printf "%03d: FAIL ((%h, %h) returned instead of (%h, %h))\n%!" n l r l' r'
in
List.iter f cases
| null | https://raw.githubusercontent.com/ocsigen/js_of_ocaml/31c8a3d9d4e34f3fd573dd5056e733233ca4f4f6/compiler/tests-ocaml/lib-float/test.ml | ocaml | TEST
tie resolve differently
tie resolve differently |
let is_nan2 (x, y) = Float.is_nan x && Float.is_nan y
type test = True of (unit -> bool)
| False of (unit -> bool)
| Equal of ((unit -> float) * float)
| Pair of ((unit -> float * float) * (float * float))
let cases = [
( 1, True (fun () -> Float.is_finite 1.));
( 2, True (fun () -> Float.is_finite Float.pi));
( 3, False(fun () -> Float.is_finite Float.infinity));
( 4, False(fun () -> Float.is_finite Float.nan));
( 5, True (fun () -> Float.is_infinite Float.infinity));
( 6, False(fun () -> Float.is_infinite 1.));
( 7, False(fun () -> Float.is_infinite Float.nan));
( 8, True (fun () -> Float.is_nan Float.nan));
( 9, False(fun () -> Float.is_nan 1.));
(10, False(fun () -> Float.is_nan neg_infinity));
(11, True (fun () -> Float.is_integer 1.));
(12, True (fun () -> Float.is_integer (-1e10)));
(13, False(fun () -> Float.is_integer 1.5));
(14, False(fun () -> Float.is_integer Float.infinity));
(15, False(fun () -> Float.is_integer Float.nan));
(16, Equal((fun () -> Float.trunc 1.5), 1.));
(17, Equal((fun () -> Float.trunc (-1.5)), -1.));
(18, Equal(Float.((fun () -> trunc infinity), infinity)));
(19, Equal(Float.(((fun () -> trunc neg_infinity), neg_infinity))));
(20, True (fun () -> Float.(is_nan(trunc nan))));
(21, Equal((fun () -> Float.round 0.5), 1.));
( 22 , Equal((fun ( ) - > Float.round ( -0.5 ) ) , -1 . ) ) ;
(23, Equal((fun () -> Float.round 1.5), 2.));
( 24 , Equal((fun ( ) - > Float.round ( -1.5 ) ) , -2 . ) ) ;
x + 0.5 rounds to x + . 1 .
Equal((fun () -> Float.round x), x));
(26, Equal((fun () -> Float.round (Float.next_after 0.5 0.)), 0.));
(27, Equal(Float.((fun () -> round infinity), infinity)));
(28, Equal(Float.((fun () -> round neg_infinity), neg_infinity)));
(29, True (fun () -> Float.(is_nan(round nan))));
(30, Equal((fun () -> Float.next_after 0x1.FFFFFFFFFFFFFp-2 1.), 0.5));
(31, Equal((fun () -> Float.next_after 0x1.FFFFFFFFFFFFFp-2 0.), 0x1.FFFFFFFFFFFFEp-2));
(32, Equal(Float.((fun () -> next_after 0x1.FFFFFFFFFFFFFp-2 infinity), 0.5)));
(33, Equal(Float.((fun () -> next_after 0x1.FFFFFFFFFFFFFp-2 neg_infinity), 0x1.FFFFFFFFFFFFEp-2)));
(34, Equal((fun () -> Float.next_after 1. 1.), 1.));
(35, True (fun () -> Float.(is_nan(next_after nan 1.))));
(36, True (fun () -> Float.(is_nan(next_after 3. nan))));
(37, Equal(Float.((fun () -> succ 0x1.FFFFFFFFFFFFFp-2), 0.5)));
(38, Equal(Float.((fun () -> pred 0.5), 0x1.FFFFFFFFFFFFFp-2)));
(39, True (Float.(fun () -> succ 0. > 0.)));
(40, True (Float.(fun () -> pred 0. < 0.)));
(41, Equal(Float.((fun () -> succ max_float), infinity)));
(42, Equal(Float.((fun () -> pred (-. max_float)), neg_infinity)));
(43, True (Float.(fun () -> succ 0. < min_float)));
(44, Equal(Float.((fun () -> succ infinity), infinity)));
(45, Equal(Float.((fun () -> pred neg_infinity), neg_infinity)));
(46, True (Float.(fun () -> is_nan(succ nan))));
(47, True (Float.(fun () -> is_nan(pred nan))));
(48, False(fun () -> Float.sign_bit 1.));
(49, True (fun () -> Float.sign_bit (-1.)));
(50, False(fun () -> Float.sign_bit 0.));
(51, True (fun () -> Float.sign_bit (-0.)));
(52, False(fun () -> Float.sign_bit infinity));
(53, True (fun () -> Float.sign_bit neg_infinity));
(54, Equal((fun () -> Float.min 1. 2.), 1.));
(55, Equal((fun () -> Float.min 2. 1.), 1.));
(56, True (fun () -> Float.(is_nan(min 1. nan))));
(57, True (fun () -> Float.(is_nan(min nan 2.))));
(58, True (fun () -> Float.(is_nan(min nan nan))));
(59, Equal((fun () -> 1. /. Float.min (-0.) (+0.)), neg_infinity));
(60, Equal((fun () -> 1. /. Float.min (+0.) (-0.)), neg_infinity));
(61, Equal((fun () -> Float.max 1. 2.), 2.));
(62, Equal((fun () -> Float.max 2. 1.), 2.));
(63, True (fun () -> Float.(is_nan(max 1. nan))));
(64, True (fun () -> Float.(is_nan(max nan 2.))));
(65, True (fun () -> Float.(is_nan(max nan nan))));
(66, Equal((fun () -> 1. /. Float.max (-0.) (+0.)), infinity));
(67, Equal((fun () -> 1. /. Float.max (+0.) (-0.)), infinity));
(68, Pair ((fun () -> Float.min_max 1. 2.), (1., 2.)));
(69, Pair ((fun () -> Float.min_max 2. 1.), (1., 2.)));
(70, True (fun () -> Float.(is_nan2(min_max 1. nan))));
(71, True (fun () -> Float.(is_nan2(min_max nan 2.))));
(72, True (fun () -> Float.(is_nan2(min_max nan nan))));
(73, Pair ((fun () -> let x, y = Float.min_max (-0.) (+0.) in
(1. /. x, 1. /. y)), (neg_infinity, infinity)));
(74, Pair ((fun () -> let x, y = Float.min_max (+0.) (-0.) in
(1. /. x, 1. /. y)), (neg_infinity, infinity)));
(75, Equal((fun () -> Float.min_num 1. 2.), 1.));
(76, Equal(Float.((fun () -> min_num 1. nan), 1.)));
(77, Equal(Float.((fun () -> min_num nan 2.), 2.)));
(78, True (fun () -> Float.(is_nan(min_num nan nan))));
(79, Equal((fun () -> 1. /. Float.min_num (-0.) (+0.)), neg_infinity));
(80, Equal((fun () -> 1. /. Float.min_num (+0.) (-0.)), neg_infinity));
(81, Equal((fun () -> Float.max_num 1. 2.), 2.));
(82, Equal(Float.((fun () -> max_num 1. nan), 1.)));
(83, Equal(Float.((fun () -> max_num nan 2.), 2.)));
(84, True (fun () -> Float.(is_nan(max_num nan nan))));
(85, Equal((fun () -> 1. /. Float.max_num (-0.) (+0.)), infinity));
(86, Equal((fun () -> 1. /. Float.max_num (+0.) (-0.)), infinity));
(87, Pair ((fun () -> Float.min_max_num 1. 2.), (1., 2.)));
(88, Pair ((fun () -> Float.min_max_num 2. 1.), (1., 2.)));
(89, Pair ((fun () -> Float.min_max_num 1. nan), (1., 1.)));
(90, Pair ((fun () -> Float.min_max_num nan 1.), (1., 1.)));
(91, True (fun () -> Float.(is_nan2(min_max_num nan nan))));
(92, Pair ((fun () -> let x, y = Float.min_max_num (-0.) (+0.) in
(1. /. x, 1. /. y)), (neg_infinity, infinity)));
(93, Pair ((fun () -> let x, y = Float.min_max_num (+0.) (-0.) in
(1. /. x, 1. /. y)), (neg_infinity, infinity)));
]
let () =
let f (n, test) =
match test with
| True p ->
Printf.printf "%03d: %s\n%!" n (if p () then "OK" else "FAIL")
| False p ->
Printf.printf "%03d: %s\n%!" n (if p () then "FAIL" else "OK")
| Equal (f, result) ->
let v = f () in
if v = result then
Printf.printf "%03d: OK\n%!" n
else
Printf.printf "%03d: FAIL (%h returned instead of %h)\n%!" n v result
| Pair (f, ((l', r') as result)) ->
let (l, r) as v = f () in
if v = result then
Printf.printf "%03d: OK\n%!" n
else
Printf.printf "%03d: FAIL ((%h, %h) returned instead of (%h, %h))\n%!" n l r l' r'
in
List.iter f cases
|
8969054f4c79e32e63b14e8d3795fab85c87a93a5eceef37da9db9392fe69439 | vmchale/kempe | IR.hs | module Kempe.IR ( writeModule
, runTempM
, TempM
, prettyIR
, WriteSt (..)
, size
) where
import Data.Foldable (toList, traverse_)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
-- strict b/c it's faster according to benchmarks
import Control.Monad (zipWithM)
import Control.Monad.State.Strict (State, gets, modify, runState)
import Data.Bifunctor (second)
import Data.Foldable.Ext
import Data.Int (Int64)
import qualified Data.IntMap as IM
import Data.Text.Encoding (encodeUtf8)
import Kempe.AST
import Kempe.AST.Size
import Kempe.IR.Type
import Kempe.Name
import Kempe.Unique
import Lens.Micro (Lens')
import Lens.Micro.Mtl (modifying)
import Prettyprinter (Doc, Pretty (pretty))
import Prettyprinter.Ext
data TempSt = TempSt { labels :: [Label]
, tempSupply :: [Int]
, atLabels :: IM.IntMap Label
-- TODO: type sizes in state
}
asWriteSt :: TempSt -> WriteSt
asWriteSt (TempSt ls ts _) = WriteSt ls ts
runTempM :: TempM a -> (a, WriteSt)
runTempM = second asWriteSt . flip runState (TempSt [1..] [1..] mempty)
atLabelsLens :: Lens' TempSt (IM.IntMap Label)
atLabelsLens f s = fmap (\x -> s { atLabels = x }) (f (atLabels s))
nextLabels :: TempSt -> TempSt
nextLabels (TempSt ls ts ats) = TempSt (tail ls) ts ats
nextTemps :: TempSt -> TempSt
nextTemps (TempSt ls ts ats) = TempSt ls (tail ts) ats
type TempM = State TempSt
getTemp :: TempM Int
getTemp = gets (head . tempSupply) <* modify nextTemps
getTemp64 :: TempM Temp
getTemp64 = Temp64 <$> getTemp
getTemp8 :: TempM Temp
getTemp8 = Temp8 <$> getTemp
newLabel :: TempM Label
newLabel = gets (head . labels) <* modify nextLabels
broadcastName :: Unique -> TempM ()
broadcastName (Unique i) = do
l <- newLabel
modifying atLabelsLens (IM.insert i l)
lookupName :: Name a -> TempM Label
lookupName (Name _ (Unique i) _) =
gets
(IM.findWithDefault (error "Internal error in IR phase: could not look find label for name") i . atLabels)
prettyIR :: [Stmt] -> Doc ann
prettyIR = prettyLines . fmap pretty
writeModule :: SizeEnv -> Declarations () (ConsAnn MonoStackType) MonoStackType -> TempM [Stmt]
writeModule env m = traverse_ assignName m *> foldMapA (writeDecl env) m
-- optimize tail-recursion, if possible
-- This is a little slow
tryTCO :: Bool -- ^ Can it be optimized here?
-> [Stmt]
-> [Stmt]
tryTCO _ [] = []
tryTCO False stmts = stmts
tryTCO True stmts =
let end = last stmts
in
case end of
KCall l' -> init stmts ++ [Jump l']
_ -> stmts
assignName :: KempeDecl a c b -> TempM ()
assignName (FunDecl _ (Name _ u _) _ _ _) = broadcastName u
assignName (ExtFnDecl _ (Name _ u _) _ _ _) = broadcastName u
assignName Export{} = pure ()
assignName TyDecl{} = error "Internal error: type declarations should not exist at this stage"
writeDecl :: SizeEnv -> KempeDecl () (ConsAnn MonoStackType) MonoStackType -> TempM [Stmt]
writeDecl env (FunDecl _ n _ _ as) = do
bl <- lookupName n
(++ [Ret]) . (Labeled bl:) . tryTCO True <$> writeAtoms env True as
writeDecl _ (ExtFnDecl ty n _ _ cName) = do
bl <- lookupName n
pure [Labeled bl, CCall ty cName, Ret]
writeDecl _ (Export sTy abi n) = pure . WrapKCall abi sTy (encodeUtf8 $ name n) <$> lookupName n
writeDecl _ TyDecl{} = error "Internal error: type declarations should not exist at this stage"
writeAtoms :: SizeEnv -> Bool -> [Atom (ConsAnn MonoStackType) MonoStackType] -> TempM [Stmt]
writeAtoms _ _ [] = pure []
writeAtoms env False stmts = foldMapA (writeAtom env False) stmts
writeAtoms env l stmts =
let end = last stmts
in (++) <$> foldMapA (writeAtom env False) (init stmts) <*> writeAtom env l end
intShift :: IntBinOp -> TempM [Stmt]
intShift cons = do
t0 <- getTemp64
t1 <- getTemp64
pure $
pop 8 t0 ++ pop 8 t1 ++ push 8 (ExprIntBinOp cons (Reg t1) (Reg t0))
boolOp :: BoolBinOp -> TempM [Stmt]
boolOp op = do
t0 <- getTemp8
t1 <- getTemp8
pure $
pop 1 t0 ++ pop 1 t1 ++ push 1 (BoolBinOp op (Reg t1) (Reg t0))
intOp :: IntBinOp -> TempM [Stmt]
intOp cons = do
registers are 64 bits for integers
t1 <- getTemp64
pure $
pop 8 t0 ++ pop 8 t1 ++ push 8 (ExprIntBinOp cons (Reg t1) (Reg t0))
| Push bytes onto the data pointer
push :: Int64 -> Exp -> [Stmt]
push off e =
[ MovMem (Reg DataPointer) off e
increment instead of decrement b / c this is the Kempe ABI
]
pop :: Int64 -> Temp -> [Stmt]
pop sz t =
[ dataPointerDec sz
, MovTemp t (Mem sz (Reg DataPointer))
]
-- FIXME: just use expressions from memory accesses
intRel :: RelBinOp -> TempM [Stmt]
intRel cons = do
t0 <- getTemp64
t1 <- getTemp64
pure $
pop 8 t0 ++ pop 8 t1 ++ push 1 (ExprIntRel cons (Reg t1) (Reg t0))
intNeg :: TempM [Stmt]
intNeg = do
t0 <- getTemp64
pure $
pop 8 t0 ++ push 8 (IntNegIR (Reg t0))
wordCount :: TempM [Stmt]
wordCount = do
t0 <- getTemp64
pure $
pop 8 t0 ++ push 8 (PopcountIR (Reg t0))
-- | This throws exceptions on nonsensical input.
writeAtom :: SizeEnv
-> Bool -- ^ Can we do TCO?
-> Atom (ConsAnn MonoStackType) MonoStackType
-> TempM [Stmt]
writeAtom _ _ (IntLit _ i) = pure $ push 8 (ConstInt $ fromInteger i)
writeAtom _ _ (Int8Lit _ i) = pure $ push 1 (ConstInt8 i)
writeAtom _ _ (WordLit _ w) = pure $ push 8 (ConstWord $ fromIntegral w)
writeAtom _ _ (BoolLit _ b) = pure $ push 1 (ConstBool b)
writeAtom _ _ (AtName _ n) = pure . KCall <$> lookupName n
writeAtom _ _ (AtBuiltin ([], _) Drop) = error "Internal error: Ill-typed drop!"
writeAtom _ _ (AtBuiltin ([], _) Dup) = error "Internal error: Ill-typed dup!"
writeAtom _ _ (Dip ([], _) _) = error "Internal error: Ill-typed dip()!"
writeAtom _ _ (AtBuiltin _ IntPlus) = intOp IntPlusIR
writeAtom _ _ (AtBuiltin _ IntMinus) = intOp IntMinusIR
writeAtom _ _ (AtBuiltin _ IntTimes) = intOp IntTimesIR
writeAtom _ _ (AtBuiltin _ IntDiv) = intOp IntDivIR -- what to do on failure?
writeAtom _ _ (AtBuiltin _ IntMod) = intOp IntModIR
writeAtom _ _ (AtBuiltin _ IntXor) = intOp IntXorIR
FIXME : shr or sar ?
writeAtom _ _ (AtBuiltin _ IntShiftL) = intShift WordShiftLIR
writeAtom _ _ (AtBuiltin _ IntEq) = intRel IntEqIR
writeAtom _ _ (AtBuiltin _ IntLt) = intRel IntLtIR
writeAtom _ _ (AtBuiltin _ IntLeq) = intRel IntLeqIR
writeAtom _ _ (AtBuiltin _ WordPlus) = intOp IntPlusIR
writeAtom _ _ (AtBuiltin _ WordTimes) = intOp IntTimesIR
writeAtom _ _ (AtBuiltin _ WordXor) = intOp IntXorIR
writeAtom _ _ (AtBuiltin _ WordMinus) = intOp IntMinusIR
writeAtom _ _ (AtBuiltin _ IntNeq) = intRel IntNeqIR
writeAtom _ _ (AtBuiltin _ IntGeq) = intRel IntGeqIR
writeAtom _ _ (AtBuiltin _ IntGt) = intRel IntGtIR
writeAtom _ _ (AtBuiltin _ WordShiftL) = intShift WordShiftLIR
writeAtom _ _ (AtBuiltin _ WordShiftR) = intShift WordShiftRIR
writeAtom _ _ (AtBuiltin _ WordDiv) = intOp WordDivIR
writeAtom _ _ (AtBuiltin _ WordMod) = intOp WordModIR
writeAtom _ _ (AtBuiltin _ And) = boolOp BoolAnd
writeAtom _ _ (AtBuiltin _ Or) = boolOp BoolOr
writeAtom _ _ (AtBuiltin _ Xor) = boolOp BoolXor
writeAtom _ _ (AtBuiltin _ IntNeg) = intNeg
writeAtom _ _ (AtBuiltin _ Popcount) = wordCount
writeAtom env _ (AtBuiltin (is, _) Drop) =
let sz = size' env (last is) in
pure [ dataPointerDec sz ]
writeAtom env _ (AtBuiltin (is, _) Dup) =
let sz = size' env (last is) in
pure $
copyBytes 0 (-sz) sz
++ [ dataPointerInc sz ] -- move data pointer over sz bytes
writeAtom env l (If _ as as') = do
l0 <- newLabel
l1 <- newLabel
let ifIR = CJump (Mem 1 (Reg DataPointer)) l0 l1
asIR <- tryTCO l <$> writeAtoms env l as
asIR' <- tryTCO l <$> writeAtoms env l as'
l2 <- newLabel
pure $ dataPointerDec 1 : ifIR : (Labeled l0 : asIR ++ [Jump l2]) ++ (Labeled l1 : asIR') ++ [Labeled l2]
writeAtom env _ (Dip (is, _) as) =
let sz = size' env (last is)
in foldMapA (dipify env sz) as
writeAtom env _ (AtBuiltin ([i0, i1], _) Swap) =
let sz0 = size' env i0
sz1 = size' env i1
in
pure $
copyBytes 0 (-sz0 - sz1) sz0 -- copy i0 to end of the stack
++ copyBytes (-sz0 - sz1) (-sz1) sz1 -- copy i1 to where i0 used to be
++ copyBytes (-sz0) 0 sz0 -- copy i0 at end of stack to its new place
writeAtom _ _ (AtBuiltin _ Swap) = error "Ill-typed swap!"
writeAtom env _ (AtCons ann@(ConsAnn _ tag' _) _) =
pure $ dataPointerInc (padBytes env ann) : push 1 (ConstTag tag')
writeAtom _ _ (Case ([], _) _) = error "Internal error: Ill-typed case statement?!"
-- single-case leaf (we still have the tag but we don't need to check cases etc.
writeAtom env l (Case _ ((_, as) :| [])) =
(dataPointerDec 1:) <$> writeAtoms env l as
writeAtom env l (Case (is, _) ls) =
let (ps, ass) = NE.unzip ls
decSz = case last is of
TyBuiltin _ TyInt -> 8
TyBuiltin _ TyWord -> 8
-- one for constructor tags, etc.
_ -> 1
in do
leaves <- zipWithM (mkLeaf env l) (toList ps) (NE.init ass)
lastLeaf <- mkLeaf env l (PatternWildcard undefined) (NE.last ass)
let (switches, meat) = unzip (leaves ++ [lastLeaf])
ret <- newLabel
let meat' = (++ [Jump ret]) . toList <$> meat
pure $ dataPointerDec decSz : switches ++ concat meat' ++ [Labeled ret]
mkLeaf :: SizeEnv -> Bool -> Pattern (ConsAnn MonoStackType) MonoStackType -> [Atom (ConsAnn MonoStackType) MonoStackType] -> TempM (Stmt, [Stmt])
mkLeaf env l p as = do
l' <- newLabel
as' <- writeAtoms env l as
let (s, mAfter) = patternSwitch env p l'
modAs = case mAfter of
Just dec -> (dec:)
Nothing -> id
pure (s, Labeled l' : modAs as')
patternSwitch :: SizeEnv -> Pattern (ConsAnn MonoStackType) MonoStackType -> Label -> (Stmt, Maybe Stmt)
patternSwitch _ (PatternBool _ True) l = (MJump (Mem 1 (Reg DataPointer)) l, Nothing)
patternSwitch _ (PatternBool _ False) l = (MJump (EqByte (Mem 1 (Reg DataPointer)) (ConstTag 0)) l, Nothing)
patternSwitch _ (PatternWildcard _) l = (Jump l, Nothing) -- TODO: padding?
patternSwitch _ (PatternInt _ i) l = (MJump (ExprIntRel IntEqIR (Mem 8 (Reg DataPointer)) (ConstInt $ fromInteger i)) l, Nothing)
patternSwitch env (PatternCons ann@(ConsAnn _ tag' _) _) l =
let padAt = padBytesCons env ann
in (MJump (EqByte (Mem 1 (Reg DataPointer)) (ConstTag tag')) l, Just $ dataPointerDec padAt)
-- FIXME: in addition to flushing padding, we should copy bytes too...
-- | Constructors may need to be padded, this computes the number of bytes of
-- padding
padBytes :: SizeEnv -> ConsAnn MonoStackType -> Int64
padBytes env (ConsAnn sz _ (is, _)) = sz - sizeStack env is - 1
-- | Patterns for constructors are annotated differently
padBytesCons :: SizeEnv -> ConsAnn MonoStackType -> Int64
padBytesCons env (ConsAnn sz _ (_, os)) = sz - sizeStack env os - 1
dipify :: SizeEnv -> Int64 -> Atom (ConsAnn MonoStackType) MonoStackType -> TempM [Stmt]
dipify _ _ (AtBuiltin ([], _) Drop) = error "Internal error: Ill-typed drop!"
dipify env sz (AtBuiltin (is, _) Drop) =
let sz' = size' env (last is)
shift = dataPointerDec sz' -- shift data pointer over by sz' bytes
-- copy sz bytes over (-sz') bytes from the data pointer
copyBytes' = copyBytes (-sz - sz') (-sz) sz
in pure $ copyBytes' ++ [shift]
dipify env sz (AtBuiltin ([i0, i1], _) Swap) =
let sz0 = size' env i0
sz1 = size' env i1
in
pure $
copyBytes 0 (-sz - sz0 - sz1) sz0 -- copy i0 to end of the stack
++ copyBytes (-sz - sz0 - sz1) (-sz - sz1) sz1 -- copy i1 to where i0 used to be
++ copyBytes (-sz - sz0) 0 sz0 -- copy i0 at end of stack to its new place
dipify _ _ (Dip ([], _) _) = error "Internal error: Ill-typed dip()!"
dipify env sz (Dip (is, _) as) =
let sz' = size' env (last is)
in foldMapA (dipify env (sz + sz')) as
dipify _ _ (AtBuiltin _ Swap) = error "Internal error: Ill-typed swap!"
dipify _ sz (AtBuiltin _ IntTimes) = dipOp sz IntTimesIR
dipify _ sz (AtBuiltin _ IntPlus) = dipOp sz IntPlusIR
dipify _ sz (AtBuiltin _ IntMinus) = dipOp sz IntMinusIR
dipify _ sz (AtBuiltin _ IntDiv) = dipOp sz IntDivIR
dipify _ sz (AtBuiltin _ IntMod) = dipOp sz IntModIR
dipify _ sz (AtBuiltin _ IntXor) = dipOp sz IntXorIR
dipify _ sz (AtBuiltin _ IntEq) = dipRel sz IntEqIR
dipify _ sz (AtBuiltin _ IntLt) = dipRel sz IntLtIR
dipify _ sz (AtBuiltin _ IntLeq) = dipRel sz IntLeqIR
dipify _ sz (AtBuiltin _ IntShiftL) = dipShift sz WordShiftLIR
dipify _ sz (AtBuiltin _ IntShiftR) = dipShift sz WordShiftRIR
dipify _ sz (AtBuiltin _ WordXor) = dipOp sz IntXorIR
dipify _ sz (AtBuiltin _ WordShiftL) = dipShift sz WordShiftLIR
dipify _ sz (AtBuiltin _ WordShiftR) = dipShift sz WordShiftRIR
dipify _ sz (AtBuiltin _ WordPlus) = dipOp sz IntPlusIR
dipify _ sz (AtBuiltin _ WordTimes) = dipOp sz IntTimesIR
dipify _ sz (AtBuiltin _ IntGeq) = dipRel sz IntGeqIR
dipify _ sz (AtBuiltin _ IntGt) = dipRel sz IntGtIR
dipify _ sz (AtBuiltin _ IntNeq) = dipRel sz IntNeqIR
dipify _ sz (AtBuiltin _ IntNeg) = plainShift sz <$> intNeg
dipify _ sz (AtBuiltin _ Popcount) = plainShift sz <$> wordCount
dipify _ sz (AtBuiltin _ And) = dipBoolOp sz BoolAnd
dipify _ sz (AtBuiltin _ Or) = dipBoolOp sz BoolOr
dipify _ sz (AtBuiltin _ Xor) = dipBoolOp sz BoolXor
dipify _ sz (AtBuiltin _ WordMinus) = dipOp sz IntMinusIR
dipify _ sz (AtBuiltin _ WordDiv) = dipOp sz WordDivIR
dipify _ sz (AtBuiltin _ WordMod) = dipOp sz WordModIR
dipify _ _ (AtBuiltin ([], _) Dup) = error "Internal error: Ill-typed dup!"
dipify env sz (AtBuiltin (is, _) Dup) = do
let sz' = size' env (last is) in
pure $
copyBytes 0 (-sz) sz -- copy sz bytes over to the end of the stack
++ copyBytes (-sz) (-sz - sz') sz' -- copy sz' bytes over (duplicate)
++ copyBytes (-sz + sz') 0 sz -- copy sz bytes back
++ [ dataPointerInc sz' ] -- move data pointer over sz' bytes
dipify _ sz (IntLit _ i) = pure $ dipPush sz 8 (ConstInt $ fromInteger i)
dipify _ sz (WordLit _ w) = pure $ dipPush sz 8 (ConstWord $ fromIntegral w)
dipify _ sz (Int8Lit _ i) = pure $ dipPush sz 1 (ConstInt8 i)
dipify _ sz (BoolLit _ b) = pure $ dipPush sz 1 (ConstBool b)
dipify env sz (AtCons ann@(ConsAnn _ tag' _) _) =
pure $
copyBytes 0 (-sz) sz
++ dataPointerInc (padBytes env ann) : push 1 (ConstTag tag')
++ copyBytes (-sz) 0 sz
dipify env sz a@(If sty _ _) =
dipSupp env sz sty <$> writeAtom env False a
dipify env sz (AtName sty n) =
dipSupp env sz sty . pure . KCall <$> lookupName n
dipify env sz a@(Case sty _) =
dipSupp env sz sty <$> writeAtom env False a
dipSupp :: SizeEnv -> Int64 -> MonoStackType -> [Stmt] -> [Stmt]
dipSupp env sz (is, os) stmts =
let excessSz = sizeStack env os - sizeStack env is -- how much the atom(s) grow the stack
in case compare excessSz 0 of
EQ -> plainShift sz stmts
LT -> dipDo sz stmts
GT -> dipHelp excessSz sz stmts
dipHelp :: Int64 -> Int64 -> [Stmt] -> [Stmt]
dipHelp excessSz dipSz stmts =
let shiftNext = dataPointerDec dipSz
shiftBack = dataPointerInc dipSz
in
shiftNext
: copyBytes excessSz (-dipSz) dipSz -- copy bytes past end of stack
++ stmts
copy bytes back ( now from 0 of stack ; data pointer has been set )
++ [shiftBack]
dipPush :: Int64
-> Int64 -- ^ Size of thing being pushed
-> Exp
-> [Stmt]
dipPush sz sz' e | sz > sz' =
copyBytes 0 (-sz) sz
++ dataPointerDec sz
: push sz' e
++ copyBytes (sz'-sz) 0 sz -- copy bytes back (data pointer has been incremented by push)
++ [dataPointerInc sz]
| otherwise =
copyBytes (sz'-sz) (-sz) sz
++ dataPointerDec sz
: push sz' e
++ [dataPointerInc sz]
-- for e.g. negation where the stack size stays the same
plainShift :: Int64 -> [Stmt] -> [Stmt]
plainShift sz stmt =
let shiftNext = dataPointerDec sz
shiftBack = dataPointerInc sz
in
(shiftNext : stmt ++ [shiftBack])
-- works in general because relations, shifts, operations shrink the size of the
-- stack.
dipDo :: Int64 -> [Stmt] -> [Stmt]
dipDo sz stmt =
let shiftNext = dataPointerDec sz
shiftBack = dataPointerInc sz
copyBytes' = copyBytes 0 sz sz
in
(shiftNext : stmt ++ copyBytes' ++ [shiftBack])
dipShift :: Int64 -> IntBinOp -> TempM [Stmt]
dipShift sz op = dipDo sz <$> intShift op
dipRel :: Int64 -> RelBinOp -> TempM [Stmt]
dipRel sz rel = dipDo sz <$> intRel rel
dipOp :: Int64 -> IntBinOp -> TempM [Stmt]
dipOp sz op = dipDo sz <$> intOp op
dipBoolOp :: Int64 -> BoolBinOp -> TempM [Stmt]
dipBoolOp sz op = dipDo sz <$> boolOp op
copyBytes :: Int64 -- ^ dest offset
-> Int64 -- ^ src offset
-> Int64 -- ^ Number of bytes to copy
-> [Stmt]
copyBytes off1 off2 b | off1 == off2 = []
| otherwise =
let (b8, b1) = b `quotRem` 8
in copyBytes8 off1 off2 b8 ++ copyBytes1 (off1 + b8 * 8) (off2 + b8 * 8) b1
| Copy bytes 8 at a time . Note that must be divisible by 8 .
copyBytes8 :: Int64
-> Int64
^ ( number 8 - byte chunks to copy )
-> [Stmt]
copyBytes8 off1 off2 b =
let is = fmap (8*) [0..(b - 1)] in
[ MovMem (dataPointerPlus (i + off1)) 8 (Mem 8 $ dataPointerPlus (i + off2)) | i <- is ]
copyBytes1 :: Int64 -> Int64 -> Int64 -> [Stmt]
copyBytes1 off1 off2 b =
[ MovMem (dataPointerPlus (i + off1)) 1 (Mem 1 $ dataPointerPlus (i + off2)) | i <- [0..(b-1)] ]
dataPointerDec :: Int64 -> Stmt
dataPointerDec i = MovTemp DataPointer (ExprIntBinOp IntMinusIR (Reg DataPointer) (ConstInt i))
dataPointerInc :: Int64 -> Stmt
dataPointerInc i = MovTemp DataPointer (ExprIntBinOp IntPlusIR (Reg DataPointer) (ConstInt i))
dataPointerPlus :: Int64 -> Exp
dataPointerPlus off =
if off > 0
then ExprIntBinOp IntPlusIR (Reg DataPointer) (ConstInt off)
else ExprIntBinOp IntMinusIR (Reg DataPointer) (ConstInt (negate off))
| null | https://raw.githubusercontent.com/vmchale/kempe/aac73a386390747c0a54819d63c7438b54cdb168/src/Kempe/IR.hs | haskell | strict b/c it's faster according to benchmarks
TODO: type sizes in state
optimize tail-recursion, if possible
This is a little slow
^ Can it be optimized here?
FIXME: just use expressions from memory accesses
| This throws exceptions on nonsensical input.
^ Can we do TCO?
what to do on failure?
move data pointer over sz bytes
copy i0 to end of the stack
copy i1 to where i0 used to be
copy i0 at end of stack to its new place
single-case leaf (we still have the tag but we don't need to check cases etc.
one for constructor tags, etc.
TODO: padding?
FIXME: in addition to flushing padding, we should copy bytes too...
| Constructors may need to be padded, this computes the number of bytes of
padding
| Patterns for constructors are annotated differently
shift data pointer over by sz' bytes
copy sz bytes over (-sz') bytes from the data pointer
copy i0 to end of the stack
copy i1 to where i0 used to be
copy i0 at end of stack to its new place
copy sz bytes over to the end of the stack
copy sz' bytes over (duplicate)
copy sz bytes back
move data pointer over sz' bytes
how much the atom(s) grow the stack
copy bytes past end of stack
^ Size of thing being pushed
copy bytes back (data pointer has been incremented by push)
for e.g. negation where the stack size stays the same
works in general because relations, shifts, operations shrink the size of the
stack.
^ dest offset
^ src offset
^ Number of bytes to copy | module Kempe.IR ( writeModule
, runTempM
, TempM
, prettyIR
, WriteSt (..)
, size
) where
import Data.Foldable (toList, traverse_)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import Control.Monad (zipWithM)
import Control.Monad.State.Strict (State, gets, modify, runState)
import Data.Bifunctor (second)
import Data.Foldable.Ext
import Data.Int (Int64)
import qualified Data.IntMap as IM
import Data.Text.Encoding (encodeUtf8)
import Kempe.AST
import Kempe.AST.Size
import Kempe.IR.Type
import Kempe.Name
import Kempe.Unique
import Lens.Micro (Lens')
import Lens.Micro.Mtl (modifying)
import Prettyprinter (Doc, Pretty (pretty))
import Prettyprinter.Ext
data TempSt = TempSt { labels :: [Label]
, tempSupply :: [Int]
, atLabels :: IM.IntMap Label
}
asWriteSt :: TempSt -> WriteSt
asWriteSt (TempSt ls ts _) = WriteSt ls ts
runTempM :: TempM a -> (a, WriteSt)
runTempM = second asWriteSt . flip runState (TempSt [1..] [1..] mempty)
atLabelsLens :: Lens' TempSt (IM.IntMap Label)
atLabelsLens f s = fmap (\x -> s { atLabels = x }) (f (atLabels s))
nextLabels :: TempSt -> TempSt
nextLabels (TempSt ls ts ats) = TempSt (tail ls) ts ats
nextTemps :: TempSt -> TempSt
nextTemps (TempSt ls ts ats) = TempSt ls (tail ts) ats
type TempM = State TempSt
getTemp :: TempM Int
getTemp = gets (head . tempSupply) <* modify nextTemps
getTemp64 :: TempM Temp
getTemp64 = Temp64 <$> getTemp
getTemp8 :: TempM Temp
getTemp8 = Temp8 <$> getTemp
newLabel :: TempM Label
newLabel = gets (head . labels) <* modify nextLabels
broadcastName :: Unique -> TempM ()
broadcastName (Unique i) = do
l <- newLabel
modifying atLabelsLens (IM.insert i l)
lookupName :: Name a -> TempM Label
lookupName (Name _ (Unique i) _) =
gets
(IM.findWithDefault (error "Internal error in IR phase: could not look find label for name") i . atLabels)
prettyIR :: [Stmt] -> Doc ann
prettyIR = prettyLines . fmap pretty
writeModule :: SizeEnv -> Declarations () (ConsAnn MonoStackType) MonoStackType -> TempM [Stmt]
writeModule env m = traverse_ assignName m *> foldMapA (writeDecl env) m
-> [Stmt]
-> [Stmt]
tryTCO _ [] = []
tryTCO False stmts = stmts
tryTCO True stmts =
let end = last stmts
in
case end of
KCall l' -> init stmts ++ [Jump l']
_ -> stmts
assignName :: KempeDecl a c b -> TempM ()
assignName (FunDecl _ (Name _ u _) _ _ _) = broadcastName u
assignName (ExtFnDecl _ (Name _ u _) _ _ _) = broadcastName u
assignName Export{} = pure ()
assignName TyDecl{} = error "Internal error: type declarations should not exist at this stage"
writeDecl :: SizeEnv -> KempeDecl () (ConsAnn MonoStackType) MonoStackType -> TempM [Stmt]
writeDecl env (FunDecl _ n _ _ as) = do
bl <- lookupName n
(++ [Ret]) . (Labeled bl:) . tryTCO True <$> writeAtoms env True as
writeDecl _ (ExtFnDecl ty n _ _ cName) = do
bl <- lookupName n
pure [Labeled bl, CCall ty cName, Ret]
writeDecl _ (Export sTy abi n) = pure . WrapKCall abi sTy (encodeUtf8 $ name n) <$> lookupName n
writeDecl _ TyDecl{} = error "Internal error: type declarations should not exist at this stage"
writeAtoms :: SizeEnv -> Bool -> [Atom (ConsAnn MonoStackType) MonoStackType] -> TempM [Stmt]
writeAtoms _ _ [] = pure []
writeAtoms env False stmts = foldMapA (writeAtom env False) stmts
writeAtoms env l stmts =
let end = last stmts
in (++) <$> foldMapA (writeAtom env False) (init stmts) <*> writeAtom env l end
intShift :: IntBinOp -> TempM [Stmt]
intShift cons = do
t0 <- getTemp64
t1 <- getTemp64
pure $
pop 8 t0 ++ pop 8 t1 ++ push 8 (ExprIntBinOp cons (Reg t1) (Reg t0))
boolOp :: BoolBinOp -> TempM [Stmt]
boolOp op = do
t0 <- getTemp8
t1 <- getTemp8
pure $
pop 1 t0 ++ pop 1 t1 ++ push 1 (BoolBinOp op (Reg t1) (Reg t0))
intOp :: IntBinOp -> TempM [Stmt]
intOp cons = do
registers are 64 bits for integers
t1 <- getTemp64
pure $
pop 8 t0 ++ pop 8 t1 ++ push 8 (ExprIntBinOp cons (Reg t1) (Reg t0))
| Push bytes onto the data pointer
push :: Int64 -> Exp -> [Stmt]
push off e =
[ MovMem (Reg DataPointer) off e
increment instead of decrement b / c this is the Kempe ABI
]
pop :: Int64 -> Temp -> [Stmt]
pop sz t =
[ dataPointerDec sz
, MovTemp t (Mem sz (Reg DataPointer))
]
intRel :: RelBinOp -> TempM [Stmt]
intRel cons = do
t0 <- getTemp64
t1 <- getTemp64
pure $
pop 8 t0 ++ pop 8 t1 ++ push 1 (ExprIntRel cons (Reg t1) (Reg t0))
intNeg :: TempM [Stmt]
intNeg = do
t0 <- getTemp64
pure $
pop 8 t0 ++ push 8 (IntNegIR (Reg t0))
wordCount :: TempM [Stmt]
wordCount = do
t0 <- getTemp64
pure $
pop 8 t0 ++ push 8 (PopcountIR (Reg t0))
writeAtom :: SizeEnv
-> Atom (ConsAnn MonoStackType) MonoStackType
-> TempM [Stmt]
writeAtom _ _ (IntLit _ i) = pure $ push 8 (ConstInt $ fromInteger i)
writeAtom _ _ (Int8Lit _ i) = pure $ push 1 (ConstInt8 i)
writeAtom _ _ (WordLit _ w) = pure $ push 8 (ConstWord $ fromIntegral w)
writeAtom _ _ (BoolLit _ b) = pure $ push 1 (ConstBool b)
writeAtom _ _ (AtName _ n) = pure . KCall <$> lookupName n
writeAtom _ _ (AtBuiltin ([], _) Drop) = error "Internal error: Ill-typed drop!"
writeAtom _ _ (AtBuiltin ([], _) Dup) = error "Internal error: Ill-typed dup!"
writeAtom _ _ (Dip ([], _) _) = error "Internal error: Ill-typed dip()!"
writeAtom _ _ (AtBuiltin _ IntPlus) = intOp IntPlusIR
writeAtom _ _ (AtBuiltin _ IntMinus) = intOp IntMinusIR
writeAtom _ _ (AtBuiltin _ IntTimes) = intOp IntTimesIR
writeAtom _ _ (AtBuiltin _ IntMod) = intOp IntModIR
writeAtom _ _ (AtBuiltin _ IntXor) = intOp IntXorIR
FIXME : shr or sar ?
writeAtom _ _ (AtBuiltin _ IntShiftL) = intShift WordShiftLIR
writeAtom _ _ (AtBuiltin _ IntEq) = intRel IntEqIR
writeAtom _ _ (AtBuiltin _ IntLt) = intRel IntLtIR
writeAtom _ _ (AtBuiltin _ IntLeq) = intRel IntLeqIR
writeAtom _ _ (AtBuiltin _ WordPlus) = intOp IntPlusIR
writeAtom _ _ (AtBuiltin _ WordTimes) = intOp IntTimesIR
writeAtom _ _ (AtBuiltin _ WordXor) = intOp IntXorIR
writeAtom _ _ (AtBuiltin _ WordMinus) = intOp IntMinusIR
writeAtom _ _ (AtBuiltin _ IntNeq) = intRel IntNeqIR
writeAtom _ _ (AtBuiltin _ IntGeq) = intRel IntGeqIR
writeAtom _ _ (AtBuiltin _ IntGt) = intRel IntGtIR
writeAtom _ _ (AtBuiltin _ WordShiftL) = intShift WordShiftLIR
writeAtom _ _ (AtBuiltin _ WordShiftR) = intShift WordShiftRIR
writeAtom _ _ (AtBuiltin _ WordDiv) = intOp WordDivIR
writeAtom _ _ (AtBuiltin _ WordMod) = intOp WordModIR
writeAtom _ _ (AtBuiltin _ And) = boolOp BoolAnd
writeAtom _ _ (AtBuiltin _ Or) = boolOp BoolOr
writeAtom _ _ (AtBuiltin _ Xor) = boolOp BoolXor
writeAtom _ _ (AtBuiltin _ IntNeg) = intNeg
writeAtom _ _ (AtBuiltin _ Popcount) = wordCount
writeAtom env _ (AtBuiltin (is, _) Drop) =
let sz = size' env (last is) in
pure [ dataPointerDec sz ]
writeAtom env _ (AtBuiltin (is, _) Dup) =
let sz = size' env (last is) in
pure $
copyBytes 0 (-sz) sz
writeAtom env l (If _ as as') = do
l0 <- newLabel
l1 <- newLabel
let ifIR = CJump (Mem 1 (Reg DataPointer)) l0 l1
asIR <- tryTCO l <$> writeAtoms env l as
asIR' <- tryTCO l <$> writeAtoms env l as'
l2 <- newLabel
pure $ dataPointerDec 1 : ifIR : (Labeled l0 : asIR ++ [Jump l2]) ++ (Labeled l1 : asIR') ++ [Labeled l2]
writeAtom env _ (Dip (is, _) as) =
let sz = size' env (last is)
in foldMapA (dipify env sz) as
writeAtom env _ (AtBuiltin ([i0, i1], _) Swap) =
let sz0 = size' env i0
sz1 = size' env i1
in
pure $
writeAtom _ _ (AtBuiltin _ Swap) = error "Ill-typed swap!"
writeAtom env _ (AtCons ann@(ConsAnn _ tag' _) _) =
pure $ dataPointerInc (padBytes env ann) : push 1 (ConstTag tag')
writeAtom _ _ (Case ([], _) _) = error "Internal error: Ill-typed case statement?!"
writeAtom env l (Case _ ((_, as) :| [])) =
(dataPointerDec 1:) <$> writeAtoms env l as
writeAtom env l (Case (is, _) ls) =
let (ps, ass) = NE.unzip ls
decSz = case last is of
TyBuiltin _ TyInt -> 8
TyBuiltin _ TyWord -> 8
_ -> 1
in do
leaves <- zipWithM (mkLeaf env l) (toList ps) (NE.init ass)
lastLeaf <- mkLeaf env l (PatternWildcard undefined) (NE.last ass)
let (switches, meat) = unzip (leaves ++ [lastLeaf])
ret <- newLabel
let meat' = (++ [Jump ret]) . toList <$> meat
pure $ dataPointerDec decSz : switches ++ concat meat' ++ [Labeled ret]
mkLeaf :: SizeEnv -> Bool -> Pattern (ConsAnn MonoStackType) MonoStackType -> [Atom (ConsAnn MonoStackType) MonoStackType] -> TempM (Stmt, [Stmt])
mkLeaf env l p as = do
l' <- newLabel
as' <- writeAtoms env l as
let (s, mAfter) = patternSwitch env p l'
modAs = case mAfter of
Just dec -> (dec:)
Nothing -> id
pure (s, Labeled l' : modAs as')
patternSwitch :: SizeEnv -> Pattern (ConsAnn MonoStackType) MonoStackType -> Label -> (Stmt, Maybe Stmt)
patternSwitch _ (PatternBool _ True) l = (MJump (Mem 1 (Reg DataPointer)) l, Nothing)
patternSwitch _ (PatternBool _ False) l = (MJump (EqByte (Mem 1 (Reg DataPointer)) (ConstTag 0)) l, Nothing)
patternSwitch _ (PatternInt _ i) l = (MJump (ExprIntRel IntEqIR (Mem 8 (Reg DataPointer)) (ConstInt $ fromInteger i)) l, Nothing)
patternSwitch env (PatternCons ann@(ConsAnn _ tag' _) _) l =
let padAt = padBytesCons env ann
in (MJump (EqByte (Mem 1 (Reg DataPointer)) (ConstTag tag')) l, Just $ dataPointerDec padAt)
padBytes :: SizeEnv -> ConsAnn MonoStackType -> Int64
padBytes env (ConsAnn sz _ (is, _)) = sz - sizeStack env is - 1
padBytesCons :: SizeEnv -> ConsAnn MonoStackType -> Int64
padBytesCons env (ConsAnn sz _ (_, os)) = sz - sizeStack env os - 1
dipify :: SizeEnv -> Int64 -> Atom (ConsAnn MonoStackType) MonoStackType -> TempM [Stmt]
dipify _ _ (AtBuiltin ([], _) Drop) = error "Internal error: Ill-typed drop!"
dipify env sz (AtBuiltin (is, _) Drop) =
let sz' = size' env (last is)
copyBytes' = copyBytes (-sz - sz') (-sz) sz
in pure $ copyBytes' ++ [shift]
dipify env sz (AtBuiltin ([i0, i1], _) Swap) =
let sz0 = size' env i0
sz1 = size' env i1
in
pure $
dipify _ _ (Dip ([], _) _) = error "Internal error: Ill-typed dip()!"
dipify env sz (Dip (is, _) as) =
let sz' = size' env (last is)
in foldMapA (dipify env (sz + sz')) as
dipify _ _ (AtBuiltin _ Swap) = error "Internal error: Ill-typed swap!"
dipify _ sz (AtBuiltin _ IntTimes) = dipOp sz IntTimesIR
dipify _ sz (AtBuiltin _ IntPlus) = dipOp sz IntPlusIR
dipify _ sz (AtBuiltin _ IntMinus) = dipOp sz IntMinusIR
dipify _ sz (AtBuiltin _ IntDiv) = dipOp sz IntDivIR
dipify _ sz (AtBuiltin _ IntMod) = dipOp sz IntModIR
dipify _ sz (AtBuiltin _ IntXor) = dipOp sz IntXorIR
dipify _ sz (AtBuiltin _ IntEq) = dipRel sz IntEqIR
dipify _ sz (AtBuiltin _ IntLt) = dipRel sz IntLtIR
dipify _ sz (AtBuiltin _ IntLeq) = dipRel sz IntLeqIR
dipify _ sz (AtBuiltin _ IntShiftL) = dipShift sz WordShiftLIR
dipify _ sz (AtBuiltin _ IntShiftR) = dipShift sz WordShiftRIR
dipify _ sz (AtBuiltin _ WordXor) = dipOp sz IntXorIR
dipify _ sz (AtBuiltin _ WordShiftL) = dipShift sz WordShiftLIR
dipify _ sz (AtBuiltin _ WordShiftR) = dipShift sz WordShiftRIR
dipify _ sz (AtBuiltin _ WordPlus) = dipOp sz IntPlusIR
dipify _ sz (AtBuiltin _ WordTimes) = dipOp sz IntTimesIR
dipify _ sz (AtBuiltin _ IntGeq) = dipRel sz IntGeqIR
dipify _ sz (AtBuiltin _ IntGt) = dipRel sz IntGtIR
dipify _ sz (AtBuiltin _ IntNeq) = dipRel sz IntNeqIR
dipify _ sz (AtBuiltin _ IntNeg) = plainShift sz <$> intNeg
dipify _ sz (AtBuiltin _ Popcount) = plainShift sz <$> wordCount
dipify _ sz (AtBuiltin _ And) = dipBoolOp sz BoolAnd
dipify _ sz (AtBuiltin _ Or) = dipBoolOp sz BoolOr
dipify _ sz (AtBuiltin _ Xor) = dipBoolOp sz BoolXor
dipify _ sz (AtBuiltin _ WordMinus) = dipOp sz IntMinusIR
dipify _ sz (AtBuiltin _ WordDiv) = dipOp sz WordDivIR
dipify _ sz (AtBuiltin _ WordMod) = dipOp sz WordModIR
dipify _ _ (AtBuiltin ([], _) Dup) = error "Internal error: Ill-typed dup!"
dipify env sz (AtBuiltin (is, _) Dup) = do
let sz' = size' env (last is) in
pure $
dipify _ sz (IntLit _ i) = pure $ dipPush sz 8 (ConstInt $ fromInteger i)
dipify _ sz (WordLit _ w) = pure $ dipPush sz 8 (ConstWord $ fromIntegral w)
dipify _ sz (Int8Lit _ i) = pure $ dipPush sz 1 (ConstInt8 i)
dipify _ sz (BoolLit _ b) = pure $ dipPush sz 1 (ConstBool b)
dipify env sz (AtCons ann@(ConsAnn _ tag' _) _) =
pure $
copyBytes 0 (-sz) sz
++ dataPointerInc (padBytes env ann) : push 1 (ConstTag tag')
++ copyBytes (-sz) 0 sz
dipify env sz a@(If sty _ _) =
dipSupp env sz sty <$> writeAtom env False a
dipify env sz (AtName sty n) =
dipSupp env sz sty . pure . KCall <$> lookupName n
dipify env sz a@(Case sty _) =
dipSupp env sz sty <$> writeAtom env False a
dipSupp :: SizeEnv -> Int64 -> MonoStackType -> [Stmt] -> [Stmt]
dipSupp env sz (is, os) stmts =
in case compare excessSz 0 of
EQ -> plainShift sz stmts
LT -> dipDo sz stmts
GT -> dipHelp excessSz sz stmts
dipHelp :: Int64 -> Int64 -> [Stmt] -> [Stmt]
dipHelp excessSz dipSz stmts =
let shiftNext = dataPointerDec dipSz
shiftBack = dataPointerInc dipSz
in
shiftNext
++ stmts
copy bytes back ( now from 0 of stack ; data pointer has been set )
++ [shiftBack]
dipPush :: Int64
-> Exp
-> [Stmt]
dipPush sz sz' e | sz > sz' =
copyBytes 0 (-sz) sz
++ dataPointerDec sz
: push sz' e
++ [dataPointerInc sz]
| otherwise =
copyBytes (sz'-sz) (-sz) sz
++ dataPointerDec sz
: push sz' e
++ [dataPointerInc sz]
plainShift :: Int64 -> [Stmt] -> [Stmt]
plainShift sz stmt =
let shiftNext = dataPointerDec sz
shiftBack = dataPointerInc sz
in
(shiftNext : stmt ++ [shiftBack])
dipDo :: Int64 -> [Stmt] -> [Stmt]
dipDo sz stmt =
let shiftNext = dataPointerDec sz
shiftBack = dataPointerInc sz
copyBytes' = copyBytes 0 sz sz
in
(shiftNext : stmt ++ copyBytes' ++ [shiftBack])
dipShift :: Int64 -> IntBinOp -> TempM [Stmt]
dipShift sz op = dipDo sz <$> intShift op
dipRel :: Int64 -> RelBinOp -> TempM [Stmt]
dipRel sz rel = dipDo sz <$> intRel rel
dipOp :: Int64 -> IntBinOp -> TempM [Stmt]
dipOp sz op = dipDo sz <$> intOp op
dipBoolOp :: Int64 -> BoolBinOp -> TempM [Stmt]
dipBoolOp sz op = dipDo sz <$> boolOp op
-> [Stmt]
copyBytes off1 off2 b | off1 == off2 = []
| otherwise =
let (b8, b1) = b `quotRem` 8
in copyBytes8 off1 off2 b8 ++ copyBytes1 (off1 + b8 * 8) (off2 + b8 * 8) b1
| Copy bytes 8 at a time . Note that must be divisible by 8 .
copyBytes8 :: Int64
-> Int64
^ ( number 8 - byte chunks to copy )
-> [Stmt]
copyBytes8 off1 off2 b =
let is = fmap (8*) [0..(b - 1)] in
[ MovMem (dataPointerPlus (i + off1)) 8 (Mem 8 $ dataPointerPlus (i + off2)) | i <- is ]
copyBytes1 :: Int64 -> Int64 -> Int64 -> [Stmt]
copyBytes1 off1 off2 b =
[ MovMem (dataPointerPlus (i + off1)) 1 (Mem 1 $ dataPointerPlus (i + off2)) | i <- [0..(b-1)] ]
dataPointerDec :: Int64 -> Stmt
dataPointerDec i = MovTemp DataPointer (ExprIntBinOp IntMinusIR (Reg DataPointer) (ConstInt i))
dataPointerInc :: Int64 -> Stmt
dataPointerInc i = MovTemp DataPointer (ExprIntBinOp IntPlusIR (Reg DataPointer) (ConstInt i))
dataPointerPlus :: Int64 -> Exp
dataPointerPlus off =
if off > 0
then ExprIntBinOp IntPlusIR (Reg DataPointer) (ConstInt off)
else ExprIntBinOp IntMinusIR (Reg DataPointer) (ConstInt (negate off))
|
4534e63017c29d75af46b78710f1ffb5f8ad3e08a5f5346a084d697f4044d77b | hbr/fmlib | result.mli | (** Result: Handling results of operations which can fail *)
(** {1 Overview} *)
(**
Operations returning a result type can be used to have some {i functional
exception handling}.
Let's say that you have some operatios returning a result object.
{[
let op1 ... : (int, error) result = ...
let op2 ... : (char, error) result = ...
let op3 ... : (string, error) result = ...
let op3 ... : (t, error) result = ...
]}
You can chain these operations by concentrating on the success case only and
handling the error case at the end of the chain.
{[
match
let* i = op1 ... in
let* c = op2 ... i ... in
let* s = op3 ... i ... c ... in
op4 ... i ... c ... s
with
| Ok x ->
(* Handling of the success case *)
| Error e ->
(* Handling of the error case which might have
occurred in any of the steps *)
]}
A simple example:
{[
type 'a r = ('a, string) result
let add (a: int r) (b: int r): int r =
let* x = a in
let* y = b in
Ok (x + y)
let divide (a: int r) (b: int r): int r =
let* x = a in
let* y = b in
if y = 0 then
Error "Division by Zero"
else
Ok (x / y)
assert (
add (Ok 1) (divide (Ok 2) (Ok 0))
=
Error "Division by Zero"
)
assert (
add (Ok 1) (divide (Ok 10) (Ok 2))
=
Ok 6
)
]}
*)
(** {1 API} *)
type ('a,'e) t = ('a, 'e) result
* [ ' a ] is the result type in case of success and [ ' e ] is the result type in
case of failure . It is implemented by the ocaml type [ result ] from the ocaml
standard library .
case of failure. It is implemented by the ocaml type [result] from the ocaml
standard library.
*)
val return: 'a -> ('a, 'e) t
(** [return a] Equivalent to [Ok a]. *)
val fail: 'e -> ('a, 'e) t
(** [fail e] Equivalent to [Error e]. *)
val to_option: ('a, 'e) t -> 'a option
(** [to_option r] Map [r] to an optional element i.e. [Some a] in case of [Ok a]
and [None] in case of [Error _]. *)
val (>>=): ('a,'e) t -> ('a -> ('b,'e) t) -> ('b,'e) t
(** [m >>= f]
maps success result [m] to [f a]. In case of an error result [f]
is not called and the error remains.
*)
val ( let* ): ('a,'e) t -> ('a -> ('b,'e) t) -> ('b,'e) t
(**
[let* a = m in f a] is the same as [m >>= f]
*)
val map: ('a -> 'b) -> ('a, 'e) t -> ('b, 'e) t
(** [map f m] Map the result in [m] via the function [f]. *)
val map_error: ('e -> 'f) -> ('a, 'e) t -> ('a, 'f) t
(** [map_error f m] Map the error in [m] via the function [f]. *)
val get: ('a, Void.t) t -> 'a
(** [get m] Get the ok content of a result object which cannot have errors. *)
(** {1 Monad} *)
(** The result type encapsulated in a module which satisfies the monadic
interface. *)
module Monad (E: Interfaces.ANY):
sig
type 'a t = ('a, E.t) result
val return: 'a -> 'a t
val fail: E.t -> 'a t
val to_option: 'a t -> 'a option
val (>>=): 'a t -> ('a -> 'b t) -> 'b t
val ( let* ): 'a t -> ('a -> 'b t) -> 'b t
end
| null | https://raw.githubusercontent.com/hbr/fmlib/92ac0e65db09375fad79029072e0c45e80d2586f/src/std/result.mli | ocaml | * Result: Handling results of operations which can fail
* {1 Overview}
*
Operations returning a result type can be used to have some {i functional
exception handling}.
Let's say that you have some operatios returning a result object.
{[
let op1 ... : (int, error) result = ...
let op2 ... : (char, error) result = ...
let op3 ... : (string, error) result = ...
let op3 ... : (t, error) result = ...
]}
You can chain these operations by concentrating on the success case only and
handling the error case at the end of the chain.
{[
match
let* i = op1 ... in
let* c = op2 ... i ... in
let* s = op3 ... i ... c ... in
op4 ... i ... c ... s
with
| Ok x ->
(* Handling of the success case
Handling of the error case which might have
occurred in any of the steps
* {1 API}
* [return a] Equivalent to [Ok a].
* [fail e] Equivalent to [Error e].
* [to_option r] Map [r] to an optional element i.e. [Some a] in case of [Ok a]
and [None] in case of [Error _].
* [m >>= f]
maps success result [m] to [f a]. In case of an error result [f]
is not called and the error remains.
*
[let* a = m in f a] is the same as [m >>= f]
* [map f m] Map the result in [m] via the function [f].
* [map_error f m] Map the error in [m] via the function [f].
* [get m] Get the ok content of a result object which cannot have errors.
* {1 Monad}
* The result type encapsulated in a module which satisfies the monadic
interface. |
| Error e ->
]}
A simple example:
{[
type 'a r = ('a, string) result
let add (a: int r) (b: int r): int r =
let* x = a in
let* y = b in
Ok (x + y)
let divide (a: int r) (b: int r): int r =
let* x = a in
let* y = b in
if y = 0 then
Error "Division by Zero"
else
Ok (x / y)
assert (
add (Ok 1) (divide (Ok 2) (Ok 0))
=
Error "Division by Zero"
)
assert (
add (Ok 1) (divide (Ok 10) (Ok 2))
=
Ok 6
)
]}
*)
type ('a,'e) t = ('a, 'e) result
* [ ' a ] is the result type in case of success and [ ' e ] is the result type in
case of failure . It is implemented by the ocaml type [ result ] from the ocaml
standard library .
case of failure. It is implemented by the ocaml type [result] from the ocaml
standard library.
*)
val return: 'a -> ('a, 'e) t
val fail: 'e -> ('a, 'e) t
val to_option: ('a, 'e) t -> 'a option
val (>>=): ('a,'e) t -> ('a -> ('b,'e) t) -> ('b,'e) t
val ( let* ): ('a,'e) t -> ('a -> ('b,'e) t) -> ('b,'e) t
val map: ('a -> 'b) -> ('a, 'e) t -> ('b, 'e) t
val map_error: ('e -> 'f) -> ('a, 'e) t -> ('a, 'f) t
val get: ('a, Void.t) t -> 'a
module Monad (E: Interfaces.ANY):
sig
type 'a t = ('a, E.t) result
val return: 'a -> 'a t
val fail: E.t -> 'a t
val to_option: 'a t -> 'a option
val (>>=): 'a t -> ('a -> 'b t) -> 'b t
val ( let* ): 'a t -> ('a -> 'b t) -> 'b t
end
|
018bc55bf3856707c4e6838a773423cd9b3954bd3f59458ad664e427a3371664 | cubicle-model-checker/cubicle | symbols.mli | (**************************************************************************)
(* *)
Cubicle
(* *)
Copyright ( C ) 2011 - 2014
(* *)
and
Universite Paris - Sud 11
(* *)
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(**************************************************************************)
type operator =
| Plus | Minus | Mult | Div | Modulo
type name_kind = Ac | Constructor | Other
type t =
| True
| False
| Name of Hstring.t * name_kind
| Int of Hstring.t
| Real of Hstring.t
| Op of operator
| Var of Hstring.t
val name : ?kind:name_kind -> Hstring.t -> t
val var : string -> t
val int : string -> t
val real : string -> t
val is_ac : t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val hash : t -> int
val print : Format.formatter -> t -> unit
module Map : Map.S with type key = t
module Set : Set.S with type elt = t
| null | https://raw.githubusercontent.com/cubicle-model-checker/cubicle/00f09bb2d4bb496549775e770d7ada08bc1e4866/smt/symbols.mli | ocaml | ************************************************************************
License version 2.0
************************************************************************ | Cubicle
Copyright ( C ) 2011 - 2014
and
Universite Paris - Sud 11
This file is distributed under the terms of the Apache Software
type operator =
| Plus | Minus | Mult | Div | Modulo
type name_kind = Ac | Constructor | Other
type t =
| True
| False
| Name of Hstring.t * name_kind
| Int of Hstring.t
| Real of Hstring.t
| Op of operator
| Var of Hstring.t
val name : ?kind:name_kind -> Hstring.t -> t
val var : string -> t
val int : string -> t
val real : string -> t
val is_ac : t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
val hash : t -> int
val print : Format.formatter -> t -> unit
module Map : Map.S with type key = t
module Set : Set.S with type elt = t
|
76f12d591d167e0c8232b5caa3dd1f503fb18c43e252383c5cfec8c49bbab106 | mariachris/Concuerror | depend_4.erl | -module(depend_4).
-export([depend_4/0]).
-export([scenarios/0]).
scenarios() -> [{?MODULE, inf, dpor}].
depend_4() ->
ets:new(table, [public, named_table]),
ets:insert(table, {x, 0}),
ets:insert(table, {y, 0}),
ets:insert(table, {z, 0}),
spawn(fun() -> ets:insert(table, {z, 1}) end),
spawn(fun() -> ets:insert(table, {x, 1}) end),
spawn(fun() -> ets:insert(table, {y, 1}) end),
spawn(fun() ->
[{x, X}] = ets:lookup(table, x),
case X of
1 ->
[{y, Y}] = ets:lookup(table, y),
case Y of
1 -> ets:lookup(table, z);
_ -> ok
end;
_ -> ok
end
end),
spawn(fun() ->
[{y, Y}] = ets:lookup(table, y),
case Y of
1 -> ets:lookup(table, z);
_ -> ok
end
end),
spawn(fun() -> ets:insert(table, {x, 2}) end),
block().
block() ->
receive
after
infinity -> ok
end.
| null | https://raw.githubusercontent.com/mariachris/Concuerror/87e63f10ac615bf2eeac5b0916ef54d11a933e0b/testsuite/suites/dpor/src/depend_4.erl | erlang | -module(depend_4).
-export([depend_4/0]).
-export([scenarios/0]).
scenarios() -> [{?MODULE, inf, dpor}].
depend_4() ->
ets:new(table, [public, named_table]),
ets:insert(table, {x, 0}),
ets:insert(table, {y, 0}),
ets:insert(table, {z, 0}),
spawn(fun() -> ets:insert(table, {z, 1}) end),
spawn(fun() -> ets:insert(table, {x, 1}) end),
spawn(fun() -> ets:insert(table, {y, 1}) end),
spawn(fun() ->
[{x, X}] = ets:lookup(table, x),
case X of
1 ->
[{y, Y}] = ets:lookup(table, y),
case Y of
1 -> ets:lookup(table, z);
_ -> ok
end;
_ -> ok
end
end),
spawn(fun() ->
[{y, Y}] = ets:lookup(table, y),
case Y of
1 -> ets:lookup(table, z);
_ -> ok
end
end),
spawn(fun() -> ets:insert(table, {x, 2}) end),
block().
block() ->
receive
after
infinity -> ok
end.
| |
5b985cc388a746bcaa6645784bad261d7162f4fc0e8989e1c3e0f1c61a89273f | expipiplus1/vulkan | Write.hs | module Render.Element.Write where
import Data.Char ( isLower )
import Data.List ( lookup )
import Data.List.Extra ( groupOn
, nubOrd
, nubOrdOn
)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Set ( unions )
import Data.Text as T
import Data.Text.IO as T
import qualified Data.Vector.Extra as V
import Data.Vector.Extra ( Vector )
import Foreign.Ptr
import Language.Haskell.TH ( mkName
, nameBase
, nameModule
)
import qualified Ormolu
import qualified Ormolu.Config as Ormolu
import Polysemy
import Polysemy.Input
import Prettyprinter
import Prettyprinter.Render.Text
import Relude hiding ( Handle
, State
, modify'
, runState
)
import System.Directory
import System.FilePath
import qualified Data.Vector.Generic as VG
import Type.Reflection
import Control.Exception ( IOException, try )
import Control.Exception.Base ( catch )
import Documentation
import Documentation.Haddock
import Error
import Haskell.Name
import qualified Prelude
import Render.Element
import Render.Names
import Render.SpecInfo
import Render.Utils
import Spec.Types
import Write.Segment
----------------------------------------------------------------
-- Rendering
----------------------------------------------------------------
renderSegments
:: forall r
. ( HasErr r
, Member (Embed IO) r
, HasSpecInfo r
, HasTypeInfo r
, HasRenderedNames r
, HasRenderParams r
)
=> (Documentee -> Maybe Documentation)
-> FilePath
-> [Segment ModName RenderElement]
-> Sem r ()
renderSegments getDoc out segments = do
let exportMap :: Map.Map HName (Export, ModName)
exportMap = Map.fromList
[ (n, (e, m))
| Segment m rs <- segments
, r <- toList rs
, e <- toList (reExports r)
, n <- exportName e : (exportName <$> V.toList (exportWith e))
]
findLocalModule :: HName -> Maybe ModName
findLocalModule n = snd <$> Map.lookup n exportMap
findModule :: Name -> Maybe ModName
findModule n = ModName . T.pack <$> nameModule n
--
-- Boot module handling
TODO , move this checking elsewhere
--
allBootSegments :: [Segment ModName RenderElement]
allBootSegments =
Relude.filter (\(Segment _ es) -> not (V.null es))
$ segments
<&> \(Segment m es) -> Segment m (V.mapMaybe reBoot es)
findBootElems :: HName -> Sem r (ModName, RenderElement)
findBootElems =
let bootElemMap :: Map HName (ModName, RenderElement)
bootElemMap = Map.fromList
[ (n, (m, re))
| Segment m res <- allBootSegments
, re <- toList res
, e <- toList (reExports re)
, n <- exportName e : (exportName <$> V.toList (exportWith e))
]
in \n ->
note @r ("Unable to find boot element for " <> show n)
$ Map.lookup n bootElemMap
sourceImportNames = nubOrd
[ n
| Segment _ res <- segments
, re <- toList res
, Import { importName = n, importSource = True } <- toList
(reLocalImports re <> maybe mempty reLocalImports (reBoot re))
]
-- TODO: do this segmentation properly, nubbing here is nasty
requiredBootElements <-
nubOrdOn (reExports . snd) <$> forV sourceImportNames findBootElems
let requiredBootSegments =
fmap (\case
[] -> error "empty group"
((m, re) : res) -> Segment m (fromList (re : (snd <$> res))))
. groupOn fst
. sortOn fst
$ requiredBootElements
--
-- Write the files
--
traverseV_ (renderModule out False getDoc findModule findLocalModule) segments
traverseV_ (renderModule out True getDoc findModule findLocalModule)
requiredBootSegments
renderModule
:: ( Member (Embed IO) r
, HasErr r
, HasSpecInfo r
, HasTypeInfo r
, HasRenderedNames r
, HasRenderParams r
)
=> FilePath
-- ^ out directory
-> Bool
-- ^ Is a boot file
-> (Documentee -> Maybe Documentation)
-> (Name -> Maybe ModName)
-> (HName -> Maybe ModName)
-> Segment ModName RenderElement
-> Sem r ()
renderModule out boot getDoc findModule findLocalModule (Segment modName unsortedElements)
= do
let exportsType = V.any (isTyConName . exportName) . reExports
es = fromList . sortOn exportsType . toList $ unsortedElements
RenderParams {..} <- input
let
ext = bool ".hs" ".hs-boot" boot
f =
toString
(out <> "/" <> T.unpack (T.replace "." "/" (unModName modName) <> ext)
)
openImports = vsep
( fmap (\(ModName n) -> "import" <+> pretty n)
. Set.toList
. Set.unions
$ (reReexportedModules <$> V.toList es)
)
declaredNames = V.concatMap
(\RenderElement {..} -> allExports (reExports <> reInternal))
es
importFilter =
Relude.filter (\(Import n _ _ _ _) -> n `V.notElem` declaredNames)
findModule' n =
note ("Unable to find module for " <> show n) (findModule n)
findLocalModule' n =
note ("Unable to find local module for " <> show n) (findLocalModule n)
imports <- vsep <$> traverseV
(renderImport findModule' (T.pack . nameBase) thNameNamespace id)
( mapMaybe
(\i -> do
n <- if V.null (importChildren i)
then fixOddImport (importName i)
else Just (importName i)
pure i { importName = n }
)
. Relude.toList
. unions
$ (reImports <$> V.toList es)
)
let
exportToImport (Export name withAll with _) =
Import name False mempty (withAll || not (V.null with)) False
allReexportImports =
fmap exportToImport
. Relude.toList
. unions
. fmap reReexportedNames
. V.toList
$ es
allLocalImports =
Relude.toList . unions . fmap reLocalImports . V.toList $ es
resolveAlias <- getResolveAlias
parentedImports <- traverse adoptConstructors
(allLocalImports <> allReexportImports)
localImports <- vsep <$> traverseV
(renderImport findLocalModule' unName nameNameSpace resolveAlias)
(importFilter parentedImports)
let
locate :: CName -> DocumenteeLocation
locate n =
let names = case n of
CName "" -> []
CName n' | isLower (T.head n') -> [mkFunName n]
_ -> [mkTyName n, mkFunName n, mkPatternName n]
in case asum ((\n -> (n, ) <$> findLocalModule n) <$> names) of
Just (n, m) | m == modName -> ThisModule n
Just (n, m) -> OtherModule m n
Nothing -> Unknown
getDocumentation :: Documentee -> Doc ()
getDocumentation target = case getDoc target of
Nothing -> "-- No documentation found for" <+> viaShow target
Just d -> case documentationToHaddock externalDocHTML locate d of
Left e ->
"-- Error getting documentation for"
<+> viaShow target
<> ":"
<+> viaShow e
Right (Haddock t) -> commentNoWrap t
allReexportedModules =
V.fromList
. Set.toList
. Set.unions
. fmap reReexportedModules
. toList
$ es
exports = V.concatMap reExports es
reexports = V.concatMap
(\re -> V.fromList
( (\(Export name withAll with reexportable) ->
Export name (withAll || not (V.null with)) mempty reexportable
)
<$> toList (reReexportedNames re)
)
)
es
languageExtensions =
let allExts =
Set.toList
. Set.insert (LanguageExtension "CPP")
. Set.unions
. toList
. fmap reExtensions
$ es
in [ "{-# language" <+> pretty e <+> "#-}" | e <- allExts ]
moduleChapter (ModName m) =
let lastComponent = Prelude.last (T.splitOn "." m)
in Chapter lastComponent
moduleDocumentation = getDocumentation (moduleChapter modName)
layoutDoc = renderStrict . layoutPretty defaultLayoutOptions
{ layoutPageWidth = AvailablePerLine 80 1
}
headerContents = vsep
[ vsep languageExtensions
, moduleDocumentation
, "module"
<+> pretty modName
<> indent
2
( parenList
$ (fmap exportDoc . nubOrdOnV exportName $ (exports <> reexports)
)
<> ( (\(ModName m) -> renderExport Module m mempty)
<$> allReexportedModules
)
)
<+> "where"
, openImports
, imports
, localImports
]
layoutContent e = runMaybeT $ do
d <- maybe mzero pure $ reDoc e getDocumentation
let t = layoutDoc (d <> line <> line)
if getAll (reCanFormat e)
then
liftIO (try (Ormolu.ormolu ormoluConfig "<stdin>" (T.unpack t)))
>>= \case
Left ex ->
error
$ "Fail: Ormolu failed to handle module:\n"
<> T.pack (displayException @Ormolu.OrmoluException ex)
<> "\n\n\n"
<> t
Right f -> pure f
else pure t
contentsTexts <- mapMaybeM layoutContent (V.toList es)
let moduleText =
T.intercalate "\n" (layoutDoc headerContents : contentsTexts)
liftIO $ createDirectoryIfMissing True (takeDirectory f)
writeIfChanged f moduleText
allExports :: Vector Export -> Vector HName
allExports =
V.concatMap (\Export {..} -> exportName `V.cons` allExports exportWith)
-- | If we are importing constructors of a type alias, resolve the alias and
-- import the constructors with the resolved name.
renderImport
:: (HasErr r, HasSpecInfo r, Eq a)
=> (a -> Sem r ModName)
-> (a -> Text)
-> (a -> NameSpace)
-> (a -> a)
-> Import a
-> Sem r (Doc ())
renderImport findModule getName getNameSpace resolveAlias i =
let resolved = resolveAlias (importName i)
importsNoChildren = V.null (importChildren i) && not (importWithAll i)
in if importsNoChildren || resolved == importName i
then renderImport' findModule getName getNameSpace i
else do
a <- renderImport'
findModule
getName
getNameSpace
i { importWithAll = False, importChildren = mempty }
c <- renderImport' findModule
getName
getNameSpace
i { importName = resolved }
pure $ vsep [a, c]
renderImport'
:: (HasErr r, HasSpecInfo r, Eq a)
=> (a -> Sem r ModName)
-> (a -> Text)
-> (a -> NameSpace)
-> Import a
-> Sem r (Doc ())
renderImport' findModule getName getNameSpace (Import n qual children withAll source)
= do
ModName mod' <- findModule n
let sourceDoc = bool "" " {-# SOURCE #-}" source
qualDoc = bool "" " qualified" qual
base = getName n
ns = getNameSpace n
baseP = wrapSymbol ns base
spec = nameSpacePrefix ns
childrenDoc = if V.null children && not withAll
then ""
else parenList
( (wrapSymbol (getNameSpace n) . getName <$> children)
<> (if withAll then V.singleton ".." else V.empty)
)
when (T.null mod') $ throw "Trying to render an import with no module!"
pure $ "import" <> sourceDoc <> qualDoc <+> pretty mod' <+> parenList
(V.singleton (spec <> baseP <> childrenDoc))
fixOddImport :: Name -> Maybe Name
fixOddImport n = fromMaybe (Just n) (lookup n fixes)
where
fixes =
[ -- Prelude types
(''Maybe , Nothing)
, (''Word , Nothing)
, (''() , Nothing)
, (''IO , Nothing)
, (''Integral , Nothing)
, (''Eq , Nothing)
, (''Float , Nothing)
, (''Double , Nothing)
, (''Int , Nothing)
, (''Bool , Nothing)
,
-- Base
(''Int8 , Just (mkName "Data.Int.Int8"))
, (''Int16 , Just (mkName "Data.Int.Int16"))
, (''Int32 , Just (mkName "Data.Int.Int32"))
, (''Int64 , Just (mkName "Data.Int.Int64"))
, (''Word8 , Just (mkName "Data.Word.Word8"))
, (''Word16 , Just (mkName "Data.Word.Word16"))
, (''Word32 , Just (mkName "Data.Word.Word32"))
, (''Word64 , Just (mkName "Data.Word.Word64"))
, (''Ptr , Just (mkName "Foreign.Ptr.Ptr"))
, (''FunPtr , Just (mkName "Foreign.Ptr.FunPtr"))
, ('nullPtr , Just (mkName "Foreign.Ptr.nullPtr"))
, ('castFunPtr, Just (mkName "Foreign.Ptr.castFunPtr"))
, ('plusPtr , Just (mkName "Foreign.Ptr.plusPtr"))
, (''Type , Just (mkName "Data.Kind.Type"))
, (''Nat , Just (mkName "GHC.TypeNats.Nat"))
, (''Constraint, Just (mkName "Data.Kind.Constraint"))
, (''Typeable, Just (mkName "Data.Typeable.Typeable"))
, ('typeRep, Just (mkName "Type.Reflection.typeRep"))
, (''TypeRep, Just (mkName "Type.Reflection.TypeRep"))
, ('coerce , Just (mkName "Data.Coerce.coerce"))
,
-- Other
(''ByteString, Just (mkName "Data.ByteString.ByteString"))
, (''VG.Vector, Just (mkName "Data.Vector.Generic.Vector"))
]
----------------------------------------------------------------
--
----------------------------------------------------------------
newtype TypeInfo = TypeInfo
{ tiConMap :: HName -> Maybe HName
}
type HasTypeInfo r = Member (Input TypeInfo) r
withTypeInfo
:: HasRenderParams r => Spec t -> Sem (Input TypeInfo ': r) a -> Sem r a
withTypeInfo spec a = do
ti <- specTypeInfo spec
runInputConst ti a
specTypeInfo :: HasRenderParams r => Spec t -> Sem r TypeInfo
specTypeInfo Spec {..} = do
RenderParams {..} <- input
let tyMap :: Map HName HName
tyMap = Map.fromList
[ (mkConName eExportedName evName, mkTyName eExportedName)
| Enum {..} <- V.toList specEnums
, let eExportedName = case eType of
AnEnum -> eName
ABitmask flags _ -> flags
, EnumValue {..} <- V.toList eValues
]
pure $ TypeInfo (`Map.lookup` tyMap)
adoptConstructors :: HasTypeInfo r => Import HName -> Sem r (Import HName)
adoptConstructors = \case
i@(Import n q cs _ source) -> getConParent n <&> \case
Just p -> Import p q (V.singleton n <> cs) False source
Nothing -> i
where getConParent n = inputs (`tiConMap` n)
----------------------------------------------------------------
--
----------------------------------------------------------------
nubOrdOnV :: Ord b => (a -> b) -> Vector a -> Vector a
nubOrdOnV p = fromList . nubOrdOn p . toList
writeIfChanged :: MonadIO m => FilePath -> Text -> m ()
writeIfChanged f t' = liftIO $ do
t <- readFileMaybe f
when (t /= Just t') $ T.writeFile f t'
readFileMaybe :: FilePath -> IO (Maybe Text)
readFileMaybe f =
(Just <$> T.readFile f) `catch` (\(_ :: IOException) -> pure Nothing)
-- If we don't put PatternSynonyms here the fourmolu eatst he comments on them
ormoluConfig :: Ormolu.Config Ormolu.RegionIndices
ormoluConfig = Ormolu.defaultConfig
{ Ormolu.cfgDynOptions = [Ormolu.DynOption "-XPatternSynonyms"]
, Ormolu.cfgPrinterOpts = Ormolu.defaultPrinterOpts
{ Ormolu.poIndentation = pure 2
, Ormolu.poFunctionArrows = pure Ormolu . LeadingArrows
, Ormolu.poCommaStyle = pure Ormolu.Leading
, Ormolu.poImportExportStyle = pure Ormolu.ImportExportLeading
, Ormolu.poIndentWheres = pure False
, Ormolu.poRecordBraceSpace = pure False
, Ormolu.poNewlinesBetweenDecls = pure 1
, Ormolu.poHaddockStyle = pure Ormolu.HaddockSingleLine
, Ormolu.poRespectful = pure False
}
}
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/70d8cca16893f8de76c0eb89e79e73f5a455db76/generate-new/src/Render/Element/Write.hs | haskell | --------------------------------------------------------------
Rendering
--------------------------------------------------------------
Boot module handling
TODO: do this segmentation properly, nubbing here is nasty
Write the files
^ out directory
^ Is a boot file
| If we are importing constructors of a type alias, resolve the alias and
import the constructors with the resolved name.
Prelude types
Base
Other
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
If we don't put PatternSynonyms here the fourmolu eatst he comments on them | module Render.Element.Write where
import Data.Char ( isLower )
import Data.List ( lookup )
import Data.List.Extra ( groupOn
, nubOrd
, nubOrdOn
)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Set ( unions )
import Data.Text as T
import Data.Text.IO as T
import qualified Data.Vector.Extra as V
import Data.Vector.Extra ( Vector )
import Foreign.Ptr
import Language.Haskell.TH ( mkName
, nameBase
, nameModule
)
import qualified Ormolu
import qualified Ormolu.Config as Ormolu
import Polysemy
import Polysemy.Input
import Prettyprinter
import Prettyprinter.Render.Text
import Relude hiding ( Handle
, State
, modify'
, runState
)
import System.Directory
import System.FilePath
import qualified Data.Vector.Generic as VG
import Type.Reflection
import Control.Exception ( IOException, try )
import Control.Exception.Base ( catch )
import Documentation
import Documentation.Haddock
import Error
import Haskell.Name
import qualified Prelude
import Render.Element
import Render.Names
import Render.SpecInfo
import Render.Utils
import Spec.Types
import Write.Segment
renderSegments
:: forall r
. ( HasErr r
, Member (Embed IO) r
, HasSpecInfo r
, HasTypeInfo r
, HasRenderedNames r
, HasRenderParams r
)
=> (Documentee -> Maybe Documentation)
-> FilePath
-> [Segment ModName RenderElement]
-> Sem r ()
renderSegments getDoc out segments = do
let exportMap :: Map.Map HName (Export, ModName)
exportMap = Map.fromList
[ (n, (e, m))
| Segment m rs <- segments
, r <- toList rs
, e <- toList (reExports r)
, n <- exportName e : (exportName <$> V.toList (exportWith e))
]
findLocalModule :: HName -> Maybe ModName
findLocalModule n = snd <$> Map.lookup n exportMap
findModule :: Name -> Maybe ModName
findModule n = ModName . T.pack <$> nameModule n
TODO , move this checking elsewhere
allBootSegments :: [Segment ModName RenderElement]
allBootSegments =
Relude.filter (\(Segment _ es) -> not (V.null es))
$ segments
<&> \(Segment m es) -> Segment m (V.mapMaybe reBoot es)
findBootElems :: HName -> Sem r (ModName, RenderElement)
findBootElems =
let bootElemMap :: Map HName (ModName, RenderElement)
bootElemMap = Map.fromList
[ (n, (m, re))
| Segment m res <- allBootSegments
, re <- toList res
, e <- toList (reExports re)
, n <- exportName e : (exportName <$> V.toList (exportWith e))
]
in \n ->
note @r ("Unable to find boot element for " <> show n)
$ Map.lookup n bootElemMap
sourceImportNames = nubOrd
[ n
| Segment _ res <- segments
, re <- toList res
, Import { importName = n, importSource = True } <- toList
(reLocalImports re <> maybe mempty reLocalImports (reBoot re))
]
requiredBootElements <-
nubOrdOn (reExports . snd) <$> forV sourceImportNames findBootElems
let requiredBootSegments =
fmap (\case
[] -> error "empty group"
((m, re) : res) -> Segment m (fromList (re : (snd <$> res))))
. groupOn fst
. sortOn fst
$ requiredBootElements
traverseV_ (renderModule out False getDoc findModule findLocalModule) segments
traverseV_ (renderModule out True getDoc findModule findLocalModule)
requiredBootSegments
renderModule
:: ( Member (Embed IO) r
, HasErr r
, HasSpecInfo r
, HasTypeInfo r
, HasRenderedNames r
, HasRenderParams r
)
=> FilePath
-> Bool
-> (Documentee -> Maybe Documentation)
-> (Name -> Maybe ModName)
-> (HName -> Maybe ModName)
-> Segment ModName RenderElement
-> Sem r ()
renderModule out boot getDoc findModule findLocalModule (Segment modName unsortedElements)
= do
let exportsType = V.any (isTyConName . exportName) . reExports
es = fromList . sortOn exportsType . toList $ unsortedElements
RenderParams {..} <- input
let
ext = bool ".hs" ".hs-boot" boot
f =
toString
(out <> "/" <> T.unpack (T.replace "." "/" (unModName modName) <> ext)
)
openImports = vsep
( fmap (\(ModName n) -> "import" <+> pretty n)
. Set.toList
. Set.unions
$ (reReexportedModules <$> V.toList es)
)
declaredNames = V.concatMap
(\RenderElement {..} -> allExports (reExports <> reInternal))
es
importFilter =
Relude.filter (\(Import n _ _ _ _) -> n `V.notElem` declaredNames)
findModule' n =
note ("Unable to find module for " <> show n) (findModule n)
findLocalModule' n =
note ("Unable to find local module for " <> show n) (findLocalModule n)
imports <- vsep <$> traverseV
(renderImport findModule' (T.pack . nameBase) thNameNamespace id)
( mapMaybe
(\i -> do
n <- if V.null (importChildren i)
then fixOddImport (importName i)
else Just (importName i)
pure i { importName = n }
)
. Relude.toList
. unions
$ (reImports <$> V.toList es)
)
let
exportToImport (Export name withAll with _) =
Import name False mempty (withAll || not (V.null with)) False
allReexportImports =
fmap exportToImport
. Relude.toList
. unions
. fmap reReexportedNames
. V.toList
$ es
allLocalImports =
Relude.toList . unions . fmap reLocalImports . V.toList $ es
resolveAlias <- getResolveAlias
parentedImports <- traverse adoptConstructors
(allLocalImports <> allReexportImports)
localImports <- vsep <$> traverseV
(renderImport findLocalModule' unName nameNameSpace resolveAlias)
(importFilter parentedImports)
let
locate :: CName -> DocumenteeLocation
locate n =
let names = case n of
CName "" -> []
CName n' | isLower (T.head n') -> [mkFunName n]
_ -> [mkTyName n, mkFunName n, mkPatternName n]
in case asum ((\n -> (n, ) <$> findLocalModule n) <$> names) of
Just (n, m) | m == modName -> ThisModule n
Just (n, m) -> OtherModule m n
Nothing -> Unknown
getDocumentation :: Documentee -> Doc ()
getDocumentation target = case getDoc target of
Nothing -> "-- No documentation found for" <+> viaShow target
Just d -> case documentationToHaddock externalDocHTML locate d of
Left e ->
"-- Error getting documentation for"
<+> viaShow target
<> ":"
<+> viaShow e
Right (Haddock t) -> commentNoWrap t
allReexportedModules =
V.fromList
. Set.toList
. Set.unions
. fmap reReexportedModules
. toList
$ es
exports = V.concatMap reExports es
reexports = V.concatMap
(\re -> V.fromList
( (\(Export name withAll with reexportable) ->
Export name (withAll || not (V.null with)) mempty reexportable
)
<$> toList (reReexportedNames re)
)
)
es
languageExtensions =
let allExts =
Set.toList
. Set.insert (LanguageExtension "CPP")
. Set.unions
. toList
. fmap reExtensions
$ es
in [ "{-# language" <+> pretty e <+> "#-}" | e <- allExts ]
moduleChapter (ModName m) =
let lastComponent = Prelude.last (T.splitOn "." m)
in Chapter lastComponent
moduleDocumentation = getDocumentation (moduleChapter modName)
layoutDoc = renderStrict . layoutPretty defaultLayoutOptions
{ layoutPageWidth = AvailablePerLine 80 1
}
headerContents = vsep
[ vsep languageExtensions
, moduleDocumentation
, "module"
<+> pretty modName
<> indent
2
( parenList
$ (fmap exportDoc . nubOrdOnV exportName $ (exports <> reexports)
)
<> ( (\(ModName m) -> renderExport Module m mempty)
<$> allReexportedModules
)
)
<+> "where"
, openImports
, imports
, localImports
]
layoutContent e = runMaybeT $ do
d <- maybe mzero pure $ reDoc e getDocumentation
let t = layoutDoc (d <> line <> line)
if getAll (reCanFormat e)
then
liftIO (try (Ormolu.ormolu ormoluConfig "<stdin>" (T.unpack t)))
>>= \case
Left ex ->
error
$ "Fail: Ormolu failed to handle module:\n"
<> T.pack (displayException @Ormolu.OrmoluException ex)
<> "\n\n\n"
<> t
Right f -> pure f
else pure t
contentsTexts <- mapMaybeM layoutContent (V.toList es)
let moduleText =
T.intercalate "\n" (layoutDoc headerContents : contentsTexts)
liftIO $ createDirectoryIfMissing True (takeDirectory f)
writeIfChanged f moduleText
allExports :: Vector Export -> Vector HName
allExports =
V.concatMap (\Export {..} -> exportName `V.cons` allExports exportWith)
renderImport
:: (HasErr r, HasSpecInfo r, Eq a)
=> (a -> Sem r ModName)
-> (a -> Text)
-> (a -> NameSpace)
-> (a -> a)
-> Import a
-> Sem r (Doc ())
renderImport findModule getName getNameSpace resolveAlias i =
let resolved = resolveAlias (importName i)
importsNoChildren = V.null (importChildren i) && not (importWithAll i)
in if importsNoChildren || resolved == importName i
then renderImport' findModule getName getNameSpace i
else do
a <- renderImport'
findModule
getName
getNameSpace
i { importWithAll = False, importChildren = mempty }
c <- renderImport' findModule
getName
getNameSpace
i { importName = resolved }
pure $ vsep [a, c]
renderImport'
:: (HasErr r, HasSpecInfo r, Eq a)
=> (a -> Sem r ModName)
-> (a -> Text)
-> (a -> NameSpace)
-> Import a
-> Sem r (Doc ())
renderImport' findModule getName getNameSpace (Import n qual children withAll source)
= do
ModName mod' <- findModule n
let sourceDoc = bool "" " {-# SOURCE #-}" source
qualDoc = bool "" " qualified" qual
base = getName n
ns = getNameSpace n
baseP = wrapSymbol ns base
spec = nameSpacePrefix ns
childrenDoc = if V.null children && not withAll
then ""
else parenList
( (wrapSymbol (getNameSpace n) . getName <$> children)
<> (if withAll then V.singleton ".." else V.empty)
)
when (T.null mod') $ throw "Trying to render an import with no module!"
pure $ "import" <> sourceDoc <> qualDoc <+> pretty mod' <+> parenList
(V.singleton (spec <> baseP <> childrenDoc))
fixOddImport :: Name -> Maybe Name
fixOddImport n = fromMaybe (Just n) (lookup n fixes)
where
fixes =
(''Maybe , Nothing)
, (''Word , Nothing)
, (''() , Nothing)
, (''IO , Nothing)
, (''Integral , Nothing)
, (''Eq , Nothing)
, (''Float , Nothing)
, (''Double , Nothing)
, (''Int , Nothing)
, (''Bool , Nothing)
,
(''Int8 , Just (mkName "Data.Int.Int8"))
, (''Int16 , Just (mkName "Data.Int.Int16"))
, (''Int32 , Just (mkName "Data.Int.Int32"))
, (''Int64 , Just (mkName "Data.Int.Int64"))
, (''Word8 , Just (mkName "Data.Word.Word8"))
, (''Word16 , Just (mkName "Data.Word.Word16"))
, (''Word32 , Just (mkName "Data.Word.Word32"))
, (''Word64 , Just (mkName "Data.Word.Word64"))
, (''Ptr , Just (mkName "Foreign.Ptr.Ptr"))
, (''FunPtr , Just (mkName "Foreign.Ptr.FunPtr"))
, ('nullPtr , Just (mkName "Foreign.Ptr.nullPtr"))
, ('castFunPtr, Just (mkName "Foreign.Ptr.castFunPtr"))
, ('plusPtr , Just (mkName "Foreign.Ptr.plusPtr"))
, (''Type , Just (mkName "Data.Kind.Type"))
, (''Nat , Just (mkName "GHC.TypeNats.Nat"))
, (''Constraint, Just (mkName "Data.Kind.Constraint"))
, (''Typeable, Just (mkName "Data.Typeable.Typeable"))
, ('typeRep, Just (mkName "Type.Reflection.typeRep"))
, (''TypeRep, Just (mkName "Type.Reflection.TypeRep"))
, ('coerce , Just (mkName "Data.Coerce.coerce"))
,
(''ByteString, Just (mkName "Data.ByteString.ByteString"))
, (''VG.Vector, Just (mkName "Data.Vector.Generic.Vector"))
]
newtype TypeInfo = TypeInfo
{ tiConMap :: HName -> Maybe HName
}
type HasTypeInfo r = Member (Input TypeInfo) r
withTypeInfo
:: HasRenderParams r => Spec t -> Sem (Input TypeInfo ': r) a -> Sem r a
withTypeInfo spec a = do
ti <- specTypeInfo spec
runInputConst ti a
specTypeInfo :: HasRenderParams r => Spec t -> Sem r TypeInfo
specTypeInfo Spec {..} = do
RenderParams {..} <- input
let tyMap :: Map HName HName
tyMap = Map.fromList
[ (mkConName eExportedName evName, mkTyName eExportedName)
| Enum {..} <- V.toList specEnums
, let eExportedName = case eType of
AnEnum -> eName
ABitmask flags _ -> flags
, EnumValue {..} <- V.toList eValues
]
pure $ TypeInfo (`Map.lookup` tyMap)
adoptConstructors :: HasTypeInfo r => Import HName -> Sem r (Import HName)
adoptConstructors = \case
i@(Import n q cs _ source) -> getConParent n <&> \case
Just p -> Import p q (V.singleton n <> cs) False source
Nothing -> i
where getConParent n = inputs (`tiConMap` n)
nubOrdOnV :: Ord b => (a -> b) -> Vector a -> Vector a
nubOrdOnV p = fromList . nubOrdOn p . toList
writeIfChanged :: MonadIO m => FilePath -> Text -> m ()
writeIfChanged f t' = liftIO $ do
t <- readFileMaybe f
when (t /= Just t') $ T.writeFile f t'
readFileMaybe :: FilePath -> IO (Maybe Text)
readFileMaybe f =
(Just <$> T.readFile f) `catch` (\(_ :: IOException) -> pure Nothing)
ormoluConfig :: Ormolu.Config Ormolu.RegionIndices
ormoluConfig = Ormolu.defaultConfig
{ Ormolu.cfgDynOptions = [Ormolu.DynOption "-XPatternSynonyms"]
, Ormolu.cfgPrinterOpts = Ormolu.defaultPrinterOpts
{ Ormolu.poIndentation = pure 2
, Ormolu.poFunctionArrows = pure Ormolu . LeadingArrows
, Ormolu.poCommaStyle = pure Ormolu.Leading
, Ormolu.poImportExportStyle = pure Ormolu.ImportExportLeading
, Ormolu.poIndentWheres = pure False
, Ormolu.poRecordBraceSpace = pure False
, Ormolu.poNewlinesBetweenDecls = pure 1
, Ormolu.poHaddockStyle = pure Ormolu.HaddockSingleLine
, Ormolu.poRespectful = pure False
}
}
|
a2204c6ab7d9e31d259bbf370b6a439472511207f82809c29d93b216fa6e79c1 | kiranlak/austin-sbst | baseObjValue.ml | module Log = LogManager
type branchCovObjVal =
{
appLevel : int;
branchDist : float;
}
type objectiveValue = Simple of float | BranchCoverage of branchCovObjVal
let mkBranchCovObjVal (a:int) (bd:float) =
BranchCoverage({appLevel=a;branchDist=bd})
let compareObjVal (o1:objectiveValue) (o2:objectiveValue) =
match o1,o2 with
| BranchCoverage(b1),BranchCoverage(b2) ->
if b1.appLevel < b2.appLevel then (-1)
else if b1.appLevel > b2.appLevel then 1
else (
if b1.branchDist < b2.branchDist then (-1)
else if b1.branchDist > b2.branchDist then 1
else 0
)
| _,_ -> Log.warn "Trying to compare different types of objective value\n";0
let fitness_to_string (v:objectiveValue) =
match v with
| Simple(f) -> string_of_float f
| BranchCoverage(bo) ->
Printf.sprintf "approach level=%d, branch distance=%.10f" bo.appLevel bo.branchDist | null | https://raw.githubusercontent.com/kiranlak/austin-sbst/9c8aac72692dca952302e0e4fdb9ff381bba58ae/AustinOcaml/searchMethods/objectives/baseObjValue.ml | ocaml | module Log = LogManager
type branchCovObjVal =
{
appLevel : int;
branchDist : float;
}
type objectiveValue = Simple of float | BranchCoverage of branchCovObjVal
let mkBranchCovObjVal (a:int) (bd:float) =
BranchCoverage({appLevel=a;branchDist=bd})
let compareObjVal (o1:objectiveValue) (o2:objectiveValue) =
match o1,o2 with
| BranchCoverage(b1),BranchCoverage(b2) ->
if b1.appLevel < b2.appLevel then (-1)
else if b1.appLevel > b2.appLevel then 1
else (
if b1.branchDist < b2.branchDist then (-1)
else if b1.branchDist > b2.branchDist then 1
else 0
)
| _,_ -> Log.warn "Trying to compare different types of objective value\n";0
let fitness_to_string (v:objectiveValue) =
match v with
| Simple(f) -> string_of_float f
| BranchCoverage(bo) ->
Printf.sprintf "approach level=%d, branch distance=%.10f" bo.appLevel bo.branchDist | |
6477f509c2823cf90057c18a2ade4ec4e7d3b26902f24feae86e0001327aa9d6 | yuriy-chumak/ol | joystick.scm | (define-library (lib joystick)
(version 1.0)
(license MIT/LGPL3)
(description "joystick support library")
(import
(otus lisp) (otus ffi))
(export
axis-count
buttons-count
read-event)
(cond-expand
(Windows
(begin
#false
))
(Android
(begin
#false
))
(Linux
(begin
; /usr/include/linux/joystick.h
(define js0 (open-binary-input-file "/dev/input/js0"))
(define ioctl ((load-dynamic-library #false) fft-int "ioctl" type-port fft-unsigned-long))
(define (axis-count)
(define count (box 0))
(unbox count))
(define (buttons-count)
(define count (box 0))
(ioctl js0 2147576338 (cons (fft& fft-char) count)) ;JSIOCGBUTTONS
(unbox count))
(define (read-event)
(define bytes (syscall 0 js0 8))
(when (bytevector? bytes) [
(bytevector->int16 bytes 4)
(ref bytes 6) (ref bytes 7) ]))
))
(Darwin
(begin
#false
))
(else
(begin
(runtime-error "Unsupported platform" (syscall 63))))))
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/37bbcbf67b058e54f646d81d368c73c214ea92b2/libraries/lib/joystick.scm | scheme | /usr/include/linux/joystick.h
JSIOCGBUTTONS | (define-library (lib joystick)
(version 1.0)
(license MIT/LGPL3)
(description "joystick support library")
(import
(otus lisp) (otus ffi))
(export
axis-count
buttons-count
read-event)
(cond-expand
(Windows
(begin
#false
))
(Android
(begin
#false
))
(Linux
(begin
(define js0 (open-binary-input-file "/dev/input/js0"))
(define ioctl ((load-dynamic-library #false) fft-int "ioctl" type-port fft-unsigned-long))
(define (axis-count)
(define count (box 0))
(unbox count))
(define (buttons-count)
(define count (box 0))
(unbox count))
(define (read-event)
(define bytes (syscall 0 js0 8))
(when (bytevector? bytes) [
(bytevector->int16 bytes 4)
(ref bytes 6) (ref bytes 7) ]))
))
(Darwin
(begin
#false
))
(else
(begin
(runtime-error "Unsupported platform" (syscall 63))))))
|
230d3b044e70d94ee0f2eeead07d5e23766a0137ea57a73c08e6d3046e56a237 | cabol/west | west_util.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2013 , 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.
%%
%% -------------------------------------------------------------------
%%%-------------------------------------------------------------------
@author < >
( C ) 2013 , < > , All Rights Reserved .
%%% @doc Common utilities.
%%% @end
Created : 07 . Oct 2013 9:30 PM
%%%-------------------------------------------------------------------
-module(west_util).
%% API
-export([keyfind/2, keyfind/3, parse_query_string/1,
get_prop/3, props_for_types/2, format_datetime/2,
curr_date/0, parse_datetime/1, get_timestamp_ms/0,
parse_timestamp_ms/1, hash_string/2, bin_to_hex/1,
hmac/3, build_name/1, random_hash/1,
random_string/1, strong_rand/1, next_id/1,
to_bin/1, to_atom/1, to_integer/1, to_float/1,
start_app_deps/1, dec_json/1, enc_json/1]).
%% Types
-type tuple_list() :: [{any(), any()}].
-type json_term() :: [json_term()] | {[json_term()]} |
[{binary() | atom() | integer(), json_term()}] |
integer() | float() | binary() | atom().
%%%===================================================================
%%% API
%%%===================================================================
%% @doc Calls keyfind/3 with Default = undefined.
-spec keyfind(any(), tuple_list()) -> term().
keyfind(Key, TupleList) ->
keyfind(Key, TupleList, undefined).
@doc Searches the list of tuples TupleList for a tuple whose Nth element
%% compares equal to Key. Returns Tuple's value if such a tuple is
found , otherwise .
-spec keyfind(any(), tuple_list(), any()) -> term().
keyfind(Key, TupleList, Default) ->
case lists:keyfind(Key, 1, TupleList) of
{_K, V} -> V;
_ -> Default
end.
@doc a given query string and returns a key / value pair list .
-spec parse_query_string(string()) -> [{string(), string()}] | error.
parse_query_string(Str) ->
F = fun(Q) ->
[{K, V} || [K, V] <- [string:tokens(L, "=") || L <- string:tokens(Q, "&")]]
end,
case string:tokens(Str, "?") of
[_, X] -> F(X);
[X] -> F(X);
_ -> []
end.
%% @doc Gets a property given by Name and if it doesn't exist, returns Default.
-spec get_prop(string(), list(), string()) -> term().
get_prop(Name, Props, Default) ->
case lists:keyfind(Name, 1, Props) of
{_K, V} -> V;
_ -> Default
end.
%% @doc Filter all values in Props that match with some value in Types.
-spec props_for_types(list(), list()) -> list().
props_for_types(Types, Props) ->
Fun =
fun(Type, Acc) ->
case lists:keyfind(Type, 1, Props) of
{_, Param} -> [{Type, Param}] ++ Acc;
_ -> Acc
end
end,
lists:foldl(Fun, [], Types).
%% @doc Format the given DateTime with the format specified in the atom().
-spec format_datetime(atom(), calendar:datetime()) -> string().
format_datetime(iso8601, DateTime) ->
{{Year, Month, Day}, {Hour, Min, Sec}} = DateTime,
lists:flatten(io_lib:format(
"~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B",
[Year, Month, Day, Hour, Min, Sec]));
format_datetime(yyyymmdd, DateTime) ->
{{Year, Month, Day}, _} = DateTime,
lists:flatten(io_lib:format("~4.10.0B~2.10.0B~2.10.0B", [Year, Month, Day]));
format_datetime(rfc1123, DateTime) ->
httpd_util:rfc1123_date(DateTime).
%% @doc Return current datetime in RFC-1123 format.
-spec curr_date() -> iolist().
curr_date() ->
iolist_to_binary(format_datetime(rfc1123, calendar:local_time())).
%% @doc Converts a date string into datetime() format.
-spec parse_datetime(string()) -> term().
parse_datetime(DateStr) ->
httpd_util:convert_request_date(DateStr).
%% @doc Returns a timestamp in milliseconds.
-spec get_timestamp_ms() -> integer().
get_timestamp_ms() ->
{Mega, Sec, Micro} = os:timestamp(),
(Mega * 1000000 + Sec) * 1000000 + Micro.
@doc a given ms timestamp to os : timestamp ( ) format .
-spec parse_timestamp_ms(integer()) -> {integer(), integer(), integer()}.
parse_timestamp_ms(Timestamp) ->
{Timestamp div 1000000000000,
Timestamp div 1000000 rem 1000000,
Timestamp rem 1000000}.
%% @doc Hash the given data and return the hex-string result.
-spec hash_string(atom(), iodata()) -> string().
hash_string(Hash, Data) ->
bin_to_hex(crypto:hash(Hash, Data)).
%% @doc Converts the given binary to hex string.
@see [ hd(integer_to_list(Nibble , 16 ) ) || < < Nibble:4 > > < = B ]
-spec bin_to_hex(binary()) -> string().
bin_to_hex(B) when is_binary(B) ->
bin_to_hex(B, []).
@doc Wrap original hmac/3 from erlang crypto module , and converts it
%% result into hex string to return it.
@see Erlang crypto : hmac(Type , Key , Data ) .
-spec hmac(atom(), iodata(), iodata()) -> string().
hmac(Type, Key, Data) ->
bin_to_hex(crypto:hmac(Type, Key, Data)).
%% @doc Hash the given list and return an atom representation of that hash.
-spec build_name([any()]) -> atom().
build_name(L) when is_list(L) ->
F = fun(X, Acc) -> <<Acc/binary, (<<"_">>)/binary, (to_bin(X))/binary>> end,
Suffix = lists:foldl(F, <<"">>, L),
binary_to_atom(<<(<<"p">>)/binary, Suffix/binary>>, utf8).
%% @doc Generates a random hash hex-string.
-spec random_hash(atom()) -> string().
random_hash(Hash) ->
Ts = lists:flatten(io_lib:format("~p", [erlang:phash2(os:timestamp())])),
string:to_upper(bin_to_hex(crypto:hash(Hash, Ts))).
%% @doc Generates a random string.
-spec random_string(integer()) -> string().
random_string(Len) ->
<<A1:32, A2:32, A3:32>> = crypto:strong_rand_bytes(12),
random:seed({A1, A2, A3}),
Chrs = list_to_tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),
list_to_tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 " ) ,
ChrsSize = size(Chrs),
F = fun(_, R) -> [element(random:uniform(ChrsSize), Chrs) | R] end,
lists:foldl(F, "", lists:seq(1, Len)).
@doc Generates N bytes randomly uniform 0 .. 255 , and returns result encoded
%% Base64. Uses a cryptographically secure prng seeded and periodically
%% mixed with operating system provided entropy. By default this is the
RAND_bytes method from OpenSSL .
May throw exception low_entropy in case the random generator failed
%% due to lack of secure "randomness".
-spec strong_rand(integer()) -> iolist().
strong_rand(N) ->
F = fun($/) -> $X; ($+) -> $Y; (D) -> D end,
<<<<(F(D))>> || <<D>> <= base64:encode(crypto:strong_rand_bytes(N)), D =/= $=>>.
%% @doc Generates an unique ID.
-spec next_id(iolist()|binary()) -> iolist() | binary().
next_id(Prefix) ->
<<Prefix/binary, (iolist_to_binary(random_string(32)))/binary>>.
%% @doc Converts any type to binary.
-spec to_bin(any()) -> atom().
to_bin(Data) when is_integer(Data) ->
integer_to_binary(Data);
to_bin(Data) when is_float(Data) ->
float_to_binary(Data);
to_bin(Data) when is_atom(Data) ->
atom_to_binary(Data, utf8);
to_bin(Data) when is_list(Data) ->
iolist_to_binary(Data);
to_bin(Data) when is_pid(Data); is_reference(Data); is_tuple(Data) ->
integer_to_binary(erlang:phash2(Data));
to_bin(Data) ->
Data.
%% @doc Converts any type to atom.
-spec to_atom(any()) -> atom().
to_atom(Data) when is_binary(Data) ->
binary_to_atom(Data, utf8);
to_atom(Data) when is_list(Data) ->
list_to_atom(Data);
to_atom(Data) when is_pid(Data); is_reference(Data); is_tuple(Data) ->
list_to_atom(integer_to_list(erlang:phash2(Data)));
to_atom(Data) ->
Data.
%% @doc Converts any type to integer.
-spec to_integer(any()) -> integer().
to_integer(Data) when is_binary(Data) ->
binary_to_integer(Data);
to_integer(Data) when is_list(Data) ->
list_to_integer(Data);
to_integer(Data) when is_pid(Data); is_reference(Data); is_tuple(Data) ->
erlang:phash2(Data);
to_integer(Data) ->
Data.
%% @doc Converts any type to float.
-spec to_float(any()) -> float().
to_float(Data) when is_binary(Data) ->
binary_to_float(Data);
to_float(Data) when is_list(Data) ->
list_to_float(Data);
to_float(Data) when is_pid(Data); is_reference(Data); is_tuple(Data) ->
erlang:phash2(Data);
to_float(Data) ->
Data.
%% @doc Starts the given application, starting recursively all its
%% application dependencies. Returns a list with all started
%% applications.
-spec start_app_deps(App :: atom()) -> StartedApps :: list().
start_app_deps(App) ->
case application:start(App) of
{error, {not_started, Dep}} ->
start_app_deps([Dep | [App]], []);
{error, {Reason, _}} ->
[{Reason, App}];
ok ->
[{ok, App}]
end.
start_app_deps([], Acc) ->
Acc;
start_app_deps([H | T] = L, Acc) ->
case application:start(H) of
{error, {not_started, Dep}} ->
start_app_deps([Dep | L], Acc);
{error, {Reason, _}} ->
start_app_deps(T, [{Reason, H} | Acc]);
ok ->
start_app_deps(T, [{ok, H} | Acc])
end.
%% @doc Decode a JSON iodata into JSON term.
-spec dec_json(iolist()) -> json_term().
dec_json(Json) ->
try
jiffy:decode(Json)
catch
_:_ -> {error, invalid_json}
end.
%% @doc Encode a JSON term into a JSON IOstring.
-spec enc_json(json_term()) -> iolist().
enc_json(JsonTerm) ->
try
jiffy:encode(JsonTerm)
catch
_:_ -> {error, invalid_json_term}
end.
%%%===================================================================
Internal functions
%%%===================================================================
@private
hexdigit(C) when C >= 0, C =< 9 ->
C + $0;
hexdigit(C) when C =< 15 ->
C + $a -10.
@private
bin_to_hex(<<>>, Acc) ->
lists:reverse(Acc);
bin_to_hex(<<C1:4, C2:4, Rest/binary>>, Acc) ->
bin_to_hex(Rest, [hexdigit(C2), hexdigit(C1) | Acc]).
| null | https://raw.githubusercontent.com/cabol/west/c3c31dff9ad727ce9b82dde6eb690f7b11cd4d24/src/west_util.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
-------------------------------------------------------------------
@doc Common utilities.
@end
-------------------------------------------------------------------
API
Types
===================================================================
API
===================================================================
@doc Calls keyfind/3 with Default = undefined.
compares equal to Key. Returns Tuple's value if such a tuple is
@doc Gets a property given by Name and if it doesn't exist, returns Default.
@doc Filter all values in Props that match with some value in Types.
@doc Format the given DateTime with the format specified in the atom().
@doc Return current datetime in RFC-1123 format.
@doc Converts a date string into datetime() format.
@doc Returns a timestamp in milliseconds.
@doc Hash the given data and return the hex-string result.
@doc Converts the given binary to hex string.
result into hex string to return it.
@doc Hash the given list and return an atom representation of that hash.
@doc Generates a random hash hex-string.
@doc Generates a random string.
Base64. Uses a cryptographically secure prng seeded and periodically
mixed with operating system provided entropy. By default this is the
due to lack of secure "randomness".
@doc Generates an unique ID.
@doc Converts any type to binary.
@doc Converts any type to atom.
@doc Converts any type to integer.
@doc Converts any type to float.
@doc Starts the given application, starting recursively all its
application dependencies. Returns a list with all started
applications.
@doc Decode a JSON iodata into JSON term.
@doc Encode a JSON term into a JSON IOstring.
===================================================================
=================================================================== | Copyright ( c ) 2013 , 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
@author < >
( C ) 2013 , < > , All Rights Reserved .
Created : 07 . Oct 2013 9:30 PM
-module(west_util).
-export([keyfind/2, keyfind/3, parse_query_string/1,
get_prop/3, props_for_types/2, format_datetime/2,
curr_date/0, parse_datetime/1, get_timestamp_ms/0,
parse_timestamp_ms/1, hash_string/2, bin_to_hex/1,
hmac/3, build_name/1, random_hash/1,
random_string/1, strong_rand/1, next_id/1,
to_bin/1, to_atom/1, to_integer/1, to_float/1,
start_app_deps/1, dec_json/1, enc_json/1]).
-type tuple_list() :: [{any(), any()}].
-type json_term() :: [json_term()] | {[json_term()]} |
[{binary() | atom() | integer(), json_term()}] |
integer() | float() | binary() | atom().
-spec keyfind(any(), tuple_list()) -> term().
keyfind(Key, TupleList) ->
keyfind(Key, TupleList, undefined).
@doc Searches the list of tuples TupleList for a tuple whose Nth element
found , otherwise .
-spec keyfind(any(), tuple_list(), any()) -> term().
keyfind(Key, TupleList, Default) ->
case lists:keyfind(Key, 1, TupleList) of
{_K, V} -> V;
_ -> Default
end.
@doc a given query string and returns a key / value pair list .
-spec parse_query_string(string()) -> [{string(), string()}] | error.
parse_query_string(Str) ->
F = fun(Q) ->
[{K, V} || [K, V] <- [string:tokens(L, "=") || L <- string:tokens(Q, "&")]]
end,
case string:tokens(Str, "?") of
[_, X] -> F(X);
[X] -> F(X);
_ -> []
end.
-spec get_prop(string(), list(), string()) -> term().
get_prop(Name, Props, Default) ->
case lists:keyfind(Name, 1, Props) of
{_K, V} -> V;
_ -> Default
end.
-spec props_for_types(list(), list()) -> list().
props_for_types(Types, Props) ->
Fun =
fun(Type, Acc) ->
case lists:keyfind(Type, 1, Props) of
{_, Param} -> [{Type, Param}] ++ Acc;
_ -> Acc
end
end,
lists:foldl(Fun, [], Types).
-spec format_datetime(atom(), calendar:datetime()) -> string().
format_datetime(iso8601, DateTime) ->
{{Year, Month, Day}, {Hour, Min, Sec}} = DateTime,
lists:flatten(io_lib:format(
"~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B",
[Year, Month, Day, Hour, Min, Sec]));
format_datetime(yyyymmdd, DateTime) ->
{{Year, Month, Day}, _} = DateTime,
lists:flatten(io_lib:format("~4.10.0B~2.10.0B~2.10.0B", [Year, Month, Day]));
format_datetime(rfc1123, DateTime) ->
httpd_util:rfc1123_date(DateTime).
-spec curr_date() -> iolist().
curr_date() ->
iolist_to_binary(format_datetime(rfc1123, calendar:local_time())).
-spec parse_datetime(string()) -> term().
parse_datetime(DateStr) ->
httpd_util:convert_request_date(DateStr).
-spec get_timestamp_ms() -> integer().
get_timestamp_ms() ->
{Mega, Sec, Micro} = os:timestamp(),
(Mega * 1000000 + Sec) * 1000000 + Micro.
@doc a given ms timestamp to os : timestamp ( ) format .
-spec parse_timestamp_ms(integer()) -> {integer(), integer(), integer()}.
parse_timestamp_ms(Timestamp) ->
{Timestamp div 1000000000000,
Timestamp div 1000000 rem 1000000,
Timestamp rem 1000000}.
-spec hash_string(atom(), iodata()) -> string().
hash_string(Hash, Data) ->
bin_to_hex(crypto:hash(Hash, Data)).
@see [ hd(integer_to_list(Nibble , 16 ) ) || < < Nibble:4 > > < = B ]
-spec bin_to_hex(binary()) -> string().
bin_to_hex(B) when is_binary(B) ->
bin_to_hex(B, []).
@doc Wrap original hmac/3 from erlang crypto module , and converts it
@see Erlang crypto : hmac(Type , Key , Data ) .
-spec hmac(atom(), iodata(), iodata()) -> string().
hmac(Type, Key, Data) ->
bin_to_hex(crypto:hmac(Type, Key, Data)).
-spec build_name([any()]) -> atom().
build_name(L) when is_list(L) ->
F = fun(X, Acc) -> <<Acc/binary, (<<"_">>)/binary, (to_bin(X))/binary>> end,
Suffix = lists:foldl(F, <<"">>, L),
binary_to_atom(<<(<<"p">>)/binary, Suffix/binary>>, utf8).
-spec random_hash(atom()) -> string().
random_hash(Hash) ->
Ts = lists:flatten(io_lib:format("~p", [erlang:phash2(os:timestamp())])),
string:to_upper(bin_to_hex(crypto:hash(Hash, Ts))).
-spec random_string(integer()) -> string().
random_string(Len) ->
<<A1:32, A2:32, A3:32>> = crypto:strong_rand_bytes(12),
random:seed({A1, A2, A3}),
Chrs = list_to_tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),
list_to_tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 " ) ,
ChrsSize = size(Chrs),
F = fun(_, R) -> [element(random:uniform(ChrsSize), Chrs) | R] end,
lists:foldl(F, "", lists:seq(1, Len)).
@doc Generates N bytes randomly uniform 0 .. 255 , and returns result encoded
RAND_bytes method from OpenSSL .
May throw exception low_entropy in case the random generator failed
-spec strong_rand(integer()) -> iolist().
strong_rand(N) ->
F = fun($/) -> $X; ($+) -> $Y; (D) -> D end,
<<<<(F(D))>> || <<D>> <= base64:encode(crypto:strong_rand_bytes(N)), D =/= $=>>.
-spec next_id(iolist()|binary()) -> iolist() | binary().
next_id(Prefix) ->
<<Prefix/binary, (iolist_to_binary(random_string(32)))/binary>>.
-spec to_bin(any()) -> atom().
to_bin(Data) when is_integer(Data) ->
integer_to_binary(Data);
to_bin(Data) when is_float(Data) ->
float_to_binary(Data);
to_bin(Data) when is_atom(Data) ->
atom_to_binary(Data, utf8);
to_bin(Data) when is_list(Data) ->
iolist_to_binary(Data);
to_bin(Data) when is_pid(Data); is_reference(Data); is_tuple(Data) ->
integer_to_binary(erlang:phash2(Data));
to_bin(Data) ->
Data.
-spec to_atom(any()) -> atom().
to_atom(Data) when is_binary(Data) ->
binary_to_atom(Data, utf8);
to_atom(Data) when is_list(Data) ->
list_to_atom(Data);
to_atom(Data) when is_pid(Data); is_reference(Data); is_tuple(Data) ->
list_to_atom(integer_to_list(erlang:phash2(Data)));
to_atom(Data) ->
Data.
-spec to_integer(any()) -> integer().
to_integer(Data) when is_binary(Data) ->
binary_to_integer(Data);
to_integer(Data) when is_list(Data) ->
list_to_integer(Data);
to_integer(Data) when is_pid(Data); is_reference(Data); is_tuple(Data) ->
erlang:phash2(Data);
to_integer(Data) ->
Data.
-spec to_float(any()) -> float().
to_float(Data) when is_binary(Data) ->
binary_to_float(Data);
to_float(Data) when is_list(Data) ->
list_to_float(Data);
to_float(Data) when is_pid(Data); is_reference(Data); is_tuple(Data) ->
erlang:phash2(Data);
to_float(Data) ->
Data.
-spec start_app_deps(App :: atom()) -> StartedApps :: list().
start_app_deps(App) ->
case application:start(App) of
{error, {not_started, Dep}} ->
start_app_deps([Dep | [App]], []);
{error, {Reason, _}} ->
[{Reason, App}];
ok ->
[{ok, App}]
end.
start_app_deps([], Acc) ->
Acc;
start_app_deps([H | T] = L, Acc) ->
case application:start(H) of
{error, {not_started, Dep}} ->
start_app_deps([Dep | L], Acc);
{error, {Reason, _}} ->
start_app_deps(T, [{Reason, H} | Acc]);
ok ->
start_app_deps(T, [{ok, H} | Acc])
end.
-spec dec_json(iolist()) -> json_term().
dec_json(Json) ->
try
jiffy:decode(Json)
catch
_:_ -> {error, invalid_json}
end.
-spec enc_json(json_term()) -> iolist().
enc_json(JsonTerm) ->
try
jiffy:encode(JsonTerm)
catch
_:_ -> {error, invalid_json_term}
end.
Internal functions
@private
hexdigit(C) when C >= 0, C =< 9 ->
C + $0;
hexdigit(C) when C =< 15 ->
C + $a -10.
@private
bin_to_hex(<<>>, Acc) ->
lists:reverse(Acc);
bin_to_hex(<<C1:4, C2:4, Rest/binary>>, Acc) ->
bin_to_hex(Rest, [hexdigit(C2), hexdigit(C1) | Acc]).
|
c995b6ad9b030d2664b59b404595dc968f2abfefa200b6575405429faae183c5 | webyrd/mediKanren | read.rkt | #lang racket/base
(provide
read-all
read-all/stream
read-all-from-file
)
(require
racket/stream
)
(define (read-all in)
(define datum (read in))
(if (eof-object? datum) '() (cons datum (read-all in))))
(define (read-all/stream in)
(define datum (read in))
(if (eof-object? datum) '() (stream-cons datum (read-all/stream in))))
(define (read-all-from-file path)
(call-with-input-file (expand-user-path path) read-all))
| null | https://raw.githubusercontent.com/webyrd/mediKanren/a2b80ea94f66bcdd4305b9369ad4184c2afe9829/attic/code/read.rkt | racket | #lang racket/base
(provide
read-all
read-all/stream
read-all-from-file
)
(require
racket/stream
)
(define (read-all in)
(define datum (read in))
(if (eof-object? datum) '() (cons datum (read-all in))))
(define (read-all/stream in)
(define datum (read in))
(if (eof-object? datum) '() (stream-cons datum (read-all/stream in))))
(define (read-all-from-file path)
(call-with-input-file (expand-user-path path) read-all))
| |
83b2309a4d26e34beed0f5743fc3a310ba044ec7534b3f96fce519799dc1f4ec | brendanhay/terrafomo | Provider.hs | -- This module is auto-generated.
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# OPTIONS_GHC -fno - warn - unused - imports #
-- |
Module : . MySQL.Provider
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.MySQL.Provider
(
-- * MySQL Specific Aliases
Provider
, DataSource
, Resource
-- * MySQL Configuration
, currentVersion
, newProvider
, MySQL (..)
, MySQL_Required (..)
) where
import Data.Function ((&))
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import Data.Version (Version, makeVersion, showVersion)
import GHC.Base (($))
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.HCL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.MySQL.Types as P
import qualified Terrafomo.Schema as TF
type Provider = TF.Provider MySQL
type DataSource = TF.Resource MySQL TF.Ignored
type Resource = TF.Resource MySQL TF.Meta
type instance TF.ProviderName MySQL = "mysql"
currentVersion :: Version
currentVersion = makeVersion [1, 1, 0]
| The @mysql@ Terraform provider configuration .
data MySQL = MySQL_Internal
{ endpoint :: P.Text
^ @endpoint@
-- - (Required)
, password :: P.Maybe P.Text
-- ^ @password@
-- - (Optional)
, username :: P.Text
-- ^ @username@
-- - (Required)
} deriving (P.Show)
{- | Specify a new MySQL provider configuration.
See the < terraform documentation> for more information.
-}
newProvider
:: MySQL_Required -- ^ The minimal/required arguments.
-> Provider
newProvider x =
TF.Provider
{ TF.providerVersion = P.Just ("~> " P.++ showVersion currentVersion)
, TF.providerConfig =
(let MySQL{..} = x in MySQL_Internal
{ endpoint = endpoint
, password = P.Nothing
, username = username
})
, TF.providerEncoder =
(\MySQL_Internal{..} ->
P.mempty
<> TF.pair "endpoint" endpoint
<> P.maybe P.mempty (TF.pair "password") password
<> TF.pair "username" username
)
}
-- | The required arguments for 'newProvider'.
data MySQL_Required = MySQL
{ endpoint :: P.Text
-- ^ (Required)
, username :: P.Text
-- ^ (Required)
} deriving (P.Show)
instance Lens.HasField "endpoint" f Provider (P.Text) where
field = Lens.providerLens P.. Lens.lens'
(endpoint :: MySQL -> P.Text)
(\s a -> s { endpoint = a } :: MySQL)
instance Lens.HasField "password" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(password :: MySQL -> P.Maybe P.Text)
(\s a -> s { password = a } :: MySQL)
instance Lens.HasField "username" f Provider (P.Text) where
field = Lens.providerLens P.. Lens.lens'
(username :: MySQL -> P.Text)
(\s a -> s { username = a } :: MySQL)
| null | https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-mysql/gen/Terrafomo/MySQL/Provider.hs | haskell | This module is auto-generated.
|
Stability : auto-generated
* MySQL Specific Aliases
* MySQL Configuration
- (Required)
^ @password@
- (Optional)
^ @username@
- (Required)
| Specify a new MySQL provider configuration.
See the < terraform documentation> for more information.
^ The minimal/required arguments.
| The required arguments for 'newProvider'.
^ (Required)
^ (Required) |
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# OPTIONS_GHC -fno - warn - unused - imports #
Module : . MySQL.Provider
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Terrafomo.MySQL.Provider
(
Provider
, DataSource
, Resource
, currentVersion
, newProvider
, MySQL (..)
, MySQL_Required (..)
) where
import Data.Function ((&))
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import Data.Version (Version, makeVersion, showVersion)
import GHC.Base (($))
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.HCL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.MySQL.Types as P
import qualified Terrafomo.Schema as TF
type Provider = TF.Provider MySQL
type DataSource = TF.Resource MySQL TF.Ignored
type Resource = TF.Resource MySQL TF.Meta
type instance TF.ProviderName MySQL = "mysql"
currentVersion :: Version
currentVersion = makeVersion [1, 1, 0]
| The @mysql@ Terraform provider configuration .
data MySQL = MySQL_Internal
{ endpoint :: P.Text
^ @endpoint@
, password :: P.Maybe P.Text
, username :: P.Text
} deriving (P.Show)
newProvider
-> Provider
newProvider x =
TF.Provider
{ TF.providerVersion = P.Just ("~> " P.++ showVersion currentVersion)
, TF.providerConfig =
(let MySQL{..} = x in MySQL_Internal
{ endpoint = endpoint
, password = P.Nothing
, username = username
})
, TF.providerEncoder =
(\MySQL_Internal{..} ->
P.mempty
<> TF.pair "endpoint" endpoint
<> P.maybe P.mempty (TF.pair "password") password
<> TF.pair "username" username
)
}
data MySQL_Required = MySQL
{ endpoint :: P.Text
, username :: P.Text
} deriving (P.Show)
instance Lens.HasField "endpoint" f Provider (P.Text) where
field = Lens.providerLens P.. Lens.lens'
(endpoint :: MySQL -> P.Text)
(\s a -> s { endpoint = a } :: MySQL)
instance Lens.HasField "password" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(password :: MySQL -> P.Maybe P.Text)
(\s a -> s { password = a } :: MySQL)
instance Lens.HasField "username" f Provider (P.Text) where
field = Lens.providerLens P.. Lens.lens'
(username :: MySQL -> P.Text)
(\s a -> s { username = a } :: MySQL)
|
bc3f7bc5cfce6c79acd3b3982984a6efa082b5d67b1e63fc033839d73ac5e429 | thephoeron/cl-isaac | isaac-64.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - ISAAC ; Base : 10 -*- file : isaac-64.lisp
Copyright ( c ) 2008 ,
Copyright ( c ) 2014 - 2022 , " the Phoeron "
BSD license : you can do anything you want with it ( but no warranty ) .
(in-package #:cl-isaac)
TODO : proof these against ISAAC-64 implementation from
(defstruct isaac64-ctx
(randcnt 0 :type (unsigned-byte 64))
(randrsl (make-array 256 :element-type '(unsigned-byte 64) :initial-element 0)
:type (simple-array (unsigned-byte 64) (256)))
(randmem (make-array 256 :element-type '(unsigned-byte 64) :initial-element 0)
:type (simple-array (unsigned-byte 64) (256)))
(a 0 :type (unsigned-byte 64))
(b 0 :type (unsigned-byte 64))
(c 0 :type (unsigned-byte 64)))
(defun generate-next-isaac64-block (ctx)
(declare (optimize (speed 3) (safety 0)))
(incf (isaac64-ctx-c ctx))
(incf (isaac64-ctx-b ctx) (isaac64-ctx-c ctx))
(loop for i from 0 below 256 do
(setf (isaac64-ctx-a ctx)
(logxor (isaac64-ctx-a ctx)
(logand #xFFFFFFFFFFFFFFFF
(the (unsigned-byte 64)
(ash (isaac64-ctx-a ctx)
(ecase (logand i 3)
((0) 21)
((1) -5)
((2) 12)
((3) -33)))))))
(setf (isaac64-ctx-a ctx)
(logand #xFFFFFFFFFFFFFFFF
(+ (isaac64-ctx-a ctx)
(aref (isaac64-ctx-randmem ctx) (logand (+ i 128) #xFF)))))
(let* ((x (aref (isaac64-ctx-randmem ctx) i))
(y (logand #xFFFFFFFFFFFFFFFF
(+ (aref (isaac64-ctx-randmem ctx) (logand (ash x -2) #xFF))
(isaac64-ctx-a ctx)
(isaac64-ctx-b ctx)))))
(setf (aref (isaac64-ctx-randmem ctx) i) y)
(setf (isaac64-ctx-b ctx)
(logand #xFFFFFFFFFFFFFFFF
(+ (aref (isaac64-ctx-randmem ctx) (logand (ash y -10) #xFF)) x)))
(setf (aref (isaac64-ctx-randrsl ctx) i) (isaac64-ctx-b ctx)))))
(defun rand64 (ctx)
(let ((c (isaac64-ctx-randcnt ctx)))
(declare (optimize (speed 3) (safety 0)))
(decf (isaac64-ctx-randcnt ctx))
(if (zerop c)
(progn
(generate-next-isaac64-block ctx)
(setf (isaac64-ctx-randcnt ctx) 255)
(aref (isaac64-ctx-randrsl ctx) 255))
(aref (isaac64-ctx-randrsl ctx) (isaac64-ctx-randcnt ctx)))))
(defun rand-bits-64 (ctx n)
(let ((v 0))
(loop while (> n 0) do
(setq v (logior (ash v (min n 64))
(logand (1- (ash 1 (min n 64)))
(rand64 ctx))))
(decf n (min n 64)))
v))
(defmacro incf-wrap64 (a b)
`(setf ,a (logand #xFFFFFFFFFFFFFFFF (+ ,a ,b))))
(defmacro decf-wrap64 (a b)
`(setf ,a (logand #xFFFFFFFFFFFFFFFF (- ,a ,b))))
(defmacro mix64 (a b c d e f g h)
`(progn
(decf-wrap64 ,a ,e) (setf ,f (logxor ,f (logand #xFFFFFFFFFFFFFFFF (ash ,h -9)))) (incf-wrap64 ,h ,a)
(decf-wrap64 ,b ,f) (setf ,g (logxor ,g (logand #xFFFFFFFFFFFFFFFF (ash ,a 9)))) (incf-wrap64 ,a ,b)
(decf-wrap64 ,c ,g) (setf ,h (logxor ,h (logand #xFFFFFFFFFFFFFFFF (ash ,b -23)))) (incf-wrap64 ,b ,c)
(decf-wrap64 ,d ,h) (setf ,a (logxor ,a (logand #xFFFFFFFFFFFFFFFF (ash ,c 15)))) (incf-wrap64 ,c ,d)
(decf-wrap64 ,e ,a) (setf ,b (logxor ,b (logand #xFFFFFFFFFFFFFFFF (ash ,d -14)))) (incf-wrap64 ,d ,e)
(decf-wrap64 ,f ,b) (setf ,c (logxor ,c (logand #xFFFFFFFFFFFFFFFF (ash ,e 20)))) (incf-wrap64 ,e ,f)
(decf-wrap64 ,g ,c) (setf ,d (logxor ,d (logand #xFFFFFFFFFFFFFFFF (ash ,f -17)))) (incf-wrap64 ,f ,g)
(decf-wrap64 ,h ,d) (setf ,e (logxor ,e (logand #xFFFFFFFFFFFFFFFF (ash ,g 14)))) (incf-wrap64 ,g ,h)))
(defun scramble64 (ctx)
(let (a b c d e f g h)
; golden ratio
(setf a #x9e3779b97f4a7c13 b a c a d a e a f a g a h a)
; scramble it
(loop for i from 0 below 4 do
(mix64 a b c d e f g h))
;; Pass #1
(loop for i from 0 below 256 by 8 do
(incf-wrap64 a (aref (isaac64-ctx-randrsl ctx) (+ i 0)))
(incf-wrap64 b (aref (isaac64-ctx-randrsl ctx) (+ i 1)))
(incf-wrap64 c (aref (isaac64-ctx-randrsl ctx) (+ i 2)))
(incf-wrap64 d (aref (isaac64-ctx-randrsl ctx) (+ i 3)))
(incf-wrap64 e (aref (isaac64-ctx-randrsl ctx) (+ i 4)))
(incf-wrap64 f (aref (isaac64-ctx-randrsl ctx) (+ i 5)))
(incf-wrap64 g (aref (isaac64-ctx-randrsl ctx) (+ i 6)))
(incf-wrap64 h (aref (isaac64-ctx-randrsl ctx) (+ i 7)))
(mix64 a b c d e f g h)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 0)) a)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 1)) b)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 2)) c)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 3)) d)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 4)) e)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 5)) f)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 6)) g)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 7)) h))
;; Pass #2
(loop for i from 0 below 256 by 8 do
(incf-wrap64 a (aref (isaac64-ctx-randmem ctx) (+ i 0)))
(incf-wrap64 b (aref (isaac64-ctx-randmem ctx) (+ i 1)))
(incf-wrap64 c (aref (isaac64-ctx-randmem ctx) (+ i 2)))
(incf-wrap64 d (aref (isaac64-ctx-randmem ctx) (+ i 3)))
(incf-wrap64 e (aref (isaac64-ctx-randmem ctx) (+ i 4)))
(incf-wrap64 f (aref (isaac64-ctx-randmem ctx) (+ i 5)))
(incf-wrap64 g (aref (isaac64-ctx-randmem ctx) (+ i 6)))
(incf-wrap64 h (aref (isaac64-ctx-randmem ctx) (+ i 7)))
(mix64 a b c d e f g h)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 0)) a)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 1)) b)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 2)) c)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 3)) d)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 4)) e)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 5)) f)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 6)) g)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 7)) h))
fill in first set
(generate-next-isaac64-block ctx)
prepare to use first set
(setf (isaac64-ctx-randcnt ctx) 256)
return CTX
ctx))
EOF
| null | https://raw.githubusercontent.com/thephoeron/cl-isaac/9cd88f39733be753facbf361cb0e08b9e42ff8d5/isaac-64.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - ISAAC ; Base : 10 -*- file : isaac-64.lisp
golden ratio
scramble it
Pass #1
Pass #2 |
Copyright ( c ) 2008 ,
Copyright ( c ) 2014 - 2022 , " the Phoeron "
BSD license : you can do anything you want with it ( but no warranty ) .
(in-package #:cl-isaac)
TODO : proof these against ISAAC-64 implementation from
(defstruct isaac64-ctx
(randcnt 0 :type (unsigned-byte 64))
(randrsl (make-array 256 :element-type '(unsigned-byte 64) :initial-element 0)
:type (simple-array (unsigned-byte 64) (256)))
(randmem (make-array 256 :element-type '(unsigned-byte 64) :initial-element 0)
:type (simple-array (unsigned-byte 64) (256)))
(a 0 :type (unsigned-byte 64))
(b 0 :type (unsigned-byte 64))
(c 0 :type (unsigned-byte 64)))
(defun generate-next-isaac64-block (ctx)
(declare (optimize (speed 3) (safety 0)))
(incf (isaac64-ctx-c ctx))
(incf (isaac64-ctx-b ctx) (isaac64-ctx-c ctx))
(loop for i from 0 below 256 do
(setf (isaac64-ctx-a ctx)
(logxor (isaac64-ctx-a ctx)
(logand #xFFFFFFFFFFFFFFFF
(the (unsigned-byte 64)
(ash (isaac64-ctx-a ctx)
(ecase (logand i 3)
((0) 21)
((1) -5)
((2) 12)
((3) -33)))))))
(setf (isaac64-ctx-a ctx)
(logand #xFFFFFFFFFFFFFFFF
(+ (isaac64-ctx-a ctx)
(aref (isaac64-ctx-randmem ctx) (logand (+ i 128) #xFF)))))
(let* ((x (aref (isaac64-ctx-randmem ctx) i))
(y (logand #xFFFFFFFFFFFFFFFF
(+ (aref (isaac64-ctx-randmem ctx) (logand (ash x -2) #xFF))
(isaac64-ctx-a ctx)
(isaac64-ctx-b ctx)))))
(setf (aref (isaac64-ctx-randmem ctx) i) y)
(setf (isaac64-ctx-b ctx)
(logand #xFFFFFFFFFFFFFFFF
(+ (aref (isaac64-ctx-randmem ctx) (logand (ash y -10) #xFF)) x)))
(setf (aref (isaac64-ctx-randrsl ctx) i) (isaac64-ctx-b ctx)))))
(defun rand64 (ctx)
(let ((c (isaac64-ctx-randcnt ctx)))
(declare (optimize (speed 3) (safety 0)))
(decf (isaac64-ctx-randcnt ctx))
(if (zerop c)
(progn
(generate-next-isaac64-block ctx)
(setf (isaac64-ctx-randcnt ctx) 255)
(aref (isaac64-ctx-randrsl ctx) 255))
(aref (isaac64-ctx-randrsl ctx) (isaac64-ctx-randcnt ctx)))))
(defun rand-bits-64 (ctx n)
(let ((v 0))
(loop while (> n 0) do
(setq v (logior (ash v (min n 64))
(logand (1- (ash 1 (min n 64)))
(rand64 ctx))))
(decf n (min n 64)))
v))
(defmacro incf-wrap64 (a b)
`(setf ,a (logand #xFFFFFFFFFFFFFFFF (+ ,a ,b))))
(defmacro decf-wrap64 (a b)
`(setf ,a (logand #xFFFFFFFFFFFFFFFF (- ,a ,b))))
(defmacro mix64 (a b c d e f g h)
`(progn
(decf-wrap64 ,a ,e) (setf ,f (logxor ,f (logand #xFFFFFFFFFFFFFFFF (ash ,h -9)))) (incf-wrap64 ,h ,a)
(decf-wrap64 ,b ,f) (setf ,g (logxor ,g (logand #xFFFFFFFFFFFFFFFF (ash ,a 9)))) (incf-wrap64 ,a ,b)
(decf-wrap64 ,c ,g) (setf ,h (logxor ,h (logand #xFFFFFFFFFFFFFFFF (ash ,b -23)))) (incf-wrap64 ,b ,c)
(decf-wrap64 ,d ,h) (setf ,a (logxor ,a (logand #xFFFFFFFFFFFFFFFF (ash ,c 15)))) (incf-wrap64 ,c ,d)
(decf-wrap64 ,e ,a) (setf ,b (logxor ,b (logand #xFFFFFFFFFFFFFFFF (ash ,d -14)))) (incf-wrap64 ,d ,e)
(decf-wrap64 ,f ,b) (setf ,c (logxor ,c (logand #xFFFFFFFFFFFFFFFF (ash ,e 20)))) (incf-wrap64 ,e ,f)
(decf-wrap64 ,g ,c) (setf ,d (logxor ,d (logand #xFFFFFFFFFFFFFFFF (ash ,f -17)))) (incf-wrap64 ,f ,g)
(decf-wrap64 ,h ,d) (setf ,e (logxor ,e (logand #xFFFFFFFFFFFFFFFF (ash ,g 14)))) (incf-wrap64 ,g ,h)))
(defun scramble64 (ctx)
(let (a b c d e f g h)
(setf a #x9e3779b97f4a7c13 b a c a d a e a f a g a h a)
(loop for i from 0 below 4 do
(mix64 a b c d e f g h))
(loop for i from 0 below 256 by 8 do
(incf-wrap64 a (aref (isaac64-ctx-randrsl ctx) (+ i 0)))
(incf-wrap64 b (aref (isaac64-ctx-randrsl ctx) (+ i 1)))
(incf-wrap64 c (aref (isaac64-ctx-randrsl ctx) (+ i 2)))
(incf-wrap64 d (aref (isaac64-ctx-randrsl ctx) (+ i 3)))
(incf-wrap64 e (aref (isaac64-ctx-randrsl ctx) (+ i 4)))
(incf-wrap64 f (aref (isaac64-ctx-randrsl ctx) (+ i 5)))
(incf-wrap64 g (aref (isaac64-ctx-randrsl ctx) (+ i 6)))
(incf-wrap64 h (aref (isaac64-ctx-randrsl ctx) (+ i 7)))
(mix64 a b c d e f g h)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 0)) a)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 1)) b)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 2)) c)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 3)) d)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 4)) e)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 5)) f)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 6)) g)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 7)) h))
(loop for i from 0 below 256 by 8 do
(incf-wrap64 a (aref (isaac64-ctx-randmem ctx) (+ i 0)))
(incf-wrap64 b (aref (isaac64-ctx-randmem ctx) (+ i 1)))
(incf-wrap64 c (aref (isaac64-ctx-randmem ctx) (+ i 2)))
(incf-wrap64 d (aref (isaac64-ctx-randmem ctx) (+ i 3)))
(incf-wrap64 e (aref (isaac64-ctx-randmem ctx) (+ i 4)))
(incf-wrap64 f (aref (isaac64-ctx-randmem ctx) (+ i 5)))
(incf-wrap64 g (aref (isaac64-ctx-randmem ctx) (+ i 6)))
(incf-wrap64 h (aref (isaac64-ctx-randmem ctx) (+ i 7)))
(mix64 a b c d e f g h)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 0)) a)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 1)) b)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 2)) c)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 3)) d)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 4)) e)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 5)) f)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 6)) g)
(setf (aref (isaac64-ctx-randmem ctx) (+ i 7)) h))
fill in first set
(generate-next-isaac64-block ctx)
prepare to use first set
(setf (isaac64-ctx-randcnt ctx) 256)
return CTX
ctx))
EOF
|
e2c5b24b55b7a7d629b9f809318b72de16c10c0b9176be47015ee39ee5c9fb83 | ocamllabs/ocaml-modular-implicits | t041-makeblock.ml | type t = {
mutable a : int;
mutable b : int;
mutable c : int;
mutable d : int;
};;
{ a = 0; b = 0; c = 0; d = 0 };;
*
0 CONST0
1 PUSHCONST0
2 PUSHCONST0
3 PUSHCONST0
4 MAKEBLOCK 4 , 0
7 ATOM0
8 SETGLOBAL T041 - makeblock
10 STOP
*
0 CONST0
1 PUSHCONST0
2 PUSHCONST0
3 PUSHCONST0
4 MAKEBLOCK 4, 0
7 ATOM0
8 SETGLOBAL T041-makeblock
10 STOP
**)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t041-makeblock.ml | ocaml | type t = {
mutable a : int;
mutable b : int;
mutable c : int;
mutable d : int;
};;
{ a = 0; b = 0; c = 0; d = 0 };;
*
0 CONST0
1 PUSHCONST0
2 PUSHCONST0
3 PUSHCONST0
4 MAKEBLOCK 4 , 0
7 ATOM0
8 SETGLOBAL T041 - makeblock
10 STOP
*
0 CONST0
1 PUSHCONST0
2 PUSHCONST0
3 PUSHCONST0
4 MAKEBLOCK 4, 0
7 ATOM0
8 SETGLOBAL T041-makeblock
10 STOP
**)
| |
862fdf7d3294ffe37fd554f6f340abca1018bfd81e8136cd979c1e03dcc37d80 | mirage/mirage | mirage_impl_kv.ml | open Functoria
open Astring
module Key = Mirage_key
type ro = RO
let ro = Type.v RO
let crunch dirname =
let is_valid = function
| '0' .. '9' | 'a' .. 'z' | 'A' .. 'Z' -> true
| _ -> false
in
let modname = String.filter is_valid dirname in
let name = "Static_" ^ String.Ascii.lowercase modname in
let packages =
[
package ~min:"3.0.0" ~max:"4.0.0" "mirage-kv-mem";
package ~min:"3.1.0" ~max:"4.0.0" ~build:true "crunch";
]
in
let connect _ modname _ = Fmt.str "%s.connect ()" modname in
let dune _i =
let dir = Fpath.(v dirname) in
let file ext = Fpath.(v (String.Ascii.lowercase name) + ext) in
let ml = file "ml" in
let mli = file "mli" in
let dune =
Dune.stanzaf
{|
(rule
(targets %a %a)
(deps (source_tree %a))
(action
(run ocaml-crunch -o %a %a)))
|}
Fpath.pp ml Fpath.pp mli Fpath.pp dir Fpath.pp ml Fpath.pp dir
in
[ dune ]
in
impl ~packages ~connect ~dune name ro
let direct_kv_ro dirname =
let packages = [ package ~min:"2.1.0" ~max:"3.0.0" "mirage-kv-unix" ] in
let connect _ modname _names = Fmt.str "%s.connect \"%s\"" modname dirname in
impl ~packages ~connect "Mirage_kv_unix" ro
let direct_kv_ro dirname =
match_impl
Key.(value target)
[
(`Xen, crunch dirname);
(`Qubes, crunch dirname);
(`Virtio, crunch dirname);
(`Hvt, crunch dirname);
(`Spt, crunch dirname);
(`Muen, crunch dirname);
(`Genode, crunch dirname);
]
~default:(direct_kv_ro dirname)
type rw = RW
let rw = Type.v RW
let direct_kv_rw dirname =
let packages = [ package ~min:"2.1.0" ~max:"3.0.0" "mirage-kv-unix" ] in
let connect _ modname _names = Fmt.str "%s.connect \"%s\"" modname dirname in
impl ~packages ~connect "Mirage_kv_unix" rw
let mem_kv_rw_config =
let packages = [ package ~min:"3.0.0" ~max:"4.0.0" "mirage-kv-mem" ] in
let connect _ modname _names = Fmt.str "%s.connect ()" modname in
impl ~packages ~connect "Mirage_kv_mem.Make" (Mirage_impl_pclock.pclock @-> rw)
let mem_kv_rw ?(clock = Mirage_impl_pclock.default_posix_clock) () =
mem_kv_rw_config $ clock
* generic kv_ro .
let generic_kv_ro ?group ?(key = Key.value @@ Key.kv_ro ?group ()) dir =
match_impl key
[ (`Crunch, crunch dir); (`Direct, direct_kv_ro dir) ]
~default:(direct_kv_ro dir)
| null | https://raw.githubusercontent.com/mirage/mirage/68bc2f914daf6b1936c98638ad3648388cd03ebc/lib/mirage/impl/mirage_impl_kv.ml | ocaml | open Functoria
open Astring
module Key = Mirage_key
type ro = RO
let ro = Type.v RO
let crunch dirname =
let is_valid = function
| '0' .. '9' | 'a' .. 'z' | 'A' .. 'Z' -> true
| _ -> false
in
let modname = String.filter is_valid dirname in
let name = "Static_" ^ String.Ascii.lowercase modname in
let packages =
[
package ~min:"3.0.0" ~max:"4.0.0" "mirage-kv-mem";
package ~min:"3.1.0" ~max:"4.0.0" ~build:true "crunch";
]
in
let connect _ modname _ = Fmt.str "%s.connect ()" modname in
let dune _i =
let dir = Fpath.(v dirname) in
let file ext = Fpath.(v (String.Ascii.lowercase name) + ext) in
let ml = file "ml" in
let mli = file "mli" in
let dune =
Dune.stanzaf
{|
(rule
(targets %a %a)
(deps (source_tree %a))
(action
(run ocaml-crunch -o %a %a)))
|}
Fpath.pp ml Fpath.pp mli Fpath.pp dir Fpath.pp ml Fpath.pp dir
in
[ dune ]
in
impl ~packages ~connect ~dune name ro
let direct_kv_ro dirname =
let packages = [ package ~min:"2.1.0" ~max:"3.0.0" "mirage-kv-unix" ] in
let connect _ modname _names = Fmt.str "%s.connect \"%s\"" modname dirname in
impl ~packages ~connect "Mirage_kv_unix" ro
let direct_kv_ro dirname =
match_impl
Key.(value target)
[
(`Xen, crunch dirname);
(`Qubes, crunch dirname);
(`Virtio, crunch dirname);
(`Hvt, crunch dirname);
(`Spt, crunch dirname);
(`Muen, crunch dirname);
(`Genode, crunch dirname);
]
~default:(direct_kv_ro dirname)
type rw = RW
let rw = Type.v RW
let direct_kv_rw dirname =
let packages = [ package ~min:"2.1.0" ~max:"3.0.0" "mirage-kv-unix" ] in
let connect _ modname _names = Fmt.str "%s.connect \"%s\"" modname dirname in
impl ~packages ~connect "Mirage_kv_unix" rw
let mem_kv_rw_config =
let packages = [ package ~min:"3.0.0" ~max:"4.0.0" "mirage-kv-mem" ] in
let connect _ modname _names = Fmt.str "%s.connect ()" modname in
impl ~packages ~connect "Mirage_kv_mem.Make" (Mirage_impl_pclock.pclock @-> rw)
let mem_kv_rw ?(clock = Mirage_impl_pclock.default_posix_clock) () =
mem_kv_rw_config $ clock
* generic kv_ro .
let generic_kv_ro ?group ?(key = Key.value @@ Key.kv_ro ?group ()) dir =
match_impl key
[ (`Crunch, crunch dir); (`Direct, direct_kv_ro dir) ]
~default:(direct_kv_ro dir)
| |
ba6d2acb1467d26dd93ea54edceec4e520aea10427c61788a8ba71a3d9d6a66c | spurious/sagittarius-scheme-mirror | cgen.scm | ;; -*- Scheme -*-
CGen , originally from Gauche
;;
This library just exports all variables from ( sagittarius cgen cise ) and
( sagittarius cgen unit ) . These 2 libraries do not depend on Sagittarius
;; headers. So it can be used for normal C generator (I guess).
#!core
(library (sagittarius cgen)
(export :all)
(import (sagittarius cgen cise)
(sagittarius cgen unit)))
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/sagittarius/cgen.scm | scheme | -*- Scheme -*-
headers. So it can be used for normal C generator (I guess). | CGen , originally from Gauche
This library just exports all variables from ( sagittarius cgen cise ) and
( sagittarius cgen unit ) . These 2 libraries do not depend on Sagittarius
#!core
(library (sagittarius cgen)
(export :all)
(import (sagittarius cgen cise)
(sagittarius cgen unit)))
|
45b2ade75ec8a6723b0d7d2d2c16561503ec6b0f37046372463b4d8e64ae5e48 | oxidizing/sihl-starter | service.ml | (* Kernel services *)
module Random = Sihl.Utils.Random.Service.Make ()
module Log = Sihl.Log.Service.Make ()
module Config = Sihl.Config.Service.Make (Log)
module Db = Sihl.Data.Db.Service.Make (Config) (Log)
module MigrationRepo = Sihl.Data.Migration.Service.Repo.MakeMariaDb (Db)
module Cmd = Sihl.Cmd.Service.Make ()
module Migration =
Sihl.Data.Migration.Service.Make (Log) (Cmd) (Db) (MigrationRepo)
module WebServer = Sihl.Web.Server.Service.MakeOpium (Log) (Cmd)
module Schedule = Sihl.Schedule.Service.Make (Log)
module Repo = Sihl.Data.Repo.Service.Make ()
(* Configuration providers *)
module EmailConfigProvider = Sihl.Email.Service.EnvConfigProvider (Config)
(* Repositories *)
module EmailTemplateRepo =
Sihl.Email.Service.Template.Repo.MakeMariaDb (Db) (Repo) (Migration)
(* Services *)
module EmailTemplate =
Sihl.Email.Service.Template.Make (Log) (EmailTemplateRepo)
module Email =
Sihl.Email.Service.Make.Smtp (Log) (EmailTemplate) (EmailConfigProvider)
| null | https://raw.githubusercontent.com/oxidizing/sihl-starter/d9867089892f34afcb1519c4c8fb4328c062f5a7/service.ml | ocaml | Kernel services
Configuration providers
Repositories
Services | module Random = Sihl.Utils.Random.Service.Make ()
module Log = Sihl.Log.Service.Make ()
module Config = Sihl.Config.Service.Make (Log)
module Db = Sihl.Data.Db.Service.Make (Config) (Log)
module MigrationRepo = Sihl.Data.Migration.Service.Repo.MakeMariaDb (Db)
module Cmd = Sihl.Cmd.Service.Make ()
module Migration =
Sihl.Data.Migration.Service.Make (Log) (Cmd) (Db) (MigrationRepo)
module WebServer = Sihl.Web.Server.Service.MakeOpium (Log) (Cmd)
module Schedule = Sihl.Schedule.Service.Make (Log)
module Repo = Sihl.Data.Repo.Service.Make ()
module EmailConfigProvider = Sihl.Email.Service.EnvConfigProvider (Config)
module EmailTemplateRepo =
Sihl.Email.Service.Template.Repo.MakeMariaDb (Db) (Repo) (Migration)
module EmailTemplate =
Sihl.Email.Service.Template.Make (Log) (EmailTemplateRepo)
module Email =
Sihl.Email.Service.Make.Smtp (Log) (EmailTemplate) (EmailConfigProvider)
|
a9158c176da3c690a41c928b282abcedc045aaa2b2c98d947adbba8369def9d2 | ahungry/ahungry-fleece | af.lib.ansi-colors.lisp | - A utility library .
Copyright ( C ) 2016 < >
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;
You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see </>.
;;;; af.lib.hashy.lisp
(in-package #:cl-user)
(defpackage af.lib.ansi-colors
(:use :cl
:split-sequence)
(:export
:colorize
:with-color
:*colorize-p*
))
(in-package #:af.lib.ansi-colors)
(defparameter *colors*
(list :black "0;30"
:blue "0;34"
:green "0;32"
:cyan "0;36"
:red "0;31"
:purple "0;35"
:brown "0;33"
:light-gray "0;37"
:dark-gray "1;30"
:light-blue "1;34"
:light-green "1;32"
:light-cyan "1;36"
:light-red "1;31"
:light-purple "1;35"
:yellow "1;33"
:white "1;37"))
(defparameter *colorize-p* t)
(defun colorize (color)
"Set the active color of the terminal."
(when *colorize-p*
(format t "~c[~am"
#\Esc
(or (getf *colors* color)
(getf *colors* :white)))))
(defmacro with-color (color &rest body)
"Activate COLOR and execute BODY (while reseting back to base color)."
`(progn
(colorize ,color)
,@body
(colorize :light-gray)))
;;; "af.lib.hashy" goes here. Hacks and glory await!
| null | https://raw.githubusercontent.com/ahungry/ahungry-fleece/1cef1d3a3aa9cffe9f06b7632006565bbc986814/src/libs/af.lib.ansi-colors.lisp | lisp |
This program is free software: you can redistribute it and/or modify
(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 Affero General Public License for more details.
along with this program. If not, see </>.
af.lib.hashy.lisp
"af.lib.hashy" goes here. Hacks and glory await! | - A utility library .
Copyright ( C ) 2016 < >
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU Affero General Public License
(in-package #:cl-user)
(defpackage af.lib.ansi-colors
(:use :cl
:split-sequence)
(:export
:colorize
:with-color
:*colorize-p*
))
(in-package #:af.lib.ansi-colors)
(defparameter *colors*
(list :black "0;30"
:blue "0;34"
:green "0;32"
:cyan "0;36"
:red "0;31"
:purple "0;35"
:brown "0;33"
:light-gray "0;37"
:dark-gray "1;30"
:light-blue "1;34"
:light-green "1;32"
:light-cyan "1;36"
:light-red "1;31"
:light-purple "1;35"
:yellow "1;33"
:white "1;37"))
(defparameter *colorize-p* t)
(defun colorize (color)
"Set the active color of the terminal."
(when *colorize-p*
(format t "~c[~am"
#\Esc
(or (getf *colors* color)
(getf *colors* :white)))))
(defmacro with-color (color &rest body)
"Activate COLOR and execute BODY (while reseting back to base color)."
`(progn
(colorize ,color)
,@body
(colorize :light-gray)))
|
adf1bd9a9ded13eedbe16ba9dad785adc98b49b6eb46ab566b4fd8a3d67c2d7f | huiyaozheng/Mirage-zmq | config.ml | open Mirage
let main = foreign ~packages:[package "mirage-zmq"] "Unikernel.Main" (stackv4 @-> job)
let stack = generic_stackv4 default_network
let () =
register "sub_unikernel" [
main $ stack
]
| null | https://raw.githubusercontent.com/huiyaozheng/Mirage-zmq/af288a3378a7c357bd5646a3abf4fd5ae777369b/test/SUB/unikernel/config.ml | ocaml | open Mirage
let main = foreign ~packages:[package "mirage-zmq"] "Unikernel.Main" (stackv4 @-> job)
let stack = generic_stackv4 default_network
let () =
register "sub_unikernel" [
main $ stack
]
| |
f83241ddcac1d66a3da129a4272c5f460459c3cca21a528d14ea61c01774a686 | cldm/cldm | config.lisp | (in-package :cldm)
(defparameter *libraries-directory*
(pathname "~/.cldm/cache/libraries/"))
(defparameter *local-libraries-directory*
(merge-pathnames (pathname "lib/")
(osicat:current-directory)))
(defparameter *verbose-mode* nil "When true, verbose messages are displayed on the standard output")
(defparameter *debug-mode* nil "When true, debugging messages are displayed on the standard output")
(defparameter *standard-cldm-repo*
`(make-instance 'cldm:indexed-http-cld-repository
:name "cldm-repo"
:address "-repo/cld"
:cache-directory (pathname "~/.cldm/cache/cld-repositories/cldm-repo/")))
(defparameter *cld-repositories* (list *standard-cldm-repo*))
(defparameter *address-cache-operation* :symlink "What to do when caching a local file system directory. Can be either :symlink or :copy (copy the directory recursively). Default is :symlink")
(defparameter *solving-mode* :strict "One of :strict, :lenient. If :strict, errors are signaled if a cld cannot be found, or a dependency version is not specified. If :lenient, signal warnings and try to solve dependencies loading latest versions and the like.")
(defparameter *clean-asdf-environment* nil "If T, load libraries in a clean ASDF environment")
(defparameter *minisat+-binary* "/usr/local/bin/minisat+"
"minisat+ binary for PBO solving")
;; Configuration files
(defparameter *system-config-file* #p"/etc/cldm/config")
(defparameter *user-config-file* #p"~/.cldm/config")
(defparameter *local-config-file* (merge-pathnames (pathname ".cldm")
(osicat:current-directory)))
(defun call-with-libraries-directory (pathname function)
(let ((*libraries-directory* pathname))
(funcall function)))
(defmacro with-libraries-directory (pathname &body body)
`(call-with-libraries-directory
,pathname
(lambda ()
,@body)))
(defun call-with-cld-repositories (repositories function)
(let ((*cld-repositories* repositories))
(funcall function)))
(defmacro with-cld-repositories (repositories &body body)
`(call-with-cld-repositories
(list ,@repositories)
(lambda ()
,@body)))
(defun list-cld-repositories ()
(let ((*package* (find-package :cldm)))
(setf *cld-repositories*
(mapcar #'eval *cld-repositories*)))
*cld-repositories*)
(defun read-config-file (pathname)
(when (and (probe-file pathname)
(not (cl-fad:directory-pathname-p pathname)))
(read-from-string (file-to-string pathname) nil)))
(defun read-config (scope)
(let ((config-file (ecase scope
(:local *local-config-file*)
(:user *user-config-file*)
(:system *system-config-file*))))
(read-config-file config-file)))
(defun load-config-file (pathname)
(when (and (probe-file pathname)
(not (cl-fad:directory-pathname-p pathname)))
(let ((configuration (ignore-errors (read-config-file pathname))))
(when configuration
(awhen (getf configuration :minisat+-binary)
(setf *minisat+-binary* it))
(awhen (getf configuration :libraries-directory)
(setf *libraries-directory* (eval it)))
(awhen (getf configuration :verbose-mode)
(setf *verbose-mode* it))
(awhen (getf configuration :local-libraries-directory)
(setf *local-libraries-directory*
(merge-pathnames (pathname it)
(osicat:current-directory))))
(awhen (getf configuration :address-cache-operation)
(setf *address-cache-operation* it))
(awhen (getf configuration :repositories)
(setf *cld-repositories*
(loop for repository-spec in it
collect
(apply #'make-instance repository-spec))))
(awhen (getf configuration :append-repositories)
(setf *cld-repositories*
(append
(loop for repository-spec in it
collect
(apply #'make-instance repository-spec))
*cld-repositories*)))))))
(defun dump-config (config scope)
(let ((config-file (ecase scope
(:local *local-config-file*)
(:user *user-config-file*)
(:system *system-config-file*))))
(dump-config-to-file config config-file)))
(defun dump-config-to-file (config pathname)
(with-open-file (f pathname
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format f "~S" config)))
(defun load-cldm-config ()
(clear-cldm-config)
(load-config-file *system-config-file*)
(load-config-file *user-config-file*)
(load-config-file *local-config-file*))
(defun clear-cldm-config ()
(setf *verbose-mode* nil)
(setf *debug-mode* nil)
(setf *cld-repositories* (list *standard-cldm-repo*))
(setf *address-cache-operation* :symlink)
(setf *solving-mode* :strict)
(setf *clean-asdf-environment* nil)
(setf *minisat+-binary* "/usr/local/bin/minisat+"))
(defun set-config-var (keyword type value scope &optional (reload t))
(assert (typep value type))
(let ((config (read-config scope)))
(setf (getf config keyword)
value)
(dump-config config scope)
(when reload
(load-cldm-config))))
(defun unset-config-var (keyword scope &optional (reload t))
(let ((config (read-config scope)))
(remf config keyword)
(dump-config config scope)
(when reload
(load-cldm-config))))
(defun get-config-var (keyword scope)
(let ((config (read-config scope)))
(getf config keyword)))
(defun config-set-libraries-directory (libraries-directory scope &optional (reload t))
(set-config-var :libraries-directory 'pathname libraries-directory scope reload))
(defun config-set-local-libraries-directory (local-libraries-directory scope &optional (reload t))
(set-config-var :local-libraries-directory 'pathname local-libraries-directory scope reload))
(defun config-set-verbose (verbose scope &optional (reload t))
(set-config-var :verbose 'boolean verbose scope reload))
(defun config-set-minisat+-binary (minisat scope &optional (reload t))
(set-config-var :minisat+-binary 'pathname minisat scope reload))
(defun config-set-solving-mode (solving-mode scope &optional (reload t))
(set-config-var :solving-mode '(member :strict :lenient) solving-mode scope reload))
(defun config-set-repositories (repositories scope &optional (reload t))
(set-config-var :repositories 'cons repositories scope reload))
(defun validate-repository-spec (repository-spec)
(assert (listp repository-spec))
(assert (subtypep (first repository-spec) 'cld-repository))
(apply #'make-instance repository-spec)
t)
(defun config-add-repository (repository-spec scope &optional (reload t))
(validate-repository-spec repository-spec)
;; If successful, add it to the repositories list
(let ((repositories-specs (get-config-var :repositories scope)))
(push repository-spec repositories-specs)
(set-config-var :repositories 'cons repositories-specs scope reload)))
(defun config-remove-repository (name scope &optional (reload t))
(let ((repositories (get-config-var :repositories scope)))
(setf repositories (remove name repositories
:key #'car
:test #'equalp))
(set-config-var :repositories 'list repositories scope reload)))
(defun config-append-repository (repository scope &optional (reload t))
(let ((repositories (get-config-var :append-repositories scope)))
(push repository repositories)
(set-config-var :append-repositories 'cons repositories scope reload)))
(defun config-unappend-repository (name scope &optional (reload t))
(let ((repositories (get-config-var :append-repositories scope)))
(setf repositories (remove name repositories
:key #'car
:test #'equalp))
(set-config-var :append-repositories 'list repositories scope reload)))
| null | https://raw.githubusercontent.com/cldm/cldm/899f1a92d52245ef0fc84d073ac35c4b0d2e9609/src/config.lisp | lisp | Configuration files
If successful, add it to the repositories list | (in-package :cldm)
(defparameter *libraries-directory*
(pathname "~/.cldm/cache/libraries/"))
(defparameter *local-libraries-directory*
(merge-pathnames (pathname "lib/")
(osicat:current-directory)))
(defparameter *verbose-mode* nil "When true, verbose messages are displayed on the standard output")
(defparameter *debug-mode* nil "When true, debugging messages are displayed on the standard output")
(defparameter *standard-cldm-repo*
`(make-instance 'cldm:indexed-http-cld-repository
:name "cldm-repo"
:address "-repo/cld"
:cache-directory (pathname "~/.cldm/cache/cld-repositories/cldm-repo/")))
(defparameter *cld-repositories* (list *standard-cldm-repo*))
(defparameter *address-cache-operation* :symlink "What to do when caching a local file system directory. Can be either :symlink or :copy (copy the directory recursively). Default is :symlink")
(defparameter *solving-mode* :strict "One of :strict, :lenient. If :strict, errors are signaled if a cld cannot be found, or a dependency version is not specified. If :lenient, signal warnings and try to solve dependencies loading latest versions and the like.")
(defparameter *clean-asdf-environment* nil "If T, load libraries in a clean ASDF environment")
(defparameter *minisat+-binary* "/usr/local/bin/minisat+"
"minisat+ binary for PBO solving")
(defparameter *system-config-file* #p"/etc/cldm/config")
(defparameter *user-config-file* #p"~/.cldm/config")
(defparameter *local-config-file* (merge-pathnames (pathname ".cldm")
(osicat:current-directory)))
(defun call-with-libraries-directory (pathname function)
(let ((*libraries-directory* pathname))
(funcall function)))
(defmacro with-libraries-directory (pathname &body body)
`(call-with-libraries-directory
,pathname
(lambda ()
,@body)))
(defun call-with-cld-repositories (repositories function)
(let ((*cld-repositories* repositories))
(funcall function)))
(defmacro with-cld-repositories (repositories &body body)
`(call-with-cld-repositories
(list ,@repositories)
(lambda ()
,@body)))
(defun list-cld-repositories ()
(let ((*package* (find-package :cldm)))
(setf *cld-repositories*
(mapcar #'eval *cld-repositories*)))
*cld-repositories*)
(defun read-config-file (pathname)
(when (and (probe-file pathname)
(not (cl-fad:directory-pathname-p pathname)))
(read-from-string (file-to-string pathname) nil)))
(defun read-config (scope)
(let ((config-file (ecase scope
(:local *local-config-file*)
(:user *user-config-file*)
(:system *system-config-file*))))
(read-config-file config-file)))
(defun load-config-file (pathname)
(when (and (probe-file pathname)
(not (cl-fad:directory-pathname-p pathname)))
(let ((configuration (ignore-errors (read-config-file pathname))))
(when configuration
(awhen (getf configuration :minisat+-binary)
(setf *minisat+-binary* it))
(awhen (getf configuration :libraries-directory)
(setf *libraries-directory* (eval it)))
(awhen (getf configuration :verbose-mode)
(setf *verbose-mode* it))
(awhen (getf configuration :local-libraries-directory)
(setf *local-libraries-directory*
(merge-pathnames (pathname it)
(osicat:current-directory))))
(awhen (getf configuration :address-cache-operation)
(setf *address-cache-operation* it))
(awhen (getf configuration :repositories)
(setf *cld-repositories*
(loop for repository-spec in it
collect
(apply #'make-instance repository-spec))))
(awhen (getf configuration :append-repositories)
(setf *cld-repositories*
(append
(loop for repository-spec in it
collect
(apply #'make-instance repository-spec))
*cld-repositories*)))))))
(defun dump-config (config scope)
(let ((config-file (ecase scope
(:local *local-config-file*)
(:user *user-config-file*)
(:system *system-config-file*))))
(dump-config-to-file config config-file)))
(defun dump-config-to-file (config pathname)
(with-open-file (f pathname
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format f "~S" config)))
(defun load-cldm-config ()
(clear-cldm-config)
(load-config-file *system-config-file*)
(load-config-file *user-config-file*)
(load-config-file *local-config-file*))
(defun clear-cldm-config ()
(setf *verbose-mode* nil)
(setf *debug-mode* nil)
(setf *cld-repositories* (list *standard-cldm-repo*))
(setf *address-cache-operation* :symlink)
(setf *solving-mode* :strict)
(setf *clean-asdf-environment* nil)
(setf *minisat+-binary* "/usr/local/bin/minisat+"))
(defun set-config-var (keyword type value scope &optional (reload t))
(assert (typep value type))
(let ((config (read-config scope)))
(setf (getf config keyword)
value)
(dump-config config scope)
(when reload
(load-cldm-config))))
(defun unset-config-var (keyword scope &optional (reload t))
(let ((config (read-config scope)))
(remf config keyword)
(dump-config config scope)
(when reload
(load-cldm-config))))
(defun get-config-var (keyword scope)
(let ((config (read-config scope)))
(getf config keyword)))
(defun config-set-libraries-directory (libraries-directory scope &optional (reload t))
(set-config-var :libraries-directory 'pathname libraries-directory scope reload))
(defun config-set-local-libraries-directory (local-libraries-directory scope &optional (reload t))
(set-config-var :local-libraries-directory 'pathname local-libraries-directory scope reload))
(defun config-set-verbose (verbose scope &optional (reload t))
(set-config-var :verbose 'boolean verbose scope reload))
(defun config-set-minisat+-binary (minisat scope &optional (reload t))
(set-config-var :minisat+-binary 'pathname minisat scope reload))
(defun config-set-solving-mode (solving-mode scope &optional (reload t))
(set-config-var :solving-mode '(member :strict :lenient) solving-mode scope reload))
(defun config-set-repositories (repositories scope &optional (reload t))
(set-config-var :repositories 'cons repositories scope reload))
(defun validate-repository-spec (repository-spec)
(assert (listp repository-spec))
(assert (subtypep (first repository-spec) 'cld-repository))
(apply #'make-instance repository-spec)
t)
(defun config-add-repository (repository-spec scope &optional (reload t))
(validate-repository-spec repository-spec)
(let ((repositories-specs (get-config-var :repositories scope)))
(push repository-spec repositories-specs)
(set-config-var :repositories 'cons repositories-specs scope reload)))
(defun config-remove-repository (name scope &optional (reload t))
(let ((repositories (get-config-var :repositories scope)))
(setf repositories (remove name repositories
:key #'car
:test #'equalp))
(set-config-var :repositories 'list repositories scope reload)))
(defun config-append-repository (repository scope &optional (reload t))
(let ((repositories (get-config-var :append-repositories scope)))
(push repository repositories)
(set-config-var :append-repositories 'cons repositories scope reload)))
(defun config-unappend-repository (name scope &optional (reload t))
(let ((repositories (get-config-var :append-repositories scope)))
(setf repositories (remove name repositories
:key #'car
:test #'equalp))
(set-config-var :append-repositories 'list repositories scope reload)))
|
6ed456b5278473d2326409da62e709a5a7b14e38cb24cb21f1fb87d54d0936d8 | mfoemmel/erlang-otp | wxListCtrl.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
<<EXPORT:SortItems sortItems/2 SortItems:EXPORT>>
<<SortItems
%% @spec (This::wxListCtrl(), SortCallBack::function()) -> boolean()
%% @doc Sort the items in the list control<br />
%% <pre>SortCalBack(Item1,Item2) -> integer()</pre>
< br / > SortCallBack receives the client data associated with two items
%% to compare, and should return 0 if the items are equal, a negative
value if the first item is less than the second one and a positive
value if the first item is greater than the second one .
%% <br /> NOTE: The callback may not call other processes.
sortItems(#wx_ref{type=ThisT,ref=ThisRef}, SortCallBack)
when is_function(SortCallBack, 2) ->
?CLASS(ThisT,wxListCtrl),
Sort = fun([Item1,Item2]) ->
Result = SortCallBack(Item1,Item2),
<<Result:32/?UI>>
end,
SortId = wxe_util:get_cbId(Sort),
wxe_util:call(~s, <<ThisRef:32/?UI,SortId:32/?UI>>).
SortItems>>
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/api_gen/wx_extra/wxListCtrl.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%
@spec (This::wxListCtrl(), SortCallBack::function()) -> boolean()
@doc Sort the items in the list control<br />
<pre>SortCalBack(Item1,Item2) -> integer()</pre>
to compare, and should return 0 if the items are equal, a negative
<br /> NOTE: The callback may not call other processes. | Copyright Ericsson AB 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
<<EXPORT:SortItems sortItems/2 SortItems:EXPORT>>
<<SortItems
< br / > SortCallBack receives the client data associated with two items
value if the first item is less than the second one and a positive
value if the first item is greater than the second one .
sortItems(#wx_ref{type=ThisT,ref=ThisRef}, SortCallBack)
when is_function(SortCallBack, 2) ->
?CLASS(ThisT,wxListCtrl),
Sort = fun([Item1,Item2]) ->
Result = SortCallBack(Item1,Item2),
<<Result:32/?UI>>
end,
SortId = wxe_util:get_cbId(Sort),
wxe_util:call(~s, <<ThisRef:32/?UI,SortId:32/?UI>>).
SortItems>>
|
880ca667638d526f33d52b178c3fa9d4c004c61d1fe0792f6bb8001002162381 | reenberg/wobot | Flask.dump.hs | v0 :: Float
v0 = let { v = 0.0 :: Float } in v
v1 :: (Float, Float) -> (Float, Float)
v1 = let {
v = (\(x, prev) -> let { cur = 0.5 * x + 0.5 * prev } in (,) cur cur) ::
((Float, Float) -> (Float, Float))
} in v
v2 :: Integer
v2 = let { v = 0 :: Integer } in v
f0 :: ((), Integer) -> (Float, Integer)
f0 = let { f (x, 0) = (,) 1.0 1; f (x, 1) = (,) 0.0 0 } in f
ssend3_out :: Float -> ()
ssend3_out x = ()
ssend3_in :: Float -> ()
sintegrate2_out :: Float -> ()
sintegrate2_out x = seq (ssend3_in x) ()
sintegrate2_in :: Float -> ()
sintegrate1_out :: Float -> ()
sintegrate1_out x = seq (sintegrate2_in x) ()
sintegrate1_in :: () -> ()
clock0_out :: () -> ()
clock0_out x = seq (sintegrate1_in x) ()
clock0_in :: () -> ()
clock0_in x = clock0_out () | null | https://raw.githubusercontent.com/reenberg/wobot/ce7f112096ba1abd43b8d29da7e8944c2a004125/flask/examples/ewma/Flask.dump.hs | haskell | v0 :: Float
v0 = let { v = 0.0 :: Float } in v
v1 :: (Float, Float) -> (Float, Float)
v1 = let {
v = (\(x, prev) -> let { cur = 0.5 * x + 0.5 * prev } in (,) cur cur) ::
((Float, Float) -> (Float, Float))
} in v
v2 :: Integer
v2 = let { v = 0 :: Integer } in v
f0 :: ((), Integer) -> (Float, Integer)
f0 = let { f (x, 0) = (,) 1.0 1; f (x, 1) = (,) 0.0 0 } in f
ssend3_out :: Float -> ()
ssend3_out x = ()
ssend3_in :: Float -> ()
sintegrate2_out :: Float -> ()
sintegrate2_out x = seq (ssend3_in x) ()
sintegrate2_in :: Float -> ()
sintegrate1_out :: Float -> ()
sintegrate1_out x = seq (sintegrate2_in x) ()
sintegrate1_in :: () -> ()
clock0_out :: () -> ()
clock0_out x = seq (sintegrate1_in x) ()
clock0_in :: () -> ()
clock0_in x = clock0_out () | |
27123656f882fe546bec9ac251b0c3cdb3f1232b716371b5472f9cfd40577a43 | henryw374/time-literals | data_readers_cljs.cljc | (ns time-literals.data-readers-cljs
(:refer-clojure :exclude [time])
#?(:cljs (:require
[java.time :refer [Period
LocalDate
LocalDateTime
ZonedDateTime
OffsetTime
Instant
OffsetDateTime
ZoneId
DayOfWeek
LocalTime
Month
Duration
Year
YearMonth
MonthDay]])))
(defn date [x]
#?(:clj
(list '. 'java.time.LocalDate 'parse x)
:cljs (. java.time.LocalDate parse x)
))
(defn instant [x]
#?(:clj
(list '. 'java.time.Instant 'parse x)
:cljs (. java.time.Instant parse x)
))
(defn time [x]
#?(:clj
(list '. 'java.time.LocalTime 'parse x)
:cljs (. java.time.LocalTime parse x)
))
(defn offset-time [x]
#?(:clj
(list '. 'java.time.OffsetTime 'parse x)
:cljs (. java.time.OffsetTime parse x)
))
(defn duration [x]
#?(:clj
(list '. 'java.time.Duration 'parse x)
:cljs (. java.time.Duration parse x)
))
(defn period [x]
#?(:clj
(list '. 'java.time.Period 'parse x)
:cljs (. java.time.Period parse x)
))
(defn zoned-date-time [x]
#?(:clj
(list '. 'java.time.ZonedDateTime 'parse x)
:cljs (. java.time.ZonedDateTime parse x)
))
(defn offset-date-time [x]
#?(:clj
(list '. 'java.time.OffsetDateTime 'parse x)
:cljs (. java.time.OffsetDateTime parse x)
))
(defn date-time [x]
#?(:clj
(list '. 'java.time.LocalDateTime 'parse x)
:cljs (. java.time.LocalDateTime parse x)
))
(defn year [x]
#?(:clj
(list '. 'java.time.Year 'parse x)
:cljs (. java.time.Year parse x)
))
(defn year-month [x]
#?(:clj
(list '. 'java.time.YearMonth 'parse x)
:cljs (. java.time.YearMonth parse x)
))
(defn zone [x]
#?(:clj
(list '. 'java.time.ZoneId 'of x)
:cljs (. java.time.ZoneId of x)
))
(defn day-of-week [x]
#?(:clj
(list '. 'java.time.DayOfWeek 'valueOf x)
:cljs (. java.time.DayOfWeek valueOf x)))
(defn month [x]
#?(:clj
(list '. 'java.time.Month 'valueOf x)
:cljs (. java.time.Month valueOf x)))
(defn month-day [x]
#?(:clj
(list '. 'java.time.MonthDay 'parse x)
:cljs (. java.time.MonthDay parse x)))
| null | https://raw.githubusercontent.com/henryw374/time-literals/dcc01d0e814139013ba1fbe800d2f099042da404/src/time_literals/data_readers_cljs.cljc | clojure | (ns time-literals.data-readers-cljs
(:refer-clojure :exclude [time])
#?(:cljs (:require
[java.time :refer [Period
LocalDate
LocalDateTime
ZonedDateTime
OffsetTime
Instant
OffsetDateTime
ZoneId
DayOfWeek
LocalTime
Month
Duration
Year
YearMonth
MonthDay]])))
(defn date [x]
#?(:clj
(list '. 'java.time.LocalDate 'parse x)
:cljs (. java.time.LocalDate parse x)
))
(defn instant [x]
#?(:clj
(list '. 'java.time.Instant 'parse x)
:cljs (. java.time.Instant parse x)
))
(defn time [x]
#?(:clj
(list '. 'java.time.LocalTime 'parse x)
:cljs (. java.time.LocalTime parse x)
))
(defn offset-time [x]
#?(:clj
(list '. 'java.time.OffsetTime 'parse x)
:cljs (. java.time.OffsetTime parse x)
))
(defn duration [x]
#?(:clj
(list '. 'java.time.Duration 'parse x)
:cljs (. java.time.Duration parse x)
))
(defn period [x]
#?(:clj
(list '. 'java.time.Period 'parse x)
:cljs (. java.time.Period parse x)
))
(defn zoned-date-time [x]
#?(:clj
(list '. 'java.time.ZonedDateTime 'parse x)
:cljs (. java.time.ZonedDateTime parse x)
))
(defn offset-date-time [x]
#?(:clj
(list '. 'java.time.OffsetDateTime 'parse x)
:cljs (. java.time.OffsetDateTime parse x)
))
(defn date-time [x]
#?(:clj
(list '. 'java.time.LocalDateTime 'parse x)
:cljs (. java.time.LocalDateTime parse x)
))
(defn year [x]
#?(:clj
(list '. 'java.time.Year 'parse x)
:cljs (. java.time.Year parse x)
))
(defn year-month [x]
#?(:clj
(list '. 'java.time.YearMonth 'parse x)
:cljs (. java.time.YearMonth parse x)
))
(defn zone [x]
#?(:clj
(list '. 'java.time.ZoneId 'of x)
:cljs (. java.time.ZoneId of x)
))
(defn day-of-week [x]
#?(:clj
(list '. 'java.time.DayOfWeek 'valueOf x)
:cljs (. java.time.DayOfWeek valueOf x)))
(defn month [x]
#?(:clj
(list '. 'java.time.Month 'valueOf x)
:cljs (. java.time.Month valueOf x)))
(defn month-day [x]
#?(:clj
(list '. 'java.time.MonthDay 'parse x)
:cljs (. java.time.MonthDay parse x)))
| |
c583ea9240e108fe90363999e2df23edb8ea469d23b9e34e78e01610378e5659 | dysinger/restack | config.ml | open Mirage
let main =
foreign
~packages:[ package "reason";
package "duration"; ]
"Unikernel.Hello" (time @-> job)
let () =
register "hello" [main $ default_time]
| null | https://raw.githubusercontent.com/dysinger/restack/ef8ac0ae0542f1d81d7bd3032c6077149d403d68/000-hello-world/config.ml | ocaml | open Mirage
let main =
foreign
~packages:[ package "reason";
package "duration"; ]
"Unikernel.Hello" (time @-> job)
let () =
register "hello" [main $ default_time]
| |
edba15617ad48a00a6cfc53da1cccecf6e835e74635add97a5b0cebb7a958d3a | holdenlee/depgraph | ParseUtilities.hs | {-# OPTIONS
-XMultiParamTypeClasses
-XFunctionalDependencies
-XFlexibleInstances
-XRank2Types
-XGADTs
-XPolyKinds
#-}
module ParseUtilities ( ProgramInfo (current, deps, fields, currentFile), emptyPI, insertDep, insertSF, insertSF2, lookupSF, insertField, ProgramParser, ioFile, ioFiles, fieldsParser, readFields, chain, chainPI, getFile) where
import System.Environment
import System.Directory
import System.IO
import Control.Monad
import Data.Graph.Inductive
import qualified Data.List.Ordered
import Data.Tree
import qualified Data.List
import qualified Data.Map.Strict as Map
import Text.ParserCombinators.Parsec
import Data.Char
import System.IO.Unsafe
import qualified Data.MultiMap as MM
import Data.Maybe
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (emptyDef)
import Utilities
lexer :: P.TokenParser ()
lexer = P.makeTokenParser (emptyDef)
whiteSpace= P.whiteSpace lexer
lexeme = P.lexeme lexer
symbol = P.symbol lexer
natural = P.natural lexer
parens = P.parens lexer
semi = P.semi lexer
identifier= P.identifier lexer
reserved = P.reserved lexer
reservedOp= P.reservedOp lexer
instance (Show a, Show b) => Show (MM.MultiMap a b) where
show m = show (MM.toMap m)
data ProgramInfo = ProgramInfo {deps:: MM.MultiMap String String
, subfields:: Map.Map String (Map.Map String String)
, current:: String
, fields:: [String]
, currentFile:: String
--, names:: Map.Map String String
} deriving Show
--display names
--, labels:: Map.Map String String} deriving Show
emptyPI:: ProgramInfo
emptyPI = ProgramInfo MM.empty Map.empty "" [] ""
insert2:: (Ord a, Eq b) => a -> b -> MM.MultiMap a b -> MM.MultiMap a b
insert2 x y mm = if y `elem` (MM.lookup x mm) then mm else (MM.insert x y mm)
--insertName:: String -> ProgramInfo -> ProgramInfo
insertName str pi = pi{labels = Map.insert ( current pi ) str }
insertDep:: String -> ProgramInfo -> ProgramInfo
insertDep y pi = pi{deps=insert2 (current pi) y (deps pi)}
insertSF:: String -> String -> ProgramInfo -> ProgramInfo
insertSF name y pi =
let
currentMap = Map.lookup (current pi) (subfields pi)
in
case currentMap of
Nothing -> pi{subfields=Map.insert (current pi) (Map.singleton name y) (subfields pi)}
Just mp -> pi{subfields=Map.insert (current pi) (Map.insert name y mp) (subfields pi)}
insertSF2:: String -> String -> String -> ProgramInfo -> ProgramInfo
insertSF2 lab name y pi =
let
currentMap = Map.lookup lab (subfields pi)
in
case currentMap of
Nothing -> pi{subfields=Map.insert lab (Map.singleton name y) (subfields pi)}
Just mp -> pi{subfields=Map.insert lab (Map.insert name y mp) (subfields pi)}
lookupSF:: String -> String -> ProgramInfo -> Maybe String
lookupSF propName field pi =
case (Map.lookup propName (subfields pi)) of
Nothing -> Nothing
Just sfs-> Map.lookup field sfs
insertField:: String -> ProgramInfo -> ProgramInfo
insertField y pi = pi{fields = y:(fields pi)}
type ProgramParser = ProgramInfo -> Parser ProgramInfo
ioFile:: String -> String -> (String -> String) -> IO ()
ioFile inputF outputF f =
do
handle <- openFile inputF ReadMode
contents <- hGetContents handle
appendFile outputF (f contents)
ioFiles:: [String] -> String -> (String -> String) -> IO ()
ioFiles inputFs outputF f =
do
handles <- sequence (fmap (\x -> openFile x ReadMode) inputFs)
contents <- sequence (fmap hGetContents handles)
let content = unlines contents
appendFile outputF (f content)
fieldsParser:: ProgramParser
fieldsParser pi =
do {eof; return pi}
<|> (try (do {
symbol "#";
expr <- identifier;
fieldsParser (pi{current = expr})
--parses eol automatically?
}))
<|> (do {
expr <- many1 (noneOf "\n");
fieldsParser (insertDep expr pi) -- does this preserve the order?
})
<|> do{ anyToken; fieldsParser pi}
-- -> (String -> Parser ())
readFields:: String -> MM.MultiMap String String
readFields contents = deps $ justRight (parse (fieldsParser emptyPI) "error" contents)
chain:: [String] -> a -> (a -> String -> a) -> (a -> Parser a) -> IO a
chain inputFs init action parser =
do
handles <- sequence (fmap (\x -> openFile x ReadMode) inputFs)
contents <- sequence (fmap hGetContents handles)
let pi = foldIterate2 (\fileName text pi -> justRight (parse (parser (action pi fileName)) "error" text)) inputFs contents init
return pi
chainPI:: [String] -> ProgramParser -> IO ProgramInfo
chainPI inputFs parser = chain inputFs emptyPI (\pi fileName -> pi{currentFile = fileName}) parser
--unsafe
--AAAAGGGGHHHH! Bad code! Don't use!
getFile::String -> String
getFile name = unsafePerformIO (readFile name)
chainPI : : [ String ] - > ( ProgramInfo - > Parser ProgramInfo ) - > IO ProgramInfo
| null | https://raw.githubusercontent.com/holdenlee/depgraph/30081e9b8acb1083970dec47f7c753bcd47eb534/ParseUtilities.hs | haskell | # OPTIONS
-XMultiParamTypeClasses
-XFunctionalDependencies
-XFlexibleInstances
-XRank2Types
-XGADTs
-XPolyKinds
#
, names:: Map.Map String String
display names
, labels:: Map.Map String String} deriving Show
insertName:: String -> ProgramInfo -> ProgramInfo
parses eol automatically?
does this preserve the order?
-> (String -> Parser ())
unsafe
AAAAGGGGHHHH! Bad code! Don't use!
|
module ParseUtilities ( ProgramInfo (current, deps, fields, currentFile), emptyPI, insertDep, insertSF, insertSF2, lookupSF, insertField, ProgramParser, ioFile, ioFiles, fieldsParser, readFields, chain, chainPI, getFile) where
import System.Environment
import System.Directory
import System.IO
import Control.Monad
import Data.Graph.Inductive
import qualified Data.List.Ordered
import Data.Tree
import qualified Data.List
import qualified Data.Map.Strict as Map
import Text.ParserCombinators.Parsec
import Data.Char
import System.IO.Unsafe
import qualified Data.MultiMap as MM
import Data.Maybe
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (emptyDef)
import Utilities
lexer :: P.TokenParser ()
lexer = P.makeTokenParser (emptyDef)
whiteSpace= P.whiteSpace lexer
lexeme = P.lexeme lexer
symbol = P.symbol lexer
natural = P.natural lexer
parens = P.parens lexer
semi = P.semi lexer
identifier= P.identifier lexer
reserved = P.reserved lexer
reservedOp= P.reservedOp lexer
instance (Show a, Show b) => Show (MM.MultiMap a b) where
show m = show (MM.toMap m)
data ProgramInfo = ProgramInfo {deps:: MM.MultiMap String String
, subfields:: Map.Map String (Map.Map String String)
, current:: String
, fields:: [String]
, currentFile:: String
} deriving Show
emptyPI:: ProgramInfo
emptyPI = ProgramInfo MM.empty Map.empty "" [] ""
insert2:: (Ord a, Eq b) => a -> b -> MM.MultiMap a b -> MM.MultiMap a b
insert2 x y mm = if y `elem` (MM.lookup x mm) then mm else (MM.insert x y mm)
insertName str pi = pi{labels = Map.insert ( current pi ) str }
insertDep:: String -> ProgramInfo -> ProgramInfo
insertDep y pi = pi{deps=insert2 (current pi) y (deps pi)}
insertSF:: String -> String -> ProgramInfo -> ProgramInfo
insertSF name y pi =
let
currentMap = Map.lookup (current pi) (subfields pi)
in
case currentMap of
Nothing -> pi{subfields=Map.insert (current pi) (Map.singleton name y) (subfields pi)}
Just mp -> pi{subfields=Map.insert (current pi) (Map.insert name y mp) (subfields pi)}
insertSF2:: String -> String -> String -> ProgramInfo -> ProgramInfo
insertSF2 lab name y pi =
let
currentMap = Map.lookup lab (subfields pi)
in
case currentMap of
Nothing -> pi{subfields=Map.insert lab (Map.singleton name y) (subfields pi)}
Just mp -> pi{subfields=Map.insert lab (Map.insert name y mp) (subfields pi)}
lookupSF:: String -> String -> ProgramInfo -> Maybe String
lookupSF propName field pi =
case (Map.lookup propName (subfields pi)) of
Nothing -> Nothing
Just sfs-> Map.lookup field sfs
insertField:: String -> ProgramInfo -> ProgramInfo
insertField y pi = pi{fields = y:(fields pi)}
type ProgramParser = ProgramInfo -> Parser ProgramInfo
ioFile:: String -> String -> (String -> String) -> IO ()
ioFile inputF outputF f =
do
handle <- openFile inputF ReadMode
contents <- hGetContents handle
appendFile outputF (f contents)
ioFiles:: [String] -> String -> (String -> String) -> IO ()
ioFiles inputFs outputF f =
do
handles <- sequence (fmap (\x -> openFile x ReadMode) inputFs)
contents <- sequence (fmap hGetContents handles)
let content = unlines contents
appendFile outputF (f content)
fieldsParser:: ProgramParser
fieldsParser pi =
do {eof; return pi}
<|> (try (do {
symbol "#";
expr <- identifier;
fieldsParser (pi{current = expr})
}))
<|> (do {
expr <- many1 (noneOf "\n");
})
<|> do{ anyToken; fieldsParser pi}
readFields:: String -> MM.MultiMap String String
readFields contents = deps $ justRight (parse (fieldsParser emptyPI) "error" contents)
chain:: [String] -> a -> (a -> String -> a) -> (a -> Parser a) -> IO a
chain inputFs init action parser =
do
handles <- sequence (fmap (\x -> openFile x ReadMode) inputFs)
contents <- sequence (fmap hGetContents handles)
let pi = foldIterate2 (\fileName text pi -> justRight (parse (parser (action pi fileName)) "error" text)) inputFs contents init
return pi
chainPI:: [String] -> ProgramParser -> IO ProgramInfo
chainPI inputFs parser = chain inputFs emptyPI (\pi fileName -> pi{currentFile = fileName}) parser
getFile::String -> String
getFile name = unsafePerformIO (readFile name)
chainPI : : [ String ] - > ( ProgramInfo - > Parser ProgramInfo ) - > IO ProgramInfo
|
0ea8a085381246a192fbe824b236d23975ad1cfddab710bdf516a28e50497d5f | apache/couchdb-chttpd | chttpd_handlers_tests.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(chttpd_handlers_tests).
-include_lib("couch/include/couch_eunit.hrl").
-include_lib("couch/include/couch_db.hrl").
setup() ->
Addr = config:get("chttpd", "bind_address", "127.0.0.1"),
Port = mochiweb_socket_server:get(chttpd, port),
BaseUrl = lists:concat(["http://", Addr, ":", Port]),
BaseUrl.
teardown(_Url) ->
ok.
replicate_test_() ->
{
"_replicate",
{
setup,
fun chttpd_test_util:start_couch/0,
fun chttpd_test_util:stop_couch/1,
{
foreach,
fun setup/0, fun teardown/1,
[
fun should_escape_dbname_on_replicate/1
]
}
}
}.
should_escape_dbname_on_replicate(Url) ->
?_test(
begin
UrlBin = ?l2b(Url),
Request = couch_util:json_encode({[
{<<"source">>, <<UrlBin/binary, "/foo%2Fbar">>},
{<<"target">>, <<"bar/baz">>},
{<<"create_target">>, true}
]}),
{ok, 200, _, Body} = request_replicate(Url ++ "/_replicate", Request),
JSON = couch_util:json_decode(Body),
Source = json_value(JSON, [<<"source">>]),
Target = json_value(JSON, [<<"target">>, <<"url">>]),
?assertEqual(<<UrlBin/binary, "/foo%2Fbar">>, Source),
?assertEqual(<<UrlBin/binary, "/bar%2Fbaz">>, Target)
end).
json_value(JSON, Keys) ->
couch_util:get_nested_json_value(JSON, Keys).
request_replicate(Url, Body) ->
Headers = [{"Content-Type", "application/json"}],
Handler = {chttpd_misc, handle_replicate_req},
request(post, Url, Headers, Body, Handler, fun(Req) ->
chttpd:send_json(Req, 200, get(post_body))
end).
request(Method, Url, Headers, Body, {M, F}, MockFun) ->
meck:new(M, [passthrough, non_strict]),
try
meck:expect(M, F, MockFun),
Result = test_request:Method(Url, Headers, Body),
?assert(meck:validate(M)),
Result
catch Kind:Reason ->
{Kind, Reason}
after
meck:unload(M)
end.
| null | https://raw.githubusercontent.com/apache/couchdb-chttpd/74002101513c03df74a4c25f3c892f5d003fa5da/test/chttpd_handlers_tests.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(chttpd_handlers_tests).
-include_lib("couch/include/couch_eunit.hrl").
-include_lib("couch/include/couch_db.hrl").
setup() ->
Addr = config:get("chttpd", "bind_address", "127.0.0.1"),
Port = mochiweb_socket_server:get(chttpd, port),
BaseUrl = lists:concat(["http://", Addr, ":", Port]),
BaseUrl.
teardown(_Url) ->
ok.
replicate_test_() ->
{
"_replicate",
{
setup,
fun chttpd_test_util:start_couch/0,
fun chttpd_test_util:stop_couch/1,
{
foreach,
fun setup/0, fun teardown/1,
[
fun should_escape_dbname_on_replicate/1
]
}
}
}.
should_escape_dbname_on_replicate(Url) ->
?_test(
begin
UrlBin = ?l2b(Url),
Request = couch_util:json_encode({[
{<<"source">>, <<UrlBin/binary, "/foo%2Fbar">>},
{<<"target">>, <<"bar/baz">>},
{<<"create_target">>, true}
]}),
{ok, 200, _, Body} = request_replicate(Url ++ "/_replicate", Request),
JSON = couch_util:json_decode(Body),
Source = json_value(JSON, [<<"source">>]),
Target = json_value(JSON, [<<"target">>, <<"url">>]),
?assertEqual(<<UrlBin/binary, "/foo%2Fbar">>, Source),
?assertEqual(<<UrlBin/binary, "/bar%2Fbaz">>, Target)
end).
json_value(JSON, Keys) ->
couch_util:get_nested_json_value(JSON, Keys).
request_replicate(Url, Body) ->
Headers = [{"Content-Type", "application/json"}],
Handler = {chttpd_misc, handle_replicate_req},
request(post, Url, Headers, Body, Handler, fun(Req) ->
chttpd:send_json(Req, 200, get(post_body))
end).
request(Method, Url, Headers, Body, {M, F}, MockFun) ->
meck:new(M, [passthrough, non_strict]),
try
meck:expect(M, F, MockFun),
Result = test_request:Method(Url, Headers, Body),
?assert(meck:validate(M)),
Result
catch Kind:Reason ->
{Kind, Reason}
after
meck:unload(M)
end.
|
4a7800d39b2fb549ade66b0872fd2295c1305ba73d1bb76f36cdb4bca3b919a7 | locusmath/locus | object.clj | (ns locus.algebra.groupoid.core.object
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.set.logic.sequence.object :refer :all]
[locus.con.core.setpart :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.set.quiver.relation.binary.product :refer :all]
[locus.set.quiver.relation.binary.sr :refer :all]
[locus.set.quiver.binary.core.object :refer :all]
[locus.algebra.commutative.semigroup.object :refer :all]
[locus.algebra.semigroup.core.object :refer :all]
[locus.algebra.group.core.object :refer :all]
[locus.order.lattice.core.object :refer :all]
[locus.algebra.category.core.object :refer :all]
[locus.order.general.symmetric.object :refer :all]
[locus.set.copresheaf.quiver.unital.object :refer :all]
[locus.set.copresheaf.quiver.permutable.object :refer :all]
[locus.set.copresheaf.quiver.dependency.object :refer :all]
[locus.set.copresheaf.quiver.dependency.thin-object :refer :all]
[locus.set.copresheaf.bijection.core.object :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all])
(:import (locus.algebra.group.core.object Group)
(locus.algebra.category.core.object Category)
(locus.order.general.symmetric.object Setoid)
(locus.set.copresheaf.quiver.dependency.object DependencyQuiver)
(locus.set.copresheaf.quiver.dependency.thin_object ThinDependencyQuiver)))
; A category C has isomorphisms for every object. A groupoid is a category C for which each
; morphism is an isomorphism, meaning that if f: A -> B is a morphism there always exists
a f^(-1 ) : B - > A such that ff^(-1 ) and f^(-1)f both compose to identities . We implement
this inverse function in the Groupoid class by storing it in the inv field of a Groupoid
object . are therefore categories with additional structure . We also provide
; conversion routines for groups and setoids to convert them to groupoids.
(deftype Groupoid [quiver op]
StructuredDiset
(first-set [this] (first-set quiver))
(second-set [this] (second-set quiver))
StructuredQuiver
(underlying-quiver [this] (underlying-quiver quiver))
(source-fn [this] (source-fn quiver))
(target-fn [this] (target-fn quiver))
(transition [this e] (transition quiver e))
StructuredUnitalQuiver
(identity-morphism-of [this obj] (identity-morphism-of quiver obj))
(underlying-unital-quiver [this] (underlying-unital-quiver quiver))
ConcreteMorphism
(inputs [this] (composability-relation this))
(outputs [this] (morphisms quiver))
StructuredPermutableQuiver
(underlying-permutable-quiver [this] (underlying-permutable-quiver quiver))
(invert-morphism [this x] (invert-morphism quiver x))
StructuredDependencyQuiver
(underlying-dependency-quiver [this] quiver)
clojure.lang.IFn
(invoke [this arg] (op arg))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
; The position of groupoids within the type hierarchy
(derive Groupoid :locus.set.copresheaf.structure.core.protocols/groupoid)
; Underlying relations and related notions
(defmethod underlying-relation Groupoid
[^Groupoid obj] (underlying-relation (.-quiver obj)))
(defmethod underlying-multirelation Groupoid
[^Groupoid obj] (underlying-multirelation (.-quiver obj)))
(defmethod visualize Groupoid
[^Groupoid obj] (visualize (.-quiver obj)))
; Underlying setoids
(defn underlying-setoid
[groupoid]
(Setoid. (second-set groupoid) (underlying-relation groupoid)))
; The inverse function of a groupoid
(defmethod inverse-function Groupoid
[^Groupoid groupoid]
(->SetFunction
(morphisms groupoid)
(morphisms groupoid)
(fn [elem]
(invert-morphism groupoid elem))))
; A mechanism for creating thin groupoids
(defn thin-groupoid
([rel]
(thin-groupoid (vertices rel) rel))
([vertices rel]
(Groupoid.
(ThinDependencyQuiver. vertices rel)
compose-ordered-pairs)))
; Conversion routines for groupoids
(defmulti to-groupoid type)
(defmethod to-groupoid Groupoid
[groupoid] groupoid)
(defmethod to-groupoid Group
[group]
(Groupoid.
(underlying-dependency-quiver group)
group))
(defmethod to-groupoid Setoid
[setoid]
(let [vertices (underlying-set setoid)
edges (underlying-relation setoid)]
(thin-groupoid vertices edges)))
(defmethod to-groupoid :locus.set.logic.core.set/universal
[rel]
(thin-groupoid rel))
; The underlying groupoid of the topos of sets
(def groupoid-of-sets
(Groupoid.
(->DependencyQuiver
bijection?
universal?
inputs
outputs
identity-bijection
inv)
(fn [[a b]]
(compose a b))))
; Adjoin composition to dependency quivers
(defmethod adjoin-composition DependencyQuiver
[quiv f]
(->Groupoid quiv f))
; Products and coproducts in the category of groupoids
(defmethod product Groupoid
[& groupoids]
(->Groupoid
(apply product (map underlying-dependency-quiver groupoids))
(fn [[morphisms1 morphisms2]]
(map-indexed
(fn [i c]
(c (list (nth morphisms1 i) (nth morphisms2 i))))
groupoids))))
(defmethod coproduct Groupoid
[& groupoids]
(->Groupoid
(apply coproduct (map underlying-dependency-quiver groupoids))
(fn [[[i v] [j w]]]
(when (= i j)
(let [c (nth groupoids i)]
(list i (c (list v w))))))))
(defmethod coproduct :locus.set.copresheaf.structure.core.protocols/group
[& groups]
(apply coproduct (map to-groupoid groups)))
; Opposite categories of groupoids
(defmethod dual :locus.set.copresheaf.structure.core.protocols/groupoid
[groupoid]
(->Groupoid
(dual (underlying-dependency-quiver groupoid))
(comp groupoid reverse)))
; Get underlying groupoids of categories
(defmulti underlying-groupoid type)
(defmethod underlying-groupoid :locus.set.copresheaf.structure.core.protocols/category
[category]
(->Groupoid
(->DependencyQuiver
(isomorphism-elements category)
(objects category)
(source-fn category)
(target-fn category)
(fn [obj]
(identity-morphism-of category obj))
(fn [morphism]
(first (inverse-elements category morphism))))
category))
; Get the endomorphism group of an object of a groupoid
(defn endomorphism-group
[groupoid x]
(->Group
(quiver-hom-class groupoid x x)
groupoid
(identity-morphism-of groupoid x)
(fn [x]
(invert-morphism groupoid x))))
Subobjects in the category of groupoids
(defn restrict-groupoid
[groupoid new-morphisms new-objects]
(->Groupoid
(dependency-subquiver (underlying-dependency-quiver groupoid) new-morphisms new-objects)
(fn [[a b]]
(groupoid (list a b)))))
(defn full-subgroupoid
[groupoid new-objects]
(->Groupoid
(full-dependency-subquiver (underlying-dependency-quiver groupoid) new-objects)
(fn [[a b]]
(groupoid (list a b)))))
(defn wide-subgroupoid
[groupoid new-morphisms]
(->Groupoid
(wide-dependency-subquiver (underlying-dependency-quiver groupoid) new-morphisms)
(fn [[a b]]
(groupoid (list a b)))))
(defn subgroupoid?
[groupoid new-morphisms new-objects]
(and
(dependency-subquiver? (underlying-dependency-quiver groupoid) new-morphisms new-objects)
(compositionally-closed-set? groupoid new-morphisms)))
(defn enumerate-subgroupoids
[groupoid]
(set
(filter
(fn [[a b]]
(compositionally-closed-set? groupoid a))
(dependency-subquivers (underlying-dependency-quiver groupoid)))))
; Congruences in the category of groupoids
(defn groupoid-congruence?
[groupoid in-partition out-partition]
(and
(dependency-quiver-congruence? (underlying-dependency-quiver groupoid) in-partition out-partition)
(compositional-congruence? groupoid in-partition)))
(defn enumerate-groupoid-congruences
[groupoid]
(set
(filter
(fn [[in-partition out-partition]]
(compositional-congruence? groupoid in-partition))
(dependency-quiver-congruences (underlying-dependency-quiver groupoid)))))
| null | https://raw.githubusercontent.com/locusmath/locus/b232579217be4e39458410893827a84d744168e4/src/clojure/locus/algebra/groupoid/core/object.clj | clojure | A category C has isomorphisms for every object. A groupoid is a category C for which each
morphism is an isomorphism, meaning that if f: A -> B is a morphism there always exists
conversion routines for groups and setoids to convert them to groupoids.
The position of groupoids within the type hierarchy
Underlying relations and related notions
Underlying setoids
The inverse function of a groupoid
A mechanism for creating thin groupoids
Conversion routines for groupoids
The underlying groupoid of the topos of sets
Adjoin composition to dependency quivers
Products and coproducts in the category of groupoids
Opposite categories of groupoids
Get underlying groupoids of categories
Get the endomorphism group of an object of a groupoid
Congruences in the category of groupoids | (ns locus.algebra.groupoid.core.object
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.set.logic.sequence.object :refer :all]
[locus.con.core.setpart :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.set.quiver.relation.binary.product :refer :all]
[locus.set.quiver.relation.binary.sr :refer :all]
[locus.set.quiver.binary.core.object :refer :all]
[locus.algebra.commutative.semigroup.object :refer :all]
[locus.algebra.semigroup.core.object :refer :all]
[locus.algebra.group.core.object :refer :all]
[locus.order.lattice.core.object :refer :all]
[locus.algebra.category.core.object :refer :all]
[locus.order.general.symmetric.object :refer :all]
[locus.set.copresheaf.quiver.unital.object :refer :all]
[locus.set.copresheaf.quiver.permutable.object :refer :all]
[locus.set.copresheaf.quiver.dependency.object :refer :all]
[locus.set.copresheaf.quiver.dependency.thin-object :refer :all]
[locus.set.copresheaf.bijection.core.object :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all])
(:import (locus.algebra.group.core.object Group)
(locus.algebra.category.core.object Category)
(locus.order.general.symmetric.object Setoid)
(locus.set.copresheaf.quiver.dependency.object DependencyQuiver)
(locus.set.copresheaf.quiver.dependency.thin_object ThinDependencyQuiver)))
a f^(-1 ) : B - > A such that ff^(-1 ) and f^(-1)f both compose to identities . We implement
this inverse function in the Groupoid class by storing it in the inv field of a Groupoid
object . are therefore categories with additional structure . We also provide
(deftype Groupoid [quiver op]
StructuredDiset
(first-set [this] (first-set quiver))
(second-set [this] (second-set quiver))
StructuredQuiver
(underlying-quiver [this] (underlying-quiver quiver))
(source-fn [this] (source-fn quiver))
(target-fn [this] (target-fn quiver))
(transition [this e] (transition quiver e))
StructuredUnitalQuiver
(identity-morphism-of [this obj] (identity-morphism-of quiver obj))
(underlying-unital-quiver [this] (underlying-unital-quiver quiver))
ConcreteMorphism
(inputs [this] (composability-relation this))
(outputs [this] (morphisms quiver))
StructuredPermutableQuiver
(underlying-permutable-quiver [this] (underlying-permutable-quiver quiver))
(invert-morphism [this x] (invert-morphism quiver x))
StructuredDependencyQuiver
(underlying-dependency-quiver [this] quiver)
clojure.lang.IFn
(invoke [this arg] (op arg))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
(derive Groupoid :locus.set.copresheaf.structure.core.protocols/groupoid)
(defmethod underlying-relation Groupoid
[^Groupoid obj] (underlying-relation (.-quiver obj)))
(defmethod underlying-multirelation Groupoid
[^Groupoid obj] (underlying-multirelation (.-quiver obj)))
(defmethod visualize Groupoid
[^Groupoid obj] (visualize (.-quiver obj)))
(defn underlying-setoid
[groupoid]
(Setoid. (second-set groupoid) (underlying-relation groupoid)))
(defmethod inverse-function Groupoid
[^Groupoid groupoid]
(->SetFunction
(morphisms groupoid)
(morphisms groupoid)
(fn [elem]
(invert-morphism groupoid elem))))
(defn thin-groupoid
([rel]
(thin-groupoid (vertices rel) rel))
([vertices rel]
(Groupoid.
(ThinDependencyQuiver. vertices rel)
compose-ordered-pairs)))
(defmulti to-groupoid type)
(defmethod to-groupoid Groupoid
[groupoid] groupoid)
(defmethod to-groupoid Group
[group]
(Groupoid.
(underlying-dependency-quiver group)
group))
(defmethod to-groupoid Setoid
[setoid]
(let [vertices (underlying-set setoid)
edges (underlying-relation setoid)]
(thin-groupoid vertices edges)))
(defmethod to-groupoid :locus.set.logic.core.set/universal
[rel]
(thin-groupoid rel))
(def groupoid-of-sets
(Groupoid.
(->DependencyQuiver
bijection?
universal?
inputs
outputs
identity-bijection
inv)
(fn [[a b]]
(compose a b))))
(defmethod adjoin-composition DependencyQuiver
[quiv f]
(->Groupoid quiv f))
(defmethod product Groupoid
[& groupoids]
(->Groupoid
(apply product (map underlying-dependency-quiver groupoids))
(fn [[morphisms1 morphisms2]]
(map-indexed
(fn [i c]
(c (list (nth morphisms1 i) (nth morphisms2 i))))
groupoids))))
(defmethod coproduct Groupoid
[& groupoids]
(->Groupoid
(apply coproduct (map underlying-dependency-quiver groupoids))
(fn [[[i v] [j w]]]
(when (= i j)
(let [c (nth groupoids i)]
(list i (c (list v w))))))))
(defmethod coproduct :locus.set.copresheaf.structure.core.protocols/group
[& groups]
(apply coproduct (map to-groupoid groups)))
(defmethod dual :locus.set.copresheaf.structure.core.protocols/groupoid
[groupoid]
(->Groupoid
(dual (underlying-dependency-quiver groupoid))
(comp groupoid reverse)))
(defmulti underlying-groupoid type)
(defmethod underlying-groupoid :locus.set.copresheaf.structure.core.protocols/category
[category]
(->Groupoid
(->DependencyQuiver
(isomorphism-elements category)
(objects category)
(source-fn category)
(target-fn category)
(fn [obj]
(identity-morphism-of category obj))
(fn [morphism]
(first (inverse-elements category morphism))))
category))
(defn endomorphism-group
[groupoid x]
(->Group
(quiver-hom-class groupoid x x)
groupoid
(identity-morphism-of groupoid x)
(fn [x]
(invert-morphism groupoid x))))
Subobjects in the category of groupoids
(defn restrict-groupoid
[groupoid new-morphisms new-objects]
(->Groupoid
(dependency-subquiver (underlying-dependency-quiver groupoid) new-morphisms new-objects)
(fn [[a b]]
(groupoid (list a b)))))
(defn full-subgroupoid
[groupoid new-objects]
(->Groupoid
(full-dependency-subquiver (underlying-dependency-quiver groupoid) new-objects)
(fn [[a b]]
(groupoid (list a b)))))
(defn wide-subgroupoid
[groupoid new-morphisms]
(->Groupoid
(wide-dependency-subquiver (underlying-dependency-quiver groupoid) new-morphisms)
(fn [[a b]]
(groupoid (list a b)))))
(defn subgroupoid?
[groupoid new-morphisms new-objects]
(and
(dependency-subquiver? (underlying-dependency-quiver groupoid) new-morphisms new-objects)
(compositionally-closed-set? groupoid new-morphisms)))
(defn enumerate-subgroupoids
[groupoid]
(set
(filter
(fn [[a b]]
(compositionally-closed-set? groupoid a))
(dependency-subquivers (underlying-dependency-quiver groupoid)))))
(defn groupoid-congruence?
[groupoid in-partition out-partition]
(and
(dependency-quiver-congruence? (underlying-dependency-quiver groupoid) in-partition out-partition)
(compositional-congruence? groupoid in-partition)))
(defn enumerate-groupoid-congruences
[groupoid]
(set
(filter
(fn [[in-partition out-partition]]
(compositional-congruence? groupoid in-partition))
(dependency-quiver-congruences (underlying-dependency-quiver groupoid)))))
|
3190174853f0f08324052c3270da20d02214954a7eb5022d6a906ded4494a7df | dbuenzli/mu | scales.ml | (* This code is in the public domain *)
open Mu
open Mu.Syntax
type scale = Pitch.rel list
let major = [2; 2; 1; 2; 2; 2]
let hexatonic_blues = [3; 2; 1; 1; 3]
let make_scale : Pitch.t -> scale -> Pitch.t list =
fun p scale ->
let next acc rel = Pitch.transp rel (List.hd acc) :: acc in
List.rev (List.fold_left next [p] scale)
let play_scale p scale =
let up (p, o) = (p, o + 1) in
M.tempo Q.(int 2) @@
M.line (List.map M.(note qn) (make_scale p scale)) ^ M.(note qn (up p))
let base = (`C, 4)
let major = play_scale base major
let hexatonic_blues = play_scale base hexatonic_blues
let hexatonic_blues = hexatonic_blues ^ M.retro hexatonic_blues
let main () = Mu_player.main (Music.map Pnote.of_pitch hexatonic_blues)
let () = if !Sys.interactive then () else main ()
| null | https://raw.githubusercontent.com/dbuenzli/mu/f6028ba4515bd49eb076b7394dee39e8f35e13fa/test/scales.ml | ocaml | This code is in the public domain |
open Mu
open Mu.Syntax
type scale = Pitch.rel list
let major = [2; 2; 1; 2; 2; 2]
let hexatonic_blues = [3; 2; 1; 1; 3]
let make_scale : Pitch.t -> scale -> Pitch.t list =
fun p scale ->
let next acc rel = Pitch.transp rel (List.hd acc) :: acc in
List.rev (List.fold_left next [p] scale)
let play_scale p scale =
let up (p, o) = (p, o + 1) in
M.tempo Q.(int 2) @@
M.line (List.map M.(note qn) (make_scale p scale)) ^ M.(note qn (up p))
let base = (`C, 4)
let major = play_scale base major
let hexatonic_blues = play_scale base hexatonic_blues
let hexatonic_blues = hexatonic_blues ^ M.retro hexatonic_blues
let main () = Mu_player.main (Music.map Pnote.of_pitch hexatonic_blues)
let () = if !Sys.interactive then () else main ()
|
9e43439e7a243c4e1642c7836debb439dd6eca3c9f25e0323370475b655b0bb1 | mgsloan/instance-templates | Test.hs | # LANGUAGE
TemplateHaskell
, , ScopedTypeVariables
, FlexibleInstances
, FlexibleContexts #
TemplateHaskell
, ConstraintKinds
, ScopedTypeVariables
, FlexibleInstances
, FlexibleContexts #-}
module Test where
import Classes
import Prelude ( Int, (>>), (.) )
import qualified Prelude as P
import Language.Haskell.InstanceTemplates
import Language.Haskell.TH.Syntax -- This is just for prettier -ddump-splices
$(instantiate [ template OldNum_T [t| OldNum P.Double |] [d| |] ])
newtype Nat = Nat Int
deriving P.Show
$(instantiate
[ template BijNum_T [t| BijNum P.Int Nat |] [d|
bij = Bij (Nat . P.max 0) (\(Nat i) -> i)
|]
]) | null | https://raw.githubusercontent.com/mgsloan/instance-templates/734f3fe838f194b613a270c2e1eb9502b73840a6/tests/numeric/Test.hs | haskell | This is just for prettier -ddump-splices | # LANGUAGE
TemplateHaskell
, , ScopedTypeVariables
, FlexibleInstances
, FlexibleContexts #
TemplateHaskell
, ConstraintKinds
, ScopedTypeVariables
, FlexibleInstances
, FlexibleContexts #-}
module Test where
import Classes
import Prelude ( Int, (>>), (.) )
import qualified Prelude as P
import Language.Haskell.InstanceTemplates
$(instantiate [ template OldNum_T [t| OldNum P.Double |] [d| |] ])
newtype Nat = Nat Int
deriving P.Show
$(instantiate
[ template BijNum_T [t| BijNum P.Int Nat |] [d|
bij = Bij (Nat . P.max 0) (\(Nat i) -> i)
|]
]) |
3e07963f6e9b0ce9dba083be2d3b15fc52533d7bdb0f4e45734610f68bc6d56e | project-oak/hafnium-verification | cVar_decl.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
(** Process variable declarations by saving them as local or global variables. *)
* Computes the local variables of a function or method to be added to the procdesc
val sil_var_of_decl : CContext.t -> Clang_ast_t.decl -> Procname.t -> Pvar.t
val sil_var_of_decl_ref :
CContext.t -> Clang_ast_t.source_range -> Clang_ast_t.decl_ref -> Procname.t -> Pvar.t
val add_var_to_locals : Procdesc.t -> Clang_ast_t.decl -> Typ.t -> Pvar.t -> unit
val sil_var_of_captured_var :
CContext.t
-> Clang_ast_t.source_range
-> Procname.t
-> Clang_ast_t.decl_ref
-> (Pvar.t * Typ.typ) option
val captured_vars_from_block_info :
CContext.t
-> Clang_ast_t.source_range
-> Clang_ast_t.block_captured_variable list
-> (Pvar.t * Typ.t) list
val mk_temp_sil_var : Procdesc.t -> name:string -> Pvar.t
val mk_temp_sil_var_for_expr :
CContext.t -> name:string -> clang_pointer:int -> Clang_ast_t.expr_info -> Pvar.t * Typ.t
val materialize_cpp_temporary :
CContext.t -> Clang_ast_t.stmt_info -> Clang_ast_t.expr_info -> Pvar.t * Typ.t
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/clang/cVar_decl.mli | ocaml | * Process variable declarations by saving them as local or global variables. |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
* Computes the local variables of a function or method to be added to the procdesc
val sil_var_of_decl : CContext.t -> Clang_ast_t.decl -> Procname.t -> Pvar.t
val sil_var_of_decl_ref :
CContext.t -> Clang_ast_t.source_range -> Clang_ast_t.decl_ref -> Procname.t -> Pvar.t
val add_var_to_locals : Procdesc.t -> Clang_ast_t.decl -> Typ.t -> Pvar.t -> unit
val sil_var_of_captured_var :
CContext.t
-> Clang_ast_t.source_range
-> Procname.t
-> Clang_ast_t.decl_ref
-> (Pvar.t * Typ.typ) option
val captured_vars_from_block_info :
CContext.t
-> Clang_ast_t.source_range
-> Clang_ast_t.block_captured_variable list
-> (Pvar.t * Typ.t) list
val mk_temp_sil_var : Procdesc.t -> name:string -> Pvar.t
val mk_temp_sil_var_for_expr :
CContext.t -> name:string -> clang_pointer:int -> Clang_ast_t.expr_info -> Pvar.t * Typ.t
val materialize_cpp_temporary :
CContext.t -> Clang_ast_t.stmt_info -> Clang_ast_t.expr_info -> Pvar.t * Typ.t
|
19b51e5ecd54659f33509ced63450d7c986807808bfc0272a02341faf901979c | vindarel/replic | config.lisp | (defpackage replic.config
(:use :cl)
(:import-from :replic.utils
:truthy
:falsy)
(:export :apply-config
:read-config
:has-option-p
:option))
(in-package :replic.config)
(defvar *cfg-file* ".replic.conf"
"Default name of the config file.")
(defvar *cfg* (py-configparser:make-config)
"The config read from the config.conf files found, in order: in this
project root, ~/.config/replic.conf, in the current directory.")
(defvar *cfg-sources* nil
"List of files to read the config, in order.")
(defvar *section* "default"
"Default section header of the config file(s) to read parameters from.")
(defun read-config (&optional (cfg-file *cfg-file*))
"Search for the config files, parse the config, and return the config object.
Three locations: in the package root, in ~/config/, in the home.
If no `cfg-file` argument is given, use the global `*cfg-file*` (\".replic.conf\")."
(setf *cfg-sources* (list
;; Setting here and not in defparameter:
;; ensure this is the user's value, not where the binary was built on.
(merge-pathnames (str:concat ".config/" cfg-file) (user-homedir-pathname))
(merge-pathnames cfg-file (user-homedir-pathname))
cfg-file))
(loop for it in *cfg-sources*
do (progn
(when (probe-file it)
;; xxx verbose
;; (format t "reading config ~a~&" it)
;; read-files reads a list.
(py-configparser:read-files *cfg* (list it)))))
*cfg*)
(defun config-files ()
*cfg-sources*)
(defun has-config-p ()
"Return nil if either we didn't find config files or they don't have
any section."
(when (or (config-files)
(py-configparser:sections *cfg*))
t))
(defun has-option-p (option &optional (package/section "default"))
"Check if the config object has `option` in section
`package/section` (the section is inferred from the package name)."
(ignore-errors
(py-configparser:has-option-p *cfg*
;; :PACKAGE -> "package" section name.
(str:downcase package/section)
(no-earmuffs option))))
(defun option (option &key (section *section*))
"Return this option's value (as string)."
(if (py-configparser:has-section-p *cfg* section)
(py-configparser:get-option *cfg* section option)
(values nil (format nil "no such section: ~a" section))))
;;
;; Apply replic's default config:
- get all 's exported variables ,
;; - search for them without earmuffs in the config file,
;; - get the option and set the variable back in the package.
;;
(defun get-exported-variables (package)
(assert (symbolp package))
(let ((replic.completion::*variables* nil)
(replic.completion::*commands* nil))
(replic.completion:functions-to-commands package)
(replic.completion:variables)))
;; (defun copy-no-earmuffs (vars)
;; "From this list of variables (strings), duplicate all of them, but without earmuffs.
;; So writing the config file is normal for a non-lispy user, while without surprise for a lisper (which shall have a lisp configuration file anyway)."
( assert ( listp vars ) )
;; (when vars
;; (append vars
;; (mapcar (lambda (it)
;; (when (str:starts-with? "*" it)
;; (string-trim "*" it)))
;; vars))))
(defun no-earmuffs (var)
"Return this parameter's name, without earmuffs ('*').
;; So the config file can suit non-lispers and lispers (who also shall have a lisp configuration file anyway)."
(if (str:starts-with? "*" var)
(string-trim "*" var)
var))
(defun set-option (var val package)
"Get the symbol associated to `var` in 'package' and set it."
(setf (symbol-value (find-symbol (string-upcase var) package))
val))
(defun read-option (key package)
"Interpret the value of this option: t, true or 1 means true, parse integers, etc.
key: an existing variable of the given package, which will be set from the config file."
(let ((val (option (no-earmuffs key) :section (str:downcase package))))
(cond
((truthy val)
(set-option key t package))
((falsy val)
(set-option key nil package))
((null (ignore-errors (parse-integer val)))
(set-option key val package))
(t
Integer ? Try to parse it .
(unless
(ignore-errors
(when (parse-integer val)
(set-option key (parse-integer val) package))))))))
(defun print-options (&optional (section "default" section-p))
(loop for section in (if section-p (list section)
(py-configparser:sections *cfg*))
do (loop for item in (py-configparser:items *cfg* section)
do (format t "~a: ~a~&" (car item) (cdr item)))))
(defun apply-config (&optional (section "default") (package :replic) (cfg-file *cfg-file*))
"Read the config files and for every variable of this section, get its new value.
Apply the configuration settings for the default package's variables.
In the config file, variables don't have lispy earmuffs.
Example .replic.conf:
[default]
confirm-exit: false
Then call:
(replic.config:apply-config)
by default, this reads the 'default' section and looks for parameters of the REPLIC package.
You could read another section for your app, for instance:
[default]
confirm-exit: true
[my-app]
confirm-exit: false
(replic.config:apply-config \"my-app\")
"
(declare (ignorable section))
(read-config cfg-file)
(mapcar (lambda (var)
( format t " apply - config : has ~a an option for ~a ? ~a~ & " ( str : downcase section )
;; var
;; (has-option-p var section))
(when (has-option-p var (str:downcase section))
( uiop : format ! t " ~tapplying option : ~a~ & " var ( has - option - p var section ) )
(read-option var package)))
(get-exported-variables package))
t)
| null | https://raw.githubusercontent.com/vindarel/replic/23962f901c3c6f983893f0445e40195610e3df1f/src/config.lisp | lisp | Setting here and not in defparameter:
ensure this is the user's value, not where the binary was built on.
xxx verbose
(format t "reading config ~a~&" it)
read-files reads a list.
:PACKAGE -> "package" section name.
Apply replic's default config:
- search for them without earmuffs in the config file,
- get the option and set the variable back in the package.
(defun copy-no-earmuffs (vars)
"From this list of variables (strings), duplicate all of them, but without earmuffs.
So writing the config file is normal for a non-lispy user, while without surprise for a lisper (which shall have a lisp configuration file anyway)."
(when vars
(append vars
(mapcar (lambda (it)
(when (str:starts-with? "*" it)
(string-trim "*" it)))
vars))))
So the config file can suit non-lispers and lispers (who also shall have a lisp configuration file anyway)."
var
(has-option-p var section)) | (defpackage replic.config
(:use :cl)
(:import-from :replic.utils
:truthy
:falsy)
(:export :apply-config
:read-config
:has-option-p
:option))
(in-package :replic.config)
(defvar *cfg-file* ".replic.conf"
"Default name of the config file.")
(defvar *cfg* (py-configparser:make-config)
"The config read from the config.conf files found, in order: in this
project root, ~/.config/replic.conf, in the current directory.")
(defvar *cfg-sources* nil
"List of files to read the config, in order.")
(defvar *section* "default"
"Default section header of the config file(s) to read parameters from.")
(defun read-config (&optional (cfg-file *cfg-file*))
"Search for the config files, parse the config, and return the config object.
Three locations: in the package root, in ~/config/, in the home.
If no `cfg-file` argument is given, use the global `*cfg-file*` (\".replic.conf\")."
(setf *cfg-sources* (list
(merge-pathnames (str:concat ".config/" cfg-file) (user-homedir-pathname))
(merge-pathnames cfg-file (user-homedir-pathname))
cfg-file))
(loop for it in *cfg-sources*
do (progn
(when (probe-file it)
(py-configparser:read-files *cfg* (list it)))))
*cfg*)
(defun config-files ()
*cfg-sources*)
(defun has-config-p ()
"Return nil if either we didn't find config files or they don't have
any section."
(when (or (config-files)
(py-configparser:sections *cfg*))
t))
(defun has-option-p (option &optional (package/section "default"))
"Check if the config object has `option` in section
`package/section` (the section is inferred from the package name)."
(ignore-errors
(py-configparser:has-option-p *cfg*
(str:downcase package/section)
(no-earmuffs option))))
(defun option (option &key (section *section*))
"Return this option's value (as string)."
(if (py-configparser:has-section-p *cfg* section)
(py-configparser:get-option *cfg* section option)
(values nil (format nil "no such section: ~a" section))))
- get all 's exported variables ,
(defun get-exported-variables (package)
(assert (symbolp package))
(let ((replic.completion::*variables* nil)
(replic.completion::*commands* nil))
(replic.completion:functions-to-commands package)
(replic.completion:variables)))
( assert ( listp vars ) )
(defun no-earmuffs (var)
"Return this parameter's name, without earmuffs ('*').
(if (str:starts-with? "*" var)
(string-trim "*" var)
var))
(defun set-option (var val package)
"Get the symbol associated to `var` in 'package' and set it."
(setf (symbol-value (find-symbol (string-upcase var) package))
val))
(defun read-option (key package)
"Interpret the value of this option: t, true or 1 means true, parse integers, etc.
key: an existing variable of the given package, which will be set from the config file."
(let ((val (option (no-earmuffs key) :section (str:downcase package))))
(cond
((truthy val)
(set-option key t package))
((falsy val)
(set-option key nil package))
((null (ignore-errors (parse-integer val)))
(set-option key val package))
(t
Integer ? Try to parse it .
(unless
(ignore-errors
(when (parse-integer val)
(set-option key (parse-integer val) package))))))))
(defun print-options (&optional (section "default" section-p))
(loop for section in (if section-p (list section)
(py-configparser:sections *cfg*))
do (loop for item in (py-configparser:items *cfg* section)
do (format t "~a: ~a~&" (car item) (cdr item)))))
(defun apply-config (&optional (section "default") (package :replic) (cfg-file *cfg-file*))
"Read the config files and for every variable of this section, get its new value.
Apply the configuration settings for the default package's variables.
In the config file, variables don't have lispy earmuffs.
Example .replic.conf:
[default]
confirm-exit: false
Then call:
(replic.config:apply-config)
by default, this reads the 'default' section and looks for parameters of the REPLIC package.
You could read another section for your app, for instance:
[default]
confirm-exit: true
[my-app]
confirm-exit: false
(replic.config:apply-config \"my-app\")
"
(declare (ignorable section))
(read-config cfg-file)
(mapcar (lambda (var)
( format t " apply - config : has ~a an option for ~a ? ~a~ & " ( str : downcase section )
(when (has-option-p var (str:downcase section))
( uiop : format ! t " ~tapplying option : ~a~ & " var ( has - option - p var section ) )
(read-option var package)))
(get-exported-variables package))
t)
|
3b2c027b930dff21e31ec85e744a8af52df77fb6467156e6a3d0e05502a33756 | braintripping/lark | registry.cljs | (ns lark.commands.registry
(:require [goog.object :as gobj]
[clojure.string :as string]
[clojure.set :as set]
[goog.events :as events]
["@braintripping/keypress.js" :refer [keypress]]))
(gobj/set (gobj/get js/window "goog" "events") "listen" events/listen)
(defonce Keypress (new (.-Listener keypress)))
(def mac? (let [platform (.. js/navigator -platform)]
(or (string/starts-with? platform "Mac")
(string/starts-with? platform "iP"))))
(defn capitalize [s]
(str (.toUpperCase (subs s 0 1)) (subs s 1)))
(defn format-segment [target modifier]
(let [modifier (string/lower-case modifier)]
(or (case target :Keypress.js (case modifier "m1" "meta"
"m2" "alt"
"m3" (if mac? "ctrl" "command")
modifier)
:internal (case modifier "meta" "m1"
("alt"
"option") "m2"
modifier)
:display (let [modifier (format-segment :internal modifier)]
(case modifier
"m1" (if mac? "⌘" "Ctrl")
"m2" (if mac? "Option" "Alt")
"m3" (if mac? "Ctrl" "Meta")
"left" "←"
"right" "→"
"up" "↑"
"down" "↓"
"backspace" "⌫"
(capitalize modifier))))
modifier)))
(def modifiers-internal #{"m1" "m2" "shift"})
(defn binding-string->vec [s]
(mapv (partial format-segment :internal) (string/split s #"[\s-]")))
(defn binding-set [s]
(set (binding-string->vec s)))
(defonce commands (atom {}))
(defonce mappings (atom {}))
(defonce handler (volatile! nil))
(defn M1-down? [e]
(if mac? (.-metaKey e)
(.-ctrlKey e)))
(defn get-keyset-commands
"Returns command-names for a set of keys"
[keyset]
(get-in @mappings [keyset :exec]))
(defn spaced-name [the-name]
(str (string/upper-case (first the-name)) (string/replace (subs the-name 1) "-" " ")))
(defn seq-disj
"Removes `x` from `coll`"
[coll x]
(remove #(= % x) coll))
(defn distinct-conj
"Conj `x` to coll, distinct"
[coll x]
(distinct (conj coll x)))
(defn normalize-binding [binding]
(let [{:keys [key-string] :as binding-map} (if (map? binding) binding {:key-string binding})
binding-vec (binding-string->vec key-string)]
(assoc binding-map :keys (to-array (mapv (partial format-segment :Keypress.js) binding-vec))
:binding-vec binding-vec)))
(defn- add-binding [mappings name binding]
(let [{:keys [binding-vec event] :as binding-map} (normalize-binding binding)
path [(set binding-vec) :exec]]
(when-not (seq (get-in mappings path))
(.register_combo Keypress
(clj->js
eg . if we have M1 - Shift - K bound and pressed , M1 - K should not also activate .
:is_solitary true
;; we don't care what order modifiers are pressed
:is_unordered true
(case event :keydown :on_keydown
:keyup :on_keyup
:on_keydown) #(@handler binding binding-vec)}
binding-map))))
(update-in mappings path distinct-conj name)))
(defn- remove-binding [mappings name binding]
(let [{:keys [binding-vec keys] :as binding-map} (normalize-binding binding)
path [(set binding-vec) :exec]
mappings (update-in mappings path seq-disj name)]
(when-not (seq (get-in mappings path))
(.unregister_combo Keypress #js {:keys keys}))
mappings))
(defn bind!
"Takes a map of {<command-name>, <binding>} and registers keybindings."
[bindings]
(let [[mappings* commands*] (reduce (fn [[mappings commands] [the-name binding]]
[(add-binding mappings the-name binding)
(update-in commands [the-name :bindings] (comp distinct conj) binding)])
[@mappings @commands] bindings)]
(reset! mappings mappings*)
(reset! commands commands*)))
(defn unbind!
"Takes a map of {<command-name>, <binding string>} and removes keybindings."
[bindings]
(let [[mappings* commands*] (reduce (fn [[mappings commands] [the-name binding]]
[(remove-binding mappings the-name binding)
(update-in commands [the-name :bindings] seq-disj binding)]) [@mappings @commands] bindings)]
(reset! mappings mappings*)
(reset! commands commands*)))
(defn register! [{the-name :name
priority :priority
:as the-command} bindings]
(swap! commands assoc the-name (merge the-command
{:display-namespace (some-> (namespace the-name)
(spaced-name))
:display-name (spaced-name (name the-name))
:bindings bindings
:priority (or priority 0)}))
(reset! mappings (reduce (fn [mappings pattern]
(add-binding mappings the-name pattern)) @mappings bindings)))
(defn deregister! [the-name]
(let [{:keys [bindings]} (get @commands the-name)]
(unbind! (apply hash-map (interleave (repeat the-name) bindings)))
(swap! commands dissoc the-name)))
(def sort-ks #(sort-by (fn [x] (if (string? x) x (:name (meta x)))) %))
(defn binding-segment-compare [segment]
(if (#{"m1" "m2" "shift"} segment) 0 1))
(defn keyset-string [keyset]
(let [modifiers #{"m1" "m2" "shift"}]
(->> (sort-by binding-segment-compare (seq keyset))
(mapv (partial format-segment :display))
(interpose " ")
(apply str)))) | null | https://raw.githubusercontent.com/braintripping/lark/95038a823068681c39453c46a309a3514cf48800/tools/src/lark/commands/registry.cljs | clojure | we don't care what order modifiers are pressed | (ns lark.commands.registry
(:require [goog.object :as gobj]
[clojure.string :as string]
[clojure.set :as set]
[goog.events :as events]
["@braintripping/keypress.js" :refer [keypress]]))
(gobj/set (gobj/get js/window "goog" "events") "listen" events/listen)
(defonce Keypress (new (.-Listener keypress)))
(def mac? (let [platform (.. js/navigator -platform)]
(or (string/starts-with? platform "Mac")
(string/starts-with? platform "iP"))))
(defn capitalize [s]
(str (.toUpperCase (subs s 0 1)) (subs s 1)))
(defn format-segment [target modifier]
(let [modifier (string/lower-case modifier)]
(or (case target :Keypress.js (case modifier "m1" "meta"
"m2" "alt"
"m3" (if mac? "ctrl" "command")
modifier)
:internal (case modifier "meta" "m1"
("alt"
"option") "m2"
modifier)
:display (let [modifier (format-segment :internal modifier)]
(case modifier
"m1" (if mac? "⌘" "Ctrl")
"m2" (if mac? "Option" "Alt")
"m3" (if mac? "Ctrl" "Meta")
"left" "←"
"right" "→"
"up" "↑"
"down" "↓"
"backspace" "⌫"
(capitalize modifier))))
modifier)))
(def modifiers-internal #{"m1" "m2" "shift"})
(defn binding-string->vec [s]
(mapv (partial format-segment :internal) (string/split s #"[\s-]")))
(defn binding-set [s]
(set (binding-string->vec s)))
(defonce commands (atom {}))
(defonce mappings (atom {}))
(defonce handler (volatile! nil))
(defn M1-down? [e]
(if mac? (.-metaKey e)
(.-ctrlKey e)))
(defn get-keyset-commands
"Returns command-names for a set of keys"
[keyset]
(get-in @mappings [keyset :exec]))
(defn spaced-name [the-name]
(str (string/upper-case (first the-name)) (string/replace (subs the-name 1) "-" " ")))
(defn seq-disj
"Removes `x` from `coll`"
[coll x]
(remove #(= % x) coll))
(defn distinct-conj
"Conj `x` to coll, distinct"
[coll x]
(distinct (conj coll x)))
(defn normalize-binding [binding]
(let [{:keys [key-string] :as binding-map} (if (map? binding) binding {:key-string binding})
binding-vec (binding-string->vec key-string)]
(assoc binding-map :keys (to-array (mapv (partial format-segment :Keypress.js) binding-vec))
:binding-vec binding-vec)))
(defn- add-binding [mappings name binding]
(let [{:keys [binding-vec event] :as binding-map} (normalize-binding binding)
path [(set binding-vec) :exec]]
(when-not (seq (get-in mappings path))
(.register_combo Keypress
(clj->js
eg . if we have M1 - Shift - K bound and pressed , M1 - K should not also activate .
:is_solitary true
:is_unordered true
(case event :keydown :on_keydown
:keyup :on_keyup
:on_keydown) #(@handler binding binding-vec)}
binding-map))))
(update-in mappings path distinct-conj name)))
(defn- remove-binding [mappings name binding]
(let [{:keys [binding-vec keys] :as binding-map} (normalize-binding binding)
path [(set binding-vec) :exec]
mappings (update-in mappings path seq-disj name)]
(when-not (seq (get-in mappings path))
(.unregister_combo Keypress #js {:keys keys}))
mappings))
(defn bind!
"Takes a map of {<command-name>, <binding>} and registers keybindings."
[bindings]
(let [[mappings* commands*] (reduce (fn [[mappings commands] [the-name binding]]
[(add-binding mappings the-name binding)
(update-in commands [the-name :bindings] (comp distinct conj) binding)])
[@mappings @commands] bindings)]
(reset! mappings mappings*)
(reset! commands commands*)))
(defn unbind!
"Takes a map of {<command-name>, <binding string>} and removes keybindings."
[bindings]
(let [[mappings* commands*] (reduce (fn [[mappings commands] [the-name binding]]
[(remove-binding mappings the-name binding)
(update-in commands [the-name :bindings] seq-disj binding)]) [@mappings @commands] bindings)]
(reset! mappings mappings*)
(reset! commands commands*)))
(defn register! [{the-name :name
priority :priority
:as the-command} bindings]
(swap! commands assoc the-name (merge the-command
{:display-namespace (some-> (namespace the-name)
(spaced-name))
:display-name (spaced-name (name the-name))
:bindings bindings
:priority (or priority 0)}))
(reset! mappings (reduce (fn [mappings pattern]
(add-binding mappings the-name pattern)) @mappings bindings)))
(defn deregister! [the-name]
(let [{:keys [bindings]} (get @commands the-name)]
(unbind! (apply hash-map (interleave (repeat the-name) bindings)))
(swap! commands dissoc the-name)))
(def sort-ks #(sort-by (fn [x] (if (string? x) x (:name (meta x)))) %))
(defn binding-segment-compare [segment]
(if (#{"m1" "m2" "shift"} segment) 0 1))
(defn keyset-string [keyset]
(let [modifiers #{"m1" "m2" "shift"}]
(->> (sort-by binding-segment-compare (seq keyset))
(mapv (partial format-segment :display))
(interpose " ")
(apply str)))) |
627d6c806577095e2aff364a12d89aabb7bebfc853a7cb1eb91d12af10586d44 | keigoi/ocaml-mpst | chan.ml | module Q = Queue
module M = Monitor
type 'a t = ('a Q.t ref) M.t
let create () : 'a t = M.create (ref (Q.create ()))
let send (t : 'a t) (v:'a) : unit =
M.lock t (fun q -> Q.add v !q; M.signal t)
let receive (t:'a t) : 'a =
M.wait t (fun q ->
if Q.is_empty !q then
M.WaitMore
else
M.Return (Q.take !q))
let clear_queue_ t =
M.lock t (fun q ->
let old = !q in
q := Q.create ();
old)
let peek (t:'a t) : 'a =
M.wait t (fun q ->
if Q.is_empty !q then
M.WaitMore
else
M.Return (Q.peek !q))
let clear (t:'a t) : unit =
ignore (clear_queue_ t)
let is_empty (t:'a t) : bool =
M.lock t (fun q -> Q.is_empty !q)
let length (t:'a t) : int =
M.lock t (fun q -> Q.length !q)
| null | https://raw.githubusercontent.com/keigoi/ocaml-mpst/daae64bc9fe1d10213b9e73e22a10ccc5a0426cd/lib/bare/chan.ml | ocaml | module Q = Queue
module M = Monitor
type 'a t = ('a Q.t ref) M.t
let create () : 'a t = M.create (ref (Q.create ()))
let send (t : 'a t) (v:'a) : unit =
M.lock t (fun q -> Q.add v !q; M.signal t)
let receive (t:'a t) : 'a =
M.wait t (fun q ->
if Q.is_empty !q then
M.WaitMore
else
M.Return (Q.take !q))
let clear_queue_ t =
M.lock t (fun q ->
let old = !q in
q := Q.create ();
old)
let peek (t:'a t) : 'a =
M.wait t (fun q ->
if Q.is_empty !q then
M.WaitMore
else
M.Return (Q.peek !q))
let clear (t:'a t) : unit =
ignore (clear_queue_ t)
let is_empty (t:'a t) : bool =
M.lock t (fun q -> Q.is_empty !q)
let length (t:'a t) : int =
M.lock t (fun q -> Q.length !q)
| |
741b88a51e151843d50ca450b79d016e9095ed337470ff60b1d5fab29e53106b | abakst/Brisk | Env.hs | module Brisk.Model.Env (empty, lookup, insert, addsEnv, unionEnvs, toList, Env(..)) where
import Prelude hiding (lookup, insert)
import qualified Data.Map.Strict as M
type Env k v = M.Map k v
empty :: Ord k => M.Map k v
empty = M.empty
lookup :: Ord k => M.Map k v -> k -> Maybe v
lookup e k = M.lookup k e
insert :: Ord k => M.Map k v -> k -> v -> M.Map k v
insert e k v = M.insert k v e
toList :: M.Map k v -> [(k,v)]
toList = M.toList
addsEnv :: Ord k => Env k v -> [(k,v)] -> Env k v
addsEnv = foldl go
where
go e (k,v) = insert e k v
unionEnvs :: Ord k => Env k v -> Env k v -> Env k v
unionEnvs = M.union
| null | https://raw.githubusercontent.com/abakst/Brisk/3e4ce790a742d3e3b786dba45d36f715ea0e61ef/src/Brisk/Model/Env.hs | haskell | module Brisk.Model.Env (empty, lookup, insert, addsEnv, unionEnvs, toList, Env(..)) where
import Prelude hiding (lookup, insert)
import qualified Data.Map.Strict as M
type Env k v = M.Map k v
empty :: Ord k => M.Map k v
empty = M.empty
lookup :: Ord k => M.Map k v -> k -> Maybe v
lookup e k = M.lookup k e
insert :: Ord k => M.Map k v -> k -> v -> M.Map k v
insert e k v = M.insert k v e
toList :: M.Map k v -> [(k,v)]
toList = M.toList
addsEnv :: Ord k => Env k v -> [(k,v)] -> Env k v
addsEnv = foldl go
where
go e (k,v) = insert e k v
unionEnvs :: Ord k => Env k v -> Env k v -> Env k v
unionEnvs = M.union
| |
b1ff8a2a69483b1888525de19182e234ed9547a6c6dfe82cddb74dcfaef50a1b | hanshuebner/bknr-datastore | encoding-test.lisp | (in-package :bknr.datastore)
(5am:def-suite :bknr.datastore)
(5am:in-suite :bknr.datastore)
(defun files-identical-content-p (path-a path-b)
"Are files of PATH-A and PATH-B byte per byte identical?"
(with-open-file (in-a path-a :element-type '(unsigned-byte 8))
(with-open-file (in-b path-b :element-type '(unsigned-byte 8))
(loop
for byte-a = (read-byte in-a nil nil)
for byte-b = (read-byte in-b nil nil)
while (or byte-a byte-b)
unless (and byte-a byte-b (= byte-a byte-b))
return nil
finally (return t)))))
(defun congruent-p (a b)
"Are lisp value A and B (deeply) congruent?"
(bknr.utils:with-temporary-file (path-a)
(bknr.utils:with-temporary-file (path-b)
(cl-store:store a path-a)
(cl-store:store b path-b)
(prog1
(files-identical-content-p path-a path-b)
(delete-file path-a)
(delete-file path-b)))))
(defun copy-by-encoding (value)
(bknr.utils:with-temporary-file (path)
(with-open-file (out path :direction :output :if-exists :supersede
:element-type '(unsigned-byte 8))
(encode value out))
(with-open-file (in path :element-type '(unsigned-byte 8))
(decode in))))
(defmacro test-encoding (name value)
(let ((options (alexandria:ensure-list name)))
(destructuring-bind (name &key skip) options
`(5am:test ,name
,(if skip
`(5am:skip ,skip)
`(5am:is (congruent-p ,value (copy-by-encoding ,value))))))))
(test-encoding list.1 '(1 2 3))
(test-encoding list.len.30 (loop repeat 30 collect 'x))
(test-encoding list.len.254 (loop repeat 254 collect 'x))
(test-encoding list.len.255 (loop repeat 255 collect 'x))
(test-encoding list.len.256 (loop repeat 256 collect 'x))
(test-encoding list.len.257 (loop repeat 257 collect 'x))
(test-encoding list.len.3000 (loop repeat 3000 collect 'x))
(test-encoding improper-list.1 '(1 2 3 4 . 5))
(test-encoding cons.1 '(1 . 2))
;;; from cl-store :)
(test-encoding integer.1 1)
(test-encoding integer.2 0)
(test-encoding integer.3 23423333333333333333333333423102334)
(test-encoding integer.4 -2322993)
(test-encoding integer.5 most-positive-fixnum)
(test-encoding integer.6 most-negative-fixnum)
;; ratios
(test-encoding ratio.1 1/2)
(test-encoding ratio.2 234232/23434)
(test-encoding ratio.3 -12/2)
(test-encoding ratio.4 -6/11)
(test-encoding ratio.5 23222/13)
;; complex numbers - currently not supported
( test - encoding complex.1 # C(0 1 ) )
;; (test-encoding complex.2 #C(0.0 1.0))
;; (test-encoding complex.3 #C(32 -23455))
( test - encoding complex.4 # C(-222.32 2322.21 ) )
;; (test-encoding complex.5 #C(-111 -1123))
;; (test-encoding complex.6 #C(-11.2 -34.5))
;; single-float
(test-encoding single-float.1 3244.32)
(test-encoding single-float.2 0.12)
(test-encoding single-float.3 -233.001)
(test-encoding single-float.4 most-positive-single-float)
(test-encoding single-float.5 most-negative-single-float)
;; double-float
(test-encoding double-float.1 2343.3d0)
(test-encoding double-float.2 -1211111.3343d0)
(test-encoding double-float.3 99999999999123456789012345678222222222222290.0987654321d0)
(test-encoding double-float.4 -99999999999123456789012345678222222222222290.0987654321d0)
(test-encoding double-float.5 most-positive-double-float)
(test-encoding double-float.6 most-negative-double-float)
;; characters
(test-encoding char.1 #\Space)
(test-encoding char.2 #\f )
(test-encoding char.3 #\Rubout)
(test-encoding char.4 (code-char 255))
(5am:test char.random
(5am:for-all ((char (5am:gen-character)))
(5am:is (char= char (copy-by-encoding char)))))
;; strings
(5am:test string.random
(5am:for-all ((string (5am:gen-string)))
(5am:is (string= string (copy-by-encoding string)))))
(5am:test string.random.code-limited
(5am:for-all ((string (5am:gen-string :elements (5am:gen-character :code-limit 10000))))
(5am:is (string= string (copy-by-encoding string)))))
(5am:test string.decode-utf-8
(labels ((decode-string-from-octets (octets)
(flexi-streams:with-input-from-sequence (in octets)
(bknr.datastore::%decode-string in))))
(5am:is (string-equal "<=>" (decode-string-from-octets #(1 3 60 61 62))))
;; #\? is the substitution char
(string-equal "<?>" (decode-string-from-octets #(1 3 60 188 62)))
kilian 2008 - 03 - 20 : the following for - all test failed on ccl ,
because the correct utf-8 sequence could produce a char - code
;; above char-code-limit - bknr.datastore::%decode-string should
;; throw an error in this case, but I dont know how to test this
( 5am : for - all ( ( octets ( 5am : gen - buffer ) ) )
;; (5am:finishes (decode-string-from-octets (concatenate 'vector (vector 1 (length octets)) octets))))
))
# + ( or ( and ) )
( progn
( test - encoding unicode.1 ( map # -lispworks ' string
# + lispworks ' lw : text - string
# ' code - char ( list # X20AC # X3BB ) ) )
( test - encoding unicode.2 ( intern ( map # -lispworks ' string
;; #+lispworks 'lw:text-string
# ' code - char ( list # X20AC # X3BB ) )
;; :pwgl-test-suite)))
;; vectors
(test-encoding vector.1 #(1 2 3 4))
(test-encoding vector.2 (make-array 5 :element-type 'fixnum
:initial-contents (list 1 2 3 4 5)))
(test-encoding vector.4 #*101101101110)
(test-encoding vector.3
(make-array 5
:element-type 'fixnum
:fill-pointer 2
:initial-contents (list 1 2 3 4 5)))
(test-encoding vector.5 #*)
(test-encoding vector.6 #())
;; arrays
(test-encoding array.1
(make-array '(2 2) :initial-contents '((1 2) (3 4))))
(test-encoding array.2
(make-array '(2 2) :initial-contents '((1 1) (1 1))))
(test-encoding array.3
(make-array '(2 2) :element-type 'fixnum :initial-element 3))
(test-encoding (array.3b :skip "will be fixed later - -lisp.net/bknr/ticket/31")
(make-array '(2 2) :element-type '(mod 10) :initial-element 3))
(test-encoding array.4
(make-array '(2 3 5)
:initial-contents
'(((1 2 #\f 5 12.0) (#\Space 0 4 1 0) ('d 0 #() 3 -1))
((0 #\a #\b 4 #\q) (12.0d0 0 '(d) 4 1)
(#\Newline 1 7 #\4 #\0)))))
;; (test-encoding array.5
( let * ( ( a1 ( make - array 5 ) )
( a2 ( make - array 4 : displaced - to a1
: displaced - index - offset 1 ) )
( a3 ( make - array 2 : displaced - to a2
: displaced - index - offset 2 ) ) )
;; a3))
;; symbols
(test-encoding symbol.1 t)
(test-encoding symbol.2 nil)
(test-encoding symbol.3 :foo)
(test-encoding symbol.4 'bknr.datastore::foo)
(test-encoding symbol.5 'make-hash-table)
(test-encoding symbol.6 '|foo bar|)
(test-encoding symbol.7 'foo\ bar\ baz)
;; (deftest gensym.1 (progn
( store ( " Foobar " ) * test - file * )
;; (let ((new (restore *test-file*)))
;; (list (symbol-package new)
( mismatch " Foobar " ( symbol - name new ) ) ) ) )
;; (nil 6))
This failed in cl - store < 0.5.5
( deftest gensym.2 ( let ( ( x ( ) ) )
;; (store (list x x) *test-file*)
;; (let ((new (restore *test-file*)))
( eql ( car new ) ( cadr new ) ) ) )
;; t)
;; cons
(test-encoding cons.1 '(1 2 3))
(test-encoding cons.2 '((1 2 3)))
(test-encoding cons.3 '(#\Space 1 1.2 1.3 #(1 2 3)))
(test-encoding cons.4 '(1 . 2))
(test-encoding cons.5 '(t . nil))
(test-encoding cons.6 '(1 2 3 . 5))
( deftest cons.7 ( let ( ( list ( cons nil nil ) ) ) ; ' # 1=(#1 # ) ) )
( setf ( car list ) list )
;; (store list *test-file*)
( let ( ( ret ( restore * test - file * ) ) )
( eq ret ( car ret ) ) ) )
;; t)
;; hash tables
;; for some reason (make-hash-table) is not equalp
;; to (make-hash-table) with ecl.
#-openmcl(test-encoding hash.1 (make-hash-table))
#+openmcl(5am:test hash.1 (5am:skip "the hash-table-size is not preserved - do we need to fix this?"))
#-openmcl(test-encoding hash.2 (make-hash-table :test #'equal))
#+openmcl(5am:test hash.2 (5am:skip "the hash-table-size is not preserved - do we need to fix this?"))
;; (defvar *hash* (let ((in (make-hash-table :test #'equal
: rehash - threshold 0.4 : size 20
: rehash - size 40 ) ) )
( dotimes ( x 1000 ) ( setf ( gethash ( format nil " ~R " x ) in ) x ) )
;; in))
;; (test-encoding hash.3 *hash*)
(5am:test hash.3 (5am:skip "will be fixed later - -lisp.net/bknr/ticket/29"))
;; ;; packages
;; (test-encoding package.1 (find-package :cl-store))
;; (defpackage foo
;; (:nicknames foobar)
;; (:use :cl)
;; (:shadow cl:format)
;; (:export bar))
;; (defun package-restores ()
;; (let (( *nuke-existing-packages* t))
;; (store (find-package :foo) *test-file*)
;; (delete-package :foo)
;; (restore *test-file*)
;; (list (package-name (find-package :foo))
;; (mapcar #'package-name (package-use-list :foo))
;; (package-nicknames :foo)
;; (equalp (remove-duplicates (package-shadowing-symbols :foo))
( list ( find - symbol " FORMAT " " FOO " ) ) )
;; (equalp (cl-store::external-symbols (find-package :foo))
( make - array 1 : initial - element ( find - symbol " BAR " " FOO " ) ) ) ) ) )
;; ; unfortunately it's difficult to portably test the internal symbols
;; ; in a package so we just assume that it's OK.
( deftest package.2
;; (package-restores)
( " FOO " ( " COMMON - LISP " ) ( " FOOBAR " ) t t ) )
;; ;; objects
(define-persistent-class foo ()
((x :update)))
(define-persistent-class bar (foo)
((y :update)))
;; (deftest standard-object.1
( let ( ( ( store ( make - instance ' foo :x 3 ) * test - file * ) ) )
;; (= (get-x val) (get-x (restore *test-file*))))
;; t)
;; (deftest standard-object.2
( let ( ( ( store ( make - instance ' bar
:x ( list 1 " foo " 1.0 )
;; :y (vector 1 2 3 4))
;; *test-file*)))
( let ( ( ret ( restore * test - file * ) ) )
( and ( equalp ( get - x val ) ( get - x ret ) )
;; (equalp (get-y val) (get-y ret)))))
;; t)
;; (deftest standard-object.3
;; (let ((*store-class-slots* nil)
( ( make - instance ' baz : z 9 ) ) )
;; (store val *test-file*)
( make - instance ' baz : z 2 )
;; (= (get-z (restore *test-file*))
;; 2))
;; t)
;; (deftest standard-object.4
;; (let ((*store-class-slots* t)
( ( make - instance ' baz : z 9 ) ) )
;; (store val *test-file*)
( make - instance ' baz : z 2 )
( let ( ( ret ( restore * test - file * ) ) )
(= ( get - z ret )
;; 9)))
;; t)
;; ;; classes
;; (deftest standard-class.1 (progn (store (find-class 'foo) *test-file*)
;; (restore *test-file*)
;; t)
;; t)
;; (deftest standard-class.2 (progn (store (find-class 'bar) *test-file*)
;; (restore *test-file*)
;; t)
;; t)
( deftest standard - class.3 ( progn ( store ( find - class ' baz ) * test - file * )
;; (restore *test-file*)
;; t)
;; t)
;; ;; conditions
;; (deftest condition.1
;; (handler-case (/ 1 0)
;; (division-by-zero (c)
;; (store c *test-file*)
;; (typep (restore *test-file*) 'division-by-zero)))
;; t)
;; (deftest condition.2
( handler - case ( car ( read - from - string " 3 " ) )
; ; allegro pre 7.0 signalled a simple - error here
;; ((or type-error simple-error) (c)
;; (store c *test-file*)
;; (typep (restore *test-file*)
;; '(or type-error simple-error))))
;; t)
;; ;; structure-object
;; (defstruct a
;; a b c)
;; (defstruct (b (:include a))
;; d e f)
# + ( or openmcl )
( test - encoding structure - object.1 ( make - a : a 1 : b 2 : c 3 ) )
# + ( or openmcl )
( test - encoding structure - object.2 ( make - b : a 1 : b 2 : c 3 : d 4 : e 5 : f 6 ) )
# + ( or openmcl )
( test - encoding structure - object.3 ( make - b : a 1 : b ( make - a : a 1 : b 3 : c 2 )
;; :c #\Space :d #(1 2 3) :e (list 1 2 3)
;; :f (make-hash-table)))
; ; setf test
( test - encoding setf.1 ( setf ( restore * test - file * ) 0 ) )
;; (test-encoding setf.2 (incf (restore *test-file*)))
( test - encoding setf.3 ( ( restore * test - file * ) 2 ) )
( test - encoding pathname.1 # P"/home / foo " )
;; (test-encoding pathname.2 (make-pathname :name "foo"))
;; (test-encoding pathname.3 (make-pathname :name "foo" :type "bar"))
;; ; built-in classes
;; (test-encoding built-in.1 (find-class 'hash-table))
;; (test-encoding built-in.2 (find-class 'integer))
;; ;; find-backend tests
;; (deftest find-backend.1
;; (and (find-backend 'cl-store) t)
;; t)
;; (deftest find-backend.2
( find - backend ( ) )
;; nil)
;; (deftest find-backend.3
( handler - case ( find - backend ( ) t )
;; (error (c) (and c t))
(: no - error ( ) ( and val nil ) ) )
;; t)
;; ;; circular objects
( ( let ( ( x ( list 1 2 3 4 ) ) )
( setf ( cdr ( last x ) ) x ) ) )
( deftest circ.1 ( progn ( store circ1 * test - file * )
;; (let ((x (restore *test-file*)))
( eql ( ) x ) ) )
;; t)
( defvar circ2 ( let ( ( x ( list 2 3 4 4 5 ) ) )
( setf ( second x ) x ) ) )
( deftest circ.2 ( progn ( store circ2 * test - file * )
;; (let ((x (restore *test-file*)))
( eql ( second x ) x ) ) )
;; t)
( ( let ( ( x ( list ( list 1 2 3 4 )
( list 5 6 7 8)
;; 9)))
( setf ( second x ) ( car x ) )
( setf ( cdr ( last x ) ) x )
;; x))
( deftest circ.3 ( progn ( store circ3 * test - file * )
;; (let ((x (restore *test-file*)))
( and ( eql ( second x ) ( car x ) )
( ( cdddr x ) x ) ) ) )
;; t)
;; (defvar circ4 (let ((x (make-hash-table)))
( setf ( gethash ' first x ) ( make - hash - table ) )
( setf ( gethash ' second x ) ( gethash ' first x ) )
( setf ( gethash ' inner ( gethash ' first x ) ) x )
;; x))
;; (deftest circ.4 (progn (store circ4 *test-file*)
;; (let ((x (restore *test-file*)))
( and ( eql ( gethash ' first x )
( gethash ' second x ) )
;; (eql x
( gethash ' inner
( gethash ' first x ) ) ) ) ) )
;; t)
( deftest circ.5 ( let ( ( circ5 ( make - instance ' bar ) ) )
( setf ( get - y circ5 ) circ5 )
;; (store circ5 *test-file*)
;; (let ((x (restore *test-file*)))
;; (eql x (get-y x))))
;; t)
( ( let ( ( y ( make - array ' ( 2 2 2 )
;; :initial-contents '((("foo" "bar")
;; ("me" "you"))
( ( 5 6 ) ( 7 8) ) ) ) ) )
( setf ( aref y 1 1 1 ) y )
( setf ( aref y 0 0 0 ) ( aref y 1 1 1 ) )
;; y))
( deftest circ.6 ( progn ( store circ6 * test - file * )
;; (let ((x (restore *test-file*)))
;; (and (eql (aref x 1 1 1) x)
;; (eql (aref x 0 0 0) (aref x 1 1 1)))))
;; t)
;; (defvar circ7 (let ((x (make-a)))
( setf ( a - a x ) x ) ) )
# + ( or )
( deftest circ.7 ( progn ( store circ7 * test - file * )
;; (let ((x (restore *test-file*)))
;; (eql (a-a x) x)))
;; t)
;; (defvar circ.8 (let ((x "foo"))
;; (make-pathname :name x :type x)))
; ; clisp apparently creates a copy of the strings in a pathname
;; ;; so a test for eqness is pointless.
;; #-clisp
;; (deftest circ.8 (progn (store circ.8 *test-file*)
;; (let ((x (restore *test-file*)))
;; (eql (pathname-name x)
;; (pathname-type x))))
;; t)
( deftest circ.9 ( let ( ( ( vector " foo " " bar " " baz " 1 2 ) ) )
( setf ( aref val 3 ) val )
( setf ( aref val 4 ) ( aref val 0 ) )
;; (store val *test-file*)
;; (let ((rest (restore *test-file*)))
( and ( eql rest ( aref rest 3 ) )
( eql ( aref rest 4 ) ( aref rest 0 ) ) ) ) )
;; t)
( deftest circ.10 ( let * ( ( a1 ( make - array 5 ) )
( a2 ( make - array 4 : displaced - to a1
: displaced - index - offset 1 ) )
( a3 ( make - array 2 : displaced - to a2
: displaced - index - offset 2 ) ) )
( setf ( aref a3 1 ) a3 )
;; (store a3 *test-file*)
( let ( ( ret ( restore * test - file * ) ) )
;; (eql a3 (aref a3 1))))
;; t)
( defvar circ.11 ( let ( ( x ( make - hash - table ) ) )
( setf ( gethash x x ) x )
;; x))
( deftest circ.11 ( progn ( store circ.11 * test - file * )
( let ( ( ( restore * test - file * ) ) )
( eql val ( gethash ) ) ) )
;; t)
( deftest circ.12 ( let ( ( x ( vector 1 2 " foo " 4 5 ) ) )
( setf ( aref x 0 ) x )
( setf ( aref x 1 ) ( aref x 2 ) )
;; (store x *test-file*)
( let ( ( ret ( restore * test - file * ) ) )
( and ( eql ( aref ret 0 ) ret )
( eql ( aref ret 1 ) ( aref ret 2 ) ) ) ) )
;; t)
;; (defclass foo.1 ()
;; ((a :accessor foo1-a)))
; ; a test from which crashed in earlier
; ; versions ( pre 0.2 )
;; (deftest circ.13 (let ((foo (make-instance 'foo.1))
;; (bar (make-instance 'foo.1)))
( setf ( foo1 - a foo ) bar )
( setf ( foo1 - a bar ) foo )
;; (store (list foo) *test-file*)
( let ( ( ret ( car ( restore * test - file * ) ) ) )
( and ( eql ret ( foo1 - a ( foo1 - a ret ) ) )
( eql ( foo1 - a ret )
( foo1 - a ( foo1 - a ( foo1 - a ret ) ) ) ) ) ) )
;; t)
( deftest circ.14 ( let ( ( list ' # 1=(1 2 3 # 1 # . # 1 # ) ) )
;; (store list *test-file*)
( let ( ( ret ( restore * test - file * ) ) )
( and ( eq ret ( ) )
( eq ( fourth ret ) ret ) ) ) )
;; t)
( deftest ( let ( ( list ' # 1=(1 2 3 # 2=(#2 # ) . # 1 # ) ) )
;; (store list *test-file*)
( let ( ( ret ( restore * test - file * ) ) )
( and ( eq ret ( ) )
( eq ( fourth ret )
( car ( fourth ret ) ) ) ) ) )
;; t)
;; ;; this had me confused for a while since what was
; ; restored # 1=(1 ( # 1 # ) # 1 # ) looks nothing like this list ,
;; ;; but it turns out that it is correct
( deftest circ.16 ( let ( ( list ' # 1=(1 # 2=(#1 # ) . # 2 # ) ) )
;; (store list *test-file*)
( let ( ( ret ( restore * test - file * ) ) )
( and ( eq ret ( caadr ret ) )
( eq ret ( third ret ) ) ) ) )
;; t)
;; ;; large circular lists
( deftest large.1 ( let ( ( list ( make - list 100000 ) ) )
( setf ( cdr ( last list ) ) list )
;; (store list *test-file*)
( let ( ( ret ( restore * test - file * ) ) )
( eq ( 100000 ret ) ret ) ) )
;; t)
;; ;; large dotted lists
( test - encoding large.2 ( let ( ( list ( make - list 100000 ) ) )
( setf ( cdr ( last list ) ) ' foo )
;; list))
;; ;; custom storing
;; (defclass random-obj () ((size :accessor size :initarg :size)))
( defvar * random - obj - code * ( register - code 100 ' random - obj ) )
;; (defstore-cl-store (obj random-obj buff)
;; (output-type-code *random-obj-code* buff)
;; (store-object (size obj) buff))
( defrestore - cl - store ( random - obj buff )
( random ( restore - object ) ) )
;; (deftest custom.1
( progn ( store ( make - instance ' random - obj : size 5 ) * test - file * )
;; (typep (restore *test-file*) '(integer 0 4)))
;; t)
;; (test-encoding function.1 #'restores)
;; (test-encoding function.2 #'car)
;; (test-encoding gfunction.1 #'cl-store:restore)
;; (test-encoding gfunction.2 #'cl-store:store)
;; #-clisp
( test - encoding gfunction.3 # ' ( setf get - y ) )
;; (deftest nocirc.1
;; (let* ((string "FOO")
;; (list `(,string . ,string))
;; (*check-for-circs* nil))
;; (store list *test-file*)
;; (let ((res (restore *test-file*)))
( and ( not ( eql ( car res ) ) ) )
( string= ( car res ) ) ) ) ) )
;; t)
( defstruct st.bar x )
( defstruct ( st.foo (: conc - name f- )
(: constructor fooo ( z y x ) )
;; (:copier cp-foo)
(: include st.bar )
;; (:predicate is-foo)
(: print - function ( lambda ( obj )
;; (declare (ignore dep))
;; (print-unreadable-object (obj st :type t)
( format st " ~A " ( f - x obj ) ) ) ) ) )
;; (y 0 :type integer) (z nil :type simple-string))
# + ( or )
;; (deftest struct-class.1
( let * ( ( obj ( fooo " Z " 2 3 ) )
( string ( format nil " ~A " obj ) ) )
;; (let ((*nuke-existing-classes* t))
;; (store (find-class 'st.foo) *test-file*)
;; (fmakunbound 'cp-foo)
;; (fmakunbound 'is-foo)
;; (fmakunbound 'fooo)
;; (fmakunbound 'f-x)
;; (fmakunbound 'f-y)
;; (fmakunbound 'f-z)
;; (restore *test-file*)
;; (let* ((new-obj (cp-foo (fooo "Z" 2 3)))
( new - string ( format nil " ~A " new - obj ) ) )
;; (list (is-foo new-obj) (equalp obj new-obj)
( string= new - string string )
;; (f-x new-obj) (f-y new-obj) (f-z new-obj)))))
;; (t t t 3 2 "Z"))
;; (defun run-tests (backend)
;; (with-backend backend
;; (regression-5am:do-tests))
;; (when (probe-file *test-file*)
;; (ignore-errors (delete-file *test-file*))))
| null | https://raw.githubusercontent.com/hanshuebner/bknr-datastore/c98d44f47cc88d19ff91ca3eefbd9719a8ace022/src/data/encoding-test.lisp | lisp | from cl-store :)
ratios
complex numbers - currently not supported
(test-encoding complex.2 #C(0.0 1.0))
(test-encoding complex.3 #C(32 -23455))
(test-encoding complex.5 #C(-111 -1123))
(test-encoding complex.6 #C(-11.2 -34.5))
single-float
double-float
characters
strings
#\? is the substitution char
above char-code-limit - bknr.datastore::%decode-string should
throw an error in this case, but I dont know how to test this
(5am:finishes (decode-string-from-octets (concatenate 'vector (vector 1 (length octets)) octets))))
#+lispworks 'lw:text-string
:pwgl-test-suite)))
vectors
arrays
(test-encoding array.5
a3))
symbols
(deftest gensym.1 (progn
(let ((new (restore *test-file*)))
(list (symbol-package new)
(nil 6))
(store (list x x) *test-file*)
(let ((new (restore *test-file*)))
t)
cons
' # 1=(#1 # ) ) )
(store list *test-file*)
t)
hash tables
for some reason (make-hash-table) is not equalp
to (make-hash-table) with ecl.
(defvar *hash* (let ((in (make-hash-table :test #'equal
in))
(test-encoding hash.3 *hash*)
;; packages
(test-encoding package.1 (find-package :cl-store))
(defpackage foo
(:nicknames foobar)
(:use :cl)
(:shadow cl:format)
(:export bar))
(defun package-restores ()
(let (( *nuke-existing-packages* t))
(store (find-package :foo) *test-file*)
(delete-package :foo)
(restore *test-file*)
(list (package-name (find-package :foo))
(mapcar #'package-name (package-use-list :foo))
(package-nicknames :foo)
(equalp (remove-duplicates (package-shadowing-symbols :foo))
(equalp (cl-store::external-symbols (find-package :foo))
; unfortunately it's difficult to portably test the internal symbols
; in a package so we just assume that it's OK.
(package-restores)
;; objects
(deftest standard-object.1
(= (get-x val) (get-x (restore *test-file*))))
t)
(deftest standard-object.2
:y (vector 1 2 3 4))
*test-file*)))
(equalp (get-y val) (get-y ret)))))
t)
(deftest standard-object.3
(let ((*store-class-slots* nil)
(store val *test-file*)
(= (get-z (restore *test-file*))
2))
t)
(deftest standard-object.4
(let ((*store-class-slots* t)
(store val *test-file*)
9)))
t)
;; classes
(deftest standard-class.1 (progn (store (find-class 'foo) *test-file*)
(restore *test-file*)
t)
t)
(deftest standard-class.2 (progn (store (find-class 'bar) *test-file*)
(restore *test-file*)
t)
t)
(restore *test-file*)
t)
t)
;; conditions
(deftest condition.1
(handler-case (/ 1 0)
(division-by-zero (c)
(store c *test-file*)
(typep (restore *test-file*) 'division-by-zero)))
t)
(deftest condition.2
; allegro pre 7.0 signalled a simple - error here
((or type-error simple-error) (c)
(store c *test-file*)
(typep (restore *test-file*)
'(or type-error simple-error))))
t)
;; structure-object
(defstruct a
a b c)
(defstruct (b (:include a))
d e f)
:c #\Space :d #(1 2 3) :e (list 1 2 3)
:f (make-hash-table)))
; setf test
(test-encoding setf.2 (incf (restore *test-file*)))
(test-encoding pathname.2 (make-pathname :name "foo"))
(test-encoding pathname.3 (make-pathname :name "foo" :type "bar"))
; built-in classes
(test-encoding built-in.1 (find-class 'hash-table))
(test-encoding built-in.2 (find-class 'integer))
;; find-backend tests
(deftest find-backend.1
(and (find-backend 'cl-store) t)
t)
(deftest find-backend.2
nil)
(deftest find-backend.3
(error (c) (and c t))
t)
;; circular objects
(let ((x (restore *test-file*)))
t)
(let ((x (restore *test-file*)))
t)
9)))
x))
(let ((x (restore *test-file*)))
t)
(defvar circ4 (let ((x (make-hash-table)))
x))
(deftest circ.4 (progn (store circ4 *test-file*)
(let ((x (restore *test-file*)))
(eql x
t)
(store circ5 *test-file*)
(let ((x (restore *test-file*)))
(eql x (get-y x))))
t)
:initial-contents '((("foo" "bar")
("me" "you"))
y))
(let ((x (restore *test-file*)))
(and (eql (aref x 1 1 1) x)
(eql (aref x 0 0 0) (aref x 1 1 1)))))
t)
(defvar circ7 (let ((x (make-a)))
(let ((x (restore *test-file*)))
(eql (a-a x) x)))
t)
(defvar circ.8 (let ((x "foo"))
(make-pathname :name x :type x)))
; clisp apparently creates a copy of the strings in a pathname
;; so a test for eqness is pointless.
#-clisp
(deftest circ.8 (progn (store circ.8 *test-file*)
(let ((x (restore *test-file*)))
(eql (pathname-name x)
(pathname-type x))))
t)
(store val *test-file*)
(let ((rest (restore *test-file*)))
t)
(store a3 *test-file*)
(eql a3 (aref a3 1))))
t)
x))
t)
(store x *test-file*)
t)
(defclass foo.1 ()
((a :accessor foo1-a)))
; a test from which crashed in earlier
; versions ( pre 0.2 )
(deftest circ.13 (let ((foo (make-instance 'foo.1))
(bar (make-instance 'foo.1)))
(store (list foo) *test-file*)
t)
(store list *test-file*)
t)
(store list *test-file*)
t)
;; this had me confused for a while since what was
; restored # 1=(1 ( # 1 # ) # 1 # ) looks nothing like this list ,
;; but it turns out that it is correct
(store list *test-file*)
t)
;; large circular lists
(store list *test-file*)
t)
;; large dotted lists
list))
;; custom storing
(defclass random-obj () ((size :accessor size :initarg :size)))
(defstore-cl-store (obj random-obj buff)
(output-type-code *random-obj-code* buff)
(store-object (size obj) buff))
(deftest custom.1
(typep (restore *test-file*) '(integer 0 4)))
t)
(test-encoding function.1 #'restores)
(test-encoding function.2 #'car)
(test-encoding gfunction.1 #'cl-store:restore)
(test-encoding gfunction.2 #'cl-store:store)
#-clisp
(deftest nocirc.1
(let* ((string "FOO")
(list `(,string . ,string))
(*check-for-circs* nil))
(store list *test-file*)
(let ((res (restore *test-file*)))
t)
(:copier cp-foo)
(:predicate is-foo)
(declare (ignore dep))
(print-unreadable-object (obj st :type t)
(y 0 :type integer) (z nil :type simple-string))
(deftest struct-class.1
(let ((*nuke-existing-classes* t))
(store (find-class 'st.foo) *test-file*)
(fmakunbound 'cp-foo)
(fmakunbound 'is-foo)
(fmakunbound 'fooo)
(fmakunbound 'f-x)
(fmakunbound 'f-y)
(fmakunbound 'f-z)
(restore *test-file*)
(let* ((new-obj (cp-foo (fooo "Z" 2 3)))
(list (is-foo new-obj) (equalp obj new-obj)
(f-x new-obj) (f-y new-obj) (f-z new-obj)))))
(t t t 3 2 "Z"))
(defun run-tests (backend)
(with-backend backend
(regression-5am:do-tests))
(when (probe-file *test-file*)
(ignore-errors (delete-file *test-file*)))) | (in-package :bknr.datastore)
(5am:def-suite :bknr.datastore)
(5am:in-suite :bknr.datastore)
(defun files-identical-content-p (path-a path-b)
"Are files of PATH-A and PATH-B byte per byte identical?"
(with-open-file (in-a path-a :element-type '(unsigned-byte 8))
(with-open-file (in-b path-b :element-type '(unsigned-byte 8))
(loop
for byte-a = (read-byte in-a nil nil)
for byte-b = (read-byte in-b nil nil)
while (or byte-a byte-b)
unless (and byte-a byte-b (= byte-a byte-b))
return nil
finally (return t)))))
(defun congruent-p (a b)
"Are lisp value A and B (deeply) congruent?"
(bknr.utils:with-temporary-file (path-a)
(bknr.utils:with-temporary-file (path-b)
(cl-store:store a path-a)
(cl-store:store b path-b)
(prog1
(files-identical-content-p path-a path-b)
(delete-file path-a)
(delete-file path-b)))))
(defun copy-by-encoding (value)
(bknr.utils:with-temporary-file (path)
(with-open-file (out path :direction :output :if-exists :supersede
:element-type '(unsigned-byte 8))
(encode value out))
(with-open-file (in path :element-type '(unsigned-byte 8))
(decode in))))
(defmacro test-encoding (name value)
(let ((options (alexandria:ensure-list name)))
(destructuring-bind (name &key skip) options
`(5am:test ,name
,(if skip
`(5am:skip ,skip)
`(5am:is (congruent-p ,value (copy-by-encoding ,value))))))))
(test-encoding list.1 '(1 2 3))
(test-encoding list.len.30 (loop repeat 30 collect 'x))
(test-encoding list.len.254 (loop repeat 254 collect 'x))
(test-encoding list.len.255 (loop repeat 255 collect 'x))
(test-encoding list.len.256 (loop repeat 256 collect 'x))
(test-encoding list.len.257 (loop repeat 257 collect 'x))
(test-encoding list.len.3000 (loop repeat 3000 collect 'x))
(test-encoding improper-list.1 '(1 2 3 4 . 5))
(test-encoding cons.1 '(1 . 2))
(test-encoding integer.1 1)
(test-encoding integer.2 0)
(test-encoding integer.3 23423333333333333333333333423102334)
(test-encoding integer.4 -2322993)
(test-encoding integer.5 most-positive-fixnum)
(test-encoding integer.6 most-negative-fixnum)
(test-encoding ratio.1 1/2)
(test-encoding ratio.2 234232/23434)
(test-encoding ratio.3 -12/2)
(test-encoding ratio.4 -6/11)
(test-encoding ratio.5 23222/13)
( test - encoding complex.1 # C(0 1 ) )
( test - encoding complex.4 # C(-222.32 2322.21 ) )
(test-encoding single-float.1 3244.32)
(test-encoding single-float.2 0.12)
(test-encoding single-float.3 -233.001)
(test-encoding single-float.4 most-positive-single-float)
(test-encoding single-float.5 most-negative-single-float)
(test-encoding double-float.1 2343.3d0)
(test-encoding double-float.2 -1211111.3343d0)
(test-encoding double-float.3 99999999999123456789012345678222222222222290.0987654321d0)
(test-encoding double-float.4 -99999999999123456789012345678222222222222290.0987654321d0)
(test-encoding double-float.5 most-positive-double-float)
(test-encoding double-float.6 most-negative-double-float)
(test-encoding char.1 #\Space)
(test-encoding char.2 #\f )
(test-encoding char.3 #\Rubout)
(test-encoding char.4 (code-char 255))
(5am:test char.random
(5am:for-all ((char (5am:gen-character)))
(5am:is (char= char (copy-by-encoding char)))))
(5am:test string.random
(5am:for-all ((string (5am:gen-string)))
(5am:is (string= string (copy-by-encoding string)))))
(5am:test string.random.code-limited
(5am:for-all ((string (5am:gen-string :elements (5am:gen-character :code-limit 10000))))
(5am:is (string= string (copy-by-encoding string)))))
(5am:test string.decode-utf-8
(labels ((decode-string-from-octets (octets)
(flexi-streams:with-input-from-sequence (in octets)
(bknr.datastore::%decode-string in))))
(5am:is (string-equal "<=>" (decode-string-from-octets #(1 3 60 61 62))))
(string-equal "<?>" (decode-string-from-octets #(1 3 60 188 62)))
kilian 2008 - 03 - 20 : the following for - all test failed on ccl ,
because the correct utf-8 sequence could produce a char - code
( 5am : for - all ( ( octets ( 5am : gen - buffer ) ) )
))
# + ( or ( and ) )
( progn
( test - encoding unicode.1 ( map # -lispworks ' string
# + lispworks ' lw : text - string
# ' code - char ( list # X20AC # X3BB ) ) )
( test - encoding unicode.2 ( intern ( map # -lispworks ' string
# ' code - char ( list # X20AC # X3BB ) )
(test-encoding vector.1 #(1 2 3 4))
(test-encoding vector.2 (make-array 5 :element-type 'fixnum
:initial-contents (list 1 2 3 4 5)))
(test-encoding vector.4 #*101101101110)
(test-encoding vector.3
(make-array 5
:element-type 'fixnum
:fill-pointer 2
:initial-contents (list 1 2 3 4 5)))
(test-encoding vector.5 #*)
(test-encoding vector.6 #())
(test-encoding array.1
(make-array '(2 2) :initial-contents '((1 2) (3 4))))
(test-encoding array.2
(make-array '(2 2) :initial-contents '((1 1) (1 1))))
(test-encoding array.3
(make-array '(2 2) :element-type 'fixnum :initial-element 3))
(test-encoding (array.3b :skip "will be fixed later - -lisp.net/bknr/ticket/31")
(make-array '(2 2) :element-type '(mod 10) :initial-element 3))
(test-encoding array.4
(make-array '(2 3 5)
:initial-contents
'(((1 2 #\f 5 12.0) (#\Space 0 4 1 0) ('d 0 #() 3 -1))
((0 #\a #\b 4 #\q) (12.0d0 0 '(d) 4 1)
(#\Newline 1 7 #\4 #\0)))))
( let * ( ( a1 ( make - array 5 ) )
( a2 ( make - array 4 : displaced - to a1
: displaced - index - offset 1 ) )
( a3 ( make - array 2 : displaced - to a2
: displaced - index - offset 2 ) ) )
(test-encoding symbol.1 t)
(test-encoding symbol.2 nil)
(test-encoding symbol.3 :foo)
(test-encoding symbol.4 'bknr.datastore::foo)
(test-encoding symbol.5 'make-hash-table)
(test-encoding symbol.6 '|foo bar|)
(test-encoding symbol.7 'foo\ bar\ baz)
( store ( " Foobar " ) * test - file * )
( mismatch " Foobar " ( symbol - name new ) ) ) ) )
This failed in cl - store < 0.5.5
( deftest gensym.2 ( let ( ( x ( ) ) )
( eql ( car new ) ( cadr new ) ) ) )
(test-encoding cons.1 '(1 2 3))
(test-encoding cons.2 '((1 2 3)))
(test-encoding cons.3 '(#\Space 1 1.2 1.3 #(1 2 3)))
(test-encoding cons.4 '(1 . 2))
(test-encoding cons.5 '(t . nil))
(test-encoding cons.6 '(1 2 3 . 5))
( setf ( car list ) list )
( let ( ( ret ( restore * test - file * ) ) )
( eq ret ( car ret ) ) ) )
#-openmcl(test-encoding hash.1 (make-hash-table))
#+openmcl(5am:test hash.1 (5am:skip "the hash-table-size is not preserved - do we need to fix this?"))
#-openmcl(test-encoding hash.2 (make-hash-table :test #'equal))
#+openmcl(5am:test hash.2 (5am:skip "the hash-table-size is not preserved - do we need to fix this?"))
: rehash - threshold 0.4 : size 20
: rehash - size 40 ) ) )
( dotimes ( x 1000 ) ( setf ( gethash ( format nil " ~R " x ) in ) x ) )
(5am:test hash.3 (5am:skip "will be fixed later - -lisp.net/bknr/ticket/29"))
( list ( find - symbol " FORMAT " " FOO " ) ) )
( make - array 1 : initial - element ( find - symbol " BAR " " FOO " ) ) ) ) ) )
( deftest package.2
( " FOO " ( " COMMON - LISP " ) ( " FOOBAR " ) t t ) )
(define-persistent-class foo ()
((x :update)))
(define-persistent-class bar (foo)
((y :update)))
( let ( ( ( store ( make - instance ' foo :x 3 ) * test - file * ) ) )
( let ( ( ( store ( make - instance ' bar
:x ( list 1 " foo " 1.0 )
( let ( ( ret ( restore * test - file * ) ) )
( and ( equalp ( get - x val ) ( get - x ret ) )
( ( make - instance ' baz : z 9 ) ) )
( make - instance ' baz : z 2 )
( ( make - instance ' baz : z 9 ) ) )
( make - instance ' baz : z 2 )
( let ( ( ret ( restore * test - file * ) ) )
(= ( get - z ret )
( deftest standard - class.3 ( progn ( store ( find - class ' baz ) * test - file * )
( handler - case ( car ( read - from - string " 3 " ) )
# + ( or openmcl )
( test - encoding structure - object.1 ( make - a : a 1 : b 2 : c 3 ) )
# + ( or openmcl )
( test - encoding structure - object.2 ( make - b : a 1 : b 2 : c 3 : d 4 : e 5 : f 6 ) )
# + ( or openmcl )
( test - encoding structure - object.3 ( make - b : a 1 : b ( make - a : a 1 : b 3 : c 2 )
( test - encoding setf.1 ( setf ( restore * test - file * ) 0 ) )
( test - encoding setf.3 ( ( restore * test - file * ) 2 ) )
( test - encoding pathname.1 # P"/home / foo " )
( find - backend ( ) )
( handler - case ( find - backend ( ) t )
(: no - error ( ) ( and val nil ) ) )
( ( let ( ( x ( list 1 2 3 4 ) ) )
( setf ( cdr ( last x ) ) x ) ) )
( deftest circ.1 ( progn ( store circ1 * test - file * )
( eql ( ) x ) ) )
( defvar circ2 ( let ( ( x ( list 2 3 4 4 5 ) ) )
( setf ( second x ) x ) ) )
( deftest circ.2 ( progn ( store circ2 * test - file * )
( eql ( second x ) x ) ) )
( ( let ( ( x ( list ( list 1 2 3 4 )
( list 5 6 7 8)
( setf ( second x ) ( car x ) )
( setf ( cdr ( last x ) ) x )
( deftest circ.3 ( progn ( store circ3 * test - file * )
( and ( eql ( second x ) ( car x ) )
( ( cdddr x ) x ) ) ) )
( setf ( gethash ' first x ) ( make - hash - table ) )
( setf ( gethash ' second x ) ( gethash ' first x ) )
( setf ( gethash ' inner ( gethash ' first x ) ) x )
( and ( eql ( gethash ' first x )
( gethash ' second x ) )
( gethash ' inner
( gethash ' first x ) ) ) ) ) )
( deftest circ.5 ( let ( ( circ5 ( make - instance ' bar ) ) )
( setf ( get - y circ5 ) circ5 )
( ( let ( ( y ( make - array ' ( 2 2 2 )
( ( 5 6 ) ( 7 8) ) ) ) ) )
( setf ( aref y 1 1 1 ) y )
( setf ( aref y 0 0 0 ) ( aref y 1 1 1 ) )
( deftest circ.6 ( progn ( store circ6 * test - file * )
( setf ( a - a x ) x ) ) )
# + ( or )
( deftest circ.7 ( progn ( store circ7 * test - file * )
( deftest circ.9 ( let ( ( ( vector " foo " " bar " " baz " 1 2 ) ) )
( setf ( aref val 3 ) val )
( setf ( aref val 4 ) ( aref val 0 ) )
( and ( eql rest ( aref rest 3 ) )
( eql ( aref rest 4 ) ( aref rest 0 ) ) ) ) )
( deftest circ.10 ( let * ( ( a1 ( make - array 5 ) )
( a2 ( make - array 4 : displaced - to a1
: displaced - index - offset 1 ) )
( a3 ( make - array 2 : displaced - to a2
: displaced - index - offset 2 ) ) )
( setf ( aref a3 1 ) a3 )
( let ( ( ret ( restore * test - file * ) ) )
( defvar circ.11 ( let ( ( x ( make - hash - table ) ) )
( setf ( gethash x x ) x )
( deftest circ.11 ( progn ( store circ.11 * test - file * )
( let ( ( ( restore * test - file * ) ) )
( eql val ( gethash ) ) ) )
( deftest circ.12 ( let ( ( x ( vector 1 2 " foo " 4 5 ) ) )
( setf ( aref x 0 ) x )
( setf ( aref x 1 ) ( aref x 2 ) )
( let ( ( ret ( restore * test - file * ) ) )
( and ( eql ( aref ret 0 ) ret )
( eql ( aref ret 1 ) ( aref ret 2 ) ) ) ) )
( setf ( foo1 - a foo ) bar )
( setf ( foo1 - a bar ) foo )
( let ( ( ret ( car ( restore * test - file * ) ) ) )
( and ( eql ret ( foo1 - a ( foo1 - a ret ) ) )
( eql ( foo1 - a ret )
( foo1 - a ( foo1 - a ( foo1 - a ret ) ) ) ) ) ) )
( deftest circ.14 ( let ( ( list ' # 1=(1 2 3 # 1 # . # 1 # ) ) )
( let ( ( ret ( restore * test - file * ) ) )
( and ( eq ret ( ) )
( eq ( fourth ret ) ret ) ) ) )
( deftest ( let ( ( list ' # 1=(1 2 3 # 2=(#2 # ) . # 1 # ) ) )
( let ( ( ret ( restore * test - file * ) ) )
( and ( eq ret ( ) )
( eq ( fourth ret )
( car ( fourth ret ) ) ) ) ) )
( deftest circ.16 ( let ( ( list ' # 1=(1 # 2=(#1 # ) . # 2 # ) ) )
( let ( ( ret ( restore * test - file * ) ) )
( and ( eq ret ( caadr ret ) )
( eq ret ( third ret ) ) ) ) )
( deftest large.1 ( let ( ( list ( make - list 100000 ) ) )
( setf ( cdr ( last list ) ) list )
( let ( ( ret ( restore * test - file * ) ) )
( eq ( 100000 ret ) ret ) ) )
( test - encoding large.2 ( let ( ( list ( make - list 100000 ) ) )
( setf ( cdr ( last list ) ) ' foo )
( defvar * random - obj - code * ( register - code 100 ' random - obj ) )
( defrestore - cl - store ( random - obj buff )
( random ( restore - object ) ) )
( progn ( store ( make - instance ' random - obj : size 5 ) * test - file * )
( test - encoding gfunction.3 # ' ( setf get - y ) )
( and ( not ( eql ( car res ) ) ) )
( string= ( car res ) ) ) ) ) )
( defstruct st.bar x )
( defstruct ( st.foo (: conc - name f- )
(: constructor fooo ( z y x ) )
(: include st.bar )
(: print - function ( lambda ( obj )
( format st " ~A " ( f - x obj ) ) ) ) ) )
# + ( or )
( let * ( ( obj ( fooo " Z " 2 3 ) )
( string ( format nil " ~A " obj ) ) )
( new - string ( format nil " ~A " new - obj ) ) )
( string= new - string string )
|
b65ce0392d4a368c874bc57fac395301edcc4bd39bb96c3fa03d62c3d748c538 | alanb2718/wallingford | compiled-quadrilateral.rkt | #lang s-exp rosette
; hand compiled code for quadrilateral.rkt
(require "../applications/geothings.rkt")
(require "../reactive/reactive.rkt")
(require "../reactive/abstract-reactive-thing.rkt")
(require "compiled-reactive-thing.rkt")
(require "../rhea/rhea.rkt") ; this is a symlink in the wallingford/ directory to the actual rhea directory
functions to make symbolic objects using Cassowary variables
(define (make-cassowary-point x y)
(point (new cassowary-variable% [initial-value x]) (new cassowary-variable% [initial-value y])))
(define (make-cassowary-line x1 y1 x2 y2)
(line (make-cassowary-point x1 y1) (make-cassowary-point x2 y2)))
(define (make-cassowary-midpointline x1 y1 x2 y2 solver)
(define myline (make-cassowary-line x1 y1 x2 y2))
(define midpoint (make-cassowary-point (/ (+ x1 x2) 2.0) (/ (+ y1 y2) 2.0)))
(let ([vx1 (point-x (line-end1 myline))]
[vy1 (point-y (line-end1 myline))]
[vx2 (point-x (line-end2 myline))]
[vy2 (point-y (line-end2 myline))]
[vmx (point-x midpoint)]
[vmy (point-y midpoint)])
(send solver add-constraint (send vmx = (send (send vx1 + vx2) * 0.5)))
(send solver add-constraint (send vmy = (send (send vy1 + vy2) * 0.5)))
(midpointline myline midpoint)))
(define (add-point-stay pt strength solver)
(send solver add-stay (point-x pt) strength)
(send solver add-stay (point-y pt) strength))
hack -- function to compute concrete versions of points , lines , and midpointlines
(define (compute-concrete g)
(cond [(point? g) (point (send (point-x g) value) (send (point-y g) value))]
[(line? g) (line (compute-concrete (line-end1 g)) (compute-concrete (line-end2 g)))]
[(midpointline? g) (midpointline (compute-concrete (midpointline-line g)) (compute-concrete (midpointline-midpoint g)))]
[else (error "unknown argument type")]))
(define (connect-points p1 p2 solver)
(send solver add-constraint (send (point-x p1) = (point-x p2)))
(send solver add-constraint (send (point-y p1) = (point-y p2))))
(define compiled-quadrilateral%
(class compiled-reactive-thing%
(inherit seconds image button-pressed? button-going-up? button-going-down? mouse-position)
(super-new)
(define solver (new cassowary%))
(define side1 (make-cassowary-midpointline 250 50 550 250 solver))
(define side2 (make-cassowary-midpointline 550 250 250 500 solver))
(define side3 (make-cassowary-midpointline 250 500 50 250 solver))
(define side4 (make-cassowary-midpointline 50 250 250 50 solver))
; join the corners of the quadrilateral
(connect-points (line-end2 (midpointline-line side1)) (line-end1 (midpointline-line side2)) solver)
(connect-points (line-end2 (midpointline-line side2)) (line-end1 (midpointline-line side3)) solver)
(connect-points (line-end2 (midpointline-line side3)) (line-end1 (midpointline-line side4)) solver)
(connect-points (line-end2 (midpointline-line side4)) (line-end1 (midpointline-line side1)) solver)
; add stays with explicit priorities to disambiguate behavior
(add-point-stay (line-end2 (midpointline-line side1)) (send solver medium-strength) solver)
(add-point-stay (line-end2 (midpointline-line side2)) (send solver weak-strength) solver)
(add-point-stay (line-end2 (midpointline-line side3)) (send solver weaker-strength) solver)
(add-point-stay (line-end2 (midpointline-line side4)) (send solver weakest-strength) solver)
semi - hack : just share the endpoints of the midpoint lines ( although that 's what ThingLab did ) , rather than using equality constraints
(define mid1 (line (midpointline-midpoint side1) (midpointline-midpoint side2)))
(define mid2 (line (midpointline-midpoint side2) (midpointline-midpoint side3)))
(define mid3 (line (midpointline-midpoint side3) (midpointline-midpoint side4)))
(define mid4 (line (midpointline-midpoint side4) (midpointline-midpoint side1)))
; list of all the corners and midpoints for dragging
(define points (list (line-end1 (midpointline-line side1))
(line-end1 (midpointline-line side2))
(line-end1 (midpointline-line side3))
(line-end1 (midpointline-line side4))
(midpointline-midpoint side1)
(midpointline-midpoint side2)
(midpointline-midpoint side3)
(midpointline-midpoint side4)))
(define selected-point #f)
; the image for this is a list of the current values of the component parts
; just hacked together for now -- this makes a copy of the parts with the current values
(define (compute-image)
(let ([concrete-side1 (compute-concrete side1)]
[concrete-side2 (compute-concrete side2)]
[concrete-side3 (compute-concrete side3)]
[concrete-side4 (compute-concrete side4)]
[concrete-mid1 (compute-concrete mid1)]
[concrete-mid2 (compute-concrete mid2)]
[concrete-mid3 (compute-concrete mid3)]
[concrete-mid4 (compute-concrete mid4)])
(send this set-image! (list concrete-side1 concrete-side2 concrete-side3 concrete-side4
concrete-mid1 concrete-mid2 concrete-mid3 concrete-mid4))))
; initialize image
(compute-image)
(define (close? p1 p2)
(define gap 10)
(and (< (abs (- (point-x p1) (point-x p2))) gap) (< (abs (- (point-y p1) (point-y p2))) gap)))
; hand written versions of methods intended to be compiled automatically
(define/override (get-sampling)
(let ([s (send this button-state)])
(if (or (eq? s 'going-down) (eq? s 'down) (eq? s 'going-up)) '(push pull) '(push))))
(define/override (update-mysolution)
; compiling for the quadrilateral constraints (see quadrilateral.rkt)
; if the button is going down see if a point is being selectd
(cond [(button-going-down?)
(let ([m (send this mouse-position)])
(compute-image)
(set! selected-point (findf (lambda (p) (close? m (compute-concrete p))) points)))])
; while the button is pressed update the selected point to follow the mouse, and also satisfy the constraints
(cond [(and selected-point (button-pressed?))
; no edit constraints for now!
(let ([cx (send (point-x selected-point) = (point-x (mouse-position)))]
[cy (send (point-y selected-point) = (point-y (mouse-position)))])
(send solver add-constraint cx (send solver strong-strength))
(send solver add-constraint cy (send solver strong-strength))
(send solver solve)
(send solver remove-constraint cx)
(send solver remove-constraint cy)
(compute-image))])
(cond [(button-going-up?) ; additional check -- button-pressed? will also include the button-going-up? case
(send this notify-watchers-changed)]))
(define/override (find-time mytime target)
; if there is a button press or release between the current time and target, advance to that, and otherwise to target
(let ([potential-targets (filter (lambda (e) (and (> (mouse-event-time e) mytime)
(< (mouse-event-time e) target)
(or (eq? (mouse-event-button-state e) 'going-down)
(eq? (mouse-event-button-state e) 'going-up))))
(send this get-mouse-events))])
(values (if (null? potential-targets) target (apply min (map mouse-event-time potential-targets))) #f)))))
(make-viewer (new compiled-quadrilateral%) #:title "Compiled version of quadrilateral" #:sleep-time 0.01)
| null | https://raw.githubusercontent.com/alanb2718/wallingford/9dd436c29f737d210c5b87dc1b86b2924c0c5970/compiled-reactive/compiled-quadrilateral.rkt | racket | hand compiled code for quadrilateral.rkt
this is a symlink in the wallingford/ directory to the actual rhea directory
join the corners of the quadrilateral
add stays with explicit priorities to disambiguate behavior
list of all the corners and midpoints for dragging
the image for this is a list of the current values of the component parts
just hacked together for now -- this makes a copy of the parts with the current values
initialize image
hand written versions of methods intended to be compiled automatically
compiling for the quadrilateral constraints (see quadrilateral.rkt)
if the button is going down see if a point is being selectd
while the button is pressed update the selected point to follow the mouse, and also satisfy the constraints
no edit constraints for now!
additional check -- button-pressed? will also include the button-going-up? case
if there is a button press or release between the current time and target, advance to that, and otherwise to target | #lang s-exp rosette
(require "../applications/geothings.rkt")
(require "../reactive/reactive.rkt")
(require "../reactive/abstract-reactive-thing.rkt")
(require "compiled-reactive-thing.rkt")
functions to make symbolic objects using Cassowary variables
(define (make-cassowary-point x y)
(point (new cassowary-variable% [initial-value x]) (new cassowary-variable% [initial-value y])))
(define (make-cassowary-line x1 y1 x2 y2)
(line (make-cassowary-point x1 y1) (make-cassowary-point x2 y2)))
(define (make-cassowary-midpointline x1 y1 x2 y2 solver)
(define myline (make-cassowary-line x1 y1 x2 y2))
(define midpoint (make-cassowary-point (/ (+ x1 x2) 2.0) (/ (+ y1 y2) 2.0)))
(let ([vx1 (point-x (line-end1 myline))]
[vy1 (point-y (line-end1 myline))]
[vx2 (point-x (line-end2 myline))]
[vy2 (point-y (line-end2 myline))]
[vmx (point-x midpoint)]
[vmy (point-y midpoint)])
(send solver add-constraint (send vmx = (send (send vx1 + vx2) * 0.5)))
(send solver add-constraint (send vmy = (send (send vy1 + vy2) * 0.5)))
(midpointline myline midpoint)))
(define (add-point-stay pt strength solver)
(send solver add-stay (point-x pt) strength)
(send solver add-stay (point-y pt) strength))
hack -- function to compute concrete versions of points , lines , and midpointlines
(define (compute-concrete g)
(cond [(point? g) (point (send (point-x g) value) (send (point-y g) value))]
[(line? g) (line (compute-concrete (line-end1 g)) (compute-concrete (line-end2 g)))]
[(midpointline? g) (midpointline (compute-concrete (midpointline-line g)) (compute-concrete (midpointline-midpoint g)))]
[else (error "unknown argument type")]))
(define (connect-points p1 p2 solver)
(send solver add-constraint (send (point-x p1) = (point-x p2)))
(send solver add-constraint (send (point-y p1) = (point-y p2))))
(define compiled-quadrilateral%
(class compiled-reactive-thing%
(inherit seconds image button-pressed? button-going-up? button-going-down? mouse-position)
(super-new)
(define solver (new cassowary%))
(define side1 (make-cassowary-midpointline 250 50 550 250 solver))
(define side2 (make-cassowary-midpointline 550 250 250 500 solver))
(define side3 (make-cassowary-midpointline 250 500 50 250 solver))
(define side4 (make-cassowary-midpointline 50 250 250 50 solver))
(connect-points (line-end2 (midpointline-line side1)) (line-end1 (midpointline-line side2)) solver)
(connect-points (line-end2 (midpointline-line side2)) (line-end1 (midpointline-line side3)) solver)
(connect-points (line-end2 (midpointline-line side3)) (line-end1 (midpointline-line side4)) solver)
(connect-points (line-end2 (midpointline-line side4)) (line-end1 (midpointline-line side1)) solver)
(add-point-stay (line-end2 (midpointline-line side1)) (send solver medium-strength) solver)
(add-point-stay (line-end2 (midpointline-line side2)) (send solver weak-strength) solver)
(add-point-stay (line-end2 (midpointline-line side3)) (send solver weaker-strength) solver)
(add-point-stay (line-end2 (midpointline-line side4)) (send solver weakest-strength) solver)
semi - hack : just share the endpoints of the midpoint lines ( although that 's what ThingLab did ) , rather than using equality constraints
(define mid1 (line (midpointline-midpoint side1) (midpointline-midpoint side2)))
(define mid2 (line (midpointline-midpoint side2) (midpointline-midpoint side3)))
(define mid3 (line (midpointline-midpoint side3) (midpointline-midpoint side4)))
(define mid4 (line (midpointline-midpoint side4) (midpointline-midpoint side1)))
(define points (list (line-end1 (midpointline-line side1))
(line-end1 (midpointline-line side2))
(line-end1 (midpointline-line side3))
(line-end1 (midpointline-line side4))
(midpointline-midpoint side1)
(midpointline-midpoint side2)
(midpointline-midpoint side3)
(midpointline-midpoint side4)))
(define selected-point #f)
(define (compute-image)
(let ([concrete-side1 (compute-concrete side1)]
[concrete-side2 (compute-concrete side2)]
[concrete-side3 (compute-concrete side3)]
[concrete-side4 (compute-concrete side4)]
[concrete-mid1 (compute-concrete mid1)]
[concrete-mid2 (compute-concrete mid2)]
[concrete-mid3 (compute-concrete mid3)]
[concrete-mid4 (compute-concrete mid4)])
(send this set-image! (list concrete-side1 concrete-side2 concrete-side3 concrete-side4
concrete-mid1 concrete-mid2 concrete-mid3 concrete-mid4))))
(compute-image)
(define (close? p1 p2)
(define gap 10)
(and (< (abs (- (point-x p1) (point-x p2))) gap) (< (abs (- (point-y p1) (point-y p2))) gap)))
(define/override (get-sampling)
(let ([s (send this button-state)])
(if (or (eq? s 'going-down) (eq? s 'down) (eq? s 'going-up)) '(push pull) '(push))))
(define/override (update-mysolution)
(cond [(button-going-down?)
(let ([m (send this mouse-position)])
(compute-image)
(set! selected-point (findf (lambda (p) (close? m (compute-concrete p))) points)))])
(cond [(and selected-point (button-pressed?))
(let ([cx (send (point-x selected-point) = (point-x (mouse-position)))]
[cy (send (point-y selected-point) = (point-y (mouse-position)))])
(send solver add-constraint cx (send solver strong-strength))
(send solver add-constraint cy (send solver strong-strength))
(send solver solve)
(send solver remove-constraint cx)
(send solver remove-constraint cy)
(compute-image))])
(send this notify-watchers-changed)]))
(define/override (find-time mytime target)
(let ([potential-targets (filter (lambda (e) (and (> (mouse-event-time e) mytime)
(< (mouse-event-time e) target)
(or (eq? (mouse-event-button-state e) 'going-down)
(eq? (mouse-event-button-state e) 'going-up))))
(send this get-mouse-events))])
(values (if (null? potential-targets) target (apply min (map mouse-event-time potential-targets))) #f)))))
(make-viewer (new compiled-quadrilateral%) #:title "Compiled version of quadrilateral" #:sleep-time 0.01)
|
083648204f3f39cadf0908a800fd0d011913448e9c52e372df8f0df84c32f764 | apache/couchdb-ddoc-cache | ddoc_cache_sup.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(ddoc_cache_sup).
-behaviour(supervisor).
-export([
start_link/0,
init/1
]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Children = [
{
ddoc_cache_lru,
{ets_lru, start_link, [ddoc_cache_lru, lru_opts()]},
permanent,
5000,
worker,
[ets_lru]
},
{
ddoc_cache_opener,
{ddoc_cache_opener, start_link, []},
permanent,
5000,
worker,
[ddoc_cache_opener]
}
],
{ok, {{one_for_one, 5, 10}, Children}}.
lru_opts() ->
case application:get_env(ddoc_cache, max_objects) of
{ok, MxObjs} when is_integer(MxObjs), MxObjs > 0 ->
[{max_objects, MxObjs}];
_ ->
[]
end ++
case application:get_env(ddoc_cache, max_size) of
{ok, MxSize} when is_integer(MxSize), MxSize > 0 ->
[{max_size, MxSize}];
_ ->
[]
end ++
case application:get_env(ddoc_cache, max_lifetime) of
{ok, MxLT} when is_integer(MxLT), MxLT > 0 ->
[{max_lifetime, MxLT}];
_ ->
[]
end.
| null | https://raw.githubusercontent.com/apache/couchdb-ddoc-cache/c762e90a33ce3cda19ef142dd1120f1087ecd876/src/ddoc_cache_sup.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(ddoc_cache_sup).
-behaviour(supervisor).
-export([
start_link/0,
init/1
]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
Children = [
{
ddoc_cache_lru,
{ets_lru, start_link, [ddoc_cache_lru, lru_opts()]},
permanent,
5000,
worker,
[ets_lru]
},
{
ddoc_cache_opener,
{ddoc_cache_opener, start_link, []},
permanent,
5000,
worker,
[ddoc_cache_opener]
}
],
{ok, {{one_for_one, 5, 10}, Children}}.
lru_opts() ->
case application:get_env(ddoc_cache, max_objects) of
{ok, MxObjs} when is_integer(MxObjs), MxObjs > 0 ->
[{max_objects, MxObjs}];
_ ->
[]
end ++
case application:get_env(ddoc_cache, max_size) of
{ok, MxSize} when is_integer(MxSize), MxSize > 0 ->
[{max_size, MxSize}];
_ ->
[]
end ++
case application:get_env(ddoc_cache, max_lifetime) of
{ok, MxLT} when is_integer(MxLT), MxLT > 0 ->
[{max_lifetime, MxLT}];
_ ->
[]
end.
|
22f8d3665ba91ae9af3af629a5af122095088b88d1e2b101e26e4311f1fdbd26 | DaveWM/lobster-writer | views.cljs | (ns lobster-writer.views
(:require
[re-frame.core :as re-frame]
[lobster-writer.subs :as subs]
[lobster-writer.events :as events]
[lobster-writer.components.editable-list :refer [editable-list]]
[lobster-writer.utils :as utils]
[lobster-writer.constants :as constants]
[lobster-writer.components.helpers :refer [essay-display next-step]]
[clojure.string :as s]
[reagent.core :as r]
[cljsjs.prop-types]
[cljsjs.react-quill]
[cljs-time.core :as t]
[cljs-time.format :as tf]
[cljs-time.coerce :as tc]
[lobster-writer.components.file-chooser :refer [file-chooser]]
[clojure.string :as str]
[lobster-writer.remote-storage :as rs]))
(def react-quill (r/adapt-react-class js/ReactQuill))
(defn quill [props]
[react-quill (assoc props
:modules {:toolbar [[{:header [1 2 3 false]}]
["bold" "italic" "underline" "strike" "blockquote"]
[{:list "ordered"} {:list "bullet"} {:indent "-1"} {:indent "+1"}]
["link"]
["clean"]
["code-block"]]})])
(defn loading-spinner []
[:div.flipped
[:i.zmdi.zmdi-hc-spin-reverse.zmdi-replay]])
;; home
(defn home []
(let [*all-essays (re-frame/subscribe [::subs/all-essays])
*rs-info (re-frame/subscribe [::subs/remote-storage])]
[:div
(when (:available? @*rs-info)
[:<>
[:div.uk-margin
[:h4 "Remote Storage"]
[:div.uk-flex.uk-flex-start
[:button.uk-button.uk-button-default.uk-margin-right
{:on-click #(re-frame/dispatch [::events/remote-storage-save-all-requested])}
(if (:uploading? @*rs-info)
[loading-spinner]
"Upload All")]
[:button.uk-button.uk-button-default
{:on-click #(re-frame/dispatch [::events/remote-storage-retrieve-all-requested])}
(if (:downloading? @*rs-info)
[loading-spinner]
"Download All")]]]
[:hr]])
[:div
[:h4 "Essays"]
(->> @*all-essays
(map val)
(map (fn [essay]
^{:key (:id essay)}
[:div.uk-card.uk-card-body.uk-card-default.uk-margin
[:a {:href "#"
:style {:display "flex"
:justify-content "space-between"
:align-items "center"}
:on-click (partial re-frame/dispatch [::events/essay-selected (:id essay)])}
[:div.uk-flex.uk-flex-column.uk-flex-1
[:h3 (:title essay)]
[:progress.uk-progress
{:value (utils/percentage-complete (:highest-step essay))
:max "100"}]]
[:div.uk-margin-left.uk-margin-right
[:button.uk-button.uk-button-default.uk-button-small
{:tooltip "Export"
:on-click (fn [evt]
(re-frame/dispatch [::events/export-requested (:id essay)])
(.stopPropagation evt))}
[:i {:class "zmdi zmdi-download"}]]]]])))]
[:div.uk-flex
[:button.uk-button.uk-button-primary {:on-click #(re-frame/dispatch [::events/start-new-essay])} "New Essay"]
[file-chooser {:accept ".edn"
:on-change #(re-frame/dispatch [::events/import-requested (utils/ev-val %)])}
[:span "Import " [:i.zmdi.zmdi-hc-fw-rc.zmdi-upload]]]]]))
(defn about []
[:div
[:p "Lobster Writer is an application to help you write essays. It is based on the advice of Dr. Jordan Peterson in "
[:a {:href "/Jordan-Peterson-Writing-Template.docx" :target "_blank"} "this essay writing guide"]
". According to Dr. Peterson, this method will help you \"to write an excellent essay from beginning to end\". "]
[:p "Lobster Writer is also available as an Android app:"
[:a.play-badge {:href "-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1"}
[:img {:alt "Get it on Google Play" :src ""}]]]
[:p
"Lobster Writer is free (both gratis and libre) software - you can find the souce code "
[:a {:href "-writer"} "here"]
". If you would like to support me in developing Lobster Writer, please follow the link below."]
[:p.uk-text-bolder "Lobster Writer is not associated with Dr. Peterson in any way."]])
(defn candidate-topics [current-essay]
[:div.step
[:p "This is the first step in writing your essay. List around "
[:b "10"]
" topics that you would like to write about, or questions that you would like to answer."]
[editable-list {:items (:candidate-topics current-essay)
:on-item-added #(re-frame/dispatch [::events/candidate-topic-added %])
:on-item-removed #(re-frame/dispatch [::events/candidate-topic-removed %])}]
[:button.uk-button.uk-button-primary.next-step
{:disabled (empty? (:candidate-topics current-essay))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])
(defn reading-list [current-essay]
[:div.step
[:p
"Great, you've thought of some potential topics to write about. Now you need to find some books or articles to read. "
"You should read around " [:b "5 to 10 books per 1000 words of essay."] " List them here."]
[editable-list {:items (:reading-list current-essay)
:on-item-added #(re-frame/dispatch [::events/reading-list-item-added %])
:on-item-removed #(re-frame/dispatch [::events/reading-list-item-removed %])}]
[:p
"You can also make some notes if you want. "
"One good way to make notes is to read a small section at a time, then write down what you have learned and any questions that you have. "]
[:span
"Where do you want to store the notes?"]
[:form {:style {:display :flex
:flex-direction :column
:flex-wrap "nowrap"
:margin-top "10px"
:margin-bottom "25px"}}
[:label {:for "in-app"}
[:input.uk-radio {:id "in-app"
:type "radio"
:name "notes-type"
:value :in-app
:checked (= (:notes-type current-essay) :in-app)
:on-change (fn [v]
(re-frame/dispatch [::events/notes-type-updated (-> v
.-target
.-value
keyword)]))}]
" here"]
[:label {:for "external"}
[:input.uk-radio {:id "external"
:type "radio"
:name "notes-type"
:value :external
:checked (= (:notes-type current-essay) :external)
:on-change (fn [v]
(re-frame/dispatch [::events/notes-type-updated (-> v
.-target
.-value
keyword)]))}]
" in another app"]]
(if (= (:notes-type current-essay) :in-app)
[quill {:default-value (:notes current-essay)
:on-change (fn [html _ _ editor]
(re-frame/dispatch [::events/in-app-notes-updated html (.call (aget editor "getText"))]))}]
[:input.uk-input
{:default-value (:external-notes-url current-essay)
:on-blur #(re-frame/dispatch [::events/external-notes-url-updated (utils/ev-val %)])
:placeholder "Enter the URL of your notes here"}])
[:button.uk-button.uk-button-primary.next-step
{:disabled (empty? (:reading-list current-essay))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])
(defn topic-choice [current-essay]
[:div.step
[:p "You now need to choose your topic, and the length your essay will be. "]
[:b "Please pick a topic from the below choices"]
[:ul.uk-card.uk-card-default.uk-list.uk-list-striped.topic-selection
(->> (:candidate-topics current-essay)
(map #(-> [:li.topic-selection__item {:class (when (= % (:title current-essay)) "topic-selection__item--selected")
:on-click (partial re-frame/dispatch [::events/topic-selected %])}
%])))]
[:label.uk-form-label {:for "target-essay-length"}
"Target Essay Length"]
[:input#target-essay-length.uk-input
{:default-value (str (:target-length current-essay))
:on-change #(re-frame/dispatch [::events/essay-target-length-changed (utils/parse-int (utils/ev-val %))])}]
[:button.uk-button.uk-button-primary.next-step
{:disabled (not (and (contains? (:candidate-topics current-essay) (:title current-essay))
(:target-length current-essay)))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])
(defn outline [current-essay]
(let [min-sentences (min 15 (int (/ (:target-length current-essay) 100)))]
[:div.step
[:p "It's now time to write the outline of your essay. You need to write "
[:b min-sentences] " headings, one per 100 words of your essay (up to 15 headings)."]
[editable-list {:items (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
:label-fn :heading
:on-item-added #(re-frame/dispatch [::events/outline-heading-added %])
:on-item-removed #(re-frame/dispatch [::events/outline-heading-removed (:heading %)])
:on-item-moved-up #(re-frame/dispatch [::events/paragraph-moved-up %])
:on-item-moved-down #(re-frame/dispatch [::events/paragraph-moved-down %])}]
[:p "You have written " [:b (count (:outline current-essay))] " headings out of " [:b min-sentences] "."]
[:button.uk-button.uk-button-primary.next-step
{:disabled (zero? (count (:outline current-essay)))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]]))
(defn outline-paragraphs [current-essay]
[:div.step.outline-paragraphs
(concat [[:p.outline-paragraphs__explanation
"Aim to write about " [:b "10 to 15"] " sentences per outline heading."
"You can write more or less if you want."]
[:p.outline-paragraphs__explanation
"You can use triple-backticks (```) to mark out code blocks, e.g. ```1 + 1```."]
[:p.outline-paragraphs__explanation
"To review your notes, "
[:a {:on-click #(re-frame/dispatch [::events/view-notes-requested (:id current-essay)])}
"click here."]]]
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(mapcat (fn [section]
[[:h5.uk-margin-small-top (:heading section)]
[:textarea.uk-textarea
{:default-value (:v1 (:paragraph section))
:on-change #(re-frame/dispatch [::events/outline-paragraph-updated (:heading section) (utils/ev-val %)])
:rows 8}]
[:p "You have written "
[:b (count (get-in section [:sentences :v1]))]
" sentences, and "
[:b (-> (get-in section [:paragraph :v1]) (utils/words) count)]
" words."]])))
[[:p
"You have written "
(->> (:outline current-essay)
vals
(map (comp :v1 :paragraph))
(mapcat utils/words)
count)
" words, out of a target number of "
(:target-length current-essay)
" (aim for 25% above the target, " (int (* 1.25 (:target-length current-essay))) ")"]
[:button.uk-button.uk-button-primary.next-step
{:disabled (not-every? (comp #(not (s/blank? (:v1 (:paragraph %)))) val) (:outline current-essay))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])])
(defn rewrite-sentences [current-essay]
[:div.step
(concat [[:p
"Re-write all the sentences you wrote in the previous step. "
"If you can't improve on a sentence, just copy and paste it into the input box."
"If you want to completely remove a sentence, leave the input box blank."]]
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(map (fn [section]
[:div
[:h5.uk-margin-top (:heading section)]
(->> (get-in section [:sentences :v1])
(map-indexed (fn [idx v1]
[idx v1 (get-in section [:sentences :v2 idx])]))
(mapcat (fn [[idx v1 v2]]
(let [label (if (= (:type v1) :sentence)
(:value v1)
"Code Block")]
[[:h6.uk-margin-small-top label]
[:textarea.uk-textarea
{:rows 3
:default-value (:value v2)
:on-change #(re-frame/dispatch [::events/sentence-rewritten (:heading section) idx (utils/ev-val %)])}]]))))])))
[[:p
"You have written "
(->> (:outline current-essay)
vals
(map (comp utils/join-sentences :v2 :sentences))
(mapcat utils/words)
count)
" words, out of a target number of "
(:target-length current-essay)
" (aim for 25% above the target, " (int (* 1.25 (:target-length current-essay))) ")"]
[:button.uk-button.uk-button-primary.next-step
{:disabled (->> (get-in current-essay [:outline])
(mapcat (comp :v2 :sentences val))
(every? (comp s/blank? :value)))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])])
(defn reorder-sentences [current-essay]
[:div.step
(concat [[:p "Try re-ordering the sentences within each paragraph."]]
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(map (fn [section]
[:div
[:h5.uk-margin-top (:heading section)]
[:p (->> (get-in section [:sentences :v2])
(map utils/mask-code)
(utils/join-sentences))]
[editable-list {:items (->> (get-in section [:sentences :v2])
(map utils/mask-code)
(map :value)
(map-indexed vector))
:label-fn second
:on-item-moved-up (fn [[i _]]
(re-frame/dispatch [::events/sentence-moved-up (:heading section) i]))
:on-item-moved-down (fn [[i _]]
(re-frame/dispatch [::events/sentence-moved-down (:heading section) i]))}]])))
[[:button.uk-button.uk-button-primary.next-step
{:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])])
(defn reorder-paragraphs [current-essay]
(let [ordered-sections (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))]
[:div.step
[:p "If you want to, re-order the paragraphs."]
[editable-list {:items ordered-sections
:label-fn #(->> (get-in % [:sentences :v2])
(map utils/mask-code)
(utils/join-sentences))
:on-item-moved-up #(re-frame/dispatch [::events/paragraph-moved-up %])
:on-item-moved-down #(re-frame/dispatch [::events/paragraph-moved-down %])}]
[essay-display
(->> ordered-sections
(map (comp :v2 :sentences)))
(:title current-essay)]
[:button.uk-button.uk-button-primary.next-step
{:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]]))
(defn read-draft [current-essay]
[:div.step
[:p "Read your draft essay. You don't need to memorize it, just read it as you would someone else's essay."]
[essay-display
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(map (comp :v2 :sentences)))
(:title current-essay)]
[:button.uk-button.uk-button-primary.next-step
{:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])
(defn second-outline [current-essay]
[:div.step
[:p "Now write a new outline. " [:b "Don’t look back at your essay while you are doing this."]]
[editable-list {:items (utils/ordered-by (:second-outline current-essay) (:second-paragraph-order current-essay))
:label-fn :heading
:on-item-added #(re-frame/dispatch [::events/second-outline-heading-added %])
:on-item-removed #(re-frame/dispatch [::events/second-outline-heading-removed (:heading %)])
:on-item-moved-up #(re-frame/dispatch [::events/second-paragraph-moved-up %])
:on-item-moved-down #(re-frame/dispatch [::events/second-paragraph-moved-down %])}]
[next-step
{:disabled (zero? (count (:second-outline current-essay)))
:on-click #(re-frame/dispatch [::events/next-step])}]])
(defn copy-from-draft [current-essay]
[:div.step
(concat [[:p
"Copy from your draft essay into the new outline. "
"You'll get a chance to edit your final essay in the next step, so don't worry about the formatting too much."]
[essay-display
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(map (comp :v2 :sentences)))
(:title current-essay)]]
(->> (utils/ordered-by (:second-outline current-essay) (:second-paragraph-order current-essay))
(mapcat (fn [{:keys [heading paragraph]}]
[[:h5 heading]
[:textarea.uk-textarea
{:default-value paragraph
:on-change #(re-frame/dispatch [::events/second-outline-paragraph-updated heading (utils/ev-val %)])
:rows 8}]])))
[[next-step
{:disabled? (not-every? (comp #(not (s/blank? (:paragraph %))) val) (:second-outline current-essay))
:on-click #(re-frame/dispatch [::events/next-step])}]
[:button.uk-button.uk-button-default
{:on-click #(re-frame/dispatch [::events/repeat-sentence-rewrite])}
[:div.uk-flex.uk-flex-column {"uk-tooltip" "Repeat the process from the 'Outline' step, using the new outline"}
"Repeat"]]])])
(defn final-essay [current-essay]
[:div.step
[:p
"You can now format your final essay, and add citations if you wish. "
"Your reading list is displayed below for you to copy citations from. "
"When you've completed the essay, you can copy and paste it into a Word doc or Google doc."]
[:p "To review your notes, " [:a {:on-click #(re-frame/dispatch [::events/view-notes-requested (:id current-essay)])} "click here."]]
[editable-list {:items (:reading-list current-essay)}]
[quill {:default-value (:final-essay current-essay)
:on-change (fn [html _ _ editor]
(re-frame/dispatch [::events/final-essay-updated html (.call (aget editor "getText"))]))}]
[:p
"You have written "
(:final-essay-word-count current-essay)
" words, out of a target number of "
(:target-length current-essay) "."]])
(defn sidebar [current-essay]
[:div.sidebar.uk-card.uk-card-body
[:h4.sidebar__header "Essay Steps"]
[:div.sidebar__list
(->> constants/steps
(map #(let [enabled (utils/step-before-or-equal? % (:highest-step current-essay))]
^{:key %}
[:a.sidebar__step
{:href (when enabled (utils/step-url (:id current-essay) %))
:class (str (when (= (:current-step current-essay) %)
"sidebar__step--active ")
(when-not enabled
"sidebar__step--disabled "))}
(utils/displayable-step-name %)])))]])
(defn essay-step []
(let [share-dialog-open (r/atom false)
encryption-key (r/atom nil)
sidebar-open (re-frame/subscribe [::subs/sidebar-open])
rs-info (re-frame/subscribe [::subs/remote-storage])]
(fn [current-essay page page-component]
[:div.uk-flex.uk-flex-column.essay
[:div.uk-flex.uk-flex-row.uk-flex-between.uk-flex-middle.essay__header
[:h3.uk-margin-remove
(:title current-essay)]
[:div.uk-flex
(when (:available? @rs-info)
[:<>
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: Upload to Remote Storage; pos: bottom"
:on-click #(re-frame/dispatch [::events/remote-storage-save-requested (:id current-essay)])}
(if (:uploading? @rs-info)
[loading-spinner]
[:i.zmdi.zmdi-cloud-upload])]
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: Download from Remote Storage; pos: bottom"
:on-click #(re-frame/dispatch [::events/remote-storage-retrieve-requested (:id current-essay)])}
(if (:downloading? @rs-info)
[loading-spinner]
[:i.zmdi.zmdi-cloud-download])]])
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: Download Essay; pos: bottom"
:on-click #(re-frame/dispatch [::events/export-requested (:id current-essay)])}
[:i.zmdi.zmdi-download]]
(when-not (or (and (= (:notes-type current-essay) :in-app) (str/blank? (:notes current-essay)))
(and (= (:notes-type current-essay) :external) (str/blank? (:external-notes-url current-essay))))
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: View Notes; pos: bottom"
:on-click #(re-frame/dispatch [::events/view-notes-requested (:id current-essay)])}
[:i.zmdi.zmdi-file-text]])
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: Share Essay; pos: bottom"
"uk-toggle" "target: #share-modal"}
[:i.zmdi.zmdi-share]]]]
[:div.uk-offcanvas {:class (when @sidebar-open "uk-offcanvas-overlay uk-open")
:style {:display :block}}
[:div.uk-offcanvas-bar.uk-flex.uk-padding-remove.uk-offcanvas-bar-animation.uk-offcanvas-slide
[:button.uk-offcanvas-close {"uk-close" ""
:on-click #(re-frame/dispatch [::events/sidebar-closed])}]
[sidebar current-essay]]]
[:div {"uk-grid" "true"
:class "uk-child-width-expand@s"}
[:div.uk-width-auto.uk-flex {:class "uk-visible@m"}
[sidebar current-essay]]
[:div.uk-width-expand
[:h3
(utils/displayable-step-name page)
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded.uk-margin-left
{:class "uk-hidden@m"
:on-click #(re-frame/dispatch [::events/sidebar-opened])}
[:i.zmdi.zmdi-menu]]]
[page-component current-essay]]]
[:div#share-modal {"uk-modal" "true"}
[:div.uk-modal-dialog.uk-modal-body
[:h3 "Share Essay"]
[:p
"This will share your essay by uploading it to " [:a {:href "" :target "_blank"} "PasteBin"] "."]
[:p
"If you enter an encryption key, nobody will be able to view your essay without the password.
It is recommended to use 4 random words for this password, like \"correct-horse-battery-staple\"."]
[:label {:for "password"}
"Encryption Password"]
[:input#password.uk-input
{:value @encryption-key
:on-change #(reset! encryption-key (.-value (.-target %)))}]
[:small "(Leave blank to share essay unencrypted)"]
[:div.uk-margin-top
[:button.uk-button.uk-button-primary.uk-modal-close
{:on-click #(re-frame/dispatch [::events/remote-save-requested (:id current-essay) @encryption-key])}
"OK"]
[:button.uk-button.uk-button-default.uk-modal-close
{:on-click #(reset! share-dialog-open false)}
"Cancel"]]]]])))
(defn not-found []
[:p "Route not found!"])
(defn import-essay []
[:p "Importing..."])
(defn pages [page]
(let [page-component (case page
:home home
:about about
:import-essay import-essay
:candidate-topics candidate-topics
:reading-list reading-list
:topic-choice topic-choice
:outline outline
:outline-paragraphs outline-paragraphs
:rewrite-sentences rewrite-sentences
:reorder-sentences reorder-sentences
:reorder-paragraphs reorder-paragraphs
:read-draft read-draft
:second-outline second-outline
:copy-from-draft copy-from-draft
:final-essay final-essay
not-found)
for-single-essay (not (contains? #{home about import-essay not-found} page-component))]
(if for-single-essay
(let [*current-essay (re-frame/subscribe [::subs/current-essay])]
(if @*current-essay
[essay-step @*current-essay page page-component]
[:p "Essay not found!"]))
[page-component])))
(defn remote-storage-widget []
(reagent.core/create-class
{:component-did-mount (fn [this]
(doto (js/Widget. rs/remote-storage (clj->js {:leaveOpen true
:skipInitial true}))
(.attach "rs")))
:reagent-render (fn [] [:div#rs])}))
(defn remote-storage-modal []
[:div#remote-storage-modal {"uk-modal" "true"}
[:div.uk-modal-dialog.uk-modal-body
[:h3 "Connect to Remote Storage"]
[:p
"Connect to external storage (Google Drive, Dropbox, or remotestorage.io) to save your essays."]
[:a.uk-navbar-item
[remote-storage-widget]]]])
(defn header []
[:div#app-bar.uk-navbar-container.uk-light {"uk-navbar" ""}
[:div.uk-navbar-left
[:div.uk-navbar-item
[:a.uk-logo.app-bar__title {:href "/"} "Lobster Writer"]]]
[:div.uk-navbar-right.app-bar__options
[:a.uk-navbar-item {:href "/"} "Home"]
[:a.uk-navbar-item {:href "/about"} "About"]
[:a.uk-navbar-item.remote-storage-logo
{"uk-toggle" "target: #remote-storage-modal"}
[:img {:src "/images/icons/remote-storage.svg"}]]
[:a.uk-navbar-item
{:style {:text-decoration "none"}
:href "-writer"
:target "_blank"}
[:i.zmdi.zmdi-hc-2x.zmdi-github]]
[:a.uk-navbar-item.dm-logo {:href "" :target "_blank"}
[:img {:src "/images/dmp-logo.png"}]]]])
(defn main-panel []
(let [*active-page (re-frame/subscribe [::subs/active-page])
*alerts (re-frame/subscribe [::subs/alerts])
*rs-info (re-frame/subscribe [::subs/remote-storage])]
[:div
[header @*rs-info]
[:div.uk-section
[:div.uk-container
[:div
(for [alert @*alerts]
^{:key (:id alert)}
[:div.uk-alert.uk-alert-danger
[:a.uk-alert-close {"uk-close" "true"
:on-click #(re-frame/dispatch [::events/close-alert %])}]
(:body alert)])]
[pages @*active-page]]
[remote-storage-modal]
[:div#saving-indicator
[:i.zmdi.zmdi-hc-2x.zmdi-floppy]]]]))
| null | https://raw.githubusercontent.com/DaveWM/lobster-writer/de40ee73d612abd1cdb4281e61a604f73afb215d/src/cljs/lobster_writer/views.cljs | clojure | home | (ns lobster-writer.views
(:require
[re-frame.core :as re-frame]
[lobster-writer.subs :as subs]
[lobster-writer.events :as events]
[lobster-writer.components.editable-list :refer [editable-list]]
[lobster-writer.utils :as utils]
[lobster-writer.constants :as constants]
[lobster-writer.components.helpers :refer [essay-display next-step]]
[clojure.string :as s]
[reagent.core :as r]
[cljsjs.prop-types]
[cljsjs.react-quill]
[cljs-time.core :as t]
[cljs-time.format :as tf]
[cljs-time.coerce :as tc]
[lobster-writer.components.file-chooser :refer [file-chooser]]
[clojure.string :as str]
[lobster-writer.remote-storage :as rs]))
(def react-quill (r/adapt-react-class js/ReactQuill))
(defn quill [props]
[react-quill (assoc props
:modules {:toolbar [[{:header [1 2 3 false]}]
["bold" "italic" "underline" "strike" "blockquote"]
[{:list "ordered"} {:list "bullet"} {:indent "-1"} {:indent "+1"}]
["link"]
["clean"]
["code-block"]]})])
(defn loading-spinner []
[:div.flipped
[:i.zmdi.zmdi-hc-spin-reverse.zmdi-replay]])
(defn home []
(let [*all-essays (re-frame/subscribe [::subs/all-essays])
*rs-info (re-frame/subscribe [::subs/remote-storage])]
[:div
(when (:available? @*rs-info)
[:<>
[:div.uk-margin
[:h4 "Remote Storage"]
[:div.uk-flex.uk-flex-start
[:button.uk-button.uk-button-default.uk-margin-right
{:on-click #(re-frame/dispatch [::events/remote-storage-save-all-requested])}
(if (:uploading? @*rs-info)
[loading-spinner]
"Upload All")]
[:button.uk-button.uk-button-default
{:on-click #(re-frame/dispatch [::events/remote-storage-retrieve-all-requested])}
(if (:downloading? @*rs-info)
[loading-spinner]
"Download All")]]]
[:hr]])
[:div
[:h4 "Essays"]
(->> @*all-essays
(map val)
(map (fn [essay]
^{:key (:id essay)}
[:div.uk-card.uk-card-body.uk-card-default.uk-margin
[:a {:href "#"
:style {:display "flex"
:justify-content "space-between"
:align-items "center"}
:on-click (partial re-frame/dispatch [::events/essay-selected (:id essay)])}
[:div.uk-flex.uk-flex-column.uk-flex-1
[:h3 (:title essay)]
[:progress.uk-progress
{:value (utils/percentage-complete (:highest-step essay))
:max "100"}]]
[:div.uk-margin-left.uk-margin-right
[:button.uk-button.uk-button-default.uk-button-small
{:tooltip "Export"
:on-click (fn [evt]
(re-frame/dispatch [::events/export-requested (:id essay)])
(.stopPropagation evt))}
[:i {:class "zmdi zmdi-download"}]]]]])))]
[:div.uk-flex
[:button.uk-button.uk-button-primary {:on-click #(re-frame/dispatch [::events/start-new-essay])} "New Essay"]
[file-chooser {:accept ".edn"
:on-change #(re-frame/dispatch [::events/import-requested (utils/ev-val %)])}
[:span "Import " [:i.zmdi.zmdi-hc-fw-rc.zmdi-upload]]]]]))
(defn about []
[:div
[:p "Lobster Writer is an application to help you write essays. It is based on the advice of Dr. Jordan Peterson in "
[:a {:href "/Jordan-Peterson-Writing-Template.docx" :target "_blank"} "this essay writing guide"]
". According to Dr. Peterson, this method will help you \"to write an excellent essay from beginning to end\". "]
[:p "Lobster Writer is also available as an Android app:"
[:a.play-badge {:href "-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1"}
[:img {:alt "Get it on Google Play" :src ""}]]]
[:p
"Lobster Writer is free (both gratis and libre) software - you can find the souce code "
[:a {:href "-writer"} "here"]
". If you would like to support me in developing Lobster Writer, please follow the link below."]
[:p.uk-text-bolder "Lobster Writer is not associated with Dr. Peterson in any way."]])
(defn candidate-topics [current-essay]
[:div.step
[:p "This is the first step in writing your essay. List around "
[:b "10"]
" topics that you would like to write about, or questions that you would like to answer."]
[editable-list {:items (:candidate-topics current-essay)
:on-item-added #(re-frame/dispatch [::events/candidate-topic-added %])
:on-item-removed #(re-frame/dispatch [::events/candidate-topic-removed %])}]
[:button.uk-button.uk-button-primary.next-step
{:disabled (empty? (:candidate-topics current-essay))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])
(defn reading-list [current-essay]
[:div.step
[:p
"Great, you've thought of some potential topics to write about. Now you need to find some books or articles to read. "
"You should read around " [:b "5 to 10 books per 1000 words of essay."] " List them here."]
[editable-list {:items (:reading-list current-essay)
:on-item-added #(re-frame/dispatch [::events/reading-list-item-added %])
:on-item-removed #(re-frame/dispatch [::events/reading-list-item-removed %])}]
[:p
"You can also make some notes if you want. "
"One good way to make notes is to read a small section at a time, then write down what you have learned and any questions that you have. "]
[:span
"Where do you want to store the notes?"]
[:form {:style {:display :flex
:flex-direction :column
:flex-wrap "nowrap"
:margin-top "10px"
:margin-bottom "25px"}}
[:label {:for "in-app"}
[:input.uk-radio {:id "in-app"
:type "radio"
:name "notes-type"
:value :in-app
:checked (= (:notes-type current-essay) :in-app)
:on-change (fn [v]
(re-frame/dispatch [::events/notes-type-updated (-> v
.-target
.-value
keyword)]))}]
" here"]
[:label {:for "external"}
[:input.uk-radio {:id "external"
:type "radio"
:name "notes-type"
:value :external
:checked (= (:notes-type current-essay) :external)
:on-change (fn [v]
(re-frame/dispatch [::events/notes-type-updated (-> v
.-target
.-value
keyword)]))}]
" in another app"]]
(if (= (:notes-type current-essay) :in-app)
[quill {:default-value (:notes current-essay)
:on-change (fn [html _ _ editor]
(re-frame/dispatch [::events/in-app-notes-updated html (.call (aget editor "getText"))]))}]
[:input.uk-input
{:default-value (:external-notes-url current-essay)
:on-blur #(re-frame/dispatch [::events/external-notes-url-updated (utils/ev-val %)])
:placeholder "Enter the URL of your notes here"}])
[:button.uk-button.uk-button-primary.next-step
{:disabled (empty? (:reading-list current-essay))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])
(defn topic-choice [current-essay]
[:div.step
[:p "You now need to choose your topic, and the length your essay will be. "]
[:b "Please pick a topic from the below choices"]
[:ul.uk-card.uk-card-default.uk-list.uk-list-striped.topic-selection
(->> (:candidate-topics current-essay)
(map #(-> [:li.topic-selection__item {:class (when (= % (:title current-essay)) "topic-selection__item--selected")
:on-click (partial re-frame/dispatch [::events/topic-selected %])}
%])))]
[:label.uk-form-label {:for "target-essay-length"}
"Target Essay Length"]
[:input#target-essay-length.uk-input
{:default-value (str (:target-length current-essay))
:on-change #(re-frame/dispatch [::events/essay-target-length-changed (utils/parse-int (utils/ev-val %))])}]
[:button.uk-button.uk-button-primary.next-step
{:disabled (not (and (contains? (:candidate-topics current-essay) (:title current-essay))
(:target-length current-essay)))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])
(defn outline [current-essay]
(let [min-sentences (min 15 (int (/ (:target-length current-essay) 100)))]
[:div.step
[:p "It's now time to write the outline of your essay. You need to write "
[:b min-sentences] " headings, one per 100 words of your essay (up to 15 headings)."]
[editable-list {:items (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
:label-fn :heading
:on-item-added #(re-frame/dispatch [::events/outline-heading-added %])
:on-item-removed #(re-frame/dispatch [::events/outline-heading-removed (:heading %)])
:on-item-moved-up #(re-frame/dispatch [::events/paragraph-moved-up %])
:on-item-moved-down #(re-frame/dispatch [::events/paragraph-moved-down %])}]
[:p "You have written " [:b (count (:outline current-essay))] " headings out of " [:b min-sentences] "."]
[:button.uk-button.uk-button-primary.next-step
{:disabled (zero? (count (:outline current-essay)))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]]))
(defn outline-paragraphs [current-essay]
[:div.step.outline-paragraphs
(concat [[:p.outline-paragraphs__explanation
"Aim to write about " [:b "10 to 15"] " sentences per outline heading."
"You can write more or less if you want."]
[:p.outline-paragraphs__explanation
"You can use triple-backticks (```) to mark out code blocks, e.g. ```1 + 1```."]
[:p.outline-paragraphs__explanation
"To review your notes, "
[:a {:on-click #(re-frame/dispatch [::events/view-notes-requested (:id current-essay)])}
"click here."]]]
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(mapcat (fn [section]
[[:h5.uk-margin-small-top (:heading section)]
[:textarea.uk-textarea
{:default-value (:v1 (:paragraph section))
:on-change #(re-frame/dispatch [::events/outline-paragraph-updated (:heading section) (utils/ev-val %)])
:rows 8}]
[:p "You have written "
[:b (count (get-in section [:sentences :v1]))]
" sentences, and "
[:b (-> (get-in section [:paragraph :v1]) (utils/words) count)]
" words."]])))
[[:p
"You have written "
(->> (:outline current-essay)
vals
(map (comp :v1 :paragraph))
(mapcat utils/words)
count)
" words, out of a target number of "
(:target-length current-essay)
" (aim for 25% above the target, " (int (* 1.25 (:target-length current-essay))) ")"]
[:button.uk-button.uk-button-primary.next-step
{:disabled (not-every? (comp #(not (s/blank? (:v1 (:paragraph %)))) val) (:outline current-essay))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])])
(defn rewrite-sentences [current-essay]
[:div.step
(concat [[:p
"Re-write all the sentences you wrote in the previous step. "
"If you can't improve on a sentence, just copy and paste it into the input box."
"If you want to completely remove a sentence, leave the input box blank."]]
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(map (fn [section]
[:div
[:h5.uk-margin-top (:heading section)]
(->> (get-in section [:sentences :v1])
(map-indexed (fn [idx v1]
[idx v1 (get-in section [:sentences :v2 idx])]))
(mapcat (fn [[idx v1 v2]]
(let [label (if (= (:type v1) :sentence)
(:value v1)
"Code Block")]
[[:h6.uk-margin-small-top label]
[:textarea.uk-textarea
{:rows 3
:default-value (:value v2)
:on-change #(re-frame/dispatch [::events/sentence-rewritten (:heading section) idx (utils/ev-val %)])}]]))))])))
[[:p
"You have written "
(->> (:outline current-essay)
vals
(map (comp utils/join-sentences :v2 :sentences))
(mapcat utils/words)
count)
" words, out of a target number of "
(:target-length current-essay)
" (aim for 25% above the target, " (int (* 1.25 (:target-length current-essay))) ")"]
[:button.uk-button.uk-button-primary.next-step
{:disabled (->> (get-in current-essay [:outline])
(mapcat (comp :v2 :sentences val))
(every? (comp s/blank? :value)))
:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])])
(defn reorder-sentences [current-essay]
[:div.step
(concat [[:p "Try re-ordering the sentences within each paragraph."]]
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(map (fn [section]
[:div
[:h5.uk-margin-top (:heading section)]
[:p (->> (get-in section [:sentences :v2])
(map utils/mask-code)
(utils/join-sentences))]
[editable-list {:items (->> (get-in section [:sentences :v2])
(map utils/mask-code)
(map :value)
(map-indexed vector))
:label-fn second
:on-item-moved-up (fn [[i _]]
(re-frame/dispatch [::events/sentence-moved-up (:heading section) i]))
:on-item-moved-down (fn [[i _]]
(re-frame/dispatch [::events/sentence-moved-down (:heading section) i]))}]])))
[[:button.uk-button.uk-button-primary.next-step
{:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])])
(defn reorder-paragraphs [current-essay]
(let [ordered-sections (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))]
[:div.step
[:p "If you want to, re-order the paragraphs."]
[editable-list {:items ordered-sections
:label-fn #(->> (get-in % [:sentences :v2])
(map utils/mask-code)
(utils/join-sentences))
:on-item-moved-up #(re-frame/dispatch [::events/paragraph-moved-up %])
:on-item-moved-down #(re-frame/dispatch [::events/paragraph-moved-down %])}]
[essay-display
(->> ordered-sections
(map (comp :v2 :sentences)))
(:title current-essay)]
[:button.uk-button.uk-button-primary.next-step
{:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]]))
(defn read-draft [current-essay]
[:div.step
[:p "Read your draft essay. You don't need to memorize it, just read it as you would someone else's essay."]
[essay-display
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(map (comp :v2 :sentences)))
(:title current-essay)]
[:button.uk-button.uk-button-primary.next-step
{:on-click #(re-frame/dispatch [::events/next-step])}
"Next Step"]])
(defn second-outline [current-essay]
[:div.step
[:p "Now write a new outline. " [:b "Don’t look back at your essay while you are doing this."]]
[editable-list {:items (utils/ordered-by (:second-outline current-essay) (:second-paragraph-order current-essay))
:label-fn :heading
:on-item-added #(re-frame/dispatch [::events/second-outline-heading-added %])
:on-item-removed #(re-frame/dispatch [::events/second-outline-heading-removed (:heading %)])
:on-item-moved-up #(re-frame/dispatch [::events/second-paragraph-moved-up %])
:on-item-moved-down #(re-frame/dispatch [::events/second-paragraph-moved-down %])}]
[next-step
{:disabled (zero? (count (:second-outline current-essay)))
:on-click #(re-frame/dispatch [::events/next-step])}]])
(defn copy-from-draft [current-essay]
[:div.step
(concat [[:p
"Copy from your draft essay into the new outline. "
"You'll get a chance to edit your final essay in the next step, so don't worry about the formatting too much."]
[essay-display
(->> (utils/ordered-by (:outline current-essay) (:paragraph-order current-essay))
(map (comp :v2 :sentences)))
(:title current-essay)]]
(->> (utils/ordered-by (:second-outline current-essay) (:second-paragraph-order current-essay))
(mapcat (fn [{:keys [heading paragraph]}]
[[:h5 heading]
[:textarea.uk-textarea
{:default-value paragraph
:on-change #(re-frame/dispatch [::events/second-outline-paragraph-updated heading (utils/ev-val %)])
:rows 8}]])))
[[next-step
{:disabled? (not-every? (comp #(not (s/blank? (:paragraph %))) val) (:second-outline current-essay))
:on-click #(re-frame/dispatch [::events/next-step])}]
[:button.uk-button.uk-button-default
{:on-click #(re-frame/dispatch [::events/repeat-sentence-rewrite])}
[:div.uk-flex.uk-flex-column {"uk-tooltip" "Repeat the process from the 'Outline' step, using the new outline"}
"Repeat"]]])])
(defn final-essay [current-essay]
[:div.step
[:p
"You can now format your final essay, and add citations if you wish. "
"Your reading list is displayed below for you to copy citations from. "
"When you've completed the essay, you can copy and paste it into a Word doc or Google doc."]
[:p "To review your notes, " [:a {:on-click #(re-frame/dispatch [::events/view-notes-requested (:id current-essay)])} "click here."]]
[editable-list {:items (:reading-list current-essay)}]
[quill {:default-value (:final-essay current-essay)
:on-change (fn [html _ _ editor]
(re-frame/dispatch [::events/final-essay-updated html (.call (aget editor "getText"))]))}]
[:p
"You have written "
(:final-essay-word-count current-essay)
" words, out of a target number of "
(:target-length current-essay) "."]])
(defn sidebar [current-essay]
[:div.sidebar.uk-card.uk-card-body
[:h4.sidebar__header "Essay Steps"]
[:div.sidebar__list
(->> constants/steps
(map #(let [enabled (utils/step-before-or-equal? % (:highest-step current-essay))]
^{:key %}
[:a.sidebar__step
{:href (when enabled (utils/step-url (:id current-essay) %))
:class (str (when (= (:current-step current-essay) %)
"sidebar__step--active ")
(when-not enabled
"sidebar__step--disabled "))}
(utils/displayable-step-name %)])))]])
(defn essay-step []
(let [share-dialog-open (r/atom false)
encryption-key (r/atom nil)
sidebar-open (re-frame/subscribe [::subs/sidebar-open])
rs-info (re-frame/subscribe [::subs/remote-storage])]
(fn [current-essay page page-component]
[:div.uk-flex.uk-flex-column.essay
[:div.uk-flex.uk-flex-row.uk-flex-between.uk-flex-middle.essay__header
[:h3.uk-margin-remove
(:title current-essay)]
[:div.uk-flex
(when (:available? @rs-info)
[:<>
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: Upload to Remote Storage; pos: bottom"
:on-click #(re-frame/dispatch [::events/remote-storage-save-requested (:id current-essay)])}
(if (:uploading? @rs-info)
[loading-spinner]
[:i.zmdi.zmdi-cloud-upload])]
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: Download from Remote Storage; pos: bottom"
:on-click #(re-frame/dispatch [::events/remote-storage-retrieve-requested (:id current-essay)])}
(if (:downloading? @rs-info)
[loading-spinner]
[:i.zmdi.zmdi-cloud-download])]])
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: Download Essay; pos: bottom"
:on-click #(re-frame/dispatch [::events/export-requested (:id current-essay)])}
[:i.zmdi.zmdi-download]]
(when-not (or (and (= (:notes-type current-essay) :in-app) (str/blank? (:notes current-essay)))
(and (= (:notes-type current-essay) :external) (str/blank? (:external-notes-url current-essay))))
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: View Notes; pos: bottom"
:on-click #(re-frame/dispatch [::events/view-notes-requested (:id current-essay)])}
[:i.zmdi.zmdi-file-text]])
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded
{"uk-tooltip" "title: Share Essay; pos: bottom"
"uk-toggle" "target: #share-modal"}
[:i.zmdi.zmdi-share]]]]
[:div.uk-offcanvas {:class (when @sidebar-open "uk-offcanvas-overlay uk-open")
:style {:display :block}}
[:div.uk-offcanvas-bar.uk-flex.uk-padding-remove.uk-offcanvas-bar-animation.uk-offcanvas-slide
[:button.uk-offcanvas-close {"uk-close" ""
:on-click #(re-frame/dispatch [::events/sidebar-closed])}]
[sidebar current-essay]]]
[:div {"uk-grid" "true"
:class "uk-child-width-expand@s"}
[:div.uk-width-auto.uk-flex {:class "uk-visible@m"}
[sidebar current-essay]]
[:div.uk-width-expand
[:h3
(utils/displayable-step-name page)
[:button.uk-button.uk-button-default.uk-button-small.uk-border-rounded.uk-margin-left
{:class "uk-hidden@m"
:on-click #(re-frame/dispatch [::events/sidebar-opened])}
[:i.zmdi.zmdi-menu]]]
[page-component current-essay]]]
[:div#share-modal {"uk-modal" "true"}
[:div.uk-modal-dialog.uk-modal-body
[:h3 "Share Essay"]
[:p
"This will share your essay by uploading it to " [:a {:href "" :target "_blank"} "PasteBin"] "."]
[:p
"If you enter an encryption key, nobody will be able to view your essay without the password.
It is recommended to use 4 random words for this password, like \"correct-horse-battery-staple\"."]
[:label {:for "password"}
"Encryption Password"]
[:input#password.uk-input
{:value @encryption-key
:on-change #(reset! encryption-key (.-value (.-target %)))}]
[:small "(Leave blank to share essay unencrypted)"]
[:div.uk-margin-top
[:button.uk-button.uk-button-primary.uk-modal-close
{:on-click #(re-frame/dispatch [::events/remote-save-requested (:id current-essay) @encryption-key])}
"OK"]
[:button.uk-button.uk-button-default.uk-modal-close
{:on-click #(reset! share-dialog-open false)}
"Cancel"]]]]])))
(defn not-found []
[:p "Route not found!"])
(defn import-essay []
[:p "Importing..."])
(defn pages [page]
(let [page-component (case page
:home home
:about about
:import-essay import-essay
:candidate-topics candidate-topics
:reading-list reading-list
:topic-choice topic-choice
:outline outline
:outline-paragraphs outline-paragraphs
:rewrite-sentences rewrite-sentences
:reorder-sentences reorder-sentences
:reorder-paragraphs reorder-paragraphs
:read-draft read-draft
:second-outline second-outline
:copy-from-draft copy-from-draft
:final-essay final-essay
not-found)
for-single-essay (not (contains? #{home about import-essay not-found} page-component))]
(if for-single-essay
(let [*current-essay (re-frame/subscribe [::subs/current-essay])]
(if @*current-essay
[essay-step @*current-essay page page-component]
[:p "Essay not found!"]))
[page-component])))
(defn remote-storage-widget []
(reagent.core/create-class
{:component-did-mount (fn [this]
(doto (js/Widget. rs/remote-storage (clj->js {:leaveOpen true
:skipInitial true}))
(.attach "rs")))
:reagent-render (fn [] [:div#rs])}))
(defn remote-storage-modal []
[:div#remote-storage-modal {"uk-modal" "true"}
[:div.uk-modal-dialog.uk-modal-body
[:h3 "Connect to Remote Storage"]
[:p
"Connect to external storage (Google Drive, Dropbox, or remotestorage.io) to save your essays."]
[:a.uk-navbar-item
[remote-storage-widget]]]])
(defn header []
[:div#app-bar.uk-navbar-container.uk-light {"uk-navbar" ""}
[:div.uk-navbar-left
[:div.uk-navbar-item
[:a.uk-logo.app-bar__title {:href "/"} "Lobster Writer"]]]
[:div.uk-navbar-right.app-bar__options
[:a.uk-navbar-item {:href "/"} "Home"]
[:a.uk-navbar-item {:href "/about"} "About"]
[:a.uk-navbar-item.remote-storage-logo
{"uk-toggle" "target: #remote-storage-modal"}
[:img {:src "/images/icons/remote-storage.svg"}]]
[:a.uk-navbar-item
{:style {:text-decoration "none"}
:href "-writer"
:target "_blank"}
[:i.zmdi.zmdi-hc-2x.zmdi-github]]
[:a.uk-navbar-item.dm-logo {:href "" :target "_blank"}
[:img {:src "/images/dmp-logo.png"}]]]])
(defn main-panel []
(let [*active-page (re-frame/subscribe [::subs/active-page])
*alerts (re-frame/subscribe [::subs/alerts])
*rs-info (re-frame/subscribe [::subs/remote-storage])]
[:div
[header @*rs-info]
[:div.uk-section
[:div.uk-container
[:div
(for [alert @*alerts]
^{:key (:id alert)}
[:div.uk-alert.uk-alert-danger
[:a.uk-alert-close {"uk-close" "true"
:on-click #(re-frame/dispatch [::events/close-alert %])}]
(:body alert)])]
[pages @*active-page]]
[remote-storage-modal]
[:div#saving-indicator
[:i.zmdi.zmdi-hc-2x.zmdi-floppy]]]]))
|
72c7fc5690f84389872610dd3e5fb5cf68712e18a1592050f3c86eb5e4333d3c | racketscript/racketscript | let-tail-nontail.rkt | #lang racket
(define (extract-current-continuation-marks key)
(continuation-mark-set->list
(current-continuation-marks)
key))
(define (main)
(define result-a #f)
(define result-b #f)
(with-continuation-mark 'key 'mark-main
(let ([x (add1 0)])
(with-continuation-mark 'key 'mark-let
(set! result-a (extract-current-continuation-marks 'key)))
(with-continuation-mark 'key 'mark-set
(set! result-b (extract-current-continuation-marks 'key)))))
(list result-a result-b))
(displayln (main))
| null | https://raw.githubusercontent.com/racketscript/racketscript/f94006d11338a674ae10f6bd83fc53e6806d07d8/tests/wcm/let-tail-nontail.rkt | racket | #lang racket
(define (extract-current-continuation-marks key)
(continuation-mark-set->list
(current-continuation-marks)
key))
(define (main)
(define result-a #f)
(define result-b #f)
(with-continuation-mark 'key 'mark-main
(let ([x (add1 0)])
(with-continuation-mark 'key 'mark-let
(set! result-a (extract-current-continuation-marks 'key)))
(with-continuation-mark 'key 'mark-set
(set! result-b (extract-current-continuation-marks 'key)))))
(list result-a result-b))
(displayln (main))
| |
0336b4eee36698595a2617dda72be14a28d6c244b1563861556496c80a6b38f9 | cjohansen/dumdom | dom_test.clj | (ns dumdom.dom-test
(:require [clojure.test :refer [deftest testing is]]
[dumdom.dom :as sut]))
(defn remove-fns [x]
(cond-> x
(:data x) (update :data dissoc :on :hook)))
(defn render [comp]
(-> (comp [] 0)
remove-fns
(update :children #(map remove-fns %))))
(deftest element-test
(testing "Renders element"
(is (= {:sel "div"
:data {:attrs {}
:style nil
:props {}
:dataset {}}
:dumdom/component-key ["" 0]
:children [{:text "Hello world"}]}
(render (sut/div {} "Hello world")))))
(testing "Renders element with attributes, props, and styles"
(is (= {:sel "input"
:data {:attrs {:width 10}
:style {:border "1px solid red"}
:dataset {}
:props {:value "Hello"}}
:dumdom/component-key ["" 0]
:children [{:text "Hello world"}]}
(render (sut/input {:width 10
:value "Hello"
:style {:border "1px solid red"}}
"Hello world")))))
(testing "Renders element with children"
(is (= {:sel "div"
:data {:attrs {}
:style nil
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:sel "h1"
:data {:style {:border "1px solid cyan"}
:dataset {}
:props {}
:attrs {}}
:dumdom/component-key ["" 0]
:children [{:text "Hello"}]}
{:sel "img"
:data {:style nil
:attrs {:border "2"}
:props {}
:dataset {}}
:dumdom/component-key ["" 1]
:children []}]}
(render (sut/div {}
(sut/h1 {:style {:border "1px solid cyan"}} "Hello")
(sut/img {:border "2"}))))))
(testing "Parses hiccup element name for classes"
(is (= {:sel "div"
:data {:attrs {}
:style nil
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:sel "h1"
:data {:style nil
:attrs {:class "something nice and beautiful"}
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:text "Hello"}]}]}
(render (sut/div {} [:h1.something.nice.and.beautiful "Hello"])))))
(testing "Parses hiccup element name for id and classes, combines with existing"
(is (= {:sel "div"
:data {:attrs {}
:style nil
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:sel "h1"
:data {:style nil
:attrs {:id "helau", :class "andhere here"}
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:text "Hello"}]}
{:sel "h1"
:data {:style nil
:attrs {:id "first", :class "lol"}
:dataset {}
:props {}}
:dumdom/component-key ["" 1]
:children [{:text "Hello"}]}]}
(render (sut/div {}
[:h1.here#helau {:className "andhere"} "Hello"]
[:h1#first.lol {} "Hello"]))))))
| null | https://raw.githubusercontent.com/cjohansen/dumdom/7ad911c2c487253df9caf75d49c2c274d91d0bf7/test/dumdom/dom_test.clj | clojure | (ns dumdom.dom-test
(:require [clojure.test :refer [deftest testing is]]
[dumdom.dom :as sut]))
(defn remove-fns [x]
(cond-> x
(:data x) (update :data dissoc :on :hook)))
(defn render [comp]
(-> (comp [] 0)
remove-fns
(update :children #(map remove-fns %))))
(deftest element-test
(testing "Renders element"
(is (= {:sel "div"
:data {:attrs {}
:style nil
:props {}
:dataset {}}
:dumdom/component-key ["" 0]
:children [{:text "Hello world"}]}
(render (sut/div {} "Hello world")))))
(testing "Renders element with attributes, props, and styles"
(is (= {:sel "input"
:data {:attrs {:width 10}
:style {:border "1px solid red"}
:dataset {}
:props {:value "Hello"}}
:dumdom/component-key ["" 0]
:children [{:text "Hello world"}]}
(render (sut/input {:width 10
:value "Hello"
:style {:border "1px solid red"}}
"Hello world")))))
(testing "Renders element with children"
(is (= {:sel "div"
:data {:attrs {}
:style nil
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:sel "h1"
:data {:style {:border "1px solid cyan"}
:dataset {}
:props {}
:attrs {}}
:dumdom/component-key ["" 0]
:children [{:text "Hello"}]}
{:sel "img"
:data {:style nil
:attrs {:border "2"}
:props {}
:dataset {}}
:dumdom/component-key ["" 1]
:children []}]}
(render (sut/div {}
(sut/h1 {:style {:border "1px solid cyan"}} "Hello")
(sut/img {:border "2"}))))))
(testing "Parses hiccup element name for classes"
(is (= {:sel "div"
:data {:attrs {}
:style nil
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:sel "h1"
:data {:style nil
:attrs {:class "something nice and beautiful"}
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:text "Hello"}]}]}
(render (sut/div {} [:h1.something.nice.and.beautiful "Hello"])))))
(testing "Parses hiccup element name for id and classes, combines with existing"
(is (= {:sel "div"
:data {:attrs {}
:style nil
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:sel "h1"
:data {:style nil
:attrs {:id "helau", :class "andhere here"}
:dataset {}
:props {}}
:dumdom/component-key ["" 0]
:children [{:text "Hello"}]}
{:sel "h1"
:data {:style nil
:attrs {:id "first", :class "lol"}
:dataset {}
:props {}}
:dumdom/component-key ["" 1]
:children [{:text "Hello"}]}]}
(render (sut/div {}
[:h1.here#helau {:className "andhere"} "Hello"]
[:h1#first.lol {} "Hello"]))))))
| |
07ff19a421c9b3f292e858d08125ceeca8d556724462b656a54c2fca4c707297 | jherrlin/guitar-theory-training | fretboard_matrix.cljc | (ns v4.se.jherrlin.music-theory.models.fretboard-matrix
"Representation of a fretboard as a matrix.
Example:
[[{:x 0, :tone #{:e}, :y 0}
{:x 1, :tone #{:f}, :y 0}
{:x 2, :tone #{:gb :f#}, :y 0}]
[{:x 0, :tone #{:b}, :y 1}
{:x 1, :tone #{:c}, :y 1}
{:x 2, :tone #{:db :c#}, :y 1}]
[{:x 0, :tone #{:g}, :y 2}
{:x 1, :tone #{:g# :ab}, :y 2}
{:x 2, :tone #{:a}, :y 2}]
[{:x 0, :tone #{:a}, :y 3}
{:x 1, :tone #{:bb :a#}, :y 3}
{:x 2, :tone #{:b}, :y 3}]
[{:x 0, :tone #{:b}, :y 4}
{:x 1, :tone #{:c}, :y 4}
{:x 2, :tone #{:db :c#}, :y 4}]]"
(:require
[malli.destructure :as md]
[malli.provider :as mp]
[malli.core :as m]))
(def FretboardMatrix
[:vector
[:+
[:map
[:x int?]
[:y int?]
[:tone [:set keyword?]]]]])
(def validate-fretboard-matrix? (partial m/validate FretboardMatrix))
(def explain-fretboard-matrix (partial m/explain FretboardMatrix))
(comment
(validate-fretboard-matrix?
[[{:x 0, :tone #{:e}, :y 0}
{:x 1, :tone #{:f}, :y 0}
{:x 2, :tone #{:gb :f#}, :y 0}]
[{:x 0, :tone #{:b}, :y 1}
{:x 1, :tone #{:c}, :y 1}
{:x 2, :tone #{:db :c#}, :y 1}]
[{:x 0, :tone #{:g}, :y 2}
{:x 1, :tone #{:g# :ab}, :y 2}
{:x 2, :tone #{:a}, :y 2}]
[{:x 0, :tone #{:a}, :y 3}
{:x 1, :tone #{:bb :a#}, :y 3}
{:x 2, :tone #{:b}, :y 3}]
[{:x 0, :tone #{:b}, :y 4}
{:x 1, :tone #{:c}, :y 4}
{:x 2, :tone #{:db :c#}, :y 4}]])
)
| null | https://raw.githubusercontent.com/jherrlin/guitar-theory-training/fd2866d4bdf314d54f68e39c31f2f3d81da699e2/src/v4/se/jherrlin/music_theory/models/fretboard_matrix.cljc | clojure | (ns v4.se.jherrlin.music-theory.models.fretboard-matrix
"Representation of a fretboard as a matrix.
Example:
[[{:x 0, :tone #{:e}, :y 0}
{:x 1, :tone #{:f}, :y 0}
{:x 2, :tone #{:gb :f#}, :y 0}]
[{:x 0, :tone #{:b}, :y 1}
{:x 1, :tone #{:c}, :y 1}
{:x 2, :tone #{:db :c#}, :y 1}]
[{:x 0, :tone #{:g}, :y 2}
{:x 1, :tone #{:g# :ab}, :y 2}
{:x 2, :tone #{:a}, :y 2}]
[{:x 0, :tone #{:a}, :y 3}
{:x 1, :tone #{:bb :a#}, :y 3}
{:x 2, :tone #{:b}, :y 3}]
[{:x 0, :tone #{:b}, :y 4}
{:x 1, :tone #{:c}, :y 4}
{:x 2, :tone #{:db :c#}, :y 4}]]"
(:require
[malli.destructure :as md]
[malli.provider :as mp]
[malli.core :as m]))
(def FretboardMatrix
[:vector
[:+
[:map
[:x int?]
[:y int?]
[:tone [:set keyword?]]]]])
(def validate-fretboard-matrix? (partial m/validate FretboardMatrix))
(def explain-fretboard-matrix (partial m/explain FretboardMatrix))
(comment
(validate-fretboard-matrix?
[[{:x 0, :tone #{:e}, :y 0}
{:x 1, :tone #{:f}, :y 0}
{:x 2, :tone #{:gb :f#}, :y 0}]
[{:x 0, :tone #{:b}, :y 1}
{:x 1, :tone #{:c}, :y 1}
{:x 2, :tone #{:db :c#}, :y 1}]
[{:x 0, :tone #{:g}, :y 2}
{:x 1, :tone #{:g# :ab}, :y 2}
{:x 2, :tone #{:a}, :y 2}]
[{:x 0, :tone #{:a}, :y 3}
{:x 1, :tone #{:bb :a#}, :y 3}
{:x 2, :tone #{:b}, :y 3}]
[{:x 0, :tone #{:b}, :y 4}
{:x 1, :tone #{:c}, :y 4}
{:x 2, :tone #{:db :c#}, :y 4}]])
)
| |
ba0d4ff417664ccd09b0e6195f438e7f79bf626cf98954c4f8d8954493f4b301 | LaurentMazare/tensorflow-ocaml | var.mli | val create : int list -> type_:'a Node.Type.t -> init:'a Node.t -> 'a Node.t
val float : int list -> init:[ `float ] Node.t -> [ `float ] Node.t
val double : int list -> init:[ `double ] Node.t -> [ `double ] Node.t
val f_or_d
: int list
-> float
-> type_:([< `float | `double ] as 'a) Node.Type.t
-> 'a Node.t
val f : int list -> float -> [ `float ] Node.t
val d : int list -> float -> [ `double ] Node.t
val normal
: int list
-> stddev:float
-> type_:([< `float | `double ] as 'a) Node.Type.t
-> 'a Node.t
val normalf : int list -> stddev:float -> [ `float ] Node.t
val normald : int list -> stddev:float -> [ `double ] Node.t
val truncated_normal
: int list
-> stddev:float
-> type_:([< `float | `double ] as 'a) Node.Type.t
-> 'a Node.t
val truncated_normalf : int list -> stddev:float -> [ `float ] Node.t
val truncated_normald : int list -> stddev:float -> [ `double ] Node.t
val uniform
: int list
-> lo:float
-> hi:float
-> type_:([< `float | `double ] as 'a) Node.Type.t
-> 'a Node.t
val uniformf : int list -> lo:float -> hi:float -> [ `float ] Node.t
val uniformd : int list -> lo:float -> hi:float -> [ `double ] Node.t
val load_f : int list -> filename:string -> tensor:string -> [ `float ] Node.t
val load_d : int list -> filename:string -> tensor:string -> [ `double ] Node.t
(** [get_all_vars nodes] returns all the variables that can be used when
evaluating a node in [nodes].
Each variable is only returned once.
*)
val get_all_vars : Node.p list -> Node.p list
| null | https://raw.githubusercontent.com/LaurentMazare/tensorflow-ocaml/52c5f1dec1a8b7dc9bc6ef06abbc07da6cd90d39/src/graph/var.mli | ocaml | * [get_all_vars nodes] returns all the variables that can be used when
evaluating a node in [nodes].
Each variable is only returned once.
| val create : int list -> type_:'a Node.Type.t -> init:'a Node.t -> 'a Node.t
val float : int list -> init:[ `float ] Node.t -> [ `float ] Node.t
val double : int list -> init:[ `double ] Node.t -> [ `double ] Node.t
val f_or_d
: int list
-> float
-> type_:([< `float | `double ] as 'a) Node.Type.t
-> 'a Node.t
val f : int list -> float -> [ `float ] Node.t
val d : int list -> float -> [ `double ] Node.t
val normal
: int list
-> stddev:float
-> type_:([< `float | `double ] as 'a) Node.Type.t
-> 'a Node.t
val normalf : int list -> stddev:float -> [ `float ] Node.t
val normald : int list -> stddev:float -> [ `double ] Node.t
val truncated_normal
: int list
-> stddev:float
-> type_:([< `float | `double ] as 'a) Node.Type.t
-> 'a Node.t
val truncated_normalf : int list -> stddev:float -> [ `float ] Node.t
val truncated_normald : int list -> stddev:float -> [ `double ] Node.t
val uniform
: int list
-> lo:float
-> hi:float
-> type_:([< `float | `double ] as 'a) Node.Type.t
-> 'a Node.t
val uniformf : int list -> lo:float -> hi:float -> [ `float ] Node.t
val uniformd : int list -> lo:float -> hi:float -> [ `double ] Node.t
val load_f : int list -> filename:string -> tensor:string -> [ `float ] Node.t
val load_d : int list -> filename:string -> tensor:string -> [ `double ] Node.t
val get_all_vars : Node.p list -> Node.p list
|
1720a4ce3224507e82e62cbb9ea881ef5519451132ffd1c0de99abd83a9063be | originrose/cortex | math_test.clj | (ns cortex.datasets.math-test
(:require [clojure.test :refer :all]
[clojure.core.matrix :as m]
[mikera.vectorz.matrix-api]
[cortex.util :as util]))
(m/set-current-implementation :vectorz)
(deftest normalize-test
(let [num-rows 10
num-cols 20
test-mat (m/array (partition num-cols (range (* num-rows num-cols))))]
(util/normalize-data! test-mat)
(let [means (util/matrix-col-means test-mat)
stddevs (util/matrix-col-stddevs test-mat)]
(is (util/very-near? (m/esum means) 0))
(is (util/very-near? (m/esum stddevs) num-cols)))))
(deftest parallel-normalize-test
(let [num-rows 200
num-cols 100
test-mat (m/array (partition num-cols (range (* num-rows num-cols))))
answer-mat (m/clone test-mat)
parallel-answers (util/parallel-normalize-data! test-mat)
answers (util/normalize-data! answer-mat)
means (util/matrix-col-means (:data parallel-answers))
stddevs (util/matrix-col-stddevs (:data parallel-answers))]
(is (m/equals (:means parallel-answers) (:means answers)))
(is (m/equals (:stddevs parallel-answers) (:stddevs answers)))
(is (util/very-near? (m/esum means) 0.0))
(is (util/very-near? (m/esum stddevs) num-cols))))
| null | https://raw.githubusercontent.com/originrose/cortex/94b1430538e6187f3dfd1697c36ff2c62b475901/test/clj/cortex/datasets/math_test.clj | clojure | (ns cortex.datasets.math-test
(:require [clojure.test :refer :all]
[clojure.core.matrix :as m]
[mikera.vectorz.matrix-api]
[cortex.util :as util]))
(m/set-current-implementation :vectorz)
(deftest normalize-test
(let [num-rows 10
num-cols 20
test-mat (m/array (partition num-cols (range (* num-rows num-cols))))]
(util/normalize-data! test-mat)
(let [means (util/matrix-col-means test-mat)
stddevs (util/matrix-col-stddevs test-mat)]
(is (util/very-near? (m/esum means) 0))
(is (util/very-near? (m/esum stddevs) num-cols)))))
(deftest parallel-normalize-test
(let [num-rows 200
num-cols 100
test-mat (m/array (partition num-cols (range (* num-rows num-cols))))
answer-mat (m/clone test-mat)
parallel-answers (util/parallel-normalize-data! test-mat)
answers (util/normalize-data! answer-mat)
means (util/matrix-col-means (:data parallel-answers))
stddevs (util/matrix-col-stddevs (:data parallel-answers))]
(is (m/equals (:means parallel-answers) (:means answers)))
(is (m/equals (:stddevs parallel-answers) (:stddevs answers)))
(is (util/very-near? (m/esum means) 0.0))
(is (util/very-near? (m/esum stddevs) num-cols))))
| |
158e34318d39592c636dfe7e3b48b9c3814e661396c7de0d7c6471d4b4eb4330 | uxbox/uxbox-backend | icons.clj | 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 ) 2016 < >
(ns uxbox.services.icons
"Icons library related services."
(:require [clojure.spec :as s]
[suricatta.core :as sc]
[uxbox.util.spec :as us]
[uxbox.sql :as sql]
[uxbox.db :as db]
[uxbox.services.core :as core]
[uxbox.util.exceptions :as ex]
[uxbox.util.transit :as t]
[uxbox.util.uuid :as uuid]
[uxbox.util.blob :as blob]
[uxbox.util.data :as data])
(:import ratpack.form.UploadedFile
org.apache.commons.io.FilenameUtils))
;; --- Helpers & Specs
(s/def ::user uuid?)
(s/def ::collection (s/nilable uuid?))
(s/def ::width (s/and number? pos?))
(s/def ::height (s/and number? pos?))
(s/def ::view-box (s/and (s/coll-of number?)
#(= 4 (count %))
vector?))
(s/def ::content string?)
(s/def ::mimetype string?)
(s/def ::metadata
(s/keys :opt-un [::width ::height ::view-box ::mimetype]))
(defn decode-metadata
[{:keys [metadata] :as data}]
(if metadata
(assoc data :metadata (-> metadata blob/decode t/decode))
data))
;; --- Create Collection
(defn create-collection
[conn {:keys [id user name]}]
(let [id (or id (uuid/random))
params {:id id :user user :name name}
sqlv (sql/create-icon-collection params)]
(-> (sc/fetch-one conn sqlv)
(data/normalize))))
(s/def ::create-icon-collection
(s/keys :req-un [::user ::us/name]
:opt-un [::us/id]))
(defmethod core/novelty :create-icon-collection
[params]
(s/assert ::create-icon-collection params)
(with-open [conn (db/connection)]
(create-collection conn params)))
;; --- Update Collection
(defn update-collection
[conn {:keys [id user name version]}]
(let [sqlv (sql/update-icon-collection {:id id
:user user
:name name
:version version})]
(some-> (sc/fetch-one conn sqlv)
(data/normalize))))
(s/def ::update-icon-collection
(s/keys :req-un [::user ::us/name ::us/version]
:opt-un [::us/id]))
(defmethod core/novelty :update-icon-collection
[params]
(s/assert ::update-icon-collection params)
(with-open [conn (db/connection)]
(sc/apply-atomic conn update-collection params)))
;; --- Copy Icon
(s/def ::copy-icon
(s/keys :req-un [:us/id ::collection ::user]))
(defn- retrieve-icon
[conn {:keys [user id]}]
(let [sqlv (sql/get-icon {:user user :id id})]
(some->> (sc/fetch-one conn sqlv)
(data/normalize-attrs))))
(declare create-icon)
(defn- copy-icon
[conn {:keys [user id collection]}]
(let [icon (retrieve-icon conn {:id id :user user})]
(when-not icon
(ex/raise :type :validation
:code ::icon-does-not-exists))
(let [params (dissoc icon :id)]
(create-icon conn params))))
(defmethod core/novelty :copy-icon
[params]
(s/assert ::copy-icon params)
(with-open [conn (db/connection)]
(sc/apply-atomic conn copy-icon params)))
;; --- List Collections
(defn get-collections-by-user
[conn user]
(let [sqlv (sql/get-icon-collections {:user user})]
(->> (sc/fetch conn sqlv)
(map data/normalize))))
(defmethod core/query :list-icon-collections
[{:keys [user] :as params}]
(s/assert ::user user)
(with-open [conn (db/connection)]
(get-collections-by-user conn user)))
;; --- Delete Collection
(defn delete-collection
[conn {:keys [id user]}]
(let [sqlv (sql/delete-icon-collection {:id id :user user})]
(pos? (sc/execute conn sqlv))))
(s/def ::delete-icon-collection
(s/keys :req-un [::user]
:opt-un [::us/id]))
(defmethod core/novelty :delete-icon-collection
[params]
(s/assert ::delete-icon-collection params)
(with-open [conn (db/connection)]
(delete-collection conn params)))
;; --- Create Icon (Upload)
(defn create-icon
[conn {:keys [id user name collection
metadata content] :as params}]
(let [id (or id (uuid/random))
params {:id id
:name name
:content content
:metadata (-> metadata t/encode blob/encode)
:collection collection
:user user}
sqlv (sql/create-icon params)]
(some-> (sc/fetch-one conn sqlv)
(data/normalize)
(decode-metadata))))
(s/def ::create-icon
(s/keys :req-un [::user ::us/name ::metadata ::content]
:opt-un [::us/id ::collection]))
(defmethod core/novelty :create-icon
[params]
(s/assert ::create-icon params)
(with-open [conn (db/connection)]
(create-icon conn params)))
;; --- Update Icon
(defn update-icon
[conn {:keys [id name version user collection]}]
(let [sqlv (sql/update-icon {:id id
:collection collection
:name name
:user user
:version version})]
(some-> (sc/fetch-one conn sqlv)
(data/normalize)
(decode-metadata))))
(s/def ::update-icon
(s/keys :req-un [::us/id ::user ::us/name ::us/version ::collection]))
(defmethod core/novelty :update-icon
[params]
(s/assert ::update-icon params)
(with-open [conn (db/connection)]
(update-icon conn params)))
;; --- Delete Icon
(defn delete-icon
[conn {:keys [user id]}]
(let [sqlv (sql/delete-icon {:id id :user user})]
(pos? (sc/execute conn sqlv))))
(s/def ::delete-icon
(s/keys :req-un [::user]
:opt-un [::us/id]))
(defmethod core/novelty :delete-icon
[params]
(s/assert ::delete-icon params)
(with-open [conn (db/connection)]
(delete-icon conn params)))
;; --- List Icons
(defn get-icons-by-user
[conn user collection]
(let [sqlv (if collection
(sql/get-icons-by-collection {:user user :collection collection})
(sql/get-icons {:user user}))]
(->> (sc/fetch conn sqlv)
(map data/normalize)
(map decode-metadata))))
(s/def ::list-icons
(s/keys :req-un [::user ::collection]))
(defmethod core/query :list-icons
[{:keys [user collection] :as params}]
(s/assert ::list-icons params)
(with-open [conn (db/connection)]
(get-icons-by-user conn user collection)))
| null | https://raw.githubusercontent.com/uxbox/uxbox-backend/036c42db8424be3ac34c38be80577ee279141681/src/uxbox/services/icons.clj | clojure |
--- Helpers & Specs
--- Create Collection
--- Update Collection
--- Copy Icon
--- List Collections
--- Delete Collection
--- Create Icon (Upload)
--- Update Icon
--- Delete Icon
--- List Icons | 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 ) 2016 < >
(ns uxbox.services.icons
"Icons library related services."
(:require [clojure.spec :as s]
[suricatta.core :as sc]
[uxbox.util.spec :as us]
[uxbox.sql :as sql]
[uxbox.db :as db]
[uxbox.services.core :as core]
[uxbox.util.exceptions :as ex]
[uxbox.util.transit :as t]
[uxbox.util.uuid :as uuid]
[uxbox.util.blob :as blob]
[uxbox.util.data :as data])
(:import ratpack.form.UploadedFile
org.apache.commons.io.FilenameUtils))
(s/def ::user uuid?)
(s/def ::collection (s/nilable uuid?))
(s/def ::width (s/and number? pos?))
(s/def ::height (s/and number? pos?))
(s/def ::view-box (s/and (s/coll-of number?)
#(= 4 (count %))
vector?))
(s/def ::content string?)
(s/def ::mimetype string?)
(s/def ::metadata
(s/keys :opt-un [::width ::height ::view-box ::mimetype]))
(defn decode-metadata
[{:keys [metadata] :as data}]
(if metadata
(assoc data :metadata (-> metadata blob/decode t/decode))
data))
(defn create-collection
[conn {:keys [id user name]}]
(let [id (or id (uuid/random))
params {:id id :user user :name name}
sqlv (sql/create-icon-collection params)]
(-> (sc/fetch-one conn sqlv)
(data/normalize))))
(s/def ::create-icon-collection
(s/keys :req-un [::user ::us/name]
:opt-un [::us/id]))
(defmethod core/novelty :create-icon-collection
[params]
(s/assert ::create-icon-collection params)
(with-open [conn (db/connection)]
(create-collection conn params)))
(defn update-collection
[conn {:keys [id user name version]}]
(let [sqlv (sql/update-icon-collection {:id id
:user user
:name name
:version version})]
(some-> (sc/fetch-one conn sqlv)
(data/normalize))))
(s/def ::update-icon-collection
(s/keys :req-un [::user ::us/name ::us/version]
:opt-un [::us/id]))
(defmethod core/novelty :update-icon-collection
[params]
(s/assert ::update-icon-collection params)
(with-open [conn (db/connection)]
(sc/apply-atomic conn update-collection params)))
(s/def ::copy-icon
(s/keys :req-un [:us/id ::collection ::user]))
(defn- retrieve-icon
[conn {:keys [user id]}]
(let [sqlv (sql/get-icon {:user user :id id})]
(some->> (sc/fetch-one conn sqlv)
(data/normalize-attrs))))
(declare create-icon)
(defn- copy-icon
[conn {:keys [user id collection]}]
(let [icon (retrieve-icon conn {:id id :user user})]
(when-not icon
(ex/raise :type :validation
:code ::icon-does-not-exists))
(let [params (dissoc icon :id)]
(create-icon conn params))))
(defmethod core/novelty :copy-icon
[params]
(s/assert ::copy-icon params)
(with-open [conn (db/connection)]
(sc/apply-atomic conn copy-icon params)))
(defn get-collections-by-user
[conn user]
(let [sqlv (sql/get-icon-collections {:user user})]
(->> (sc/fetch conn sqlv)
(map data/normalize))))
(defmethod core/query :list-icon-collections
[{:keys [user] :as params}]
(s/assert ::user user)
(with-open [conn (db/connection)]
(get-collections-by-user conn user)))
(defn delete-collection
[conn {:keys [id user]}]
(let [sqlv (sql/delete-icon-collection {:id id :user user})]
(pos? (sc/execute conn sqlv))))
(s/def ::delete-icon-collection
(s/keys :req-un [::user]
:opt-un [::us/id]))
(defmethod core/novelty :delete-icon-collection
[params]
(s/assert ::delete-icon-collection params)
(with-open [conn (db/connection)]
(delete-collection conn params)))
(defn create-icon
[conn {:keys [id user name collection
metadata content] :as params}]
(let [id (or id (uuid/random))
params {:id id
:name name
:content content
:metadata (-> metadata t/encode blob/encode)
:collection collection
:user user}
sqlv (sql/create-icon params)]
(some-> (sc/fetch-one conn sqlv)
(data/normalize)
(decode-metadata))))
(s/def ::create-icon
(s/keys :req-un [::user ::us/name ::metadata ::content]
:opt-un [::us/id ::collection]))
(defmethod core/novelty :create-icon
[params]
(s/assert ::create-icon params)
(with-open [conn (db/connection)]
(create-icon conn params)))
(defn update-icon
[conn {:keys [id name version user collection]}]
(let [sqlv (sql/update-icon {:id id
:collection collection
:name name
:user user
:version version})]
(some-> (sc/fetch-one conn sqlv)
(data/normalize)
(decode-metadata))))
(s/def ::update-icon
(s/keys :req-un [::us/id ::user ::us/name ::us/version ::collection]))
(defmethod core/novelty :update-icon
[params]
(s/assert ::update-icon params)
(with-open [conn (db/connection)]
(update-icon conn params)))
(defn delete-icon
[conn {:keys [user id]}]
(let [sqlv (sql/delete-icon {:id id :user user})]
(pos? (sc/execute conn sqlv))))
(s/def ::delete-icon
(s/keys :req-un [::user]
:opt-un [::us/id]))
(defmethod core/novelty :delete-icon
[params]
(s/assert ::delete-icon params)
(with-open [conn (db/connection)]
(delete-icon conn params)))
(defn get-icons-by-user
[conn user collection]
(let [sqlv (if collection
(sql/get-icons-by-collection {:user user :collection collection})
(sql/get-icons {:user user}))]
(->> (sc/fetch conn sqlv)
(map data/normalize)
(map decode-metadata))))
(s/def ::list-icons
(s/keys :req-un [::user ::collection]))
(defmethod core/query :list-icons
[{:keys [user collection] :as params}]
(s/assert ::list-icons params)
(with-open [conn (db/connection)]
(get-icons-by-user conn user collection)))
|
f4ffeb10ec4f9f8c0b954496efdaf994e0d6b7877496918ad16c1f8585afb68a | kraison/langutils | tagger-oldctx.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : utils -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: tagger-ctxold
;;;; Purpose: Non-macro version of context rule parser/generator
;;;;
Programmer :
Date Started : October 2004
;;;;
(in-package :langutils)
(defun make-contextual-rule-old ( contextual-rule )
(declare (optimize speed (safety 0))
(type list contextual-rule)
(inline svref))
(let ((old (mkkeysym (first contextual-rule)))
(new (mkkeysym (second contextual-rule)))
(name (string-upcase (third contextual-rule)))
(arg1 (fourth contextual-rule))
(arg2 (fifth contextual-rule)))
(cond ((string= name "SURROUNDTAG")
(let ((t1 (mkkeysym arg1))
(t2 (mkkeysym arg2)))
#'(lambda (tokens tags pos)
(declare (ignore tokens)
(type simple-vector tags)
(type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (svref tags (- pos 1)) t1)
(eq (svref tags (+ pos 1)) t2))
(progn
(write-log tagger-contextual "SURROUNDTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXTTAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare (ignore tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (svref tags (+ pos 1)) t1))
(progn
(write-log tagger-contextual "NEXTTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "CURWD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-array fixnum) tokens)
#-mcl (type simple-vector tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1))
(progn
(write-log tagger-contextual "CURWD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXTWD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens (+ pos 1)) w1))
(progn
(write-log tagger-contextual "NEXTWD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "RBIGRAM")
(let ((me (id-for-token arg1))
(next (id-for-token arg2)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) me)
(eq (aref tokens (+ pos 1)) next))
(progn
(write-log tagger-contextual "RBIGRAM: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDNEXTTAG")
(let ((me (id-for-token arg1))
(t2 (mkkeysym arg2)))
#'(lambda (tokens tags pos)
(declare (type #-mcl (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) me)
(eq (svref tags (+ pos 1)) t2))
(progn
(write-log tagger-contextual "WDNEXTTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDAND2AFT")
(let ((w1 (id-for-token arg1))
(w2 (id-for-token arg2)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (aref tokens (+ pos 2)) w2))
(progn
(write-log tagger-contextual "WDAND2AFT: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDAND2TAGAFT")
(let ((w1 (id-for-token arg1))
(t2 (mkkeysym arg2)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (svref tags (+ pos 2)) t2))
(progn
(write-log tagger-contextual "WDAND2TAGAFT: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT2TAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare (ignore tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos))
(if (and (eq (svref tags pos) old)
(eq (svref tags (+ pos 2)) t1))
(progn
(write-log tagger-contextual "NEXT2TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT2WD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(if (and (eq (svref tags pos) old)
(eq (aref tokens (+ pos 2)) w1))
(progn
(write-log tagger-contextual "NEXT2WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXTBIGRAM")
(let ((t1 (mkkeysym arg1))
(t2 (mkkeysym arg2)))
#-mcl (declare (type symbol t1 t2))
#'(lambda (tokens tags pos)
(declare (ignore tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos))
(if (and (eq (svref tags pos) old)
(eq (svref tags (+ pos 1)) t1)
(eq (svref tags (+ pos 2)) t2))
(progn
(write-log tagger-contextual "NEXTBIGRAM: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT1OR2TAG")
(let ((t1 (mkkeysym arg1)))
#-mcl (declare (type symbol t1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(or (eq (svref tags (+ pos 1)) t1)
(eq (svref tags (+ pos 2)) t1)))
(progn
(write-log tagger-contextual "NEXT1OR2TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT1OR2WD")
(let ((w1 (id-for-token arg1)))
(declare (type fixnum w1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(or (eq (aref tokens (+ pos 1)) w1)
(eq (aref tokens (+ pos 2)) w1)))
(progn
(write-log tagger-contextual "NEXT1OR2WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT1OR2OR3TAG")
(let ((t1 (mkkeysym arg1)))
(declare (type symbol t1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(or (eq (svref tags (+ pos 1)) t1)
(eq (svref tags (+ pos 2)) t1)
(eq (svref tags (+ pos 3)) t1)))
(progn
(write-log tagger-contextual "NEXT1OR2OR3TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT1OR2OR3WD")
(let ((w1 (id-for-token arg1)))
(declare (type fixnum w1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(or (eq (aref tokens (+ pos 1)) w1)
(eq (aref tokens (+ pos 2)) w1)
(eq (aref tokens (+ pos 2)) w1)))
(progn
(write-log tagger-contextual "NEXT1OR2OR3WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREVTAG")
(let ((t1 (mkkeysym arg1)))
(declare (type symbol t1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-array fixnum ) tokens)
#-mcl (type (simple-array symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(eq (svref tags (- pos 1)) t1))
(progn
(write-log tagger-contextual "PREVTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREVWD")
(let ((w1 (id-for-token arg1)))
#-mcl (declare (type fixnum w1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens (- pos 1)) w1))
(progn
(write-log tagger-contextual "PREVWD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "LBIGRAM")
(let ((w1 (id-for-token arg1))
(w2 (id-for-token arg2)))
#-mcl (declare (type fixnum w1 w2))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (aref tokens (- pos 1)) w2))
(progn
(write-log tagger-contextual "LBIGRAM: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDPREVTAG")
(let ((me (id-for-token arg1))
(t2 (mkkeysym arg2)))
#-mcl (declare (type fixnum me) (type symbol t2))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) me)
(eq (svref tags (- pos 1)) t2))
(progn
(write-log tagger-contextual "WDPREVTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDAND2BFR")
(let ((w1 (id-for-token arg1))
(w2 (id-for-token arg2)))
#-mcl (declare (type fixnum w1 w2))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (aref tokens (- pos 2)) w2))
(progn
(write-log tagger-contextual "WDAND2BFR: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDAND2TAGBFR")
(let ((w1 (id-for-token arg1))
(t2 (mkkeysym arg2)))
#-mcl (declare (type fixnum w1) (type symbol t2))
#'(lambda (tokens tags pos)
(declare #-mcl (type fixnum pos)
#-mcl (type (simple-array fixnum ) tokens)
#-mcl (type (simple-array symbol ) tags)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (svref tags (- pos 2)) t2))
(progn
(write-log tagger-contextual "WDAND2TAGBFR: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV2TAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(eq (svref tags (- pos 2)) t1))
(progn
(write-log tagger-contextual "PREV2TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV2WD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens (- pos 2)) w1))
(progn
(write-log tagger-contextual "PREV2WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV1OR2TAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(or (eq (svref tags (- pos 1)) t1)
(eq (svref tags (- pos 2)) t1)))
(progn
(write-log tagger-contextual "PREV1OR2TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV1OR2WD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(or (eq (aref tokens (- pos 1)) w1)
(eq (aref tokens (- pos 2)) w1)))
(progn
(write-log tagger-contextual "PREV1OR2WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV1OR2OR3TAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(or (eq (svref tags (- pos 1)) t1)
(eq (svref tags (- pos 2)) t1)
(eq (svref tags (- pos 3)) t1)))
(progn
(write-log tagger-contextual "PREV1OR2OR3TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV1OR2OR3WD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(or (eq (aref tokens (- pos 1)) w1)
(eq (aref tokens (- pos 2)) w1)
(eq (aref tokens (- pos 3)) w1)))
(progn
(write-log tagger-contextual "PREV1OR2OR3WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREVBIGRAM")
(let ((t1 (mkkeysym arg1))
(t2 (mkkeysym arg2)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(eq (svref tags (- pos 1)) t2)
(eq (svref tags (- pos 2)) t1))
(progn
(write-log tagger-contextual "PREVBIGRAM: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
(t (write-log tagger-contextual "Unrecognized rule: ~A" contextual-rule)))))
| null | https://raw.githubusercontent.com/kraison/langutils/2c75cf08c9dbaf22ed7209c485b7157e5ab5143a/langutils/src/tagger-oldctx.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : utils -*-
*************************************************************************
FILE IDENTIFICATION
Name: tagger-ctxold
Purpose: Non-macro version of context rule parser/generator
| Programmer :
Date Started : October 2004
(in-package :langutils)
(defun make-contextual-rule-old ( contextual-rule )
(declare (optimize speed (safety 0))
(type list contextual-rule)
(inline svref))
(let ((old (mkkeysym (first contextual-rule)))
(new (mkkeysym (second contextual-rule)))
(name (string-upcase (third contextual-rule)))
(arg1 (fourth contextual-rule))
(arg2 (fifth contextual-rule)))
(cond ((string= name "SURROUNDTAG")
(let ((t1 (mkkeysym arg1))
(t2 (mkkeysym arg2)))
#'(lambda (tokens tags pos)
(declare (ignore tokens)
(type simple-vector tags)
(type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (svref tags (- pos 1)) t1)
(eq (svref tags (+ pos 1)) t2))
(progn
(write-log tagger-contextual "SURROUNDTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXTTAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare (ignore tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (svref tags (+ pos 1)) t1))
(progn
(write-log tagger-contextual "NEXTTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "CURWD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-array fixnum) tokens)
#-mcl (type simple-vector tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1))
(progn
(write-log tagger-contextual "CURWD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXTWD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens (+ pos 1)) w1))
(progn
(write-log tagger-contextual "NEXTWD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "RBIGRAM")
(let ((me (id-for-token arg1))
(next (id-for-token arg2)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) me)
(eq (aref tokens (+ pos 1)) next))
(progn
(write-log tagger-contextual "RBIGRAM: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDNEXTTAG")
(let ((me (id-for-token arg1))
(t2 (mkkeysym arg2)))
#'(lambda (tokens tags pos)
(declare (type #-mcl (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) me)
(eq (svref tags (+ pos 1)) t2))
(progn
(write-log tagger-contextual "WDNEXTTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDAND2AFT")
(let ((w1 (id-for-token arg1))
(w2 (id-for-token arg2)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (aref tokens (+ pos 2)) w2))
(progn
(write-log tagger-contextual "WDAND2AFT: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDAND2TAGAFT")
(let ((w1 (id-for-token arg1))
(t2 (mkkeysym arg2)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (svref tags (+ pos 2)) t2))
(progn
(write-log tagger-contextual "WDAND2TAGAFT: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT2TAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare (ignore tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos))
(if (and (eq (svref tags pos) old)
(eq (svref tags (+ pos 2)) t1))
(progn
(write-log tagger-contextual "NEXT2TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT2WD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(if (and (eq (svref tags pos) old)
(eq (aref tokens (+ pos 2)) w1))
(progn
(write-log tagger-contextual "NEXT2WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXTBIGRAM")
(let ((t1 (mkkeysym arg1))
(t2 (mkkeysym arg2)))
#-mcl (declare (type symbol t1 t2))
#'(lambda (tokens tags pos)
(declare (ignore tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos))
(if (and (eq (svref tags pos) old)
(eq (svref tags (+ pos 1)) t1)
(eq (svref tags (+ pos 2)) t2))
(progn
(write-log tagger-contextual "NEXTBIGRAM: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT1OR2TAG")
(let ((t1 (mkkeysym arg1)))
#-mcl (declare (type symbol t1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(or (eq (svref tags (+ pos 1)) t1)
(eq (svref tags (+ pos 2)) t1)))
(progn
(write-log tagger-contextual "NEXT1OR2TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT1OR2WD")
(let ((w1 (id-for-token arg1)))
(declare (type fixnum w1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(or (eq (aref tokens (+ pos 1)) w1)
(eq (aref tokens (+ pos 2)) w1)))
(progn
(write-log tagger-contextual "NEXT1OR2WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT1OR2OR3TAG")
(let ((t1 (mkkeysym arg1)))
(declare (type symbol t1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(or (eq (svref tags (+ pos 1)) t1)
(eq (svref tags (+ pos 2)) t1)
(eq (svref tags (+ pos 3)) t1)))
(progn
(write-log tagger-contextual "NEXT1OR2OR3TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "NEXT1OR2OR3WD")
(let ((w1 (id-for-token arg1)))
(declare (type fixnum w1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(or (eq (aref tokens (+ pos 1)) w1)
(eq (aref tokens (+ pos 2)) w1)
(eq (aref tokens (+ pos 2)) w1)))
(progn
(write-log tagger-contextual "NEXT1OR2OR3WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREVTAG")
(let ((t1 (mkkeysym arg1)))
(declare (type symbol t1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-array fixnum ) tokens)
#-mcl (type (simple-array symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(eq (svref tags (- pos 1)) t1))
(progn
(write-log tagger-contextual "PREVTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREVWD")
(let ((w1 (id-for-token arg1)))
#-mcl (declare (type fixnum w1))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens (- pos 1)) w1))
(progn
(write-log tagger-contextual "PREVWD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "LBIGRAM")
(let ((w1 (id-for-token arg1))
(w2 (id-for-token arg2)))
#-mcl (declare (type fixnum w1 w2))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (aref tokens (- pos 1)) w2))
(progn
(write-log tagger-contextual "LBIGRAM: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDPREVTAG")
(let ((me (id-for-token arg1))
(t2 (mkkeysym arg2)))
#-mcl (declare (type fixnum me) (type symbol t2))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) me)
(eq (svref tags (- pos 1)) t2))
(progn
(write-log tagger-contextual "WDPREVTAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDAND2BFR")
(let ((w1 (id-for-token arg1))
(w2 (id-for-token arg2)))
#-mcl (declare (type fixnum w1 w2))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (aref tokens (- pos 2)) w2))
(progn
(write-log tagger-contextual "WDAND2BFR: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "WDAND2TAGBFR")
(let ((w1 (id-for-token arg1))
(t2 (mkkeysym arg2)))
#-mcl (declare (type fixnum w1) (type symbol t2))
#'(lambda (tokens tags pos)
(declare #-mcl (type fixnum pos)
#-mcl (type (simple-array fixnum ) tokens)
#-mcl (type (simple-array symbol ) tags)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens pos) w1)
(eq (svref tags (- pos 2)) t2))
(progn
(write-log tagger-contextual "WDAND2TAGBFR: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV2TAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(eq (svref tags (- pos 2)) t1))
(progn
(write-log tagger-contextual "PREV2TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV2WD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(eq (aref tokens (- pos 2)) w1))
(progn
(write-log tagger-contextual "PREV2WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV1OR2TAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(or (eq (svref tags (- pos 1)) t1)
(eq (svref tags (- pos 2)) t1)))
(progn
(write-log tagger-contextual "PREV1OR2TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV1OR2WD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(or (eq (aref tokens (- pos 1)) w1)
(eq (aref tokens (- pos 2)) w1)))
(progn
(write-log tagger-contextual "PREV1OR2WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV1OR2OR3TAG")
(let ((t1 (mkkeysym arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(or (eq (svref tags (- pos 1)) t1)
(eq (svref tags (- pos 2)) t1)
(eq (svref tags (- pos 3)) t1)))
(progn
(write-log tagger-contextual "PREV1OR2OR3TAG: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREV1OR2OR3WD")
(let ((w1 (id-for-token arg1)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0)))
(if (and (eq (svref tags pos) old)
(or (eq (aref tokens (- pos 1)) w1)
(eq (aref tokens (- pos 2)) w1)
(eq (aref tokens (- pos 3)) w1)))
(progn
(write-log tagger-contextual "PREV1OR2OR3WD: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
((string= name "PREVBIGRAM")
(let ((t1 (mkkeysym arg1))
(t2 (mkkeysym arg2)))
#'(lambda (tokens tags pos)
(declare #-mcl (type (simple-vector fixnum ) tokens)
#-mcl (type (simple-vector symbol ) tags)
#-mcl (type fixnum pos)
(optimize speed (safety 0))
(ignore tokens))
(if (and (eq (svref tags pos) old)
(eq (svref tags (- pos 1)) t2)
(eq (svref tags (- pos 2)) t1))
(progn
(write-log tagger-contextual "PREVBIGRAM: ~A @ ~A" contextual-rule pos)
(setf (svref tags pos) new))))))
(t (write-log tagger-contextual "Unrecognized rule: ~A" contextual-rule)))))
|
dc964f50c7f386616143a4686e97dbfd9917dd1c32831ee2268f1247879671e9 | labra/Haws | testShacl.hs | module TestShacl where
import Shacl
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Node)
import Data.Set (Set)
import qualified Data.Set as Set
import RDF
import RDFUtils
import Namespaces
import Sets
import Typing
test_combineTyping1 = combineTypings typing1 typing2 @?= typing
where typing1 = singleTyping (uri_s ":s") (u "shapeC")
typing2 = singleTyping (uri_s ":s") (u "shapeB")
typing = addType (uri_s ":s") (u "shapeC")
( singleTyping (uri_s ":s") (u "shapeB")
)
test_surrounding_1 = surroundingTriples (uri_s ":a") graph1 @?= surrounding_1
where graph1 = Graph( mktriples [ (":a", ":p", ":c")
, (":c", ":r", ":e")
, (":a", ":q", ":d")
, (":d", ":r", ":f")
])
surrounding_1 = mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
]
test_surrounding_2 = surroundingTriples (uri_s ":a") graph2 @?= surrounding_2
where graph2 = Graph (mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
, (":c", ":r", ":a")
])
surrounding_2 = mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
, (":c", ":r", ":a")
]
test_same_object = same_object (uri_s ":a") (triple (":c", ":r", ":a")) @?= True
Schemas
test_empty = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":a", ":b", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_closed_empty_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":a", ":b", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_closed_empty_succeed_empty = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples []
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = noTriples, remaining = noTriples, typing = singleTyping node label }
test_closed_empty_succeed_no_surrounding = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":b", ":p", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = noTriples, remaining = noTriples, typing = singleTyping node label }
test_matchArc_1 = matchArc p vo t ctx @?= [emptyTyping]
where
p = u ":p"
vo = valueSet [u ":a1",u ":a2"]
cs = noTriples
t = triple (":x", ":p", ":a1")
rs = noTriples
typing = singleTyping (uri_s ":x") (u "label")
ctx = Context { schema = emptySchema, graph = emptyGraph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = emptyTyping }
s' = s { checked = insert t cs }
test_arc_single = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t]
rs = noTriples
graph = Graph ts
t = triple (":x", ":p", ":a1")
ts = Set.fromList [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_single_two = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1]
rs = Set.fromList [t2]
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":y")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_1ok_1bad = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1]
rs = Set.fromList [t2]
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":y")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_2ok = head (validate node label ctx) @?= s
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 2))])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1,t2]
rs = Set.fromList []
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_2_2ok = validate node label ctx @?= [s1,s2]
where
schema = Schema (mkset [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 2 2))])
node = uri_s ":x"
label = u "label"
cs = mkset [t1,t2]
rs = mkset []
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s1 = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
s2 = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_3_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2",u ":a3"]) (Range 1 2))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
t3 = triple (":x", ":p", ":a3")
ts = Set.fromList [t1,t2,t3]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_arc_23_1_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2",u ":a3"]) (Range 2 3))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
ts = Set.fromList [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_arc_11 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = ts
rs = noTriples
t1 = triple (":x", ":p", ":a1")
ts = Set.fromList [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_11_rem = validate node label ctx @?= [s]
where
schema = Schema (mkset [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t1]
rs = mkset [t2]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":c1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_and_12 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
And (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = ts
rs = noTriples
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b2")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_or_12_1 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t1]
rs = mkset [t2]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":r", ":c")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_or_12_2 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":r", ":c")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_closed_or_12_12_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label,
Closed
(Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
typ = singleTyping node label
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_xor_12_12_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label,
(Xor (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_xor_12_1 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
(Xor (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
typ = singleTyping node label
cs = mkset [t1,t2]
rs = noTriples
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":c1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_Rec = validate node shapeA ctx @?= [s]
where
schema = Schema (mkset [(shapeA, (Arc (u ":p") (ValueRef shapeA) (Range 1 1)))])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t]
rs = noTriples
t = triple (":x", ":p", ":x")
ts = mkset [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = typ }
test_Ref1 = validate nodeX shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, (Arc (u ":p") (ValueRef shapeB) (Range 1 1)))
,(shapeB, (Arc (u ":q") (valueSet [u ":b"]) (Range 1 1)))
])
nodeX = uri_s ":x"
nodeY = uri_s ":y"
shapeA = u "shapeA"
shapeB = u "shapeB"
graph = Graph ts
typ = addType nodeY shapeB $ singleTyping nodeX shapeA
cs = mkset [t1]
rs = noTriples
t1 = triple (":x", ":p", ":y")
t2 = triple (":y", ":q", ":b")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = typ }
test_Ref2 = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, (Arc (u ":p") (valueSet [u ":a"]) (Range 1 1)))
,(shapeB, (Arc (u ":q") (valueSet [u ":b"]) (Range 1 1)))
])
node = uri_s ":x"
shapeA = u "shapeA"
shapeB = u "shapeB"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t1,t2]
rs = noTriples
t1 = triple (":x", ":p", ":a")
t2 = triple (":y", ":q", ":b")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1], remaining = noTriples, typing = typ }
test_NegRec = validate node shapeA ctx @?= []
where
schema = Schema ( mkset
[(shapeA, (Not (Arc (u ":p") (ValueRef shapeA) (Range 1 1))))
])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t]
rs = noTriples
t = triple (":x", ":p", ":x")
ts = mkset [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t], remaining = noTriples, typing = typ }
test_Group_both = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, Group (And (Arc (u ":p") (ValueType xsd_string) (Range 1 1))
(Arc (u ":q") (ValueType xsd_string) (Range 1 1))) plus
)
])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t1]
rs = noTriples
t1 = tripleLit (":x", ":p", "hi")
t2 = tripleLit (":x", ":q", "bye")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1,t2], remaining = noTriples, typing = typ }
test_arc_string = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, Arc (u ":p") (ValueType xsd_string) (Range 1 1))
])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t1]
rs = noTriples
t1 = tripleLit (":x", ":p", "hi")
ts = mkset [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = ts, remaining = noTriples, typing = typ }
test_SeveralTypes1 = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[ ( shapeA, And (Arc (u ":p") (ValueRef shapeB) (From 1))
(Arc (u ":q") (ValueRef shapeC) (From 1))
)
, ( shapeB, Arc (u ":type") (valueSet [u ":Person"]) (Range 1 1))
, ( shapeC, Arc (u ":type") (valueSet [u ":Student"]) (Range 1 1))
])
node = uri_s ":a"
shapeA = u "shapeA"
shapeB = u "shapeB"
shapeC = u "shapeC"
graph = Graph ts
typ = addType (uri_s ":s") shapeB
( addType (uri_s ":t") shapeC
( singleTyping node shapeA
))
rs = noTriples
t1 = triple (":a", ":p", ":s")
t2 = triple (":a", ":q", ":t")
ts = mkset [ t1, t2
, triple (":s", ":type", ":Person")
, triple (":t", ":type", ":Student")
]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1,t2],
remaining = noTriples,
typing = typ
}
test_SeveralTypes2 = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[ ( shapeA, And (Arc (u ":p") (ValueRef shapeB) (From 1))
(Arc (u ":p") (ValueRef shapeC) (From 1))
)
, ( shapeB, Arc (u ":type") (valueSet [u ":Person"]) (Range 1 1))
, ( shapeC, Arc (u ":type") (valueSet [u ":Student"]) (Range 1 1))
])
node = uri_s ":a"
shapeA = u "shapeA"
shapeB = u "shapeB"
shapeC = u "shapeC"
graph = Graph ts
typ = addTypes (uri_s ":s") [shapeB, shapeC]
( singleTyping node shapeA )
rs = noTriples
t1 = triple (":a", ":p", ":s")
t2 = triple (":a", ":p", ":w")
ts = mkset [ t1
, triple (":s", ":type", ":Person")
, triple (":s", ":type", ":Student")
, t2
]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1],
remaining = mkset [t2],
typing = typ
}
main = defaultMain tests
tests = [ testTyping
, testsGraph
, testsArc
, testsSchema
, testsShapeArc
, testsShapeGroup
, testsIntegration
]
testTyping =
testGroup "Typing" [
testCase "combineTyping1" test_combineTyping1
]
testsGraph =
testGroup "Graph" [
testCase "test_same_object" test_same_object
, testCase "surrounding_1" test_surrounding_1
, testCase "surrounding_2" test_surrounding_2
]
testsArc =
testGroup "ValidateArc" [
testCase "matchArc_1" test_matchArc_1
]
testsShapeArc =
testGroup "ShapeArc" [
testCase "testArcString" test_arc_string
, testCase "test_arc_single" test_arc_single
, testCase "test_arc_single_two" test_arc_single_two
, testCase "test_arc_12_1ok_1bad" test_arc_12_1ok_1bad
, testCase "test_arc_12_2ok" test_arc_12_2ok
, testCase "test_arc_2_2ok" test_arc_2_2ok
, testCase "test_arc_12_3_fail" test_arc_12_3_fail
, testCase "test_arc_23_1_fail" test_arc_23_1_fail
, testCase "test_arc_11" test_arc_11
, testCase "test_arc_11_rem" test_arc_11_rem
]
testsSchema =
testGroup "Schema" [
testCase "test_empty" test_empty
, testCase "test_closed_empty_fail" test_closed_empty_fail
, testCase "test_closed_empty_succeed_empty" test_closed_empty_succeed_empty
, testCase "test_closed_empty_succeed_no_surroounding" test_closed_empty_succeed_no_surrounding
, testCase "test_and12" test_and_12
, testCase "test_or_12_1" test_or_12_1
, testCase "test_or_12_2" test_or_12_2
, testCase "test_closed_or_12_12_fail" test_closed_or_12_12_fail
, testCase "test_xor_12_12_fail" test_xor_12_12_fail
, testCase "test_xor_12_1" test_xor_12_1
, testCase "test_Rec" test_Rec
, testCase "test_Ref1" test_Ref1
, testCase "test_Ref2" test_Ref2
, testCase "test_NegRec" test_NegRec
]
testsShapeGroup =
testGroup "Schema_group" [
testCase "test_Group_both" test_Group_both
]
testsIntegration =
testGroup "Integration" [
testCase "test_SeveralTypes1" test_SeveralTypes1
, testCase "test_SeveralTypes2" test_SeveralTypes2
]
| null | https://raw.githubusercontent.com/labra/Haws/2417adc37522994e2bbb8e9e397481a1f6f4f038/papers/testShacl.hs | haskell | module TestShacl where
import Shacl
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Node)
import Data.Set (Set)
import qualified Data.Set as Set
import RDF
import RDFUtils
import Namespaces
import Sets
import Typing
test_combineTyping1 = combineTypings typing1 typing2 @?= typing
where typing1 = singleTyping (uri_s ":s") (u "shapeC")
typing2 = singleTyping (uri_s ":s") (u "shapeB")
typing = addType (uri_s ":s") (u "shapeC")
( singleTyping (uri_s ":s") (u "shapeB")
)
test_surrounding_1 = surroundingTriples (uri_s ":a") graph1 @?= surrounding_1
where graph1 = Graph( mktriples [ (":a", ":p", ":c")
, (":c", ":r", ":e")
, (":a", ":q", ":d")
, (":d", ":r", ":f")
])
surrounding_1 = mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
]
test_surrounding_2 = surroundingTriples (uri_s ":a") graph2 @?= surrounding_2
where graph2 = Graph (mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
, (":c", ":r", ":a")
])
surrounding_2 = mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
, (":c", ":r", ":a")
]
test_same_object = same_object (uri_s ":a") (triple (":c", ":r", ":a")) @?= True
Schemas
test_empty = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":a", ":b", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_closed_empty_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":a", ":b", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_closed_empty_succeed_empty = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples []
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = noTriples, remaining = noTriples, typing = singleTyping node label }
test_closed_empty_succeed_no_surrounding = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":b", ":p", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = noTriples, remaining = noTriples, typing = singleTyping node label }
test_matchArc_1 = matchArc p vo t ctx @?= [emptyTyping]
where
p = u ":p"
vo = valueSet [u ":a1",u ":a2"]
cs = noTriples
t = triple (":x", ":p", ":a1")
rs = noTriples
typing = singleTyping (uri_s ":x") (u "label")
ctx = Context { schema = emptySchema, graph = emptyGraph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = emptyTyping }
s' = s { checked = insert t cs }
test_arc_single = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t]
rs = noTriples
graph = Graph ts
t = triple (":x", ":p", ":a1")
ts = Set.fromList [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_single_two = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1]
rs = Set.fromList [t2]
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":y")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_1ok_1bad = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1]
rs = Set.fromList [t2]
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":y")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_2ok = head (validate node label ctx) @?= s
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 2))])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1,t2]
rs = Set.fromList []
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_2_2ok = validate node label ctx @?= [s1,s2]
where
schema = Schema (mkset [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 2 2))])
node = uri_s ":x"
label = u "label"
cs = mkset [t1,t2]
rs = mkset []
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s1 = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
s2 = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_3_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2",u ":a3"]) (Range 1 2))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
t3 = triple (":x", ":p", ":a3")
ts = Set.fromList [t1,t2,t3]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_arc_23_1_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2",u ":a3"]) (Range 2 3))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
ts = Set.fromList [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_arc_11 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = ts
rs = noTriples
t1 = triple (":x", ":p", ":a1")
ts = Set.fromList [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_11_rem = validate node label ctx @?= [s]
where
schema = Schema (mkset [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t1]
rs = mkset [t2]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":c1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_and_12 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
And (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = ts
rs = noTriples
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b2")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_or_12_1 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t1]
rs = mkset [t2]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":r", ":c")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_or_12_2 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":r", ":c")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_closed_or_12_12_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label,
Closed
(Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
typ = singleTyping node label
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_xor_12_12_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label,
(Xor (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_xor_12_1 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
(Xor (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
typ = singleTyping node label
cs = mkset [t1,t2]
rs = noTriples
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":c1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_Rec = validate node shapeA ctx @?= [s]
where
schema = Schema (mkset [(shapeA, (Arc (u ":p") (ValueRef shapeA) (Range 1 1)))])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t]
rs = noTriples
t = triple (":x", ":p", ":x")
ts = mkset [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = typ }
test_Ref1 = validate nodeX shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, (Arc (u ":p") (ValueRef shapeB) (Range 1 1)))
,(shapeB, (Arc (u ":q") (valueSet [u ":b"]) (Range 1 1)))
])
nodeX = uri_s ":x"
nodeY = uri_s ":y"
shapeA = u "shapeA"
shapeB = u "shapeB"
graph = Graph ts
typ = addType nodeY shapeB $ singleTyping nodeX shapeA
cs = mkset [t1]
rs = noTriples
t1 = triple (":x", ":p", ":y")
t2 = triple (":y", ":q", ":b")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = typ }
test_Ref2 = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, (Arc (u ":p") (valueSet [u ":a"]) (Range 1 1)))
,(shapeB, (Arc (u ":q") (valueSet [u ":b"]) (Range 1 1)))
])
node = uri_s ":x"
shapeA = u "shapeA"
shapeB = u "shapeB"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t1,t2]
rs = noTriples
t1 = triple (":x", ":p", ":a")
t2 = triple (":y", ":q", ":b")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1], remaining = noTriples, typing = typ }
test_NegRec = validate node shapeA ctx @?= []
where
schema = Schema ( mkset
[(shapeA, (Not (Arc (u ":p") (ValueRef shapeA) (Range 1 1))))
])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t]
rs = noTriples
t = triple (":x", ":p", ":x")
ts = mkset [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t], remaining = noTriples, typing = typ }
test_Group_both = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, Group (And (Arc (u ":p") (ValueType xsd_string) (Range 1 1))
(Arc (u ":q") (ValueType xsd_string) (Range 1 1))) plus
)
])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t1]
rs = noTriples
t1 = tripleLit (":x", ":p", "hi")
t2 = tripleLit (":x", ":q", "bye")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1,t2], remaining = noTriples, typing = typ }
test_arc_string = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, Arc (u ":p") (ValueType xsd_string) (Range 1 1))
])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t1]
rs = noTriples
t1 = tripleLit (":x", ":p", "hi")
ts = mkset [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = ts, remaining = noTriples, typing = typ }
test_SeveralTypes1 = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[ ( shapeA, And (Arc (u ":p") (ValueRef shapeB) (From 1))
(Arc (u ":q") (ValueRef shapeC) (From 1))
)
, ( shapeB, Arc (u ":type") (valueSet [u ":Person"]) (Range 1 1))
, ( shapeC, Arc (u ":type") (valueSet [u ":Student"]) (Range 1 1))
])
node = uri_s ":a"
shapeA = u "shapeA"
shapeB = u "shapeB"
shapeC = u "shapeC"
graph = Graph ts
typ = addType (uri_s ":s") shapeB
( addType (uri_s ":t") shapeC
( singleTyping node shapeA
))
rs = noTriples
t1 = triple (":a", ":p", ":s")
t2 = triple (":a", ":q", ":t")
ts = mkset [ t1, t2
, triple (":s", ":type", ":Person")
, triple (":t", ":type", ":Student")
]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1,t2],
remaining = noTriples,
typing = typ
}
test_SeveralTypes2 = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[ ( shapeA, And (Arc (u ":p") (ValueRef shapeB) (From 1))
(Arc (u ":p") (ValueRef shapeC) (From 1))
)
, ( shapeB, Arc (u ":type") (valueSet [u ":Person"]) (Range 1 1))
, ( shapeC, Arc (u ":type") (valueSet [u ":Student"]) (Range 1 1))
])
node = uri_s ":a"
shapeA = u "shapeA"
shapeB = u "shapeB"
shapeC = u "shapeC"
graph = Graph ts
typ = addTypes (uri_s ":s") [shapeB, shapeC]
( singleTyping node shapeA )
rs = noTriples
t1 = triple (":a", ":p", ":s")
t2 = triple (":a", ":p", ":w")
ts = mkset [ t1
, triple (":s", ":type", ":Person")
, triple (":s", ":type", ":Student")
, t2
]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1],
remaining = mkset [t2],
typing = typ
}
main = defaultMain tests
tests = [ testTyping
, testsGraph
, testsArc
, testsSchema
, testsShapeArc
, testsShapeGroup
, testsIntegration
]
testTyping =
testGroup "Typing" [
testCase "combineTyping1" test_combineTyping1
]
testsGraph =
testGroup "Graph" [
testCase "test_same_object" test_same_object
, testCase "surrounding_1" test_surrounding_1
, testCase "surrounding_2" test_surrounding_2
]
testsArc =
testGroup "ValidateArc" [
testCase "matchArc_1" test_matchArc_1
]
testsShapeArc =
testGroup "ShapeArc" [
testCase "testArcString" test_arc_string
, testCase "test_arc_single" test_arc_single
, testCase "test_arc_single_two" test_arc_single_two
, testCase "test_arc_12_1ok_1bad" test_arc_12_1ok_1bad
, testCase "test_arc_12_2ok" test_arc_12_2ok
, testCase "test_arc_2_2ok" test_arc_2_2ok
, testCase "test_arc_12_3_fail" test_arc_12_3_fail
, testCase "test_arc_23_1_fail" test_arc_23_1_fail
, testCase "test_arc_11" test_arc_11
, testCase "test_arc_11_rem" test_arc_11_rem
]
testsSchema =
testGroup "Schema" [
testCase "test_empty" test_empty
, testCase "test_closed_empty_fail" test_closed_empty_fail
, testCase "test_closed_empty_succeed_empty" test_closed_empty_succeed_empty
, testCase "test_closed_empty_succeed_no_surroounding" test_closed_empty_succeed_no_surrounding
, testCase "test_and12" test_and_12
, testCase "test_or_12_1" test_or_12_1
, testCase "test_or_12_2" test_or_12_2
, testCase "test_closed_or_12_12_fail" test_closed_or_12_12_fail
, testCase "test_xor_12_12_fail" test_xor_12_12_fail
, testCase "test_xor_12_1" test_xor_12_1
, testCase "test_Rec" test_Rec
, testCase "test_Ref1" test_Ref1
, testCase "test_Ref2" test_Ref2
, testCase "test_NegRec" test_NegRec
]
testsShapeGroup =
testGroup "Schema_group" [
testCase "test_Group_both" test_Group_both
]
testsIntegration =
testGroup "Integration" [
testCase "test_SeveralTypes1" test_SeveralTypes1
, testCase "test_SeveralTypes2" test_SeveralTypes2
]
| |
52930b2fbdba03834759040f9e328239b0e44b48d3ecbce238fff1e8fbaef4cc | hyperfiddle/electric | react.clj | (ns dustin.react
(:require
reagent.dom
[reagent.core :as r]))
; 1 translate to reagent
(defn UserGreeting [props] [:h1 "Welcome back!"])
(defn GuestGreeting [props] [:h1 "Please sign up."])
(defn Wrapper [& children] ...)
(defn PromptBrandLogo [isLoggedIn] ...)
(defn Greeting [{:keys [isLoggedIn]}]
[Wrapper [:div [PromptBrandLogo isLoggedIn]]
(if isLoggedIn [UserGreeting {}] [GuestGreeting {}])])
(reagent.dom/render
[Greeting {:isLoggedIn false}]
(.-body js/document))
2 remove the hiccup and use s - expressions
(defn UserGreeting [props] `(:h1 "Welcome back!"))
(defn GuestGreeting [props] `(:h1 "Please sign up."))
(defn Wrapper [& children] ...)
(defn div [& children] ...)
(defn PromptBrandLogo [isLoggedIn] ...)
(defn fib [x]
(Thread/sleep 1000)
(println "done")
`~x)
(defn Greeting [{:keys [isLoggedIn]}]
`(Wrapper [:div (PromptBrandLogo ~isLoggedIn)]
~(if isLoggedIn `(UserGreeting ~{}) `(GuestGreeting ~{}))))
(react/render! `(Greeting false) (.-body js/document))
println 42
(react/render! `(Greeting true) (.-body js/document))
; -
2
(def isLoggedIn (atom false))
(add-watch isLoggedIn :a (fn [_ _ old new]
(react/render! `(Greeting ~@isLoggedIn) (.-body js/document))))
(react/render! `(Greeting ~isLoggedIn) (.-body js/document))
3
(def isLoggedIn (atom false))
(react/render! `(Greeting ~isLoggedIn) (.-body js/document))
println 42
(reset! isLoggedIn true)
; -
(defn reactDomRender [ast $el]
(let [ast1 ast
ast2 (clojure.core/eval ast1) ; runtime eval = interpreter
new-vdom (incremental-eval ast2)] ; interpreter
(println new-vdom)
(reconcile! $el new-vdom)))
(reactDomRender '(Greeting {:isLoggedIn false}) (.-body js/document))
(eval '(Greeting {:isLoggedIn false}))
:= `(Wrapper (div (PromptBrandLogo isLoggedIn))
(fib 40)
(GuestGreeting {}))
; Abstract Syntax Tree vs Tree
; evaluation rules will be provided later to faciliate evaluation of the abstractions
'(Wrapper (div (PromptBrandLogo false)))
[:div.wrapper [:div [:div.logo "you are not loggedin"]]]
(new ReactElement "div" (new ReactElement "div" (new ReactElement "div")))
| null | https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2021/via/react.clj | clojure | 1 translate to reagent
-
-
runtime eval = interpreter
interpreter
Abstract Syntax Tree vs Tree
evaluation rules will be provided later to faciliate evaluation of the abstractions | (ns dustin.react
(:require
reagent.dom
[reagent.core :as r]))
(defn UserGreeting [props] [:h1 "Welcome back!"])
(defn GuestGreeting [props] [:h1 "Please sign up."])
(defn Wrapper [& children] ...)
(defn PromptBrandLogo [isLoggedIn] ...)
(defn Greeting [{:keys [isLoggedIn]}]
[Wrapper [:div [PromptBrandLogo isLoggedIn]]
(if isLoggedIn [UserGreeting {}] [GuestGreeting {}])])
(reagent.dom/render
[Greeting {:isLoggedIn false}]
(.-body js/document))
2 remove the hiccup and use s - expressions
(defn UserGreeting [props] `(:h1 "Welcome back!"))
(defn GuestGreeting [props] `(:h1 "Please sign up."))
(defn Wrapper [& children] ...)
(defn div [& children] ...)
(defn PromptBrandLogo [isLoggedIn] ...)
(defn fib [x]
(Thread/sleep 1000)
(println "done")
`~x)
(defn Greeting [{:keys [isLoggedIn]}]
`(Wrapper [:div (PromptBrandLogo ~isLoggedIn)]
~(if isLoggedIn `(UserGreeting ~{}) `(GuestGreeting ~{}))))
(react/render! `(Greeting false) (.-body js/document))
println 42
(react/render! `(Greeting true) (.-body js/document))
2
(def isLoggedIn (atom false))
(add-watch isLoggedIn :a (fn [_ _ old new]
(react/render! `(Greeting ~@isLoggedIn) (.-body js/document))))
(react/render! `(Greeting ~isLoggedIn) (.-body js/document))
3
(def isLoggedIn (atom false))
(react/render! `(Greeting ~isLoggedIn) (.-body js/document))
println 42
(reset! isLoggedIn true)
(defn reactDomRender [ast $el]
(let [ast1 ast
(println new-vdom)
(reconcile! $el new-vdom)))
(reactDomRender '(Greeting {:isLoggedIn false}) (.-body js/document))
(eval '(Greeting {:isLoggedIn false}))
:= `(Wrapper (div (PromptBrandLogo isLoggedIn))
(fib 40)
(GuestGreeting {}))
'(Wrapper (div (PromptBrandLogo false)))
[:div.wrapper [:div [:div.logo "you are not loggedin"]]]
(new ReactElement "div" (new ReactElement "div" (new ReactElement "div")))
|
a815b5e0c8590c7013fc426ad3db5d195ef361f9c3b4d942483934d4512c105b | vascokk/rivus_cep | rivus_cep_query_worker_tests.erl | -module(rivus_cep_query_worker_tests).
-compile([debug_info, export_all]).
-compile([{parse_transform, lager_transform}]).
-include_lib("eunit/include/eunit.hrl").
-include("rivus_cep.hrl").
query_worker_test_() ->
{setup,
fun () ->
folsom:start(),
lager:start(),
application:start(gproc),
lager:set_loglevel(lager_console_backend, debug),
application:set_env(rivus_cep, rivus_window_provider, rivus_cep_window_ets),
ok = application:start(rivus_cep)
end,
fun (_) ->
folsom:stop(),
application:stop(lager),
application:stop(gproc),
ok = application:stop(rivus_cep)
end,
[{"Test query without aggregations",
fun query_1/0},
{"Test an aggregation query",
fun query_2/0},
{"Test query on event sequence (event pattern matching)",
fun pattern/0}
]
}.
query_1() ->
{ok,SubPid} = result_subscriber:start_link(),
QueryStr = "define correlation1 as
select ev1.eventparam1, ev2.eventparam2, ev2.eventparam3, ev1.eventparam2
from event1 as ev1, event2 as ev2
where ev1.eventparam2 = ev2.eventparam2
within 60 seconds; ",
Mod = application:get_env(rivus_cep, rivus_window_provider, rivus_cep_window_ets),
{ok, Pid} = rivus_cep_window:start_link(Mod),
Window = rivus_cep_window:new(Pid, slide, 60),
{ok, Tokens, Endline} = rivus_cep_scanner:string(QueryStr, 1),
{ok, QueryClauses} = rivus_cep_parser:parse(Tokens),
{ok, QueryPid} = rivus_cep_query_worker:start_link(#query_details{
clauses = QueryClauses,
producers = [test_query_1],
subscribers = [SubPid],
options = [],
event_window = Window,
event_window_pid = Pid,
fsm_window = nil,
window_register = nil}),
Event1 = {event1, 10,b,c},
Event2 = {event1, 15,bbb,c},
Event3 = {event1, 20,b,c},
Event4 = {event2, 30,b,cc,d},
Event5 = {event2, 40,bb,cc,dd},
gproc:send({p, l, {test_query_1, element(1, Event1)}}, Event1),
gproc:send({p, l, {test_query_1, element(1, Event2)}}, Event2),
gproc:send({p, l, {test_query_1, element(1, Event3)}}, Event3),
gproc:send({p, l, {test_query_1, element(1, Event4)}}, Event4),
gproc:send({p, l, {test_query_1, element(1, Event5)}}, Event5),
timer:sleep(2000),
{ok,Values} = gen_server:call(SubPid, get_result),
%% ?debugMsg(io_lib:format("Values: ~p~n",[Values])),
? assertEqual([{10,b , cc , b},{20,b , cc , b } ] , Values ) ,
?assertEqual(2, length(Values)),
?assert(lists:any(fun(T) -> T == {10,b,cc,b} end, Values)),
?assert(lists:any(fun(T) -> T == {20,b,cc,b} end, Values)),
gen_server:call(QueryPid,stop),
gen_server:call(SubPid,stop).
query_2()->
{ok, SubPid} = result_subscriber:start_link(),
QueryStr = "define correlation2 as
select ev1.eventparam1, ev2.eventparam2, sum(ev2.eventparam3)
from event1 as ev1, event2 as ev2
where ev1.eventparam2 = ev2.eventparam2
within 60 seconds; ",
Mod = application:get_env(rivus_cep, rivus_window_provider, rivus_cep_window_ets),
{ok, Pid} = rivus_cep_window:start_link(Mod),
Window = rivus_cep_window:new(Pid, slide, 60),
{ok, Tokens, Endline} = rivus_cep_scanner:string(QueryStr, 1),
{ok, QueryClauses} = rivus_cep_parser:parse(Tokens),
{ok, QueryPid} = rivus_cep_query_worker:start_link(#query_details{
clauses = QueryClauses,
producers = [test_query_2],
subscribers = [SubPid],
options = [],
event_window = Window,
event_window_pid = Pid,
fsm_window = nil,
window_register = nil}),
%% send some events
Event1 = {event1, gr1,b,10},
Event2 = {event1, gr2,bbb,20},
Event3 = {event1, gr3,b,30},
Event4 = {event2, gr1,b,40,d},
Event5 = {event2, gr2,bb,50,dd},
Event6 = {event2, gr3,b,40,d},
gproc:send({p, l, {test_query_2, element(1, Event1)}}, Event1),
gproc:send({p, l, {test_query_2, element(1, Event2)}}, Event2),
gproc:send({p, l, {test_query_2, element(1, Event3)}}, Event3),
gproc:send({p, l, {test_query_2, element(1, Event4)}}, Event4),
gproc:send({p, l, {test_query_2, element(1, Event5)}}, Event5),
gproc:send({p, l, {test_query_2, element(1, Event6)}}, Event6),
timer:sleep(2000),
{ok,Values} = gen_server:call(SubPid, get_result),
%% ?debugMsg(io_lib:format("Values: ~p~n",[Values])),
%%?assertEqual([{gr1,b,80},{gr3,b,80}], Values),
?assertEqual(2, length(Values)),
?assert(lists:any(fun(T) -> T == {gr1,b,80} end, Values)),
?assert(lists:any(fun(T) -> T == {gr3,b,80} end, Values)),
gen_server:call(QueryPid,stop),
gen_server:call(SubPid,stop).
pattern() ->
{ok, SubPid} = result_subscriber:start_link(),
QueryStr = "define pattern1 as
select ev1.eventparam1, ev2.eventparam2, ev2.eventparam3, ev2.eventparam4
from event1 as ev1 -> event2 as ev2
where ev1.eventparam2 = ev2.eventparam2
within 60 seconds; ",
Mod = application:get_env(rivus_cep, rivus_window_provider, rivus_cep_window_ets),
{ok, Pid1} = rivus_cep_window:start_link(Mod),
{ok, Pid2} = rivus_cep_window:start_link(Mod),
Window = rivus_cep_window:new(Pid1, slide, 60),
FsmWindow = rivus_cep_window:new(Pid2, 60),
{ok, Tokens, _Endline} = rivus_cep_scanner:string(QueryStr, 1),
{ok, QueryClauses} = rivus_cep_parser:parse(Tokens),
{ok, QueryPid} = rivus_cep_query_worker:start_link(#query_details{
clauses = QueryClauses,
producers = [test_pattern_1],
subscribers = [SubPid],
options = [],
event_window = Window,
event_window_pid = Pid1,
fsm_window = FsmWindow,
fsm_window_pid = Pid2,
window_register = nil}),
Event1 = {event1, 10,b,10},
Event2 = {event1, 15,bbb,20},
Event3 = {event1, 20,b,10},
Event4 = {event2, 30,b,100,20},
Event5 = {event2, 40,bb,200,30},
gproc:send({p, l, {test_pattern_1, element(1, Event1)}}, Event1),
gproc:send({p, l, {test_pattern_1, element(1, Event2)}}, Event2),
gproc:send({p, l, {test_pattern_1, element(1, Event3)}}, Event3),
gproc:send({p, l, {test_pattern_1, element(1, Event4)}}, Event4),
gproc:send({p, l, {test_pattern_1, element(1, Event5)}}, Event5),
timer:sleep(2000),
{ok,Values} = gen_server:call(SubPid, get_result),
?debugMsg(io_lib:format("Values: ~p~n",[Values])),
?assertEqual([{10,b,100,20},{20,b,100,20}], Values),
gen_server:call(QueryPid,stop),
gen_server:call(SubPid,stop).
| null | https://raw.githubusercontent.com/vascokk/rivus_cep/e9fe6ed79201d852065f7fb2a24a880414031d27/test/rivus_cep_query_worker_tests.erl | erlang | ?debugMsg(io_lib:format("Values: ~p~n",[Values])),
send some events
?debugMsg(io_lib:format("Values: ~p~n",[Values])),
?assertEqual([{gr1,b,80},{gr3,b,80}], Values), | -module(rivus_cep_query_worker_tests).
-compile([debug_info, export_all]).
-compile([{parse_transform, lager_transform}]).
-include_lib("eunit/include/eunit.hrl").
-include("rivus_cep.hrl").
query_worker_test_() ->
{setup,
fun () ->
folsom:start(),
lager:start(),
application:start(gproc),
lager:set_loglevel(lager_console_backend, debug),
application:set_env(rivus_cep, rivus_window_provider, rivus_cep_window_ets),
ok = application:start(rivus_cep)
end,
fun (_) ->
folsom:stop(),
application:stop(lager),
application:stop(gproc),
ok = application:stop(rivus_cep)
end,
[{"Test query without aggregations",
fun query_1/0},
{"Test an aggregation query",
fun query_2/0},
{"Test query on event sequence (event pattern matching)",
fun pattern/0}
]
}.
query_1() ->
{ok,SubPid} = result_subscriber:start_link(),
QueryStr = "define correlation1 as
select ev1.eventparam1, ev2.eventparam2, ev2.eventparam3, ev1.eventparam2
from event1 as ev1, event2 as ev2
where ev1.eventparam2 = ev2.eventparam2
within 60 seconds; ",
Mod = application:get_env(rivus_cep, rivus_window_provider, rivus_cep_window_ets),
{ok, Pid} = rivus_cep_window:start_link(Mod),
Window = rivus_cep_window:new(Pid, slide, 60),
{ok, Tokens, Endline} = rivus_cep_scanner:string(QueryStr, 1),
{ok, QueryClauses} = rivus_cep_parser:parse(Tokens),
{ok, QueryPid} = rivus_cep_query_worker:start_link(#query_details{
clauses = QueryClauses,
producers = [test_query_1],
subscribers = [SubPid],
options = [],
event_window = Window,
event_window_pid = Pid,
fsm_window = nil,
window_register = nil}),
Event1 = {event1, 10,b,c},
Event2 = {event1, 15,bbb,c},
Event3 = {event1, 20,b,c},
Event4 = {event2, 30,b,cc,d},
Event5 = {event2, 40,bb,cc,dd},
gproc:send({p, l, {test_query_1, element(1, Event1)}}, Event1),
gproc:send({p, l, {test_query_1, element(1, Event2)}}, Event2),
gproc:send({p, l, {test_query_1, element(1, Event3)}}, Event3),
gproc:send({p, l, {test_query_1, element(1, Event4)}}, Event4),
gproc:send({p, l, {test_query_1, element(1, Event5)}}, Event5),
timer:sleep(2000),
{ok,Values} = gen_server:call(SubPid, get_result),
? assertEqual([{10,b , cc , b},{20,b , cc , b } ] , Values ) ,
?assertEqual(2, length(Values)),
?assert(lists:any(fun(T) -> T == {10,b,cc,b} end, Values)),
?assert(lists:any(fun(T) -> T == {20,b,cc,b} end, Values)),
gen_server:call(QueryPid,stop),
gen_server:call(SubPid,stop).
query_2()->
{ok, SubPid} = result_subscriber:start_link(),
QueryStr = "define correlation2 as
select ev1.eventparam1, ev2.eventparam2, sum(ev2.eventparam3)
from event1 as ev1, event2 as ev2
where ev1.eventparam2 = ev2.eventparam2
within 60 seconds; ",
Mod = application:get_env(rivus_cep, rivus_window_provider, rivus_cep_window_ets),
{ok, Pid} = rivus_cep_window:start_link(Mod),
Window = rivus_cep_window:new(Pid, slide, 60),
{ok, Tokens, Endline} = rivus_cep_scanner:string(QueryStr, 1),
{ok, QueryClauses} = rivus_cep_parser:parse(Tokens),
{ok, QueryPid} = rivus_cep_query_worker:start_link(#query_details{
clauses = QueryClauses,
producers = [test_query_2],
subscribers = [SubPid],
options = [],
event_window = Window,
event_window_pid = Pid,
fsm_window = nil,
window_register = nil}),
Event1 = {event1, gr1,b,10},
Event2 = {event1, gr2,bbb,20},
Event3 = {event1, gr3,b,30},
Event4 = {event2, gr1,b,40,d},
Event5 = {event2, gr2,bb,50,dd},
Event6 = {event2, gr3,b,40,d},
gproc:send({p, l, {test_query_2, element(1, Event1)}}, Event1),
gproc:send({p, l, {test_query_2, element(1, Event2)}}, Event2),
gproc:send({p, l, {test_query_2, element(1, Event3)}}, Event3),
gproc:send({p, l, {test_query_2, element(1, Event4)}}, Event4),
gproc:send({p, l, {test_query_2, element(1, Event5)}}, Event5),
gproc:send({p, l, {test_query_2, element(1, Event6)}}, Event6),
timer:sleep(2000),
{ok,Values} = gen_server:call(SubPid, get_result),
?assertEqual(2, length(Values)),
?assert(lists:any(fun(T) -> T == {gr1,b,80} end, Values)),
?assert(lists:any(fun(T) -> T == {gr3,b,80} end, Values)),
gen_server:call(QueryPid,stop),
gen_server:call(SubPid,stop).
pattern() ->
{ok, SubPid} = result_subscriber:start_link(),
QueryStr = "define pattern1 as
select ev1.eventparam1, ev2.eventparam2, ev2.eventparam3, ev2.eventparam4
from event1 as ev1 -> event2 as ev2
where ev1.eventparam2 = ev2.eventparam2
within 60 seconds; ",
Mod = application:get_env(rivus_cep, rivus_window_provider, rivus_cep_window_ets),
{ok, Pid1} = rivus_cep_window:start_link(Mod),
{ok, Pid2} = rivus_cep_window:start_link(Mod),
Window = rivus_cep_window:new(Pid1, slide, 60),
FsmWindow = rivus_cep_window:new(Pid2, 60),
{ok, Tokens, _Endline} = rivus_cep_scanner:string(QueryStr, 1),
{ok, QueryClauses} = rivus_cep_parser:parse(Tokens),
{ok, QueryPid} = rivus_cep_query_worker:start_link(#query_details{
clauses = QueryClauses,
producers = [test_pattern_1],
subscribers = [SubPid],
options = [],
event_window = Window,
event_window_pid = Pid1,
fsm_window = FsmWindow,
fsm_window_pid = Pid2,
window_register = nil}),
Event1 = {event1, 10,b,10},
Event2 = {event1, 15,bbb,20},
Event3 = {event1, 20,b,10},
Event4 = {event2, 30,b,100,20},
Event5 = {event2, 40,bb,200,30},
gproc:send({p, l, {test_pattern_1, element(1, Event1)}}, Event1),
gproc:send({p, l, {test_pattern_1, element(1, Event2)}}, Event2),
gproc:send({p, l, {test_pattern_1, element(1, Event3)}}, Event3),
gproc:send({p, l, {test_pattern_1, element(1, Event4)}}, Event4),
gproc:send({p, l, {test_pattern_1, element(1, Event5)}}, Event5),
timer:sleep(2000),
{ok,Values} = gen_server:call(SubPid, get_result),
?debugMsg(io_lib:format("Values: ~p~n",[Values])),
?assertEqual([{10,b,100,20},{20,b,100,20}], Values),
gen_server:call(QueryPid,stop),
gen_server:call(SubPid,stop).
|
bd38b689e1d124ec0561b0786272a0cc3f361340238794d8b1079feaa9e46c26 | scicloj/metamorph.ml | learning_curve_test.clj | (ns scicloj.metamorph.learning-curve-test
(:require [clojure.test :as t]
[tech.v3.dataset]
[scicloj.metamorph.core :as mm]
[tech.v3.dataset.metamorph :as mds]
[tablecloth.api :as tc]
[tablecloth.pipeline :as tc-mm]
[scicloj.metamorph.ml]
[scicloj.metamorph.ml.loss]
[scicloj.metamorph.ml.learning-curve :as lc]
[scicloj.ml.smile.classification]
[scicloj.metamorph.ml.loss :as loss]))
(def titanic-train
(->
(tech.v3.dataset/->dataset "-examples/raw/main/data/titanic/train.csv"
{:key-fn keyword})
(tc/shuffle {:seed 1234})))
(def pipe-fn
(mm/pipeline
(mds/select-columns [:Pclass :Survived :Embarked :Sex])
(tc-mm/add-or-replace-column :Survived (fn [ds] (map #(case %
1 "yes"
0 "no")
(:Survived ds))))
(mds/categorical->number [:Survived :Sex :Embarked])
(mds/set-inference-target :Survived)
{:metamorph/id :model}
(scicloj.metamorph.ml/model {:model-type :smile.classification/random-forest})))
(t/deftest test-learnining-curve []
(let [lc
(lc/learning-curve titanic-train
pipe-fn
(range 0.3 1 0.3)
{:k 3
:metric-fn loss/classification-accuracy
:loss-or-accuracy :accuracy})]
(t/is (= [:metric-train :train-size-index :metric-test :test-ds-size :train-ds-size]
(tc/column-names lc)))
(t/is (= {"1" 3, "2" 3, "0" 3}
(frequencies (:train-size-index lc))))))
| null | https://raw.githubusercontent.com/scicloj/metamorph.ml/14a5430dc90ee4757c1c21fd4f916a4fad68ae9e/test/scicloj/metamorph/learning_curve_test.clj | clojure | (ns scicloj.metamorph.learning-curve-test
(:require [clojure.test :as t]
[tech.v3.dataset]
[scicloj.metamorph.core :as mm]
[tech.v3.dataset.metamorph :as mds]
[tablecloth.api :as tc]
[tablecloth.pipeline :as tc-mm]
[scicloj.metamorph.ml]
[scicloj.metamorph.ml.loss]
[scicloj.metamorph.ml.learning-curve :as lc]
[scicloj.ml.smile.classification]
[scicloj.metamorph.ml.loss :as loss]))
(def titanic-train
(->
(tech.v3.dataset/->dataset "-examples/raw/main/data/titanic/train.csv"
{:key-fn keyword})
(tc/shuffle {:seed 1234})))
(def pipe-fn
(mm/pipeline
(mds/select-columns [:Pclass :Survived :Embarked :Sex])
(tc-mm/add-or-replace-column :Survived (fn [ds] (map #(case %
1 "yes"
0 "no")
(:Survived ds))))
(mds/categorical->number [:Survived :Sex :Embarked])
(mds/set-inference-target :Survived)
{:metamorph/id :model}
(scicloj.metamorph.ml/model {:model-type :smile.classification/random-forest})))
(t/deftest test-learnining-curve []
(let [lc
(lc/learning-curve titanic-train
pipe-fn
(range 0.3 1 0.3)
{:k 3
:metric-fn loss/classification-accuracy
:loss-or-accuracy :accuracy})]
(t/is (= [:metric-train :train-size-index :metric-test :test-ds-size :train-ds-size]
(tc/column-names lc)))
(t/is (= {"1" 3, "2" 3, "0" 3}
(frequencies (:train-size-index lc))))))
| |
6f19882fcf9528dc2e6fe92af520bd5626aaea614ae79d4b6d0222f2e47dd188 | theodormoroianu/SecondYearCourses | HaskellChurch_20210415162211.hs | {-# LANGUAGE RankNTypes #-}
module HaskellChurch where
A boolean is any way to choose between two alternatives
newtype CBool = CBool {cIf :: forall t. t -> t -> t}
An instance to show as regular Booleans
instance Show CBool where
show b = show $ cIf b True False
The boolean constant true always chooses the first alternative
cTrue :: CBool
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: CBool
cFalse = undefined
--The boolean negation switches the alternatives
cNot :: CBool -> CBool
cNot = undefined
--The boolean conjunction can be built as a conditional
(&&:) :: CBool -> CBool -> CBool
(&&:) = undefined
infixr 3 &&:
--The boolean disjunction can be built as a conditional
(||:) :: CBool -> CBool -> CBool
(||:) = undefined
infixr 2 ||:
-- a pair is a way to compute something based on the values
-- contained within the pair.
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
An instance to show CPairs as regular pairs .
instance (Show a, Show b) => Show (CPair a b) where
show p = show $ cOn p (,)
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: a -> b -> CPair a b
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: CPair a b -> a
cFst = undefined
second projection
cSnd :: CPair a b -> b
cSnd = undefined
-- A natural number is any way to iterate a function s a number of times
-- over an initial value z
newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t }
-- An instance to show CNats as regular natural numbers
instance Show CNat where
show n = show $ cFor n (1 +) (0 :: Integer)
--0 will iterate the function s 0 times over z, producing z
c0 :: CNat
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: CNat
c1 = undefined
--Successor n either
- applies s one more time in addition to what n does
-- - iterates s n times over (s z)
cS :: CNat -> CNat
cS = undefined
--Addition of m and n is done by iterating s n times over m
(+:) :: CNat -> CNat -> CNat
(+:) = undefined
infixl 6 +:
--Multiplication of m and n can be done by composing n and m
(*:) :: CNat -> CNat -> CNat
(*:) = \n m -> CNat $ cFor n . cFor m
infixl 7 *:
--Exponentiation of m and n can be done by applying n to m
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (\_ -> cFalse) cTrue
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: CNat -> CNat
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
-- of the predeccesor function
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) => p -> CNat
cNat n = undefined
We can define an instance Num CNat which will allow us to see any
integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular
-- arithmetic
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
-- m is less than (or equal to) n if when substracting n from m we get 0
(<=:) :: CNat -> CNat -> CBool
(<=:) = undefined
infix 4 <=:
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
-- equality on naturals can be defined my means of comparisons
(==:) :: CNat -> CNat -> CBool
(==:) = undefined
--Fun with arithmetic and pairs
--Define factorial. You can iterate over a pair to contain the current index and so far factorial
cFactorial :: CNat -> CNat
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: CNat -> CNat
cFibonacci = undefined
--Define
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurch_20210415162211.hs | haskell | # LANGUAGE RankNTypes #
The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
a pair is a way to compute something based on the values
contained within the pair.
a function to be applied on the values, it will apply it on them.
A natural number is any way to iterate a function s a number of times
over an initial value z
An instance to show CNats as regular natural numbers
0 will iterate the function s 0 times over z, producing z
Successor n either
- iterates s n times over (s z)
Addition of m and n is done by iterating s n times over m
Multiplication of m and n can be done by composing n and m
Exponentiation of m and n can be done by applying n to m
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
of the predeccesor function
arithmetic
m is less than (or equal to) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons
Fun with arithmetic and pairs
Define factorial. You can iterate over a pair to contain the current index and so far factorial
Define | module HaskellChurch where
A boolean is any way to choose between two alternatives
newtype CBool = CBool {cIf :: forall t. t -> t -> t}
An instance to show as regular Booleans
instance Show CBool where
show b = show $ cIf b True False
The boolean constant true always chooses the first alternative
cTrue :: CBool
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: CBool
cFalse = undefined
cNot :: CBool -> CBool
cNot = undefined
(&&:) :: CBool -> CBool -> CBool
(&&:) = undefined
infixr 3 &&:
(||:) :: CBool -> CBool -> CBool
(||:) = undefined
infixr 2 ||:
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
An instance to show CPairs as regular pairs .
instance (Show a, Show b) => Show (CPair a b) where
show p = show $ cOn p (,)
builds a pair out of two values as an object which , when given
cPair :: a -> b -> CPair a b
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: CPair a b -> a
cFst = undefined
second projection
cSnd :: CPair a b -> b
cSnd = undefined
newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t }
instance Show CNat where
show n = show $ cFor n (1 +) (0 :: Integer)
c0 :: CNat
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: CNat
c1 = undefined
- applies s one more time in addition to what n does
cS :: CNat -> CNat
cS = undefined
(+:) :: CNat -> CNat -> CNat
(+:) = undefined
infixl 6 +:
(*:) :: CNat -> CNat -> CNat
(*:) = \n m -> CNat $ cFor n . cFor m
infixl 7 *:
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (\_ -> cFalse) cTrue
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: CNat -> CNat
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) => p -> CNat
cNat n = undefined
We can define an instance Num CNat which will allow us to see any
integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
(<=:) :: CNat -> CNat -> CBool
(<=:) = undefined
infix 4 <=:
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
(==:) :: CNat -> CNat -> CBool
(==:) = undefined
cFactorial :: CNat -> CNat
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: CNat -> CNat
cFibonacci = undefined
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
|
215f3473cd6111e425b9a39c1331d5bda13957f0974e36f952006f73aa1d34a4 | colah/Haskell-Re-Syntaxed | brainstorm.hs |
Type Synonyms , type families , GADTs , Kind Sigs ...
-- ... Can be a lot nicer.
-- Summary:
-- * synonyms are syntacticly like functions,
-- except upper case names
-- * type families are like functions, just as
-- synonyms but with cases.
* GADTs are block like .
-- synonym
Foo :: Type -> Type
Foo a = (a, a -> a, Int)
GADT
List :: Type -> Type
List = data
Null :: List a
Cons :: a -> List a -> List a
-- type family
Bar :: Type -> Type
Bar Int = String
Bar String = Int
-- instead of this monstrosity:
type family Bar a :: *
type instance Bar Int = String
type instance Bar String = Int
-- constraints can be guards :)
-- They're *kind of* like Type -> Bool
Bar2 :: Type -> Type
Bar2 a | Show a = a
Bar2 _ = ()
-- With constraint kinds...
NumShow :: Type -> Constraint
NumShow a = (Show a, Num a)
-- Instead of the non-trivially unintuitive:
NumShow :: * -> Constraint
type NumShow a = (Show a, Num a)
-- Instance declarations
Num [a] | Num a = instance
(+) = zipWith (+)
...
-- You get the idea.
-- Scoped type variables by default.
-- I can't imagine why they aren't
-- It makes it much easier to catch bugs
-- inside complicated code.
foo :: Eq a => [a] -> a -> [a]
foo l e =
let
l' :: [a]
l' = filter (== e) l
in
l' ++ l' ++ l'
-- That summarizes the type level stuff.
-- I have less ideas about values, but...
-- Why do we only have _ in patterns?
curry = _ (_, _)
-- There are *lots* of silly re-organizational functions that are unneeded if you have this.
-- Also lots of code like this:
f x y z = g x y z 1
-- Can be replaced with:
f = g _ _ _ 1
-- This can also make type level things clearer....
Monad [_] = instance ...
Functor [_] = instance ...
Functor (a, _) = instance ...
Because what were people thinking with [ ] ? ! ? !
-- One still has the strangeness of this not being valid:
Functor (_, a) = instance ...
-- But it's just like with not being able to declare certain synonym instances.
Serious consideration for synonym names for Monad and Functor ( DoAble , ? )
-- What do you think? What would you change?
| null | https://raw.githubusercontent.com/colah/Haskell-Re-Syntaxed/d78645b685ef6e1108a54e9e70b4f5b4f3c8dc70/brainstorm.hs | haskell | ... Can be a lot nicer.
Summary:
* synonyms are syntacticly like functions,
except upper case names
* type families are like functions, just as
synonyms but with cases.
synonym
type family
instead of this monstrosity:
constraints can be guards :)
They're *kind of* like Type -> Bool
With constraint kinds...
Instead of the non-trivially unintuitive:
Instance declarations
You get the idea.
Scoped type variables by default.
I can't imagine why they aren't
It makes it much easier to catch bugs
inside complicated code.
That summarizes the type level stuff.
I have less ideas about values, but...
Why do we only have _ in patterns?
There are *lots* of silly re-organizational functions that are unneeded if you have this.
Also lots of code like this:
Can be replaced with:
This can also make type level things clearer....
One still has the strangeness of this not being valid:
But it's just like with not being able to declare certain synonym instances.
What do you think? What would you change? |
Type Synonyms , type families , GADTs , Kind Sigs ...
* GADTs are block like .
Foo :: Type -> Type
Foo a = (a, a -> a, Int)
GADT
List :: Type -> Type
List = data
Null :: List a
Cons :: a -> List a -> List a
Bar :: Type -> Type
Bar Int = String
Bar String = Int
type family Bar a :: *
type instance Bar Int = String
type instance Bar String = Int
Bar2 :: Type -> Type
Bar2 a | Show a = a
Bar2 _ = ()
NumShow :: Type -> Constraint
NumShow a = (Show a, Num a)
NumShow :: * -> Constraint
type NumShow a = (Show a, Num a)
Num [a] | Num a = instance
(+) = zipWith (+)
...
foo :: Eq a => [a] -> a -> [a]
foo l e =
let
l' :: [a]
l' = filter (== e) l
in
l' ++ l' ++ l'
curry = _ (_, _)
f x y z = g x y z 1
f = g _ _ _ 1
Monad [_] = instance ...
Functor [_] = instance ...
Functor (a, _) = instance ...
Because what were people thinking with [ ] ? ! ? !
Functor (_, a) = instance ...
Serious consideration for synonym names for Monad and Functor ( DoAble , ? )
|
ba9db05a758205c5fa25c3389908d4bface311fedfc0d6687bb100c488be5537 | dalaing/little-languages | Infer.hs | |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
module Component.Term.Infer (
InferRule(..)
, InferInput(..)
, InferOutput
, HasInferOutput(..)
, InferStack
, runInfer
, mkInfer
) where
import Data.Foldable (asum)
import Data.Maybe (fromMaybe)
import Control.Lens.TH (makeClassy)
import Control.Monad.Error.Lens (throwing)
import Control.Monad.Except (MonadError, Except, runExcept)
import Control.Monad.Reader (MonadReader, ReaderT(..))
import Data.Constraint
import Component.Type.Error.UnknownType.Class (AsUnknownType (..))
import Component.Type.Note.Strip (StripNoteType(..))
import Extras (Eq1(..))
newtype InferStack r e n a =
InferStack { getInfer :: ReaderT (r n String) (Except (e n String)) a}
deriving (Functor, Applicative, Monad, MonadReader (r n String), MonadError (e n String))
runInfer :: r n String
-> InferStack r e n a
-> Either (e n String) a
runInfer r =
runExcept .
flip runReaderT r .
getInfer
-- |
data InferRule r e ty tm =
InferBase (forall n. Eq n => tm n n String -> Maybe (InferStack r e n (ty n))) -- ^
| InferRecurse (forall n. Eq n => (ty n -> ty n) -> (tm n n String -> InferStack r e n (ty n)) -> tm n n String -> Maybe (InferStack r e n (ty n))) -- ^
-- |
fixInferRule :: Eq n
=> (ty n -> ty n)
-> (tm n n String -> InferStack r e n (ty n))
-> InferRule r e ty tm
-> tm n n String
-> Maybe (InferStack r e n (ty n))
fixInferRule _ _ (InferBase f) x =
f x
fixInferRule strip step (InferRecurse f) x =
f strip step x
-- |
data InferInput r e ty tm =
InferInput [InferRule r e ty tm] -- ^
instance Monoid (InferInput r e ty tm) where
mempty =
InferInput mempty
mappend (InferInput v1) (InferInput v2) =
InferInput (mappend v1 v2)
-- |
data InferOutput r e ty tm =
InferOutput {
_infer :: forall n. Eq n => tm n n String -> InferStack r e n (ty n) -- ^
, _inferRules :: forall n. Eq n => [tm n n String -> Maybe (InferStack r e n (ty n))] -- ^
}
makeClassy ''InferOutput
-- |
mkInfer :: forall r e ty tm. (
Eq1 ty
, AsUnknownType e
, StripNoteType ty ty
)
=> InferInput r e ty tm -- ^
-> InferOutput r e ty tm -- ^
mkInfer (InferInput i) =
let
inferRules' :: forall n. Eq n => [tm n n String -> Maybe (InferStack r e n (ty n))]
inferRules' =
fmap (fixInferRule stripNoteType infer' \\ (spanEq1 :: Eq n :- Eq (ty n))) i
infer' :: forall n. Eq n => tm n n String -> InferStack r e n (ty n)
infer' tm =
fromMaybe (throwing _UnknownType ()) .
asum .
fmap ($ tm) $
inferRules'
in
InferOutput
infer'
inferRules'
| null | https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/modular/common-lang/src/Component/Term/Infer.hs | haskell | # LANGUAGE TemplateHaskell #
# LANGUAGE RankNTypes #
|
^
^
|
|
^
|
^
^
|
^
^ | |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
module Component.Term.Infer (
InferRule(..)
, InferInput(..)
, InferOutput
, HasInferOutput(..)
, InferStack
, runInfer
, mkInfer
) where
import Data.Foldable (asum)
import Data.Maybe (fromMaybe)
import Control.Lens.TH (makeClassy)
import Control.Monad.Error.Lens (throwing)
import Control.Monad.Except (MonadError, Except, runExcept)
import Control.Monad.Reader (MonadReader, ReaderT(..))
import Data.Constraint
import Component.Type.Error.UnknownType.Class (AsUnknownType (..))
import Component.Type.Note.Strip (StripNoteType(..))
import Extras (Eq1(..))
newtype InferStack r e n a =
InferStack { getInfer :: ReaderT (r n String) (Except (e n String)) a}
deriving (Functor, Applicative, Monad, MonadReader (r n String), MonadError (e n String))
runInfer :: r n String
-> InferStack r e n a
-> Either (e n String) a
runInfer r =
runExcept .
flip runReaderT r .
getInfer
data InferRule r e ty tm =
fixInferRule :: Eq n
=> (ty n -> ty n)
-> (tm n n String -> InferStack r e n (ty n))
-> InferRule r e ty tm
-> tm n n String
-> Maybe (InferStack r e n (ty n))
fixInferRule _ _ (InferBase f) x =
f x
fixInferRule strip step (InferRecurse f) x =
f strip step x
data InferInput r e ty tm =
instance Monoid (InferInput r e ty tm) where
mempty =
InferInput mempty
mappend (InferInput v1) (InferInput v2) =
InferInput (mappend v1 v2)
data InferOutput r e ty tm =
InferOutput {
}
makeClassy ''InferOutput
mkInfer :: forall r e ty tm. (
Eq1 ty
, AsUnknownType e
, StripNoteType ty ty
)
mkInfer (InferInput i) =
let
inferRules' :: forall n. Eq n => [tm n n String -> Maybe (InferStack r e n (ty n))]
inferRules' =
fmap (fixInferRule stripNoteType infer' \\ (spanEq1 :: Eq n :- Eq (ty n))) i
infer' :: forall n. Eq n => tm n n String -> InferStack r e n (ty n)
infer' tm =
fromMaybe (throwing _UnknownType ()) .
asum .
fmap ($ tm) $
inferRules'
in
InferOutput
infer'
inferRules'
|
9bdb509a26ec6a05a3dd610e98b4430019c460516fd796b75924429f6c7eab0e | FranklinChen/hugs98-plus-Sep2006 | Strict.hs | -- | Produces XHTML 1.0 Strict.
module Text.XHtml.Strict (
-- * Data types
Html, HtmlAttr,
-- * Classes
HTML(..), ADDATTRS(..),
-- * Primitives and basic combinators
(<<), concatHtml, (+++),
noHtml, isNoHtml, tag, itag,
emptyAttr, intAttr, strAttr,
primHtml,
-- * Rendering
showHtml, renderHtml, prettyHtml,
showHtmlFragment, renderHtmlFragment, prettyHtmlFragment,
module Text.XHtml.Strict.Elements,
module Text.XHtml.Strict.Attributes,
module Text.XHtml.Extras
) where
import Text.XHtml.Internals
import Text.XHtml.Strict.Elements
import Text.XHtml.Strict.Attributes
import Text.XHtml.Extras
docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
++ " \"-strict.dtd\">"
-- | Output the HTML without adding newlines or spaces within the markup.
-- This should be the most time and space efficient way to
-- render HTML, though the ouput is quite unreadable.
showHtml :: HTML html => html -> String
showHtml = showHtmlInternal docType
-- | Outputs indented HTML. Because space matters in
-- HTML, the output is quite messy.
renderHtml :: HTML html => html -> String
renderHtml = renderHtmlInternal docType
-- | Outputs indented HTML, with indentation inside elements.
-- This can change the meaning of the HTML document, and
-- is mostly useful for debugging the HTML output.
-- The implementation is inefficient, and you are normally
-- better off using 'showHtml' or 'renderHtml'.
prettyHtml :: HTML html => html -> String
prettyHtml = prettyHtmlInternal docType
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/xhtml/Text/XHtml/Strict.hs | haskell | | Produces XHTML 1.0 Strict.
* Data types
* Classes
* Primitives and basic combinators
* Rendering
| Output the HTML without adding newlines or spaces within the markup.
This should be the most time and space efficient way to
render HTML, though the ouput is quite unreadable.
| Outputs indented HTML. Because space matters in
HTML, the output is quite messy.
| Outputs indented HTML, with indentation inside elements.
This can change the meaning of the HTML document, and
is mostly useful for debugging the HTML output.
The implementation is inefficient, and you are normally
better off using 'showHtml' or 'renderHtml'. | module Text.XHtml.Strict (
Html, HtmlAttr,
HTML(..), ADDATTRS(..),
(<<), concatHtml, (+++),
noHtml, isNoHtml, tag, itag,
emptyAttr, intAttr, strAttr,
primHtml,
showHtml, renderHtml, prettyHtml,
showHtmlFragment, renderHtmlFragment, prettyHtmlFragment,
module Text.XHtml.Strict.Elements,
module Text.XHtml.Strict.Attributes,
module Text.XHtml.Extras
) where
import Text.XHtml.Internals
import Text.XHtml.Strict.Elements
import Text.XHtml.Strict.Attributes
import Text.XHtml.Extras
docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
++ " \"-strict.dtd\">"
showHtml :: HTML html => html -> String
showHtml = showHtmlInternal docType
renderHtml :: HTML html => html -> String
renderHtml = renderHtmlInternal docType
prettyHtml :: HTML html => html -> String
prettyHtml = prettyHtmlInternal docType
|
123c11d177919506375f3f55de1e478cde33c3b5d338609c47feee60f4045e8b | janestreet/universe | prim.mli | (** Specification of primitive types *)
open Shexp_sexp.Std
module Args : sig
module Spec : sig
module Arg : sig
type 'a t =
| A of ('a -> Sexp.t)
| L of string * ('a -> Sexp.t)
(** L for Labeled *)
| O of string * ('a -> Sexp.t) * 'a
(** O for Optional *)
end
type 'a t =
| [] : 'a t
| ( :: ) : 'a Arg.t * 'b t -> ('a -> 'b) t
end
type ('a, 'b) t =
| A0 : unit -> ('a, 'a) t
| A1 : 'a -> ('a -> 'b, 'b) t
| A2 : 'a * 'b -> ('a -> 'b -> 'c, 'c) t
| A3 : 'a * 'b * 'c -> ('a -> 'b -> 'c -> 'd, 'd) t
| A4 : 'a * 'b * 'c * 'd -> ('a -> 'b -> 'c -> 'd -> 'e, 'e) t
| A5 : 'a * 'b * 'c * 'd * 'e -> ('a -> 'b -> 'c -> 'd -> 'e -> 'f, 'f) t
val apply : ('env -> 'a) -> 'env -> ('a, 'b) t -> 'b
end
module Result_spec : sig
type 'a t =
| Unit : unit t
| Env : Env.t t
| F : ('a -> Sexp.t) -> 'a t
end
(* The type is exposed to solve generalization problems *)
type ('a, 'b) t =
{ name : string
; args : 'a Args.Spec.t
; result : 'b Result_spec.t
; run : Env.t -> 'a
}
val make
: string
-> 'a Args.Spec.t
-> 'b Result_spec.t
-> (Env.t -> 'a)
-> ('a, 'b) t
val run : ('a, 'b) t -> Env.t -> ('a, 'b) Args.t -> 'b
val sexp_of_call : ('a, 'b) t -> ('a, 'b) Args.t -> Sexp.t
(** Returns [None] if the result is [Unit] or [Env] *)
val sexp_of_result : ('a, 'b) t -> 'b -> Sexp.t option
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/shexp/process-lib/src/prim.mli | ocaml | * Specification of primitive types
* L for Labeled
* O for Optional
The type is exposed to solve generalization problems
* Returns [None] if the result is [Unit] or [Env] |
open Shexp_sexp.Std
module Args : sig
module Spec : sig
module Arg : sig
type 'a t =
| A of ('a -> Sexp.t)
| L of string * ('a -> Sexp.t)
| O of string * ('a -> Sexp.t) * 'a
end
type 'a t =
| [] : 'a t
| ( :: ) : 'a Arg.t * 'b t -> ('a -> 'b) t
end
type ('a, 'b) t =
| A0 : unit -> ('a, 'a) t
| A1 : 'a -> ('a -> 'b, 'b) t
| A2 : 'a * 'b -> ('a -> 'b -> 'c, 'c) t
| A3 : 'a * 'b * 'c -> ('a -> 'b -> 'c -> 'd, 'd) t
| A4 : 'a * 'b * 'c * 'd -> ('a -> 'b -> 'c -> 'd -> 'e, 'e) t
| A5 : 'a * 'b * 'c * 'd * 'e -> ('a -> 'b -> 'c -> 'd -> 'e -> 'f, 'f) t
val apply : ('env -> 'a) -> 'env -> ('a, 'b) t -> 'b
end
module Result_spec : sig
type 'a t =
| Unit : unit t
| Env : Env.t t
| F : ('a -> Sexp.t) -> 'a t
end
type ('a, 'b) t =
{ name : string
; args : 'a Args.Spec.t
; result : 'b Result_spec.t
; run : Env.t -> 'a
}
val make
: string
-> 'a Args.Spec.t
-> 'b Result_spec.t
-> (Env.t -> 'a)
-> ('a, 'b) t
val run : ('a, 'b) t -> Env.t -> ('a, 'b) Args.t -> 'b
val sexp_of_call : ('a, 'b) t -> ('a, 'b) Args.t -> Sexp.t
val sexp_of_result : ('a, 'b) t -> 'b -> Sexp.t option
|
ab7ee1656a0c408f2cc6ff58fd33e3a95a75cbee030b11cbce03c81874488e23 | phoe-trash/gateway | unknown-command.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; GATEWAY
" phoe " Herda 2016
(in-package #:gateway)
#|
Error UNKNOWN-COMMAND
Should be signaled when the system attempts to execute a command that is
not present on the system.
This error is usually not signaled from within the command context, but from
the operation context and should be signaled by invoking the function
HANDLE-GATEWAY-ERROR on a condition instance.
Arguments:
* COMMAND: the command not found on the server.
|#
(define-gateway-error unknown-command
((command :reader unknown-command-command
:initarg :command
:initform (error "Must provide command.")))
(owner connection condition)
(((command (unknown-command-command condition)))
("Unknown command: ~S." command)
(declare (ignore owner))
(data-send connection `(:error :type :unknown-command :command ,command))))
(deftest test-error-unknown-command
(with-crown-and-connections crown (connection) ()
(data-send connection `(:foo :bar :baz))
(is (wait () (data-equal (data-receive connection)
`(:error :type :unknown-command :command :foo))))
(data-send connection `(:unknown-command))
(is (wait () (data-equal (data-receive connection)
`(:error :type :unknown-command :command :unknown-command))))))
| null | https://raw.githubusercontent.com/phoe-trash/gateway/a8d579ccbafcaee8678caf59d365ec2eab0b1a7e/_old/errors/unknown-command.lisp | lisp |
GATEWAY
Error UNKNOWN-COMMAND
Should be signaled when the system attempts to execute a command that is
not present on the system.
This error is usually not signaled from within the command context, but from
the operation context and should be signaled by invoking the function
HANDLE-GATEWAY-ERROR on a condition instance.
Arguments:
* COMMAND: the command not found on the server.
| " phoe " Herda 2016
(in-package #:gateway)
(define-gateway-error unknown-command
((command :reader unknown-command-command
:initarg :command
:initform (error "Must provide command.")))
(owner connection condition)
(((command (unknown-command-command condition)))
("Unknown command: ~S." command)
(declare (ignore owner))
(data-send connection `(:error :type :unknown-command :command ,command))))
(deftest test-error-unknown-command
(with-crown-and-connections crown (connection) ()
(data-send connection `(:foo :bar :baz))
(is (wait () (data-equal (data-receive connection)
`(:error :type :unknown-command :command :foo))))
(data-send connection `(:unknown-command))
(is (wait () (data-equal (data-receive connection)
`(:error :type :unknown-command :command :unknown-command))))))
|
dd12be59f5cbe01f7a4ba39576fa103e5b74430dcd5510fd57c2dd7138d01974 | mzp/coq-ide-for-ios | constrintern.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(* $Id: constrintern.ml 13620 2010-11-04 14:11:49Z herbelin $ *)
open Pp
open Util
open Flags
open Names
open Nameops
open Namegen
open Libnames
open Impargs
open Rawterm
open Pattern
open Pretyping
open Cases
open Topconstr
open Nametab
open Notation
open Inductiveops
(* To interpret implicits and arg scopes of variables in inductive
types and recursive definitions and of projection names in records *)
type var_internalization_type =
| Inductive of identifier list (* list of params *)
| Recursive
| Method
type var_internalization_data =
type of the " free " variable , for coqdoc , e.g. while typing the
constructor of JMeq , " JMeq " behaves as a variable of type Inductive
constructor of JMeq, "JMeq" behaves as a variable of type Inductive *)
var_internalization_type *
impargs to automatically add to the variable , e.g. for " JMeq A a B b "
in implicit mode , this is [ A;B ] and this adds ( A:=A ) and ( )
in implicit mode, this is [A;B] and this adds (A:=A) and (B:=B) *)
identifier list *
(* signature of impargs of the variable *)
Impargs.implicit_status list *
(* subscopes of the args of the variable *)
scope_name option list
type internalization_env =
(identifier * var_internalization_data) list
type raw_binder = (name * binding_kind * rawconstr option * rawconstr)
let interning_grammar = ref false
(* Historically for parsing grammar rules, but in fact used only for
translator, v7 parsing, and unstrict tactic internalization *)
let for_grammar f x =
interning_grammar := true;
let a = f x in
interning_grammar := false;
a
(**********************************************************************)
(* Locating reference, possibly via an abbreviation *)
let locate_reference qid =
Smartlocate.global_of_extended_global (Nametab.locate_extended qid)
let is_global id =
try
let _ = locate_reference (qualid_of_ident id) in true
with Not_found ->
false
let global_reference_of_reference ref =
locate_reference (snd (qualid_of_reference ref))
let global_reference id =
constr_of_global (locate_reference (qualid_of_ident id))
let construct_reference ctx id =
try
Term.mkVar (let _ = Sign.lookup_named id ctx in id)
with Not_found ->
global_reference id
let global_reference_in_absolute_module dir id =
constr_of_global (Nametab.global_of_path (Libnames.make_path dir id))
(**********************************************************************)
(* Internalization errors *)
type internalization_error =
| VariableCapture of identifier
| WrongExplicitImplicit
| IllegalMetavariable
| NotAConstructor of reference
| UnboundFixName of bool * identifier
| NonLinearPattern of identifier
| BadPatternsNumber of int * int
| BadExplicitationNumber of explicitation * int option
exception InternalizationError of loc * internalization_error
let explain_variable_capture id =
str "The variable " ++ pr_id id ++ str " occurs in its type"
let explain_wrong_explicit_implicit =
str "Found an explicitly given implicit argument but was expecting" ++
fnl () ++ str "a regular one"
let explain_illegal_metavariable =
str "Metavariables allowed only in patterns"
let explain_not_a_constructor ref =
str "Unknown constructor: " ++ pr_reference ref
let explain_unbound_fix_name is_cofix id =
str "The name" ++ spc () ++ pr_id id ++
spc () ++ str "is not bound in the corresponding" ++ spc () ++
str (if is_cofix then "co" else "") ++ str "fixpoint definition"
let explain_non_linear_pattern id =
str "The variable " ++ pr_id id ++ str " is bound several times in pattern"
let explain_bad_patterns_number n1 n2 =
str "Expecting " ++ int n1 ++ str (plural n1 " pattern") ++
str " but found " ++ int n2
let explain_bad_explicitation_number n po =
match n with
| ExplByPos (n,_id) ->
let s = match po with
| None -> str "a regular argument"
| Some p -> int p in
str "Bad explicitation number: found " ++ int n ++
str" but was expecting " ++ s
| ExplByName id ->
let s = match po with
| None -> str "a regular argument"
| Some p -> (*pr_id (name_of_position p) in*) failwith "" in
str "Bad explicitation name: found " ++ pr_id id ++
str" but was expecting " ++ s
let explain_internalization_error e =
let pp = match e with
| VariableCapture id -> explain_variable_capture id
| WrongExplicitImplicit -> explain_wrong_explicit_implicit
| IllegalMetavariable -> explain_illegal_metavariable
| NotAConstructor ref -> explain_not_a_constructor ref
| UnboundFixName (iscofix,id) -> explain_unbound_fix_name iscofix id
| NonLinearPattern id -> explain_non_linear_pattern id
| BadPatternsNumber (n1,n2) -> explain_bad_patterns_number n1 n2
| BadExplicitationNumber (n,po) -> explain_bad_explicitation_number n po in
pp ++ str "."
let error_bad_inductive_type loc =
user_err_loc (loc,"",str
"This should be an inductive type applied to names or \"_\".")
let error_inductive_parameter_not_implicit loc =
user_err_loc (loc,"", str
("The parameters of inductive types do not bind in\n"^
"the 'return' clauses; they must be replaced by '_' in the 'in' clauses."))
(**********************************************************************)
(* Pre-computing the implicit arguments and arguments scopes needed *)
(* for interpretation *)
let empty_internalization_env = []
let compute_explicitable_implicit imps = function
| Inductive params ->
(* In inductive types, the parameters are fixed implicit arguments *)
let sub_impl,_ = list_chop (List.length params) imps in
let sub_impl' = List.filter is_status_implicit sub_impl in
List.map name_of_implicit sub_impl'
| Recursive | Method ->
(* Unable to know in advance what the implicit arguments will be *)
[]
let compute_internalization_data env ty typ impl =
let impl = compute_implicits_with_manual env typ (is_implicit_args()) impl in
let expls_impl = compute_explicitable_implicit impl ty in
(ty, expls_impl, impl, compute_arguments_scope typ)
let compute_internalization_env env ty =
list_map3
(fun id typ impl -> (id,compute_internalization_data env ty typ impl))
(**********************************************************************)
(* Contracting "{ _ }" in notations *)
let rec wildcards ntn n =
if n = String.length ntn then []
else let l = spaces ntn (n+1) in if ntn.[n] = '_' then n::l else l
and spaces ntn n =
if n = String.length ntn then []
else if ntn.[n] = ' ' then wildcards ntn (n+1) else spaces ntn (n+1)
let expand_notation_string ntn n =
let pos = List.nth (wildcards ntn 0) n in
let hd = if pos = 0 then "" else String.sub ntn 0 pos in
let tl =
if pos = String.length ntn then ""
else String.sub ntn (pos+1) (String.length ntn - pos -1) in
hd ^ "{ _ }" ^ tl
(* This contracts the special case of "{ _ }" for sumbool, sumor notations *)
(* Remark: expansion of squash at definition is done in metasyntax.ml *)
let contract_notation ntn (l,ll,bll) =
let ntn' = ref ntn in
let rec contract_squash n = function
| [] -> []
| CNotation (_,"{ _ }",([a],[],[])) :: l ->
ntn' := expand_notation_string !ntn' n;
contract_squash n (a::l)
| a :: l ->
a::contract_squash (n+1) l in
let l = contract_squash 0 l in
(* side effect; don't inline *)
!ntn',(l,ll,bll)
let contract_pat_notation ntn (l,ll) =
let ntn' = ref ntn in
let rec contract_squash n = function
| [] -> []
| CPatNotation (_,"{ _ }",([a],[])) :: l ->
ntn' := expand_notation_string !ntn' n;
contract_squash n (a::l)
| a :: l ->
a::contract_squash (n+1) l in
let l = contract_squash 0 l in
(* side effect; don't inline *)
!ntn',(l,ll)
(**********************************************************************)
(* Remembering the parsing scope of variables in notations *)
let make_current_scope = function
| (Some tmp_scope,(sc::_ as scopes)) when sc = tmp_scope -> scopes
| (Some tmp_scope,scopes) -> tmp_scope::scopes
| None,scopes -> scopes
let pr_scope_stack = function
| [] -> str "the empty scope stack"
| [a] -> str "scope " ++ str a
| l -> str "scope stack " ++
str "[" ++ prlist_with_sep pr_comma str l ++ str "]"
let error_inconsistent_scope loc id scopes1 scopes2 =
user_err_loc (loc,"set_var_scope",
pr_id id ++ str " is used both in " ++
pr_scope_stack scopes1 ++ strbrk " and in " ++ pr_scope_stack scopes2)
let error_expect_constr_notation_type loc id =
user_err_loc (loc,"",
pr_id id ++ str " is bound in the notation to a term variable.")
let error_expect_binder_notation_type loc id =
user_err_loc (loc,"",
pr_id id ++
str " is expected to occur in binding position in the right-hand side.")
let set_var_scope loc id istermvar (_,_,scopt,scopes) ntnvars =
try
let idscopes,typ = List.assoc id ntnvars in
if !idscopes <> None &
(* scopes have no effect on the interpretation of identifiers, hence
we can tolerate having a variable occurring several times in
different scopes: *) typ <> NtnInternTypeIdent &
make_current_scope (Option.get !idscopes)
<> make_current_scope (scopt,scopes) then
error_inconsistent_scope loc id
(make_current_scope (Option.get !idscopes))
(make_current_scope (scopt,scopes))
else
idscopes := Some (scopt,scopes);
match typ with
| NtnInternTypeBinder ->
if istermvar then error_expect_binder_notation_type loc id
| NtnInternTypeConstr ->
We need sometimes to parse idents at a constr level for
factorization and we can not enforce this constraint :
if not istermvar then
factorization and we cannot enforce this constraint:
if not istermvar then error_expect_constr_notation_type loc id *)
()
| NtnInternTypeIdent -> ()
with Not_found ->
(* Not in a notation *)
()
let set_type_scope (ids,unb,tmp_scope,scopes) =
(ids,unb,Some Notation.type_scope,scopes)
let reset_tmp_scope (ids,unb,tmp_scope,scopes) =
(ids,unb,None,scopes)
let rec it_mkRProd env body =
match env with
(na, bk, _, t) :: tl -> it_mkRProd tl (RProd (dummy_loc, na, bk, t, body))
| [] -> body
let rec it_mkRLambda env body =
match env with
(na, bk, _, t) :: tl -> it_mkRLambda tl (RLambda (dummy_loc, na, bk, t, body))
| [] -> body
(**********************************************************************)
Utilities for binders
let check_capture loc ty = function
| Name id when occur_var_constr_expr id ty ->
raise (InternalizationError (loc,VariableCapture id))
| _ ->
()
let locate_if_isevar loc na = function
| RHole _ ->
(try match na with
| Name id -> Reserve.find_reserved_type id
| Anonymous -> raise Not_found
with Not_found -> RHole (loc, Evd.BinderType na))
| x -> x
let check_hidden_implicit_parameters id (_,_,_,impls) =
if List.exists (function
| (_,(Inductive indparams,_,_,_)) -> List.mem id indparams
| _ -> false) impls
then
errorlabstrm "" (strbrk "A parameter of an inductive type " ++
pr_id id ++ strbrk " is not allowed to be used as a bound variable in the type of its constructor.")
let push_name_env ?(global_level=false) lvar (ids,unb,tmpsc,scopes as env) =
function
| loc,Anonymous ->
if global_level then
user_err_loc (loc,"", str "Anonymous variables not allowed");
env
| loc,Name id ->
check_hidden_implicit_parameters id lvar;
set_var_scope loc id false env (let (_,_,ntnvars,_) = lvar in ntnvars);
if global_level then Dumpglob.dump_definition (loc,id) true "var"
else Dumpglob.dump_binding loc id;
(Idset.add id ids,unb,tmpsc,scopes)
let intern_generalized_binder ?(global_level=false) intern_type lvar
(ids,unb,tmpsc,sc as env) bl (loc, na) b b' t ty =
let ids = match na with Anonymous -> ids | Name na -> Idset.add na ids in
let ty, ids' =
if t then ty, ids else
Implicit_quantifiers.implicit_application ids
Implicit_quantifiers.combine_params_freevar ty
in
let ty' = intern_type (ids,true,tmpsc,sc) ty in
let fvs = Implicit_quantifiers.generalizable_vars_of_rawconstr ~bound:ids ~allowed:ids' ty' in
let env' = List.fold_left (fun env (x, l) -> push_name_env ~global_level lvar env (l, Name x)) env fvs in
let bl = List.map (fun (id, loc) -> (Name id, b, None, RHole (loc, Evd.BinderType (Name id)))) fvs in
let na = match na with
| Anonymous ->
if global_level then na
else
let name =
let id =
match ty with
| CApp (_, (_, CRef (Ident (loc,id))), _) -> id
| _ -> id_of_string "H"
in Implicit_quantifiers.make_fresh ids' (Global.env ()) id
in Name name
| _ -> na
in (push_name_env ~global_level lvar env' (loc,na)), (na,b',None,ty') :: List.rev bl
let intern_local_binder_aux ?(global_level=false) intern intern_type lvar (env,bl) = function
| LocalRawAssum(nal,bk,ty) ->
(match bk with
| Default k ->
let (loc,na) = List.hd nal in
(* TODO: fail if several names with different implicit types *)
let ty = locate_if_isevar loc na (intern_type env ty) in
List.fold_left
(fun (env,bl) na ->
(push_name_env lvar env na,(snd na,k,None,ty)::bl))
(env,bl) nal
| Generalized (b,b',t) ->
let env, b = intern_generalized_binder ~global_level intern_type lvar env bl (List.hd nal) b b' t ty in
env, b @ bl)
| LocalRawDef((loc,na as locna),def) ->
(push_name_env lvar env locna,
(na,Explicit,Some(intern env def),RHole(loc,Evd.BinderType na))::bl)
let intern_generalization intern (ids,unb,tmp_scope,scopes as env) lvar loc bk ak c =
let c = intern (ids,true,tmp_scope,scopes) c in
let fvs = Implicit_quantifiers.generalizable_vars_of_rawconstr ~bound:ids c in
let env', c' =
let abs =
let pi =
match ak with
| Some AbsPi -> true
| None when tmp_scope = Some Notation.type_scope
|| List.mem Notation.type_scope scopes -> true
| _ -> false
in
if pi then
(fun (id, loc') acc ->
RProd (join_loc loc' loc, Name id, bk, RHole (loc', Evd.BinderType (Name id)), acc))
else
(fun (id, loc') acc ->
RLambda (join_loc loc' loc, Name id, bk, RHole (loc', Evd.BinderType (Name id)), acc))
in
List.fold_right (fun (id, loc as lid) (env, acc) ->
let env' = push_name_env lvar env (loc, Name id) in
(env', abs lid acc)) fvs (env,c)
in c'
let iterate_binder intern lvar (env,bl) = function
| LocalRawAssum(nal,bk,ty) ->
let intern_type env = intern (set_type_scope env) in
(match bk with
| Default k ->
let (loc,na) = List.hd nal in
(* TODO: fail if several names with different implicit types *)
let ty = intern_type env ty in
let ty = locate_if_isevar loc na ty in
List.fold_left
(fun (env,bl) na -> (push_name_env lvar env na,(snd na,k,None,ty)::bl))
(env,bl) nal
| Generalized (b,b',t) ->
let env, b = intern_generalized_binder intern_type lvar env bl (List.hd nal) b b' t ty in
env, b @ bl)
| LocalRawDef((loc,na as locna),def) ->
(push_name_env lvar env locna,
(na,Explicit,Some(intern env def),RHole(loc,Evd.BinderType na))::bl)
(**********************************************************************)
(* Syntax extensions *)
let option_mem_assoc id = function
| Some (id',c) -> id = id'
| None -> false
let find_fresh_name renaming (terms,termlists,binders) id =
let fvs1 = List.map (fun (_,(c,_)) -> free_vars_of_constr_expr c) terms in
let fvs2 = List.flatten (List.map (fun (_,(l,_)) -> List.map free_vars_of_constr_expr l) termlists) in
let fvs3 = List.map snd renaming in
TODO binders
let fvs = List.flatten (List.map Idset.elements (fvs1@fvs2)) @ fvs3 in
next_ident_away id fvs
let traverse_binder (terms,_,_ as subst)
(renaming,(ids,unb,tmpsc,scopes as env))=
function
| Anonymous -> (renaming,env),Anonymous
| Name id ->
try
Binders bound in the notation are considered first - order objects
let _,na = coerce_to_name (fst (List.assoc id terms)) in
(renaming,(name_fold Idset.add na ids,unb,tmpsc,scopes)), na
with Not_found ->
(* Binders not bound in the notation do not capture variables *)
(* outside the notation (i.e. in the substitution) *)
let id' = find_fresh_name renaming subst id in
let renaming' = if id=id' then renaming else (id,id')::renaming in
(renaming',env), Name id'
let rec subst_iterator y t = function
| RVar (_,id) as x -> if id = y then t else x
| x -> map_rawconstr (subst_iterator y t) x
let subst_aconstr_in_rawconstr loc intern lvar subst infos c =
let (terms,termlists,binders) = subst in
let rec aux (terms,binderopt as subst') (renaming,(ids,unb,_,scopes as env)) c =
let subinfos = renaming,(ids,unb,None,scopes) in
match c with
| AVar id ->
begin
(* subst remembers the delimiters stack in the interpretation *)
(* of the notations *)
try
let (a,(scopt,subscopes)) = List.assoc id terms in
intern (ids,unb,scopt,subscopes@scopes) a
with Not_found ->
try
RVar (loc,List.assoc id renaming)
with Not_found ->
Happens for local notation joint with inductive /
RVar (loc,id)
end
| AList (x,_,iter,terminator,lassoc) ->
(try
All elements of the list are in scopes ( scopt , subscopes )
let (l,(scopt,subscopes)) = List.assoc x termlists in
let termin = aux subst' subinfos terminator in
List.fold_right (fun a t ->
subst_iterator ldots_var t
(aux ((x,(a,(scopt,subscopes)))::terms,binderopt) subinfos iter))
(if lassoc then List.rev l else l) termin
with Not_found ->
anomaly "Inconsistent substitution of recursive notation")
| AHole (Evd.BinderType (Name id as na)) ->
let na =
try snd (coerce_to_name (fst (List.assoc id terms)))
with Not_found -> na in
RHole (loc,Evd.BinderType na)
| ABinderList (x,_,iter,terminator) ->
(try
All elements of the list are in scopes ( scopt , subscopes )
let (bl,(scopt,subscopes)) = List.assoc x binders in
let env,bl = List.fold_left (iterate_binder intern lvar) (env,[]) bl in
let termin = aux subst' (renaming,env) terminator in
List.fold_left (fun t binder ->
subst_iterator ldots_var t
(aux (terms,Some(x,binder)) subinfos iter))
termin bl
with Not_found ->
anomaly "Inconsistent substitution of recursive notation")
| AProd (Name id, AHole _, c') when option_mem_assoc id binderopt ->
let (na,bk,_,t) = snd (Option.get binderopt) in
RProd (loc,na,bk,t,aux subst' infos c')
| ALambda (Name id,AHole _,c') when option_mem_assoc id binderopt ->
let (na,bk,_,t) = snd (Option.get binderopt) in
RLambda (loc,na,bk,t,aux subst' infos c')
| t ->
rawconstr_of_aconstr_with_binders loc (traverse_binder subst)
(aux subst') subinfos t
in aux (terms,None) infos c
let split_by_type ids =
List.fold_right (fun (x,(scl,typ)) (l1,l2,l3) ->
match typ with
| NtnTypeConstr -> ((x,scl)::l1,l2,l3)
| NtnTypeConstrList -> (l1,(x,scl)::l2,l3)
| NtnTypeBinderList -> (l1,l2,(x,scl)::l3)) ids ([],[],[])
let make_subst ids l = List.map2 (fun (id,scl) a -> (id,(a,scl))) ids l
let intern_notation intern (_,_,tmp_scope,scopes as env) lvar loc ntn fullargs =
let ntn,(args,argslist,bll as fullargs) = contract_notation ntn fullargs in
let ((ids,c),df) = interp_notation loc ntn (tmp_scope,scopes) in
Dumpglob.dump_notation_location (ntn_loc loc fullargs ntn) ntn df;
let ids,idsl,idsbl = split_by_type ids in
let terms = make_subst ids args in
let termlists = make_subst idsl argslist in
let binders = make_subst idsbl bll in
subst_aconstr_in_rawconstr loc intern lvar
(terms,termlists,binders) ([],env) c
(**********************************************************************)
(* Discriminating between bound variables and global references *)
let string_of_ty = function
| Inductive _ -> "ind"
| Recursive -> "def"
| Method -> "meth"
let intern_var (ids,_,_,_ as genv) (ltacvars,namedctxvars,ntnvars,impls) loc id =
let (ltacvars,unbndltacvars) = ltacvars in
(* Is [id] an inductive type potentially with implicit *)
try
let ty,expl_impls,impls,argsc = List.assoc id impls in
let expl_impls = List.map
(fun id -> CRef (Ident (loc,id)), Some (loc,ExplByName id)) expl_impls in
let tys = string_of_ty ty in
Dumpglob.dump_reference loc "<>" (string_of_id id) tys;
RVar (loc,id), make_implicits_list impls, argsc, expl_impls
with Not_found ->
(* Is [id] bound in current term or is an ltac var bound to constr *)
if Idset.mem id ids or List.mem id ltacvars
then
RVar (loc,id), [], [], []
(* Is [id] a notation variable *)
else if List.mem_assoc id ntnvars
then
(set_var_scope loc id true genv ntnvars; RVar (loc,id), [], [], [])
(* Is [id] the special variable for recursive notations *)
else if ntnvars <> [] && id = ldots_var
then
RVar (loc,id), [], [], []
else
(* Is [id] bound to a free name in ltac (this is an ltac error message) *)
try
match List.assoc id unbndltacvars with
| None -> user_err_loc (loc,"intern_var",
str "variable " ++ pr_id id ++ str " should be bound to a term.")
| Some id0 -> Pretype_errors.error_var_not_found_loc loc id0
with Not_found ->
(* Is [id] a goal or section variable *)
let _ = Sign.lookup_named id namedctxvars in
try
(* [id] a section variable *)
(* Redundant: could be done in intern_qualid *)
let ref = VarRef id in
let impls = implicits_of_global ref in
let scopes = find_arguments_scope ref in
Dumpglob.dump_reference loc "<>" (string_of_qualid (Decls.variable_secpath id)) "var";
RRef (loc, ref), impls, scopes, []
with _ ->
(* [id] a goal variable *)
RVar (loc,id), [], [], []
let find_appl_head_data = function
| RRef (_,ref) as x -> x,implicits_of_global ref,find_arguments_scope ref,[]
| RApp (_,RRef (_,ref),l) as x
when l <> [] & Flags.version_strictly_greater Flags.V8_2 ->
let n = List.length l in
x,List.map (drop_first_implicits n) (implicits_of_global ref),
list_skipn_at_least n (find_arguments_scope ref),[]
| x -> x,[],[],[]
let error_not_enough_arguments loc =
user_err_loc (loc,"",str "Abbreviation is not applied enough.")
let check_no_explicitation l =
let l = List.filter (fun (a,b) -> b <> None) l in
if l <> [] then
let loc = fst (Option.get (snd (List.hd l))) in
user_err_loc
(loc,"",str"Unexpected explicitation of the argument of an abbreviation.")
let dump_extended_global loc = function
| TrueGlobal ref -> Dumpglob.add_glob loc ref
| SynDef sp -> Dumpglob.add_glob_kn loc sp
let intern_extended_global_of_qualid (loc,qid) =
try let r = Nametab.locate_extended qid in dump_extended_global loc r; r
with Not_found -> error_global_not_found_loc loc qid
let intern_reference ref =
Smartlocate.global_of_extended_global
(intern_extended_global_of_qualid (qualid_of_reference ref))
(* Is it a global reference or a syntactic definition? *)
let intern_qualid loc qid intern env lvar args =
match intern_extended_global_of_qualid (loc,qid) with
| TrueGlobal ref ->
RRef (loc, ref), args
| SynDef sp ->
let (ids,c) = Syntax_def.search_syntactic_definition sp in
let nids = List.length ids in
if List.length args < nids then error_not_enough_arguments loc;
let args1,args2 = list_chop nids args in
check_no_explicitation args1;
let subst = make_subst ids (List.map fst args1) in
subst_aconstr_in_rawconstr loc intern lvar (subst,[],[]) ([],env) c, args2
(* Rule out section vars since these should have been found by intern_var *)
let intern_non_secvar_qualid loc qid intern env lvar args =
match intern_qualid loc qid intern env lvar args with
| RRef (loc, VarRef id),_ -> error_global_not_found_loc loc qid
| r -> r
let intern_applied_reference intern (_, unb, _, _ as env) lvar args = function
| Qualid (loc, qid) ->
let r,args2 = intern_qualid loc qid intern env lvar args in
find_appl_head_data r, args2
| Ident (loc, id) ->
try intern_var env lvar loc id, args
with Not_found ->
let qid = qualid_of_ident id in
try
let r,args2 = intern_non_secvar_qualid loc qid intern env lvar args in
find_appl_head_data r, args2
with e ->
(* Extra allowance for non globalizing functions *)
if !interning_grammar || unb then
(RVar (loc,id), [], [], []),args
else raise e
let interp_reference vars r =
let (r,_,_,_),_ =
intern_applied_reference (fun _ -> error_not_enough_arguments dummy_loc)
(Idset.empty,false,None,[]) (vars,[],[],[]) [] r
in r
let apply_scope_env (ids,unb,_,scopes) = function
| [] -> (ids,unb,None,scopes), []
| sc::scl -> (ids,unb,sc,scopes), scl
let rec simple_adjust_scopes n = function
| [] -> if n=0 then [] else None :: simple_adjust_scopes (n-1) []
| sc::scopes -> sc :: simple_adjust_scopes (n-1) scopes
let find_remaining_constructor_scopes pl1 pl2 (ind,j as cstr) =
let (mib,mip) = Inductive.lookup_mind_specif (Global.env()) ind in
let npar = mib.Declarations.mind_nparams in
snd (list_chop (npar + List.length pl1)
(simple_adjust_scopes (npar + List.length pl1 + List.length pl2)
(find_arguments_scope (ConstructRef cstr))))
(**********************************************************************)
(* Cases *)
let product_of_cases_patterns ids idspl =
List.fold_right (fun (ids,pl) (ids',ptaill) ->
(ids@ids',
Cartesian prod of the or - pats for the nth arg and the tail args
List.flatten (
List.map (fun (subst,p) ->
List.map (fun (subst',ptail) -> (subst@subst',p::ptail)) ptaill) pl)))
idspl (ids,[[],[]])
let simple_product_of_cases_patterns pl =
List.fold_right (fun pl ptaill ->
List.flatten (List.map (fun (subst,p) ->
List.map (fun (subst',ptail) -> (subst@subst',p::ptail)) ptaill) pl))
pl [[],[]]
(* Check linearity of pattern-matching *)
let rec has_duplicate = function
| [] -> None
| x::l -> if List.mem x l then (Some x) else has_duplicate l
let loc_of_lhs lhs =
join_loc (fst (List.hd lhs)) (fst (list_last lhs))
let check_linearity lhs ids =
match has_duplicate ids with
| Some id ->
raise (InternalizationError (loc_of_lhs lhs,NonLinearPattern id))
| None ->
()
(* Match the number of pattern against the number of matched args *)
let check_number_of_pattern loc n l =
let p = List.length l in
if n<>p then raise (InternalizationError (loc,BadPatternsNumber (n,p)))
let check_or_pat_variables loc ids idsl =
if List.exists (fun ids' -> not (list_eq_set ids ids')) idsl then
user_err_loc (loc, "", str
"The components of this disjunctive pattern must bind the same variables.")
let check_constructor_length env loc cstr pl pl0 =
let n = List.length pl + List.length pl0 in
let nargs = Inductiveops.constructor_nrealargs env cstr in
let nhyps = Inductiveops.constructor_nrealhyps env cstr in
if n <> nargs && n <> nhyps (* i.e. with let's *) then
error_wrong_numarg_constructor_loc loc env cstr nargs
(* Manage multiple aliases *)
[ merge_aliases ] returns the sets of all aliases encountered at this
point and a substitution mapping extra aliases to the first one
point and a substitution mapping extra aliases to the first one *)
let merge_aliases (ids,asubst as _aliases) id =
ids@[id], if ids=[] then asubst else (id, List.hd ids)::asubst
let alias_of = function
| ([],_) -> Anonymous
| (id::_,_) -> Name id
let message_redundant_alias (id1,id2) =
if_verbose warning
("Alias variable "^(string_of_id id1)^" is merged with "^(string_of_id id2))
(* Expanding notations *)
let error_invalid_pattern_notation loc =
user_err_loc (loc,"",str "Invalid notation for pattern.")
let chop_aconstr_constructor loc (ind,k) args =
if List.length args = 0 then (* Tolerance for a @id notation *) args else
begin
let mib,_ = Global.lookup_inductive ind in
let nparams = mib.Declarations.mind_nparams in
if nparams > List.length args then error_invalid_pattern_notation loc;
let params,args = list_chop nparams args in
List.iter (function AHole _ -> ()
| _ -> error_invalid_pattern_notation loc) params;
args
end
let rec subst_pat_iterator y t (subst,p) = match p with
| PatVar (_,id) as x ->
if id = Name y then t else [subst,x]
| PatCstr (loc,id,l,alias) ->
let l' = List.map (fun a -> (subst_pat_iterator y t ([],a))) l in
let pl = simple_product_of_cases_patterns l' in
List.map (fun (subst',pl) -> subst'@subst,PatCstr (loc,id,pl,alias)) pl
let subst_cases_pattern loc alias intern fullsubst scopes a =
let rec aux alias (subst,substlist as fullsubst) = function
| AVar id ->
begin
(* subst remembers the delimiters stack in the interpretation *)
(* of the notations *)
try
let (a,(scopt,subscopes)) = List.assoc id subst in
intern (subscopes@scopes) ([],[]) scopt a
with Not_found ->
if id = ldots_var then [], [[], PatVar (loc,Name id)] else
anomaly ("Unbound pattern notation variable: "^(string_of_id id))
( * Happens for local notation joint with inductive /
(* Happens for local notation joint with inductive/fixpoint defs *)
if aliases <> ([],[]) then
anomaly "Pattern notation without constructors";
[[id],[]], PatVar (loc,Name id)
*)
end
| ARef (ConstructRef c) ->
([],[[], PatCstr (loc,c, [], alias)])
| AApp (ARef (ConstructRef cstr),args) ->
let args = chop_aconstr_constructor loc cstr args in
let idslpll = List.map (aux Anonymous fullsubst) args in
let ids',pll = product_of_cases_patterns [] idslpll in
let pl' = List.map (fun (asubst,pl) ->
asubst,PatCstr (loc,cstr,pl,alias)) pll in
ids', pl'
| AList (x,_,iter,terminator,lassoc) ->
(try
All elements of the list are in scopes ( scopt , subscopes )
let (l,(scopt,subscopes)) = List.assoc x substlist in
let termin = aux Anonymous fullsubst terminator in
let idsl,v =
List.fold_right (fun a (tids,t) ->
let uids,u = aux Anonymous ((x,(a,(scopt,subscopes)))::subst,substlist) iter in
let pll = List.map (subst_pat_iterator ldots_var t) u in
tids@uids, List.flatten pll)
(if lassoc then List.rev l else l) termin in
idsl, List.map (fun ((asubst, pl) as x) ->
match pl with PatCstr (loc, c, pl, Anonymous) -> (asubst, PatCstr (loc, c, pl, alias)) | _ -> x) v
with Not_found ->
anomaly "Inconsistent substitution of recursive notation")
| AHole _ -> ([],[[], PatVar (loc,Anonymous)])
| t -> error_invalid_pattern_notation loc
in aux alias fullsubst a
(* Differentiating between constructors and matching variables *)
type pattern_qualid_kind =
| ConstrPat of constructor * (identifier list *
((identifier * identifier) list * cases_pattern) list) list
| VarPat of identifier
let find_constructor ref f aliases pats scopes =
let (loc,qid) = qualid_of_reference ref in
let gref =
try locate_extended qid
with Not_found -> raise (InternalizationError (loc,NotAConstructor ref)) in
match gref with
| SynDef sp ->
let (vars,a) = Syntax_def.search_syntactic_definition sp in
(match a with
| ARef (ConstructRef cstr) ->
assert (vars=[]);
cstr, [], pats
| AApp (ARef (ConstructRef cstr),args) ->
let args = chop_aconstr_constructor loc cstr args in
let nvars = List.length vars in
if List.length pats < nvars then error_not_enough_arguments loc;
let pats1,pats2 = list_chop nvars pats in
let subst = List.map2 (fun (id,scl) a -> (id,(a,scl))) vars pats1 in
let idspl1 = List.map (subst_cases_pattern loc (alias_of aliases) f (subst,[]) scopes) args in
cstr, idspl1, pats2
| _ -> raise Not_found)
| TrueGlobal r ->
let rec unf = function
| ConstRef cst ->
let v = Environ.constant_value (Global.env()) cst in
unf (global_of_constr v)
| ConstructRef cstr ->
Dumpglob.add_glob loc r;
cstr, [], pats
| _ -> raise Not_found
in unf r
let find_pattern_variable = function
| Ident (loc,id) -> id
| Qualid (loc,_) as x -> raise (InternalizationError(loc,NotAConstructor x))
let maybe_constructor ref f aliases scopes =
try
let c,idspl1,pl2 = find_constructor ref f aliases [] scopes in
assert (pl2 = []);
ConstrPat (c,idspl1)
with
(* patt var does not exists globally *)
| InternalizationError _ -> VarPat (find_pattern_variable ref)
(* patt var also exists globally but does not satisfy preconditions *)
| (Environ.NotEvaluableConst _ | Not_found) ->
if_verbose msg_warning (str "pattern " ++ pr_reference ref ++
str " is understood as a pattern variable");
VarPat (find_pattern_variable ref)
let mustbe_constructor loc ref f aliases patl scopes =
try find_constructor ref f aliases patl scopes
with (Environ.NotEvaluableConst _ | Not_found) ->
raise (InternalizationError (loc,NotAConstructor ref))
let sort_fields mode loc l completer =
(*mode=false if pattern and true if constructor*)
match l with
| [] -> None
| (refer, value)::rem ->
let (nparams, (* the number of parameters *)
base_constructor, (* the reference constructor of the record *)
(max, (* number of params *)
index of the first field of the record
list_proj))) (* list of projections *)
=
let record =
try Recordops.find_projection
(global_reference_of_reference refer)
with Not_found ->
user_err_loc (loc, "intern", str"Not a projection")
in
elimination of the first field from the projections
let rec build_patt l m i acc =
match l with
| [] -> (i, acc)
| (Some name) :: b->
(match m with
| [] -> anomaly "Number of projections mismatch"
| (_, regular)::tm ->
let boolean = not regular in
if ConstRef name = global_reference_of_reference refer
then
if boolean && mode then
user_err_loc (loc, "", str"No local fields allowed in a record construction.")
else build_patt b tm (i + 1) (i, snd acc) (* we found it *)
else
build_patt b tm (if boolean&&mode then i else i + 1)
(if boolean && mode then acc
else fst acc, (i, ConstRef name) :: snd acc))
| None :: b-> (* we don't want anonymous fields *)
if mode then
user_err_loc (loc, "", str "This record contains anonymous fields.")
else build_patt b m (i+1) acc
(* anonymous arguments don't appear in m *)
in
let ind = record.Recordops.s_CONST in
insertion of Constextern.reference_global
(record.Recordops.s_EXPECTEDPARAM,
Qualid (loc, shortest_qualid_of_global Idset.empty (ConstructRef ind)),
build_patt record.Recordops.s_PROJ record.Recordops.s_PROJKIND 1 (0,[]))
with Not_found -> anomaly "Environment corruption for records."
in
(* now we want to have all fields of the pattern indexed by their place in
the constructor *)
let rec sf patts accpatt =
match patts with
| [] -> accpatt
| p::q->
let refer, patt = p in
let rec add_patt l acc =
match l with
| [] ->
user_err_loc
(loc, "",
str "This record contains fields of different records.")
| (i, a) :: b->
if global_reference_of_reference refer = a
then (i,List.rev_append acc l)
else add_patt b ((i,a)::acc)
in
let (index, projs) = add_patt (snd accpatt) [] in
sf q ((index, patt)::fst accpatt, projs) in
let (unsorted_indexed_pattern, remainings) =
sf rem ([first_index, value], list_proj) in
(* we sort them *)
let sorted_indexed_pattern =
List.sort (fun (i, _) (j, _) -> compare i j) unsorted_indexed_pattern in
(* a function to complete with wildcards *)
let rec complete_list n l =
if n <= 1 then l else complete_list (n-1) (completer n l) in
(* a function to remove indice *)
let rec clean_list l i acc =
match l with
| [] -> complete_list (max - i) acc
| (k, p)::q-> clean_list q k (p::(complete_list (k - i) acc))
in
Some (nparams, base_constructor,
List.rev (clean_list sorted_indexed_pattern 0 []))
let rec intern_cases_pattern genv scopes (ids,asubst as aliases) tmp_scope pat=
let intern_pat = intern_cases_pattern genv in
match pat with
| CPatAlias (loc, p, id) ->
let aliases' = merge_aliases aliases id in
intern_pat scopes aliases' tmp_scope p
| CPatRecord (loc, l) ->
let sorted_fields = sort_fields false loc l (fun _ l -> (CPatAtom (loc, None))::l) in
let self_patt =
match sorted_fields with
| None -> CPatAtom (loc, None)
| Some (_, head, pl) -> CPatCstr(loc, head, pl)
in
intern_pat scopes aliases tmp_scope self_patt
| CPatCstr (loc, head, pl) ->
let c,idslpl1,pl2 = mustbe_constructor loc head intern_pat aliases pl scopes in
check_constructor_length genv loc c idslpl1 pl2;
let argscs2 = find_remaining_constructor_scopes idslpl1 pl2 c in
let idslpl2 = List.map2 (intern_pat scopes ([],[])) argscs2 pl2 in
let (ids',pll) = product_of_cases_patterns ids (idslpl1@idslpl2) in
let pl' = List.map (fun (asubst,pl) ->
(asubst, PatCstr (loc,c,pl,alias_of aliases))) pll in
ids',pl'
| CPatNotation (loc,"- _",([CPatPrim(_,Numeral p)],[]))
when Bigint.is_strictly_pos p ->
intern_pat scopes aliases tmp_scope (CPatPrim(loc,Numeral(Bigint.neg p)))
| CPatNotation (_,"( _ )",([a],[])) ->
intern_pat scopes aliases tmp_scope a
| CPatNotation (loc, ntn, fullargs) ->
let ntn,(args,argsl as fullargs) = contract_pat_notation ntn fullargs in
let ((ids',c),df) = Notation.interp_notation loc ntn (tmp_scope,scopes) in
let (ids',idsl',_) = split_by_type ids' in
Dumpglob.dump_notation_location (patntn_loc loc fullargs ntn) ntn df;
let subst = List.map2 (fun (id,scl) a -> (id,(a,scl))) ids' args in
let substlist = List.map2 (fun (id,scl) a -> (id,(a,scl))) idsl' argsl in
let ids'',pl =
subst_cases_pattern loc (alias_of aliases) intern_pat (subst,substlist)
scopes c
in ids@ids'', pl
| CPatPrim (loc, p) ->
let a = alias_of aliases in
let (c,_) = Notation.interp_prim_token_cases_pattern loc p a
(tmp_scope,scopes) in
(ids,[asubst,c])
| CPatDelimiters (loc, key, e) ->
intern_pat (find_delimiters_scope loc key::scopes) aliases None e
| CPatAtom (loc, Some head) ->
(match maybe_constructor head intern_pat aliases scopes with
| ConstrPat (c,idspl) ->
check_constructor_length genv loc c idspl [];
let (ids',pll) = product_of_cases_patterns ids idspl in
(ids,List.map (fun (asubst,pl) ->
(asubst, PatCstr (loc,c,pl,alias_of aliases))) pll)
| VarPat id ->
let ids,asubst = merge_aliases aliases id in
(ids,[asubst, PatVar (loc,alias_of (ids,asubst))]))
| CPatAtom (loc, None) ->
(ids,[asubst, PatVar (loc,alias_of aliases)])
| CPatOr (loc, pl) ->
assert (pl <> []);
let pl' = List.map (intern_pat scopes aliases tmp_scope) pl in
let (idsl,pl') = List.split pl' in
let ids = List.hd idsl in
check_or_pat_variables loc ids (List.tl idsl);
(ids,List.flatten pl')
(**********************************************************************)
Utilities for application
let merge_impargs l args =
List.fold_right (fun a l ->
match a with
| (_,Some (_,(ExplByName id as x))) when
List.exists (function (_,Some (_,y)) -> x=y | _ -> false) args -> l
| _ -> a::l)
l args
let check_projection isproj nargs r =
match (r,isproj) with
| RRef (loc, ref), Some _ ->
(try
let n = Recordops.find_projection_nparams ref + 1 in
if nargs <> n then
user_err_loc (loc,"",str "Projection has not the right number of explicit parameters.");
with Not_found ->
user_err_loc
(loc,"",pr_global_env Idset.empty ref ++ str " is not a registered projection."))
| _, Some _ -> user_err_loc (loc_of_rawconstr r, "", str "Not a projection.")
| _, None -> ()
let get_implicit_name n imps =
Some (Impargs.name_of_implicit (List.nth imps (n-1)))
let set_hole_implicit i b = function
| RRef (loc,r) | RApp (_,RRef (loc,r),_) -> (loc,Evd.ImplicitArg (r,i,b))
| RVar (loc,id) -> (loc,Evd.ImplicitArg (VarRef id,i,b))
| _ -> anomaly "Only refs have implicits"
let exists_implicit_name id =
List.exists (fun imp -> is_status_implicit imp & id = name_of_implicit imp)
let extract_explicit_arg imps args =
let rec aux = function
| [] -> [],[]
| (a,e)::l ->
let (eargs,rargs) = aux l in
match e with
| None -> (eargs,a::rargs)
| Some (loc,pos) ->
let id = match pos with
| ExplByName id ->
if not (exists_implicit_name id imps) then
user_err_loc
(loc,"",str "Wrong argument name: " ++ pr_id id ++ str ".");
if List.mem_assoc id eargs then
user_err_loc (loc,"",str "Argument name " ++ pr_id id
++ str " occurs more than once.");
id
| ExplByPos (p,_id) ->
let id =
try
let imp = List.nth imps (p-1) in
if not (is_status_implicit imp) then failwith "imp";
name_of_implicit imp
with Failure _ (* "nth" | "imp" *) ->
user_err_loc
(loc,"",str"Wrong argument position: " ++ int p ++ str ".")
in
if List.mem_assoc id eargs then
user_err_loc (loc,"",str"Argument at position " ++ int p ++
str " is mentioned more than once.");
id in
((id,(loc,a))::eargs,rargs)
in aux args
(**********************************************************************)
(* Main loop *)
let internalize sigma globalenv env allow_patvar lvar c =
let rec intern (ids,unb,tmp_scope,scopes as env) = function
| CRef ref as x ->
let (c,imp,subscopes,l),_ =
intern_applied_reference intern env lvar [] ref in
(match intern_impargs c env imp subscopes l with
| [] -> c
| l -> RApp (constr_loc x, c, l))
| CFix (loc, (locid,iddef), dl) ->
let lf = List.map (fun ((_, id),_,_,_,_) -> id) dl in
let dl = Array.of_list dl in
let n =
try list_index0 iddef lf
with Not_found ->
raise (InternalizationError (locid,UnboundFixName (false,iddef)))
in
let idl = Array.map
(fun (id,(n,order),bl,ty,bd) ->
let intern_ro_arg f =
let before, after = split_at_annot bl n in
let ((ids',_,_,_) as env',rbefore) =
List.fold_left intern_local_binder (env,[]) before in
let ro = f (intern (ids', unb, tmp_scope, scopes)) in
let n' = Option.map (fun _ -> List.length rbefore) n in
n', ro, List.fold_left intern_local_binder (env',rbefore) after
in
let n, ro, ((ids',_,_,_),rbl) =
match order with
| CStructRec ->
intern_ro_arg (fun _ -> RStructRec)
| CWfRec c ->
intern_ro_arg (fun f -> RWfRec (f c))
| CMeasureRec (m,r) ->
intern_ro_arg (fun f -> RMeasureRec (f m, Option.map f r))
in
let ids'' = List.fold_right Idset.add lf ids' in
((n, ro), List.rev rbl,
intern_type (ids',unb,tmp_scope,scopes) ty,
intern (ids'',unb,None,scopes) bd)) dl in
RRec (loc,RFix
(Array.map (fun (ro,_,_,_) -> ro) idl,n),
Array.of_list lf,
Array.map (fun (_,bl,_,_) -> bl) idl,
Array.map (fun (_,_,ty,_) -> ty) idl,
Array.map (fun (_,_,_,bd) -> bd) idl)
| CCoFix (loc, (locid,iddef), dl) ->
let lf = List.map (fun ((_, id),_,_,_) -> id) dl in
let dl = Array.of_list dl in
let n =
try list_index0 iddef lf
with Not_found ->
raise (InternalizationError (locid,UnboundFixName (true,iddef)))
in
let idl = Array.map
(fun (id,bl,ty,bd) ->
let ((ids',_,_,_),rbl) =
List.fold_left intern_local_binder (env,[]) bl in
let ids'' = List.fold_right Idset.add lf ids' in
(List.rev rbl,
intern_type (ids',unb,tmp_scope,scopes) ty,
intern (ids'',unb,None,scopes) bd)) dl in
RRec (loc,RCoFix n,
Array.of_list lf,
Array.map (fun (bl,_,_) -> bl) idl,
Array.map (fun (_,ty,_) -> ty) idl,
Array.map (fun (_,_,bd) -> bd) idl)
| CArrow (loc,c1,c2) ->
RProd (loc, Anonymous, Explicit, intern_type env c1, intern_type env c2)
| CProdN (loc,[],c2) ->
intern_type env c2
| CProdN (loc,(nal,bk,ty)::bll,c2) ->
iterate_prod loc env bk ty (CProdN (loc, bll, c2)) nal
| CLambdaN (loc,[],c2) ->
intern env c2
| CLambdaN (loc,(nal,bk,ty)::bll,c2) ->
iterate_lam loc (reset_tmp_scope env) bk ty (CLambdaN (loc, bll, c2)) nal
| CLetIn (loc,na,c1,c2) ->
RLetIn (loc, snd na, intern (reset_tmp_scope env) c1,
intern (push_name_env lvar env na) c2)
| CNotation (loc,"- _",([CPrim (_,Numeral p)],[],[]))
when Bigint.is_strictly_pos p ->
intern env (CPrim (loc,Numeral (Bigint.neg p)))
| CNotation (_,"( _ )",([a],[],[])) -> intern env a
| CNotation (loc,ntn,args) ->
intern_notation intern env lvar loc ntn args
| CGeneralization (loc,b,a,c) ->
intern_generalization intern env lvar loc b a c
| CPrim (loc, p) ->
fst (Notation.interp_prim_token loc p (tmp_scope,scopes))
| CDelimiters (loc, key, e) ->
intern (ids,unb,None,find_delimiters_scope loc key::scopes) e
| CAppExpl (loc, (isproj,ref), args) ->
let (f,_,args_scopes,_),args =
let args = List.map (fun a -> (a,None)) args in
intern_applied_reference intern env lvar args ref in
check_projection isproj (List.length args) f;
(* Rem: RApp(_,f,[]) stands for @f *)
RApp (loc, f, intern_args env args_scopes (List.map fst args))
| CApp (loc, (isproj,f), args) ->
let isproj,f,args = match f with
(* Compact notations like "t.(f args') args" *)
| CApp (_,(Some _,f), args') when isproj=None -> isproj,f,args'@args
(* Don't compact "(f args') args" to resolve implicits separately *)
| _ -> isproj,f,args in
let (c,impargs,args_scopes,l),args =
match f with
| CRef ref -> intern_applied_reference intern env lvar args ref
| CNotation (loc,ntn,([],[],[])) ->
let c = intern_notation intern env lvar loc ntn ([],[],[]) in
find_appl_head_data c, args
| x -> (intern env f,[],[],[]), args in
let args =
intern_impargs c env impargs args_scopes (merge_impargs l args) in
check_projection isproj (List.length args) c;
(match c with
(* Now compact "(f args') args" *)
| RApp (loc', f', args') -> RApp (join_loc loc' loc, f',args'@args)
| _ -> RApp (loc, c, args))
| CRecord (loc, _, fs) ->
let cargs =
sort_fields true loc fs
(fun k l -> CHole (loc, Some (Evd.QuestionMark (Evd.Define true))) :: l)
in
begin
match cargs with
| None -> user_err_loc (loc, "intern", str"No constructor inference.")
| Some (n, constrname, args) ->
let pars = list_make n (CHole (loc, None)) in
let app = CAppExpl (loc, (None, constrname), List.rev_append pars args) in
intern env app
end
| CCases (loc, sty, rtnpo, tms, eqns) ->
let tms,env' = List.fold_right
(fun citm (inds,env) ->
let (tm,ind),nal = intern_case_item env citm in
(tm,ind)::inds,List.fold_left (push_name_env lvar) env nal)
tms ([],env) in
let rtnpo = Option.map (intern_type env') rtnpo in
let eqns' = List.map (intern_eqn (List.length tms) env) eqns in
RCases (loc, sty, rtnpo, tms, List.flatten eqns')
| CLetTuple (loc, nal, (na,po), b, c) ->
let env' = reset_tmp_scope env in
let ((b',(na',_)),ids) = intern_case_item env' (b,(na,None)) in
let p' = Option.map (fun p ->
let env'' = List.fold_left (push_name_env lvar) env ids in
intern_type env'' p) po in
RLetTuple (loc, List.map snd nal, (na', p'), b',
intern (List.fold_left (push_name_env lvar) env nal) c)
| CIf (loc, c, (na,po), b1, b2) ->
let env' = reset_tmp_scope env in
let ((c',(na',_)),ids) = intern_case_item env' (c,(na,None)) in
let p' = Option.map (fun p ->
let env'' = List.fold_left (push_name_env lvar) env ids in
intern_type env'' p) po in
RIf (loc, c', (na', p'), intern env b1, intern env b2)
| CHole (loc, k) ->
RHole (loc, match k with Some k -> k | None -> Evd.QuestionMark (Evd.Define true))
| CPatVar (loc, n) when allow_patvar ->
RPatVar (loc, n)
| CPatVar (loc, _) ->
raise (InternalizationError (loc,IllegalMetavariable))
| CEvar (loc, n, l) ->
REvar (loc, n, Option.map (List.map (intern env)) l)
| CSort (loc, s) ->
RSort(loc,s)
| CCast (loc, c1, CastConv (k, c2)) ->
RCast (loc,intern env c1, CastConv (k, intern_type env c2))
| CCast (loc, c1, CastCoerce) ->
RCast (loc,intern env c1, CastCoerce)
| CDynamic (loc,d) -> RDynamic (loc,d)
and intern_type env = intern (set_type_scope env)
and intern_local_binder env bind =
intern_local_binder_aux intern intern_type lvar env bind
(* Expands a multiple pattern into a disjunction of multiple patterns *)
and intern_multiple_pattern scopes n (loc,pl) =
let idsl_pll =
List.map (intern_cases_pattern globalenv scopes ([],[]) None) pl in
check_number_of_pattern loc n pl;
product_of_cases_patterns [] idsl_pll
(* Expands a disjunction of multiple pattern *)
and intern_disjunctive_multiple_pattern scopes loc n mpl =
assert (mpl <> []);
let mpl' = List.map (intern_multiple_pattern scopes n) mpl in
let (idsl,mpl') = List.split mpl' in
let ids = List.hd idsl in
check_or_pat_variables loc ids (List.tl idsl);
(ids,List.flatten mpl')
Expands a pattern - matching clause [ lhs = > rhs ]
and intern_eqn n (ids,unb,tmp_scope,scopes) (loc,lhs,rhs) =
let eqn_ids,pll = intern_disjunctive_multiple_pattern scopes loc n lhs in
(* Linearity implies the order in ids is irrelevant *)
check_linearity lhs eqn_ids;
let env_ids = List.fold_right Idset.add eqn_ids ids in
List.map (fun (asubst,pl) ->
let rhs = replace_vars_constr_expr asubst rhs in
List.iter message_redundant_alias asubst;
let rhs' = intern (env_ids,unb,tmp_scope,scopes) rhs in
(loc,eqn_ids,pl,rhs')) pll
and intern_case_item (vars,unb,_,scopes as env) (tm,(na,t)) =
let tm' = intern env tm in
let ids,typ = match t with
| Some t ->
let tids = ids_of_cases_indtype t in
let tids = List.fold_right Idset.add tids Idset.empty in
let t = intern_type (tids,unb,None,scopes) t in
let loc,ind,l = match t with
| RRef (loc,IndRef ind) -> (loc,ind,[])
| RApp (loc,RRef (_,IndRef ind),l) -> (loc,ind,l)
| _ -> error_bad_inductive_type (loc_of_rawconstr t) in
let nparams, nrealargs = inductive_nargs globalenv ind in
let nindargs = nparams + nrealargs in
if List.length l <> nindargs then
error_wrong_numarg_inductive_loc loc globalenv ind nindargs;
let nal = List.map (function
| RHole (loc,_) -> loc,Anonymous
| RVar (loc,id) -> loc,Name id
| c -> user_err_loc (loc_of_rawconstr c,"",str "Not a name.")) l in
let parnal,realnal = list_chop nparams nal in
if List.exists (fun (_,na) -> na <> Anonymous) parnal then
error_inductive_parameter_not_implicit loc;
realnal, Some (loc,ind,nparams,List.map snd realnal)
| None ->
[], None in
let na = match tm', na with
| RVar (loc,id), None when Idset.mem id vars -> loc,Name id
| RRef (loc, VarRef id), None -> loc,Name id
| _, None -> dummy_loc,Anonymous
| _, Some (loc,na) -> loc,na in
(tm',(snd na,typ)), na::ids
and iterate_prod loc2 env bk ty body nal =
let rec default env bk = function
| (loc1,na as locna)::nal ->
if nal <> [] then check_capture loc1 ty na;
let body = default (push_name_env lvar env locna) bk nal in
let ty = locate_if_isevar loc1 na (intern_type env ty) in
RProd (join_loc loc1 loc2, na, bk, ty, body)
| [] -> intern_type env body
in
match bk with
| Default b -> default env b nal
| Generalized (b,b',t) ->
let env, ibind = intern_generalized_binder intern_type lvar env [] (List.hd nal) b b' t ty in
let body = intern_type env body in
it_mkRProd ibind body
and iterate_lam loc2 env bk ty body nal =
let rec default env bk = function
| (loc1,na as locna)::nal ->
if nal <> [] then check_capture loc1 ty na;
let body = default (push_name_env lvar env locna) bk nal in
let ty = locate_if_isevar loc1 na (intern_type env ty) in
RLambda (join_loc loc1 loc2, na, bk, ty, body)
| [] -> intern env body
in match bk with
| Default b -> default env b nal
| Generalized (b, b', t) ->
let env, ibind = intern_generalized_binder intern_type lvar env [] (List.hd nal) b b' t ty in
let body = intern env body in
it_mkRLambda ibind body
and intern_impargs c env l subscopes args =
let l = select_impargs_size (List.length args) l in
let eargs, rargs = extract_explicit_arg l args in
let rec aux n impl subscopes eargs rargs =
let (enva,subscopes') = apply_scope_env env subscopes in
match (impl,rargs) with
| (imp::impl', rargs) when is_status_implicit imp ->
begin try
let id = name_of_implicit imp in
let (_,a) = List.assoc id eargs in
let eargs' = List.remove_assoc id eargs in
intern enva a :: aux (n+1) impl' subscopes' eargs' rargs
with Not_found ->
if rargs=[] & eargs=[] & not (maximal_insertion_of imp) then
(* Less regular arguments than expected: complete *)
(* with implicit arguments if maximal insertion is set *)
[]
else
RHole (set_hole_implicit (n,get_implicit_name n l) (force_inference_of imp) c) ::
aux (n+1) impl' subscopes' eargs rargs
end
| (imp::impl', a::rargs') ->
intern enva a :: aux (n+1) impl' subscopes' eargs rargs'
| (imp::impl', []) ->
if eargs <> [] then
(let (id,(loc,_)) = List.hd eargs in
user_err_loc (loc,"",str "Not enough non implicit
arguments to accept the argument bound to " ++
pr_id id ++ str"."));
[]
| ([], rargs) ->
assert (eargs = []);
intern_args env subscopes rargs
in aux 1 l subscopes eargs rargs
and intern_args env subscopes = function
| [] -> []
| a::args ->
let (enva,subscopes) = apply_scope_env env subscopes in
(intern enva a) :: (intern_args env subscopes args)
in
try
intern env c
with
InternalizationError (loc,e) ->
user_err_loc (loc,"internalize",
explain_internalization_error e)
(**************************************************************************)
Functions to translate constr_expr into rawconstr
(**************************************************************************)
let extract_ids env =
List.fold_right Idset.add
(Termops.ids_of_rel_context (Environ.rel_context env))
Idset.empty
let intern_gen isarity sigma env
?(impls=[]) ?(allow_patvar=false) ?(ltacvars=([],[]))
c =
let tmp_scope =
if isarity then Some Notation.type_scope else None in
internalize sigma env (extract_ids env, false, tmp_scope,[])
allow_patvar (ltacvars,Environ.named_context env, [], impls) c
let intern_constr sigma env c = intern_gen false sigma env c
let intern_type sigma env c = intern_gen true sigma env c
let intern_pattern env patt =
try
intern_cases_pattern env [] ([],[]) None patt
with
InternalizationError (loc,e) ->
user_err_loc (loc,"internalize",explain_internalization_error e)
type manual_implicits = (explicitation * (bool * bool * bool)) list
(*********************************************************************)
(* Functions to parse and interpret constructions *)
let interp_gen kind sigma env
?(impls=[]) ?(allow_patvar=false) ?(ltacvars=([],[]))
c =
let c = intern_gen (kind=IsType) ~impls ~allow_patvar ~ltacvars sigma env c in
Default.understand_gen kind sigma env c
let interp_constr sigma env c =
interp_gen (OfType None) sigma env c
let interp_type sigma env ?(impls=[]) c =
interp_gen IsType sigma env ~impls c
let interp_casted_constr sigma env ?(impls=[]) c typ =
interp_gen (OfType (Some typ)) sigma env ~impls c
let interp_open_constr sigma env c =
Default.understand_tcc sigma env (intern_constr sigma env c)
let interp_open_constr_patvar sigma env c =
let raw = intern_gen false sigma env c ~allow_patvar:true in
let sigma = ref (Evd.create_evar_defs sigma) in
let evars = ref (Gmap.empty : (identifier,rawconstr) Gmap.t) in
let rec patvar_to_evar r = match r with
| RPatVar (loc,(_,id)) ->
( try Gmap.find id !evars
with Not_found ->
let ev = Evarutil.e_new_evar sigma env (Termops.new_Type()) in
let ev = Evarutil.e_new_evar sigma env ev in
TODO
evars := Gmap.add id rev !evars;
rev
)
| _ -> map_rawconstr patvar_to_evar r in
let raw = patvar_to_evar raw in
Default.understand_tcc !sigma env raw
let interp_constr_judgment sigma env c =
Default.understand_judgment sigma env (intern_constr sigma env c)
let interp_constr_evars_gen_impls ?evdref ?(fail_evar=true)
env ?(impls=[]) kind c =
let evdref =
match evdref with
| None -> ref Evd.empty
| Some evdref -> evdref
in
let istype = kind = IsType in
let c = intern_gen istype ~impls !evdref env c in
let imps = Implicit_quantifiers.implicits_of_rawterm ~with_products:istype c in
Default.understand_tcc_evars ~fail_evar evdref env kind c, imps
let interp_casted_constr_evars_impls ?evdref ?(fail_evar=true)
env ?(impls=[]) c typ =
interp_constr_evars_gen_impls ?evdref ~fail_evar env ~impls (OfType (Some typ)) c
let interp_type_evars_impls ?evdref ?(fail_evar=true) env ?(impls=[]) c =
interp_constr_evars_gen_impls ?evdref ~fail_evar env IsType ~impls c
let interp_constr_evars_impls ?evdref ?(fail_evar=true) env ?(impls=[]) c =
interp_constr_evars_gen_impls ?evdref ~fail_evar env (OfType None) ~impls c
let interp_constr_evars_gen evdref env ?(impls=[]) kind c =
let c = intern_gen (kind=IsType) ~impls ( !evdref) env c in
Default.understand_tcc_evars evdref env kind c
let interp_casted_constr_evars evdref env ?(impls=[]) c typ =
interp_constr_evars_gen evdref env ~impls (OfType (Some typ)) c
let interp_type_evars evdref env ?(impls=[]) c =
interp_constr_evars_gen evdref env IsType ~impls c
type ltac_sign = identifier list * unbound_ltac_var_map
let intern_constr_pattern sigma env ?(as_type=false) ?(ltacvars=([],[])) c =
let c = intern_gen as_type ~allow_patvar:true ~ltacvars sigma env c in
pattern_of_rawconstr c
let interp_aconstr ?(impls=[]) vars recvars a =
let env = Global.env () in
(* [vl] is intended to remember the scope of the free variables of [a] *)
let vl = List.map (fun (id,typ) -> (id,(ref None,typ))) vars in
let c = internalize Evd.empty (Global.env()) (extract_ids env, false, None, [])
false (([],[]),Environ.named_context env,vl,impls) a in
Translate and check that [ c ] has all its free variables bound in [ vars ]
let a = aconstr_of_rawconstr vars recvars c in
(* Splits variables into those that are binding, bound, or both *)
(* binding and bound *)
let out_scope = function None -> None,[] | Some (a,l) -> a,l in
let vars = List.map (fun (id,(sc,typ)) -> (id,(out_scope !sc,typ))) vl in
(* Returns [a] and the ordered list of variables with their scopes *)
vars, a
(* Interpret binders and contexts *)
let interp_binder sigma env na t =
let t = intern_gen true sigma env t in
let t' = locate_if_isevar (loc_of_rawconstr t) na t in
Default.understand_type sigma env t'
let interp_binder_evars evdref env na t =
let t = intern_gen true !evdref env t in
let t' = locate_if_isevar (loc_of_rawconstr t) na t in
Default.understand_tcc_evars evdref env IsType t'
open Environ
open Term
let my_intern_constr sigma env lvar acc c =
internalize sigma env acc false lvar c
let my_intern_type sigma env lvar acc c = my_intern_constr sigma env lvar (set_type_scope acc) c
let intern_context global_level sigma env params =
let lvar = (([],[]),Environ.named_context env, [], []) in
snd (List.fold_left
(intern_local_binder_aux ~global_level (my_intern_constr sigma env lvar) (my_intern_type sigma env lvar) lvar)
((extract_ids env,false,None,[]), []) params)
let interp_rawcontext_gen understand_type understand_judgment env bl =
let (env, par, _, impls) =
List.fold_left
(fun (env,params,n,impls) (na, k, b, t) ->
match b with
None ->
let t' = locate_if_isevar (loc_of_rawconstr t) na t in
let t = understand_type env t' in
let d = (na,None,t) in
let impls =
if k = Implicit then
let na = match na with Name n -> Some n | Anonymous -> None in
(ExplByPos (n, na), (true, true, true)) :: impls
else impls
in
(push_rel d env, d::params, succ n, impls)
| Some b ->
let c = understand_judgment env b in
let d = (na, Some c.uj_val, c.uj_type) in
(push_rel d env, d::params, succ n, impls))
(env,[],1,[]) (List.rev bl)
in (env, par), impls
let interp_context_gen understand_type understand_judgment ?(global_level=false) sigma env params =
let bl = intern_context global_level sigma env params in
interp_rawcontext_gen understand_type understand_judgment env bl
let interp_context ?(global_level=false) sigma env params =
interp_context_gen (Default.understand_type sigma)
(Default.understand_judgment sigma) ~global_level sigma env params
let interp_context_evars ?(global_level=false) evdref env params =
interp_context_gen (fun env t -> Default.understand_tcc_evars evdref env IsType t)
(Default.understand_judgment_tcc evdref) ~global_level !evdref env params
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/interp/constrintern.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
$Id: constrintern.ml 13620 2010-11-04 14:11:49Z herbelin $
To interpret implicits and arg scopes of variables in inductive
types and recursive definitions and of projection names in records
list of params
signature of impargs of the variable
subscopes of the args of the variable
Historically for parsing grammar rules, but in fact used only for
translator, v7 parsing, and unstrict tactic internalization
********************************************************************
Locating reference, possibly via an abbreviation
********************************************************************
Internalization errors
pr_id (name_of_position p) in
********************************************************************
Pre-computing the implicit arguments and arguments scopes needed
for interpretation
In inductive types, the parameters are fixed implicit arguments
Unable to know in advance what the implicit arguments will be
********************************************************************
Contracting "{ _ }" in notations
This contracts the special case of "{ _ }" for sumbool, sumor notations
Remark: expansion of squash at definition is done in metasyntax.ml
side effect; don't inline
side effect; don't inline
********************************************************************
Remembering the parsing scope of variables in notations
scopes have no effect on the interpretation of identifiers, hence
we can tolerate having a variable occurring several times in
different scopes:
Not in a notation
********************************************************************
TODO: fail if several names with different implicit types
TODO: fail if several names with different implicit types
********************************************************************
Syntax extensions
Binders not bound in the notation do not capture variables
outside the notation (i.e. in the substitution)
subst remembers the delimiters stack in the interpretation
of the notations
********************************************************************
Discriminating between bound variables and global references
Is [id] an inductive type potentially with implicit
Is [id] bound in current term or is an ltac var bound to constr
Is [id] a notation variable
Is [id] the special variable for recursive notations
Is [id] bound to a free name in ltac (this is an ltac error message)
Is [id] a goal or section variable
[id] a section variable
Redundant: could be done in intern_qualid
[id] a goal variable
Is it a global reference or a syntactic definition?
Rule out section vars since these should have been found by intern_var
Extra allowance for non globalizing functions
********************************************************************
Cases
Check linearity of pattern-matching
Match the number of pattern against the number of matched args
i.e. with let's
Manage multiple aliases
Expanding notations
Tolerance for a @id notation
subst remembers the delimiters stack in the interpretation
of the notations
Happens for local notation joint with inductive/fixpoint defs
Differentiating between constructors and matching variables
patt var does not exists globally
patt var also exists globally but does not satisfy preconditions
mode=false if pattern and true if constructor
the number of parameters
the reference constructor of the record
number of params
list of projections
we found it
we don't want anonymous fields
anonymous arguments don't appear in m
now we want to have all fields of the pattern indexed by their place in
the constructor
we sort them
a function to complete with wildcards
a function to remove indice
********************************************************************
"nth" | "imp"
********************************************************************
Main loop
Rem: RApp(_,f,[]) stands for @f
Compact notations like "t.(f args') args"
Don't compact "(f args') args" to resolve implicits separately
Now compact "(f args') args"
Expands a multiple pattern into a disjunction of multiple patterns
Expands a disjunction of multiple pattern
Linearity implies the order in ids is irrelevant
Less regular arguments than expected: complete
with implicit arguments if maximal insertion is set
************************************************************************
************************************************************************
*******************************************************************
Functions to parse and interpret constructions
[vl] is intended to remember the scope of the free variables of [a]
Splits variables into those that are binding, bound, or both
binding and bound
Returns [a] and the ordered list of variables with their scopes
Interpret binders and contexts | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Util
open Flags
open Names
open Nameops
open Namegen
open Libnames
open Impargs
open Rawterm
open Pattern
open Pretyping
open Cases
open Topconstr
open Nametab
open Notation
open Inductiveops
type var_internalization_type =
| Recursive
| Method
type var_internalization_data =
type of the " free " variable , for coqdoc , e.g. while typing the
constructor of JMeq , " JMeq " behaves as a variable of type Inductive
constructor of JMeq, "JMeq" behaves as a variable of type Inductive *)
var_internalization_type *
impargs to automatically add to the variable , e.g. for " JMeq A a B b "
in implicit mode , this is [ A;B ] and this adds ( A:=A ) and ( )
in implicit mode, this is [A;B] and this adds (A:=A) and (B:=B) *)
identifier list *
Impargs.implicit_status list *
scope_name option list
type internalization_env =
(identifier * var_internalization_data) list
type raw_binder = (name * binding_kind * rawconstr option * rawconstr)
let interning_grammar = ref false
let for_grammar f x =
interning_grammar := true;
let a = f x in
interning_grammar := false;
a
let locate_reference qid =
Smartlocate.global_of_extended_global (Nametab.locate_extended qid)
let is_global id =
try
let _ = locate_reference (qualid_of_ident id) in true
with Not_found ->
false
let global_reference_of_reference ref =
locate_reference (snd (qualid_of_reference ref))
let global_reference id =
constr_of_global (locate_reference (qualid_of_ident id))
let construct_reference ctx id =
try
Term.mkVar (let _ = Sign.lookup_named id ctx in id)
with Not_found ->
global_reference id
let global_reference_in_absolute_module dir id =
constr_of_global (Nametab.global_of_path (Libnames.make_path dir id))
type internalization_error =
| VariableCapture of identifier
| WrongExplicitImplicit
| IllegalMetavariable
| NotAConstructor of reference
| UnboundFixName of bool * identifier
| NonLinearPattern of identifier
| BadPatternsNumber of int * int
| BadExplicitationNumber of explicitation * int option
exception InternalizationError of loc * internalization_error
let explain_variable_capture id =
str "The variable " ++ pr_id id ++ str " occurs in its type"
let explain_wrong_explicit_implicit =
str "Found an explicitly given implicit argument but was expecting" ++
fnl () ++ str "a regular one"
let explain_illegal_metavariable =
str "Metavariables allowed only in patterns"
let explain_not_a_constructor ref =
str "Unknown constructor: " ++ pr_reference ref
let explain_unbound_fix_name is_cofix id =
str "The name" ++ spc () ++ pr_id id ++
spc () ++ str "is not bound in the corresponding" ++ spc () ++
str (if is_cofix then "co" else "") ++ str "fixpoint definition"
let explain_non_linear_pattern id =
str "The variable " ++ pr_id id ++ str " is bound several times in pattern"
let explain_bad_patterns_number n1 n2 =
str "Expecting " ++ int n1 ++ str (plural n1 " pattern") ++
str " but found " ++ int n2
let explain_bad_explicitation_number n po =
match n with
| ExplByPos (n,_id) ->
let s = match po with
| None -> str "a regular argument"
| Some p -> int p in
str "Bad explicitation number: found " ++ int n ++
str" but was expecting " ++ s
| ExplByName id ->
let s = match po with
| None -> str "a regular argument"
str "Bad explicitation name: found " ++ pr_id id ++
str" but was expecting " ++ s
let explain_internalization_error e =
let pp = match e with
| VariableCapture id -> explain_variable_capture id
| WrongExplicitImplicit -> explain_wrong_explicit_implicit
| IllegalMetavariable -> explain_illegal_metavariable
| NotAConstructor ref -> explain_not_a_constructor ref
| UnboundFixName (iscofix,id) -> explain_unbound_fix_name iscofix id
| NonLinearPattern id -> explain_non_linear_pattern id
| BadPatternsNumber (n1,n2) -> explain_bad_patterns_number n1 n2
| BadExplicitationNumber (n,po) -> explain_bad_explicitation_number n po in
pp ++ str "."
let error_bad_inductive_type loc =
user_err_loc (loc,"",str
"This should be an inductive type applied to names or \"_\".")
let error_inductive_parameter_not_implicit loc =
user_err_loc (loc,"", str
("The parameters of inductive types do not bind in\n"^
"the 'return' clauses; they must be replaced by '_' in the 'in' clauses."))
let empty_internalization_env = []
let compute_explicitable_implicit imps = function
| Inductive params ->
let sub_impl,_ = list_chop (List.length params) imps in
let sub_impl' = List.filter is_status_implicit sub_impl in
List.map name_of_implicit sub_impl'
| Recursive | Method ->
[]
let compute_internalization_data env ty typ impl =
let impl = compute_implicits_with_manual env typ (is_implicit_args()) impl in
let expls_impl = compute_explicitable_implicit impl ty in
(ty, expls_impl, impl, compute_arguments_scope typ)
let compute_internalization_env env ty =
list_map3
(fun id typ impl -> (id,compute_internalization_data env ty typ impl))
let rec wildcards ntn n =
if n = String.length ntn then []
else let l = spaces ntn (n+1) in if ntn.[n] = '_' then n::l else l
and spaces ntn n =
if n = String.length ntn then []
else if ntn.[n] = ' ' then wildcards ntn (n+1) else spaces ntn (n+1)
let expand_notation_string ntn n =
let pos = List.nth (wildcards ntn 0) n in
let hd = if pos = 0 then "" else String.sub ntn 0 pos in
let tl =
if pos = String.length ntn then ""
else String.sub ntn (pos+1) (String.length ntn - pos -1) in
hd ^ "{ _ }" ^ tl
let contract_notation ntn (l,ll,bll) =
let ntn' = ref ntn in
let rec contract_squash n = function
| [] -> []
| CNotation (_,"{ _ }",([a],[],[])) :: l ->
ntn' := expand_notation_string !ntn' n;
contract_squash n (a::l)
| a :: l ->
a::contract_squash (n+1) l in
let l = contract_squash 0 l in
!ntn',(l,ll,bll)
let contract_pat_notation ntn (l,ll) =
let ntn' = ref ntn in
let rec contract_squash n = function
| [] -> []
| CPatNotation (_,"{ _ }",([a],[])) :: l ->
ntn' := expand_notation_string !ntn' n;
contract_squash n (a::l)
| a :: l ->
a::contract_squash (n+1) l in
let l = contract_squash 0 l in
!ntn',(l,ll)
let make_current_scope = function
| (Some tmp_scope,(sc::_ as scopes)) when sc = tmp_scope -> scopes
| (Some tmp_scope,scopes) -> tmp_scope::scopes
| None,scopes -> scopes
let pr_scope_stack = function
| [] -> str "the empty scope stack"
| [a] -> str "scope " ++ str a
| l -> str "scope stack " ++
str "[" ++ prlist_with_sep pr_comma str l ++ str "]"
let error_inconsistent_scope loc id scopes1 scopes2 =
user_err_loc (loc,"set_var_scope",
pr_id id ++ str " is used both in " ++
pr_scope_stack scopes1 ++ strbrk " and in " ++ pr_scope_stack scopes2)
let error_expect_constr_notation_type loc id =
user_err_loc (loc,"",
pr_id id ++ str " is bound in the notation to a term variable.")
let error_expect_binder_notation_type loc id =
user_err_loc (loc,"",
pr_id id ++
str " is expected to occur in binding position in the right-hand side.")
let set_var_scope loc id istermvar (_,_,scopt,scopes) ntnvars =
try
let idscopes,typ = List.assoc id ntnvars in
if !idscopes <> None &
make_current_scope (Option.get !idscopes)
<> make_current_scope (scopt,scopes) then
error_inconsistent_scope loc id
(make_current_scope (Option.get !idscopes))
(make_current_scope (scopt,scopes))
else
idscopes := Some (scopt,scopes);
match typ with
| NtnInternTypeBinder ->
if istermvar then error_expect_binder_notation_type loc id
| NtnInternTypeConstr ->
We need sometimes to parse idents at a constr level for
factorization and we can not enforce this constraint :
if not istermvar then
factorization and we cannot enforce this constraint:
if not istermvar then error_expect_constr_notation_type loc id *)
()
| NtnInternTypeIdent -> ()
with Not_found ->
()
let set_type_scope (ids,unb,tmp_scope,scopes) =
(ids,unb,Some Notation.type_scope,scopes)
let reset_tmp_scope (ids,unb,tmp_scope,scopes) =
(ids,unb,None,scopes)
let rec it_mkRProd env body =
match env with
(na, bk, _, t) :: tl -> it_mkRProd tl (RProd (dummy_loc, na, bk, t, body))
| [] -> body
let rec it_mkRLambda env body =
match env with
(na, bk, _, t) :: tl -> it_mkRLambda tl (RLambda (dummy_loc, na, bk, t, body))
| [] -> body
Utilities for binders
let check_capture loc ty = function
| Name id when occur_var_constr_expr id ty ->
raise (InternalizationError (loc,VariableCapture id))
| _ ->
()
let locate_if_isevar loc na = function
| RHole _ ->
(try match na with
| Name id -> Reserve.find_reserved_type id
| Anonymous -> raise Not_found
with Not_found -> RHole (loc, Evd.BinderType na))
| x -> x
let check_hidden_implicit_parameters id (_,_,_,impls) =
if List.exists (function
| (_,(Inductive indparams,_,_,_)) -> List.mem id indparams
| _ -> false) impls
then
errorlabstrm "" (strbrk "A parameter of an inductive type " ++
pr_id id ++ strbrk " is not allowed to be used as a bound variable in the type of its constructor.")
let push_name_env ?(global_level=false) lvar (ids,unb,tmpsc,scopes as env) =
function
| loc,Anonymous ->
if global_level then
user_err_loc (loc,"", str "Anonymous variables not allowed");
env
| loc,Name id ->
check_hidden_implicit_parameters id lvar;
set_var_scope loc id false env (let (_,_,ntnvars,_) = lvar in ntnvars);
if global_level then Dumpglob.dump_definition (loc,id) true "var"
else Dumpglob.dump_binding loc id;
(Idset.add id ids,unb,tmpsc,scopes)
let intern_generalized_binder ?(global_level=false) intern_type lvar
(ids,unb,tmpsc,sc as env) bl (loc, na) b b' t ty =
let ids = match na with Anonymous -> ids | Name na -> Idset.add na ids in
let ty, ids' =
if t then ty, ids else
Implicit_quantifiers.implicit_application ids
Implicit_quantifiers.combine_params_freevar ty
in
let ty' = intern_type (ids,true,tmpsc,sc) ty in
let fvs = Implicit_quantifiers.generalizable_vars_of_rawconstr ~bound:ids ~allowed:ids' ty' in
let env' = List.fold_left (fun env (x, l) -> push_name_env ~global_level lvar env (l, Name x)) env fvs in
let bl = List.map (fun (id, loc) -> (Name id, b, None, RHole (loc, Evd.BinderType (Name id)))) fvs in
let na = match na with
| Anonymous ->
if global_level then na
else
let name =
let id =
match ty with
| CApp (_, (_, CRef (Ident (loc,id))), _) -> id
| _ -> id_of_string "H"
in Implicit_quantifiers.make_fresh ids' (Global.env ()) id
in Name name
| _ -> na
in (push_name_env ~global_level lvar env' (loc,na)), (na,b',None,ty') :: List.rev bl
let intern_local_binder_aux ?(global_level=false) intern intern_type lvar (env,bl) = function
| LocalRawAssum(nal,bk,ty) ->
(match bk with
| Default k ->
let (loc,na) = List.hd nal in
let ty = locate_if_isevar loc na (intern_type env ty) in
List.fold_left
(fun (env,bl) na ->
(push_name_env lvar env na,(snd na,k,None,ty)::bl))
(env,bl) nal
| Generalized (b,b',t) ->
let env, b = intern_generalized_binder ~global_level intern_type lvar env bl (List.hd nal) b b' t ty in
env, b @ bl)
| LocalRawDef((loc,na as locna),def) ->
(push_name_env lvar env locna,
(na,Explicit,Some(intern env def),RHole(loc,Evd.BinderType na))::bl)
let intern_generalization intern (ids,unb,tmp_scope,scopes as env) lvar loc bk ak c =
let c = intern (ids,true,tmp_scope,scopes) c in
let fvs = Implicit_quantifiers.generalizable_vars_of_rawconstr ~bound:ids c in
let env', c' =
let abs =
let pi =
match ak with
| Some AbsPi -> true
| None when tmp_scope = Some Notation.type_scope
|| List.mem Notation.type_scope scopes -> true
| _ -> false
in
if pi then
(fun (id, loc') acc ->
RProd (join_loc loc' loc, Name id, bk, RHole (loc', Evd.BinderType (Name id)), acc))
else
(fun (id, loc') acc ->
RLambda (join_loc loc' loc, Name id, bk, RHole (loc', Evd.BinderType (Name id)), acc))
in
List.fold_right (fun (id, loc as lid) (env, acc) ->
let env' = push_name_env lvar env (loc, Name id) in
(env', abs lid acc)) fvs (env,c)
in c'
let iterate_binder intern lvar (env,bl) = function
| LocalRawAssum(nal,bk,ty) ->
let intern_type env = intern (set_type_scope env) in
(match bk with
| Default k ->
let (loc,na) = List.hd nal in
let ty = intern_type env ty in
let ty = locate_if_isevar loc na ty in
List.fold_left
(fun (env,bl) na -> (push_name_env lvar env na,(snd na,k,None,ty)::bl))
(env,bl) nal
| Generalized (b,b',t) ->
let env, b = intern_generalized_binder intern_type lvar env bl (List.hd nal) b b' t ty in
env, b @ bl)
| LocalRawDef((loc,na as locna),def) ->
(push_name_env lvar env locna,
(na,Explicit,Some(intern env def),RHole(loc,Evd.BinderType na))::bl)
let option_mem_assoc id = function
| Some (id',c) -> id = id'
| None -> false
let find_fresh_name renaming (terms,termlists,binders) id =
let fvs1 = List.map (fun (_,(c,_)) -> free_vars_of_constr_expr c) terms in
let fvs2 = List.flatten (List.map (fun (_,(l,_)) -> List.map free_vars_of_constr_expr l) termlists) in
let fvs3 = List.map snd renaming in
TODO binders
let fvs = List.flatten (List.map Idset.elements (fvs1@fvs2)) @ fvs3 in
next_ident_away id fvs
let traverse_binder (terms,_,_ as subst)
(renaming,(ids,unb,tmpsc,scopes as env))=
function
| Anonymous -> (renaming,env),Anonymous
| Name id ->
try
Binders bound in the notation are considered first - order objects
let _,na = coerce_to_name (fst (List.assoc id terms)) in
(renaming,(name_fold Idset.add na ids,unb,tmpsc,scopes)), na
with Not_found ->
let id' = find_fresh_name renaming subst id in
let renaming' = if id=id' then renaming else (id,id')::renaming in
(renaming',env), Name id'
let rec subst_iterator y t = function
| RVar (_,id) as x -> if id = y then t else x
| x -> map_rawconstr (subst_iterator y t) x
let subst_aconstr_in_rawconstr loc intern lvar subst infos c =
let (terms,termlists,binders) = subst in
let rec aux (terms,binderopt as subst') (renaming,(ids,unb,_,scopes as env)) c =
let subinfos = renaming,(ids,unb,None,scopes) in
match c with
| AVar id ->
begin
try
let (a,(scopt,subscopes)) = List.assoc id terms in
intern (ids,unb,scopt,subscopes@scopes) a
with Not_found ->
try
RVar (loc,List.assoc id renaming)
with Not_found ->
Happens for local notation joint with inductive /
RVar (loc,id)
end
| AList (x,_,iter,terminator,lassoc) ->
(try
All elements of the list are in scopes ( scopt , subscopes )
let (l,(scopt,subscopes)) = List.assoc x termlists in
let termin = aux subst' subinfos terminator in
List.fold_right (fun a t ->
subst_iterator ldots_var t
(aux ((x,(a,(scopt,subscopes)))::terms,binderopt) subinfos iter))
(if lassoc then List.rev l else l) termin
with Not_found ->
anomaly "Inconsistent substitution of recursive notation")
| AHole (Evd.BinderType (Name id as na)) ->
let na =
try snd (coerce_to_name (fst (List.assoc id terms)))
with Not_found -> na in
RHole (loc,Evd.BinderType na)
| ABinderList (x,_,iter,terminator) ->
(try
All elements of the list are in scopes ( scopt , subscopes )
let (bl,(scopt,subscopes)) = List.assoc x binders in
let env,bl = List.fold_left (iterate_binder intern lvar) (env,[]) bl in
let termin = aux subst' (renaming,env) terminator in
List.fold_left (fun t binder ->
subst_iterator ldots_var t
(aux (terms,Some(x,binder)) subinfos iter))
termin bl
with Not_found ->
anomaly "Inconsistent substitution of recursive notation")
| AProd (Name id, AHole _, c') when option_mem_assoc id binderopt ->
let (na,bk,_,t) = snd (Option.get binderopt) in
RProd (loc,na,bk,t,aux subst' infos c')
| ALambda (Name id,AHole _,c') when option_mem_assoc id binderopt ->
let (na,bk,_,t) = snd (Option.get binderopt) in
RLambda (loc,na,bk,t,aux subst' infos c')
| t ->
rawconstr_of_aconstr_with_binders loc (traverse_binder subst)
(aux subst') subinfos t
in aux (terms,None) infos c
let split_by_type ids =
List.fold_right (fun (x,(scl,typ)) (l1,l2,l3) ->
match typ with
| NtnTypeConstr -> ((x,scl)::l1,l2,l3)
| NtnTypeConstrList -> (l1,(x,scl)::l2,l3)
| NtnTypeBinderList -> (l1,l2,(x,scl)::l3)) ids ([],[],[])
let make_subst ids l = List.map2 (fun (id,scl) a -> (id,(a,scl))) ids l
let intern_notation intern (_,_,tmp_scope,scopes as env) lvar loc ntn fullargs =
let ntn,(args,argslist,bll as fullargs) = contract_notation ntn fullargs in
let ((ids,c),df) = interp_notation loc ntn (tmp_scope,scopes) in
Dumpglob.dump_notation_location (ntn_loc loc fullargs ntn) ntn df;
let ids,idsl,idsbl = split_by_type ids in
let terms = make_subst ids args in
let termlists = make_subst idsl argslist in
let binders = make_subst idsbl bll in
subst_aconstr_in_rawconstr loc intern lvar
(terms,termlists,binders) ([],env) c
let string_of_ty = function
| Inductive _ -> "ind"
| Recursive -> "def"
| Method -> "meth"
let intern_var (ids,_,_,_ as genv) (ltacvars,namedctxvars,ntnvars,impls) loc id =
let (ltacvars,unbndltacvars) = ltacvars in
try
let ty,expl_impls,impls,argsc = List.assoc id impls in
let expl_impls = List.map
(fun id -> CRef (Ident (loc,id)), Some (loc,ExplByName id)) expl_impls in
let tys = string_of_ty ty in
Dumpglob.dump_reference loc "<>" (string_of_id id) tys;
RVar (loc,id), make_implicits_list impls, argsc, expl_impls
with Not_found ->
if Idset.mem id ids or List.mem id ltacvars
then
RVar (loc,id), [], [], []
else if List.mem_assoc id ntnvars
then
(set_var_scope loc id true genv ntnvars; RVar (loc,id), [], [], [])
else if ntnvars <> [] && id = ldots_var
then
RVar (loc,id), [], [], []
else
try
match List.assoc id unbndltacvars with
| None -> user_err_loc (loc,"intern_var",
str "variable " ++ pr_id id ++ str " should be bound to a term.")
| Some id0 -> Pretype_errors.error_var_not_found_loc loc id0
with Not_found ->
let _ = Sign.lookup_named id namedctxvars in
try
let ref = VarRef id in
let impls = implicits_of_global ref in
let scopes = find_arguments_scope ref in
Dumpglob.dump_reference loc "<>" (string_of_qualid (Decls.variable_secpath id)) "var";
RRef (loc, ref), impls, scopes, []
with _ ->
RVar (loc,id), [], [], []
let find_appl_head_data = function
| RRef (_,ref) as x -> x,implicits_of_global ref,find_arguments_scope ref,[]
| RApp (_,RRef (_,ref),l) as x
when l <> [] & Flags.version_strictly_greater Flags.V8_2 ->
let n = List.length l in
x,List.map (drop_first_implicits n) (implicits_of_global ref),
list_skipn_at_least n (find_arguments_scope ref),[]
| x -> x,[],[],[]
let error_not_enough_arguments loc =
user_err_loc (loc,"",str "Abbreviation is not applied enough.")
let check_no_explicitation l =
let l = List.filter (fun (a,b) -> b <> None) l in
if l <> [] then
let loc = fst (Option.get (snd (List.hd l))) in
user_err_loc
(loc,"",str"Unexpected explicitation of the argument of an abbreviation.")
let dump_extended_global loc = function
| TrueGlobal ref -> Dumpglob.add_glob loc ref
| SynDef sp -> Dumpglob.add_glob_kn loc sp
let intern_extended_global_of_qualid (loc,qid) =
try let r = Nametab.locate_extended qid in dump_extended_global loc r; r
with Not_found -> error_global_not_found_loc loc qid
let intern_reference ref =
Smartlocate.global_of_extended_global
(intern_extended_global_of_qualid (qualid_of_reference ref))
let intern_qualid loc qid intern env lvar args =
match intern_extended_global_of_qualid (loc,qid) with
| TrueGlobal ref ->
RRef (loc, ref), args
| SynDef sp ->
let (ids,c) = Syntax_def.search_syntactic_definition sp in
let nids = List.length ids in
if List.length args < nids then error_not_enough_arguments loc;
let args1,args2 = list_chop nids args in
check_no_explicitation args1;
let subst = make_subst ids (List.map fst args1) in
subst_aconstr_in_rawconstr loc intern lvar (subst,[],[]) ([],env) c, args2
let intern_non_secvar_qualid loc qid intern env lvar args =
match intern_qualid loc qid intern env lvar args with
| RRef (loc, VarRef id),_ -> error_global_not_found_loc loc qid
| r -> r
let intern_applied_reference intern (_, unb, _, _ as env) lvar args = function
| Qualid (loc, qid) ->
let r,args2 = intern_qualid loc qid intern env lvar args in
find_appl_head_data r, args2
| Ident (loc, id) ->
try intern_var env lvar loc id, args
with Not_found ->
let qid = qualid_of_ident id in
try
let r,args2 = intern_non_secvar_qualid loc qid intern env lvar args in
find_appl_head_data r, args2
with e ->
if !interning_grammar || unb then
(RVar (loc,id), [], [], []),args
else raise e
let interp_reference vars r =
let (r,_,_,_),_ =
intern_applied_reference (fun _ -> error_not_enough_arguments dummy_loc)
(Idset.empty,false,None,[]) (vars,[],[],[]) [] r
in r
let apply_scope_env (ids,unb,_,scopes) = function
| [] -> (ids,unb,None,scopes), []
| sc::scl -> (ids,unb,sc,scopes), scl
let rec simple_adjust_scopes n = function
| [] -> if n=0 then [] else None :: simple_adjust_scopes (n-1) []
| sc::scopes -> sc :: simple_adjust_scopes (n-1) scopes
let find_remaining_constructor_scopes pl1 pl2 (ind,j as cstr) =
let (mib,mip) = Inductive.lookup_mind_specif (Global.env()) ind in
let npar = mib.Declarations.mind_nparams in
snd (list_chop (npar + List.length pl1)
(simple_adjust_scopes (npar + List.length pl1 + List.length pl2)
(find_arguments_scope (ConstructRef cstr))))
let product_of_cases_patterns ids idspl =
List.fold_right (fun (ids,pl) (ids',ptaill) ->
(ids@ids',
Cartesian prod of the or - pats for the nth arg and the tail args
List.flatten (
List.map (fun (subst,p) ->
List.map (fun (subst',ptail) -> (subst@subst',p::ptail)) ptaill) pl)))
idspl (ids,[[],[]])
let simple_product_of_cases_patterns pl =
List.fold_right (fun pl ptaill ->
List.flatten (List.map (fun (subst,p) ->
List.map (fun (subst',ptail) -> (subst@subst',p::ptail)) ptaill) pl))
pl [[],[]]
let rec has_duplicate = function
| [] -> None
| x::l -> if List.mem x l then (Some x) else has_duplicate l
let loc_of_lhs lhs =
join_loc (fst (List.hd lhs)) (fst (list_last lhs))
let check_linearity lhs ids =
match has_duplicate ids with
| Some id ->
raise (InternalizationError (loc_of_lhs lhs,NonLinearPattern id))
| None ->
()
let check_number_of_pattern loc n l =
let p = List.length l in
if n<>p then raise (InternalizationError (loc,BadPatternsNumber (n,p)))
let check_or_pat_variables loc ids idsl =
if List.exists (fun ids' -> not (list_eq_set ids ids')) idsl then
user_err_loc (loc, "", str
"The components of this disjunctive pattern must bind the same variables.")
let check_constructor_length env loc cstr pl pl0 =
let n = List.length pl + List.length pl0 in
let nargs = Inductiveops.constructor_nrealargs env cstr in
let nhyps = Inductiveops.constructor_nrealhyps env cstr in
error_wrong_numarg_constructor_loc loc env cstr nargs
[ merge_aliases ] returns the sets of all aliases encountered at this
point and a substitution mapping extra aliases to the first one
point and a substitution mapping extra aliases to the first one *)
let merge_aliases (ids,asubst as _aliases) id =
ids@[id], if ids=[] then asubst else (id, List.hd ids)::asubst
let alias_of = function
| ([],_) -> Anonymous
| (id::_,_) -> Name id
let message_redundant_alias (id1,id2) =
if_verbose warning
("Alias variable "^(string_of_id id1)^" is merged with "^(string_of_id id2))
let error_invalid_pattern_notation loc =
user_err_loc (loc,"",str "Invalid notation for pattern.")
let chop_aconstr_constructor loc (ind,k) args =
begin
let mib,_ = Global.lookup_inductive ind in
let nparams = mib.Declarations.mind_nparams in
if nparams > List.length args then error_invalid_pattern_notation loc;
let params,args = list_chop nparams args in
List.iter (function AHole _ -> ()
| _ -> error_invalid_pattern_notation loc) params;
args
end
let rec subst_pat_iterator y t (subst,p) = match p with
| PatVar (_,id) as x ->
if id = Name y then t else [subst,x]
| PatCstr (loc,id,l,alias) ->
let l' = List.map (fun a -> (subst_pat_iterator y t ([],a))) l in
let pl = simple_product_of_cases_patterns l' in
List.map (fun (subst',pl) -> subst'@subst,PatCstr (loc,id,pl,alias)) pl
let subst_cases_pattern loc alias intern fullsubst scopes a =
let rec aux alias (subst,substlist as fullsubst) = function
| AVar id ->
begin
try
let (a,(scopt,subscopes)) = List.assoc id subst in
intern (subscopes@scopes) ([],[]) scopt a
with Not_found ->
if id = ldots_var then [], [[], PatVar (loc,Name id)] else
anomaly ("Unbound pattern notation variable: "^(string_of_id id))
( * Happens for local notation joint with inductive /
if aliases <> ([],[]) then
anomaly "Pattern notation without constructors";
[[id],[]], PatVar (loc,Name id)
*)
end
| ARef (ConstructRef c) ->
([],[[], PatCstr (loc,c, [], alias)])
| AApp (ARef (ConstructRef cstr),args) ->
let args = chop_aconstr_constructor loc cstr args in
let idslpll = List.map (aux Anonymous fullsubst) args in
let ids',pll = product_of_cases_patterns [] idslpll in
let pl' = List.map (fun (asubst,pl) ->
asubst,PatCstr (loc,cstr,pl,alias)) pll in
ids', pl'
| AList (x,_,iter,terminator,lassoc) ->
(try
All elements of the list are in scopes ( scopt , subscopes )
let (l,(scopt,subscopes)) = List.assoc x substlist in
let termin = aux Anonymous fullsubst terminator in
let idsl,v =
List.fold_right (fun a (tids,t) ->
let uids,u = aux Anonymous ((x,(a,(scopt,subscopes)))::subst,substlist) iter in
let pll = List.map (subst_pat_iterator ldots_var t) u in
tids@uids, List.flatten pll)
(if lassoc then List.rev l else l) termin in
idsl, List.map (fun ((asubst, pl) as x) ->
match pl with PatCstr (loc, c, pl, Anonymous) -> (asubst, PatCstr (loc, c, pl, alias)) | _ -> x) v
with Not_found ->
anomaly "Inconsistent substitution of recursive notation")
| AHole _ -> ([],[[], PatVar (loc,Anonymous)])
| t -> error_invalid_pattern_notation loc
in aux alias fullsubst a
type pattern_qualid_kind =
| ConstrPat of constructor * (identifier list *
((identifier * identifier) list * cases_pattern) list) list
| VarPat of identifier
let find_constructor ref f aliases pats scopes =
let (loc,qid) = qualid_of_reference ref in
let gref =
try locate_extended qid
with Not_found -> raise (InternalizationError (loc,NotAConstructor ref)) in
match gref with
| SynDef sp ->
let (vars,a) = Syntax_def.search_syntactic_definition sp in
(match a with
| ARef (ConstructRef cstr) ->
assert (vars=[]);
cstr, [], pats
| AApp (ARef (ConstructRef cstr),args) ->
let args = chop_aconstr_constructor loc cstr args in
let nvars = List.length vars in
if List.length pats < nvars then error_not_enough_arguments loc;
let pats1,pats2 = list_chop nvars pats in
let subst = List.map2 (fun (id,scl) a -> (id,(a,scl))) vars pats1 in
let idspl1 = List.map (subst_cases_pattern loc (alias_of aliases) f (subst,[]) scopes) args in
cstr, idspl1, pats2
| _ -> raise Not_found)
| TrueGlobal r ->
let rec unf = function
| ConstRef cst ->
let v = Environ.constant_value (Global.env()) cst in
unf (global_of_constr v)
| ConstructRef cstr ->
Dumpglob.add_glob loc r;
cstr, [], pats
| _ -> raise Not_found
in unf r
let find_pattern_variable = function
| Ident (loc,id) -> id
| Qualid (loc,_) as x -> raise (InternalizationError(loc,NotAConstructor x))
let maybe_constructor ref f aliases scopes =
try
let c,idspl1,pl2 = find_constructor ref f aliases [] scopes in
assert (pl2 = []);
ConstrPat (c,idspl1)
with
| InternalizationError _ -> VarPat (find_pattern_variable ref)
| (Environ.NotEvaluableConst _ | Not_found) ->
if_verbose msg_warning (str "pattern " ++ pr_reference ref ++
str " is understood as a pattern variable");
VarPat (find_pattern_variable ref)
let mustbe_constructor loc ref f aliases patl scopes =
try find_constructor ref f aliases patl scopes
with (Environ.NotEvaluableConst _ | Not_found) ->
raise (InternalizationError (loc,NotAConstructor ref))
let sort_fields mode loc l completer =
match l with
| [] -> None
| (refer, value)::rem ->
index of the first field of the record
=
let record =
try Recordops.find_projection
(global_reference_of_reference refer)
with Not_found ->
user_err_loc (loc, "intern", str"Not a projection")
in
elimination of the first field from the projections
let rec build_patt l m i acc =
match l with
| [] -> (i, acc)
| (Some name) :: b->
(match m with
| [] -> anomaly "Number of projections mismatch"
| (_, regular)::tm ->
let boolean = not regular in
if ConstRef name = global_reference_of_reference refer
then
if boolean && mode then
user_err_loc (loc, "", str"No local fields allowed in a record construction.")
else
build_patt b tm (if boolean&&mode then i else i + 1)
(if boolean && mode then acc
else fst acc, (i, ConstRef name) :: snd acc))
if mode then
user_err_loc (loc, "", str "This record contains anonymous fields.")
else build_patt b m (i+1) acc
in
let ind = record.Recordops.s_CONST in
insertion of Constextern.reference_global
(record.Recordops.s_EXPECTEDPARAM,
Qualid (loc, shortest_qualid_of_global Idset.empty (ConstructRef ind)),
build_patt record.Recordops.s_PROJ record.Recordops.s_PROJKIND 1 (0,[]))
with Not_found -> anomaly "Environment corruption for records."
in
let rec sf patts accpatt =
match patts with
| [] -> accpatt
| p::q->
let refer, patt = p in
let rec add_patt l acc =
match l with
| [] ->
user_err_loc
(loc, "",
str "This record contains fields of different records.")
| (i, a) :: b->
if global_reference_of_reference refer = a
then (i,List.rev_append acc l)
else add_patt b ((i,a)::acc)
in
let (index, projs) = add_patt (snd accpatt) [] in
sf q ((index, patt)::fst accpatt, projs) in
let (unsorted_indexed_pattern, remainings) =
sf rem ([first_index, value], list_proj) in
let sorted_indexed_pattern =
List.sort (fun (i, _) (j, _) -> compare i j) unsorted_indexed_pattern in
let rec complete_list n l =
if n <= 1 then l else complete_list (n-1) (completer n l) in
let rec clean_list l i acc =
match l with
| [] -> complete_list (max - i) acc
| (k, p)::q-> clean_list q k (p::(complete_list (k - i) acc))
in
Some (nparams, base_constructor,
List.rev (clean_list sorted_indexed_pattern 0 []))
let rec intern_cases_pattern genv scopes (ids,asubst as aliases) tmp_scope pat=
let intern_pat = intern_cases_pattern genv in
match pat with
| CPatAlias (loc, p, id) ->
let aliases' = merge_aliases aliases id in
intern_pat scopes aliases' tmp_scope p
| CPatRecord (loc, l) ->
let sorted_fields = sort_fields false loc l (fun _ l -> (CPatAtom (loc, None))::l) in
let self_patt =
match sorted_fields with
| None -> CPatAtom (loc, None)
| Some (_, head, pl) -> CPatCstr(loc, head, pl)
in
intern_pat scopes aliases tmp_scope self_patt
| CPatCstr (loc, head, pl) ->
let c,idslpl1,pl2 = mustbe_constructor loc head intern_pat aliases pl scopes in
check_constructor_length genv loc c idslpl1 pl2;
let argscs2 = find_remaining_constructor_scopes idslpl1 pl2 c in
let idslpl2 = List.map2 (intern_pat scopes ([],[])) argscs2 pl2 in
let (ids',pll) = product_of_cases_patterns ids (idslpl1@idslpl2) in
let pl' = List.map (fun (asubst,pl) ->
(asubst, PatCstr (loc,c,pl,alias_of aliases))) pll in
ids',pl'
| CPatNotation (loc,"- _",([CPatPrim(_,Numeral p)],[]))
when Bigint.is_strictly_pos p ->
intern_pat scopes aliases tmp_scope (CPatPrim(loc,Numeral(Bigint.neg p)))
| CPatNotation (_,"( _ )",([a],[])) ->
intern_pat scopes aliases tmp_scope a
| CPatNotation (loc, ntn, fullargs) ->
let ntn,(args,argsl as fullargs) = contract_pat_notation ntn fullargs in
let ((ids',c),df) = Notation.interp_notation loc ntn (tmp_scope,scopes) in
let (ids',idsl',_) = split_by_type ids' in
Dumpglob.dump_notation_location (patntn_loc loc fullargs ntn) ntn df;
let subst = List.map2 (fun (id,scl) a -> (id,(a,scl))) ids' args in
let substlist = List.map2 (fun (id,scl) a -> (id,(a,scl))) idsl' argsl in
let ids'',pl =
subst_cases_pattern loc (alias_of aliases) intern_pat (subst,substlist)
scopes c
in ids@ids'', pl
| CPatPrim (loc, p) ->
let a = alias_of aliases in
let (c,_) = Notation.interp_prim_token_cases_pattern loc p a
(tmp_scope,scopes) in
(ids,[asubst,c])
| CPatDelimiters (loc, key, e) ->
intern_pat (find_delimiters_scope loc key::scopes) aliases None e
| CPatAtom (loc, Some head) ->
(match maybe_constructor head intern_pat aliases scopes with
| ConstrPat (c,idspl) ->
check_constructor_length genv loc c idspl [];
let (ids',pll) = product_of_cases_patterns ids idspl in
(ids,List.map (fun (asubst,pl) ->
(asubst, PatCstr (loc,c,pl,alias_of aliases))) pll)
| VarPat id ->
let ids,asubst = merge_aliases aliases id in
(ids,[asubst, PatVar (loc,alias_of (ids,asubst))]))
| CPatAtom (loc, None) ->
(ids,[asubst, PatVar (loc,alias_of aliases)])
| CPatOr (loc, pl) ->
assert (pl <> []);
let pl' = List.map (intern_pat scopes aliases tmp_scope) pl in
let (idsl,pl') = List.split pl' in
let ids = List.hd idsl in
check_or_pat_variables loc ids (List.tl idsl);
(ids,List.flatten pl')
Utilities for application
let merge_impargs l args =
List.fold_right (fun a l ->
match a with
| (_,Some (_,(ExplByName id as x))) when
List.exists (function (_,Some (_,y)) -> x=y | _ -> false) args -> l
| _ -> a::l)
l args
let check_projection isproj nargs r =
match (r,isproj) with
| RRef (loc, ref), Some _ ->
(try
let n = Recordops.find_projection_nparams ref + 1 in
if nargs <> n then
user_err_loc (loc,"",str "Projection has not the right number of explicit parameters.");
with Not_found ->
user_err_loc
(loc,"",pr_global_env Idset.empty ref ++ str " is not a registered projection."))
| _, Some _ -> user_err_loc (loc_of_rawconstr r, "", str "Not a projection.")
| _, None -> ()
let get_implicit_name n imps =
Some (Impargs.name_of_implicit (List.nth imps (n-1)))
let set_hole_implicit i b = function
| RRef (loc,r) | RApp (_,RRef (loc,r),_) -> (loc,Evd.ImplicitArg (r,i,b))
| RVar (loc,id) -> (loc,Evd.ImplicitArg (VarRef id,i,b))
| _ -> anomaly "Only refs have implicits"
let exists_implicit_name id =
List.exists (fun imp -> is_status_implicit imp & id = name_of_implicit imp)
let extract_explicit_arg imps args =
let rec aux = function
| [] -> [],[]
| (a,e)::l ->
let (eargs,rargs) = aux l in
match e with
| None -> (eargs,a::rargs)
| Some (loc,pos) ->
let id = match pos with
| ExplByName id ->
if not (exists_implicit_name id imps) then
user_err_loc
(loc,"",str "Wrong argument name: " ++ pr_id id ++ str ".");
if List.mem_assoc id eargs then
user_err_loc (loc,"",str "Argument name " ++ pr_id id
++ str " occurs more than once.");
id
| ExplByPos (p,_id) ->
let id =
try
let imp = List.nth imps (p-1) in
if not (is_status_implicit imp) then failwith "imp";
name_of_implicit imp
user_err_loc
(loc,"",str"Wrong argument position: " ++ int p ++ str ".")
in
if List.mem_assoc id eargs then
user_err_loc (loc,"",str"Argument at position " ++ int p ++
str " is mentioned more than once.");
id in
((id,(loc,a))::eargs,rargs)
in aux args
let internalize sigma globalenv env allow_patvar lvar c =
let rec intern (ids,unb,tmp_scope,scopes as env) = function
| CRef ref as x ->
let (c,imp,subscopes,l),_ =
intern_applied_reference intern env lvar [] ref in
(match intern_impargs c env imp subscopes l with
| [] -> c
| l -> RApp (constr_loc x, c, l))
| CFix (loc, (locid,iddef), dl) ->
let lf = List.map (fun ((_, id),_,_,_,_) -> id) dl in
let dl = Array.of_list dl in
let n =
try list_index0 iddef lf
with Not_found ->
raise (InternalizationError (locid,UnboundFixName (false,iddef)))
in
let idl = Array.map
(fun (id,(n,order),bl,ty,bd) ->
let intern_ro_arg f =
let before, after = split_at_annot bl n in
let ((ids',_,_,_) as env',rbefore) =
List.fold_left intern_local_binder (env,[]) before in
let ro = f (intern (ids', unb, tmp_scope, scopes)) in
let n' = Option.map (fun _ -> List.length rbefore) n in
n', ro, List.fold_left intern_local_binder (env',rbefore) after
in
let n, ro, ((ids',_,_,_),rbl) =
match order with
| CStructRec ->
intern_ro_arg (fun _ -> RStructRec)
| CWfRec c ->
intern_ro_arg (fun f -> RWfRec (f c))
| CMeasureRec (m,r) ->
intern_ro_arg (fun f -> RMeasureRec (f m, Option.map f r))
in
let ids'' = List.fold_right Idset.add lf ids' in
((n, ro), List.rev rbl,
intern_type (ids',unb,tmp_scope,scopes) ty,
intern (ids'',unb,None,scopes) bd)) dl in
RRec (loc,RFix
(Array.map (fun (ro,_,_,_) -> ro) idl,n),
Array.of_list lf,
Array.map (fun (_,bl,_,_) -> bl) idl,
Array.map (fun (_,_,ty,_) -> ty) idl,
Array.map (fun (_,_,_,bd) -> bd) idl)
| CCoFix (loc, (locid,iddef), dl) ->
let lf = List.map (fun ((_, id),_,_,_) -> id) dl in
let dl = Array.of_list dl in
let n =
try list_index0 iddef lf
with Not_found ->
raise (InternalizationError (locid,UnboundFixName (true,iddef)))
in
let idl = Array.map
(fun (id,bl,ty,bd) ->
let ((ids',_,_,_),rbl) =
List.fold_left intern_local_binder (env,[]) bl in
let ids'' = List.fold_right Idset.add lf ids' in
(List.rev rbl,
intern_type (ids',unb,tmp_scope,scopes) ty,
intern (ids'',unb,None,scopes) bd)) dl in
RRec (loc,RCoFix n,
Array.of_list lf,
Array.map (fun (bl,_,_) -> bl) idl,
Array.map (fun (_,ty,_) -> ty) idl,
Array.map (fun (_,_,bd) -> bd) idl)
| CArrow (loc,c1,c2) ->
RProd (loc, Anonymous, Explicit, intern_type env c1, intern_type env c2)
| CProdN (loc,[],c2) ->
intern_type env c2
| CProdN (loc,(nal,bk,ty)::bll,c2) ->
iterate_prod loc env bk ty (CProdN (loc, bll, c2)) nal
| CLambdaN (loc,[],c2) ->
intern env c2
| CLambdaN (loc,(nal,bk,ty)::bll,c2) ->
iterate_lam loc (reset_tmp_scope env) bk ty (CLambdaN (loc, bll, c2)) nal
| CLetIn (loc,na,c1,c2) ->
RLetIn (loc, snd na, intern (reset_tmp_scope env) c1,
intern (push_name_env lvar env na) c2)
| CNotation (loc,"- _",([CPrim (_,Numeral p)],[],[]))
when Bigint.is_strictly_pos p ->
intern env (CPrim (loc,Numeral (Bigint.neg p)))
| CNotation (_,"( _ )",([a],[],[])) -> intern env a
| CNotation (loc,ntn,args) ->
intern_notation intern env lvar loc ntn args
| CGeneralization (loc,b,a,c) ->
intern_generalization intern env lvar loc b a c
| CPrim (loc, p) ->
fst (Notation.interp_prim_token loc p (tmp_scope,scopes))
| CDelimiters (loc, key, e) ->
intern (ids,unb,None,find_delimiters_scope loc key::scopes) e
| CAppExpl (loc, (isproj,ref), args) ->
let (f,_,args_scopes,_),args =
let args = List.map (fun a -> (a,None)) args in
intern_applied_reference intern env lvar args ref in
check_projection isproj (List.length args) f;
RApp (loc, f, intern_args env args_scopes (List.map fst args))
| CApp (loc, (isproj,f), args) ->
let isproj,f,args = match f with
| CApp (_,(Some _,f), args') when isproj=None -> isproj,f,args'@args
| _ -> isproj,f,args in
let (c,impargs,args_scopes,l),args =
match f with
| CRef ref -> intern_applied_reference intern env lvar args ref
| CNotation (loc,ntn,([],[],[])) ->
let c = intern_notation intern env lvar loc ntn ([],[],[]) in
find_appl_head_data c, args
| x -> (intern env f,[],[],[]), args in
let args =
intern_impargs c env impargs args_scopes (merge_impargs l args) in
check_projection isproj (List.length args) c;
(match c with
| RApp (loc', f', args') -> RApp (join_loc loc' loc, f',args'@args)
| _ -> RApp (loc, c, args))
| CRecord (loc, _, fs) ->
let cargs =
sort_fields true loc fs
(fun k l -> CHole (loc, Some (Evd.QuestionMark (Evd.Define true))) :: l)
in
begin
match cargs with
| None -> user_err_loc (loc, "intern", str"No constructor inference.")
| Some (n, constrname, args) ->
let pars = list_make n (CHole (loc, None)) in
let app = CAppExpl (loc, (None, constrname), List.rev_append pars args) in
intern env app
end
| CCases (loc, sty, rtnpo, tms, eqns) ->
let tms,env' = List.fold_right
(fun citm (inds,env) ->
let (tm,ind),nal = intern_case_item env citm in
(tm,ind)::inds,List.fold_left (push_name_env lvar) env nal)
tms ([],env) in
let rtnpo = Option.map (intern_type env') rtnpo in
let eqns' = List.map (intern_eqn (List.length tms) env) eqns in
RCases (loc, sty, rtnpo, tms, List.flatten eqns')
| CLetTuple (loc, nal, (na,po), b, c) ->
let env' = reset_tmp_scope env in
let ((b',(na',_)),ids) = intern_case_item env' (b,(na,None)) in
let p' = Option.map (fun p ->
let env'' = List.fold_left (push_name_env lvar) env ids in
intern_type env'' p) po in
RLetTuple (loc, List.map snd nal, (na', p'), b',
intern (List.fold_left (push_name_env lvar) env nal) c)
| CIf (loc, c, (na,po), b1, b2) ->
let env' = reset_tmp_scope env in
let ((c',(na',_)),ids) = intern_case_item env' (c,(na,None)) in
let p' = Option.map (fun p ->
let env'' = List.fold_left (push_name_env lvar) env ids in
intern_type env'' p) po in
RIf (loc, c', (na', p'), intern env b1, intern env b2)
| CHole (loc, k) ->
RHole (loc, match k with Some k -> k | None -> Evd.QuestionMark (Evd.Define true))
| CPatVar (loc, n) when allow_patvar ->
RPatVar (loc, n)
| CPatVar (loc, _) ->
raise (InternalizationError (loc,IllegalMetavariable))
| CEvar (loc, n, l) ->
REvar (loc, n, Option.map (List.map (intern env)) l)
| CSort (loc, s) ->
RSort(loc,s)
| CCast (loc, c1, CastConv (k, c2)) ->
RCast (loc,intern env c1, CastConv (k, intern_type env c2))
| CCast (loc, c1, CastCoerce) ->
RCast (loc,intern env c1, CastCoerce)
| CDynamic (loc,d) -> RDynamic (loc,d)
and intern_type env = intern (set_type_scope env)
and intern_local_binder env bind =
intern_local_binder_aux intern intern_type lvar env bind
and intern_multiple_pattern scopes n (loc,pl) =
let idsl_pll =
List.map (intern_cases_pattern globalenv scopes ([],[]) None) pl in
check_number_of_pattern loc n pl;
product_of_cases_patterns [] idsl_pll
and intern_disjunctive_multiple_pattern scopes loc n mpl =
assert (mpl <> []);
let mpl' = List.map (intern_multiple_pattern scopes n) mpl in
let (idsl,mpl') = List.split mpl' in
let ids = List.hd idsl in
check_or_pat_variables loc ids (List.tl idsl);
(ids,List.flatten mpl')
Expands a pattern - matching clause [ lhs = > rhs ]
and intern_eqn n (ids,unb,tmp_scope,scopes) (loc,lhs,rhs) =
let eqn_ids,pll = intern_disjunctive_multiple_pattern scopes loc n lhs in
check_linearity lhs eqn_ids;
let env_ids = List.fold_right Idset.add eqn_ids ids in
List.map (fun (asubst,pl) ->
let rhs = replace_vars_constr_expr asubst rhs in
List.iter message_redundant_alias asubst;
let rhs' = intern (env_ids,unb,tmp_scope,scopes) rhs in
(loc,eqn_ids,pl,rhs')) pll
and intern_case_item (vars,unb,_,scopes as env) (tm,(na,t)) =
let tm' = intern env tm in
let ids,typ = match t with
| Some t ->
let tids = ids_of_cases_indtype t in
let tids = List.fold_right Idset.add tids Idset.empty in
let t = intern_type (tids,unb,None,scopes) t in
let loc,ind,l = match t with
| RRef (loc,IndRef ind) -> (loc,ind,[])
| RApp (loc,RRef (_,IndRef ind),l) -> (loc,ind,l)
| _ -> error_bad_inductive_type (loc_of_rawconstr t) in
let nparams, nrealargs = inductive_nargs globalenv ind in
let nindargs = nparams + nrealargs in
if List.length l <> nindargs then
error_wrong_numarg_inductive_loc loc globalenv ind nindargs;
let nal = List.map (function
| RHole (loc,_) -> loc,Anonymous
| RVar (loc,id) -> loc,Name id
| c -> user_err_loc (loc_of_rawconstr c,"",str "Not a name.")) l in
let parnal,realnal = list_chop nparams nal in
if List.exists (fun (_,na) -> na <> Anonymous) parnal then
error_inductive_parameter_not_implicit loc;
realnal, Some (loc,ind,nparams,List.map snd realnal)
| None ->
[], None in
let na = match tm', na with
| RVar (loc,id), None when Idset.mem id vars -> loc,Name id
| RRef (loc, VarRef id), None -> loc,Name id
| _, None -> dummy_loc,Anonymous
| _, Some (loc,na) -> loc,na in
(tm',(snd na,typ)), na::ids
and iterate_prod loc2 env bk ty body nal =
let rec default env bk = function
| (loc1,na as locna)::nal ->
if nal <> [] then check_capture loc1 ty na;
let body = default (push_name_env lvar env locna) bk nal in
let ty = locate_if_isevar loc1 na (intern_type env ty) in
RProd (join_loc loc1 loc2, na, bk, ty, body)
| [] -> intern_type env body
in
match bk with
| Default b -> default env b nal
| Generalized (b,b',t) ->
let env, ibind = intern_generalized_binder intern_type lvar env [] (List.hd nal) b b' t ty in
let body = intern_type env body in
it_mkRProd ibind body
and iterate_lam loc2 env bk ty body nal =
let rec default env bk = function
| (loc1,na as locna)::nal ->
if nal <> [] then check_capture loc1 ty na;
let body = default (push_name_env lvar env locna) bk nal in
let ty = locate_if_isevar loc1 na (intern_type env ty) in
RLambda (join_loc loc1 loc2, na, bk, ty, body)
| [] -> intern env body
in match bk with
| Default b -> default env b nal
| Generalized (b, b', t) ->
let env, ibind = intern_generalized_binder intern_type lvar env [] (List.hd nal) b b' t ty in
let body = intern env body in
it_mkRLambda ibind body
and intern_impargs c env l subscopes args =
let l = select_impargs_size (List.length args) l in
let eargs, rargs = extract_explicit_arg l args in
let rec aux n impl subscopes eargs rargs =
let (enva,subscopes') = apply_scope_env env subscopes in
match (impl,rargs) with
| (imp::impl', rargs) when is_status_implicit imp ->
begin try
let id = name_of_implicit imp in
let (_,a) = List.assoc id eargs in
let eargs' = List.remove_assoc id eargs in
intern enva a :: aux (n+1) impl' subscopes' eargs' rargs
with Not_found ->
if rargs=[] & eargs=[] & not (maximal_insertion_of imp) then
[]
else
RHole (set_hole_implicit (n,get_implicit_name n l) (force_inference_of imp) c) ::
aux (n+1) impl' subscopes' eargs rargs
end
| (imp::impl', a::rargs') ->
intern enva a :: aux (n+1) impl' subscopes' eargs rargs'
| (imp::impl', []) ->
if eargs <> [] then
(let (id,(loc,_)) = List.hd eargs in
user_err_loc (loc,"",str "Not enough non implicit
arguments to accept the argument bound to " ++
pr_id id ++ str"."));
[]
| ([], rargs) ->
assert (eargs = []);
intern_args env subscopes rargs
in aux 1 l subscopes eargs rargs
and intern_args env subscopes = function
| [] -> []
| a::args ->
let (enva,subscopes) = apply_scope_env env subscopes in
(intern enva a) :: (intern_args env subscopes args)
in
try
intern env c
with
InternalizationError (loc,e) ->
user_err_loc (loc,"internalize",
explain_internalization_error e)
Functions to translate constr_expr into rawconstr
let extract_ids env =
List.fold_right Idset.add
(Termops.ids_of_rel_context (Environ.rel_context env))
Idset.empty
let intern_gen isarity sigma env
?(impls=[]) ?(allow_patvar=false) ?(ltacvars=([],[]))
c =
let tmp_scope =
if isarity then Some Notation.type_scope else None in
internalize sigma env (extract_ids env, false, tmp_scope,[])
allow_patvar (ltacvars,Environ.named_context env, [], impls) c
let intern_constr sigma env c = intern_gen false sigma env c
let intern_type sigma env c = intern_gen true sigma env c
let intern_pattern env patt =
try
intern_cases_pattern env [] ([],[]) None patt
with
InternalizationError (loc,e) ->
user_err_loc (loc,"internalize",explain_internalization_error e)
type manual_implicits = (explicitation * (bool * bool * bool)) list
let interp_gen kind sigma env
?(impls=[]) ?(allow_patvar=false) ?(ltacvars=([],[]))
c =
let c = intern_gen (kind=IsType) ~impls ~allow_patvar ~ltacvars sigma env c in
Default.understand_gen kind sigma env c
let interp_constr sigma env c =
interp_gen (OfType None) sigma env c
let interp_type sigma env ?(impls=[]) c =
interp_gen IsType sigma env ~impls c
let interp_casted_constr sigma env ?(impls=[]) c typ =
interp_gen (OfType (Some typ)) sigma env ~impls c
let interp_open_constr sigma env c =
Default.understand_tcc sigma env (intern_constr sigma env c)
let interp_open_constr_patvar sigma env c =
let raw = intern_gen false sigma env c ~allow_patvar:true in
let sigma = ref (Evd.create_evar_defs sigma) in
let evars = ref (Gmap.empty : (identifier,rawconstr) Gmap.t) in
let rec patvar_to_evar r = match r with
| RPatVar (loc,(_,id)) ->
( try Gmap.find id !evars
with Not_found ->
let ev = Evarutil.e_new_evar sigma env (Termops.new_Type()) in
let ev = Evarutil.e_new_evar sigma env ev in
TODO
evars := Gmap.add id rev !evars;
rev
)
| _ -> map_rawconstr patvar_to_evar r in
let raw = patvar_to_evar raw in
Default.understand_tcc !sigma env raw
let interp_constr_judgment sigma env c =
Default.understand_judgment sigma env (intern_constr sigma env c)
let interp_constr_evars_gen_impls ?evdref ?(fail_evar=true)
env ?(impls=[]) kind c =
let evdref =
match evdref with
| None -> ref Evd.empty
| Some evdref -> evdref
in
let istype = kind = IsType in
let c = intern_gen istype ~impls !evdref env c in
let imps = Implicit_quantifiers.implicits_of_rawterm ~with_products:istype c in
Default.understand_tcc_evars ~fail_evar evdref env kind c, imps
let interp_casted_constr_evars_impls ?evdref ?(fail_evar=true)
env ?(impls=[]) c typ =
interp_constr_evars_gen_impls ?evdref ~fail_evar env ~impls (OfType (Some typ)) c
let interp_type_evars_impls ?evdref ?(fail_evar=true) env ?(impls=[]) c =
interp_constr_evars_gen_impls ?evdref ~fail_evar env IsType ~impls c
let interp_constr_evars_impls ?evdref ?(fail_evar=true) env ?(impls=[]) c =
interp_constr_evars_gen_impls ?evdref ~fail_evar env (OfType None) ~impls c
let interp_constr_evars_gen evdref env ?(impls=[]) kind c =
let c = intern_gen (kind=IsType) ~impls ( !evdref) env c in
Default.understand_tcc_evars evdref env kind c
let interp_casted_constr_evars evdref env ?(impls=[]) c typ =
interp_constr_evars_gen evdref env ~impls (OfType (Some typ)) c
let interp_type_evars evdref env ?(impls=[]) c =
interp_constr_evars_gen evdref env IsType ~impls c
type ltac_sign = identifier list * unbound_ltac_var_map
let intern_constr_pattern sigma env ?(as_type=false) ?(ltacvars=([],[])) c =
let c = intern_gen as_type ~allow_patvar:true ~ltacvars sigma env c in
pattern_of_rawconstr c
let interp_aconstr ?(impls=[]) vars recvars a =
let env = Global.env () in
let vl = List.map (fun (id,typ) -> (id,(ref None,typ))) vars in
let c = internalize Evd.empty (Global.env()) (extract_ids env, false, None, [])
false (([],[]),Environ.named_context env,vl,impls) a in
Translate and check that [ c ] has all its free variables bound in [ vars ]
let a = aconstr_of_rawconstr vars recvars c in
let out_scope = function None -> None,[] | Some (a,l) -> a,l in
let vars = List.map (fun (id,(sc,typ)) -> (id,(out_scope !sc,typ))) vl in
vars, a
let interp_binder sigma env na t =
let t = intern_gen true sigma env t in
let t' = locate_if_isevar (loc_of_rawconstr t) na t in
Default.understand_type sigma env t'
let interp_binder_evars evdref env na t =
let t = intern_gen true !evdref env t in
let t' = locate_if_isevar (loc_of_rawconstr t) na t in
Default.understand_tcc_evars evdref env IsType t'
open Environ
open Term
let my_intern_constr sigma env lvar acc c =
internalize sigma env acc false lvar c
let my_intern_type sigma env lvar acc c = my_intern_constr sigma env lvar (set_type_scope acc) c
let intern_context global_level sigma env params =
let lvar = (([],[]),Environ.named_context env, [], []) in
snd (List.fold_left
(intern_local_binder_aux ~global_level (my_intern_constr sigma env lvar) (my_intern_type sigma env lvar) lvar)
((extract_ids env,false,None,[]), []) params)
let interp_rawcontext_gen understand_type understand_judgment env bl =
let (env, par, _, impls) =
List.fold_left
(fun (env,params,n,impls) (na, k, b, t) ->
match b with
None ->
let t' = locate_if_isevar (loc_of_rawconstr t) na t in
let t = understand_type env t' in
let d = (na,None,t) in
let impls =
if k = Implicit then
let na = match na with Name n -> Some n | Anonymous -> None in
(ExplByPos (n, na), (true, true, true)) :: impls
else impls
in
(push_rel d env, d::params, succ n, impls)
| Some b ->
let c = understand_judgment env b in
let d = (na, Some c.uj_val, c.uj_type) in
(push_rel d env, d::params, succ n, impls))
(env,[],1,[]) (List.rev bl)
in (env, par), impls
let interp_context_gen understand_type understand_judgment ?(global_level=false) sigma env params =
let bl = intern_context global_level sigma env params in
interp_rawcontext_gen understand_type understand_judgment env bl
let interp_context ?(global_level=false) sigma env params =
interp_context_gen (Default.understand_type sigma)
(Default.understand_judgment sigma) ~global_level sigma env params
let interp_context_evars ?(global_level=false) evdref env params =
interp_context_gen (fun env t -> Default.understand_tcc_evars evdref env IsType t)
(Default.understand_judgment_tcc evdref) ~global_level !evdref env params
|
6e073c42404a26469ca1df21a5d5f97a274eec1c4b27ca4f631c038070dfab49 | shayne-fletcher/zen | main.ml | let _ = Printf.printf "Hello world!\n"
| null | https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/ocamlyacc/calculator/main.ml | ocaml | let _ = Printf.printf "Hello world!\n"
| |
8669cb721fb86b8f312c5f7c988777b204dd520c9af86892aabee7cc8f3daec0 | manuel-serrano/hop | callcc_resume_push.scm | ;*=====================================================================*/
* Author : * /
* Copyright : 2007 - 11 , see LICENSE file * /
;* ------------------------------------------------------------- */
* This file is part of Scheme2Js . * /
;* */
* Scheme2Js 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 */
;* LICENSE file for more details. */
;*=====================================================================*/
(module callcc-resume-push
(import config
nodes
export-desc
walk
tail
mark-statements
verbose
tools)
(static (wide-class Call/cc-Label::Label
(resumes::pair-nil (default '()))))
(export (call/cc-resume-push! tree::Module)))
;; When call/cc resumes, the instruction following the call/cc should be
;; executed.
;; Call/cc-Resume represents this location. These nodes are introduced here.
;;
;; The Resume node is then (sometimes) pushed further, to push it to cheaper
;; locations. All skipped expressions are copied into the Resume-node and need
;; to be executed before jumping to the resume-point. At the moment only the
;; "Set!" node is skipped (and the copied expression currently is just the
;; skipped var).
(define (call/cc-resume-push! tree)
(verbose " call/cc resume push")
(resume! tree #f #f))
(define (update-hoisted! fun index instr)
(with-access::Lambda fun (call/cc-hoisted)
(let ((rev-hoisted (assq index call/cc-hoisted)))
(if (not rev-hoisted) ;; first hoisting for variable
(cons-set! call/cc-hoisted `(,index ,instr))
;; physically update the element
(set-cdr! rev-hoisted (cons instr (cdr rev-hoisted)))))))
;; if n is a Begin:
;; returns #f or the last element of the begin, if it was a Call/cc-Resume
;; physically modifies the begin, so it does not contain the resume-node
;; anymore.
(define (resume-begin-split n)
(when (isa? n Begin)
(with-access::Begin n (exprs)
(let loop ((exprs exprs))
(cond
((null? exprs) #f) ;; should never happen
((null? (cdr exprs)) #f)
((and (null? (cddr exprs))
(isa? (cadr exprs) Call/cc-Resume))
(let ((resume (cadr exprs)))
(set-cdr! exprs '())
resume))
(else
(loop (cdr exprs))))))))
(define (simplified-begin bnode::Begin)
(with-access::Begin bnode (exprs)
(cond
((null? exprs) (instantiate::Const
(location (with-access::Node bnode (location) location))
(value #unspecified)))
((null? (cdr exprs)) (car exprs))
(else
bnode))))
merges all Resumes into the first of the list .
;; returns #f if the list is empty.
(define (resumes-merge! resumes)
(and resumes
(not (null? resumes))
(let ((first-resume (car resumes)))
(with-access::Call/cc-Resume first-resume (indices)
;; first merge all the Resumes
(let loop ((resumes (cdr resumes))
(inds indices))
(if (null? resumes)
(set! indices inds)
(loop (cdr resumes)
(append (with-access::Call/cc-Resume (car resumes) (indices) indices)
inds)))))
first-resume)))
(define-nmethod (Node.resume! surrounding-fun)
(default-walk! this surrounding-fun))
(define-nmethod (Lambda.resume! surrounding-fun)
(default-walk! this this))
;; add Resume node.
(define-nmethod (Call.resume! surrounding-fun)
(with-access::Call this (call/cc? call/cc-index)
(if (or (not call/cc?)
(not call/cc-index)) ;; tail-call
(default-walk! this surrounding-fun)
(begin
(default-walk! this surrounding-fun)
(let ((resume-node (instantiate::Call/cc-Resume
(location (with-access::Node this (location) location))
(indices (list call/cc-index)))))
(instantiate::Begin
(exprs (list this resume-node))))))))
(define-nmethod (If.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::If this (then else)
(let ((then-resume (resume-begin-split then))
(else-resume (resume-begin-split else)))
(when then-resume
in case there is only one element left .
(set! then (simplified-begin then)))
(when else-resume
(set! else (simplified-begin else)))
(if (or then-resume else-resume)
(let* ((resume (cond
((and then-resume else-resume)
(resumes-merge! (list then-resume else-resume)))
(else
(or then-resume else-resume))))
(bnode (instantiate::Begin (exprs (list this resume)))))
bnode)
this))))
(define-nmethod (Case.resume! surrounding-fun)
;; TODO: implement Case-resume
(default-walk! this surrounding-fun))
(define-nmethod (Begin.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Begin this (exprs)
;; merge nested Begins.
(let loop ((exprs exprs))
(unless (null? exprs)
(let ((expr (car exprs)))
(cond
((isa? expr Begin)
;; insert into our list.
(let ((other-exprs (with-access::Begin expr (exprs) exprs))
(exprs-tail (cdr exprs)))
we know there must be at least 2 elements .
;; otherwise we wouldn't have gotten a 'Begin'.
(set-car! exprs (car other-exprs))
(set-cdr! exprs (cdr other-exprs))
(set-cdr! (last-pair other-exprs) exprs-tail))
(loop exprs))
((isa? expr Call/cc-Resume)
(let ((next (and (not (null? (cdr exprs)))
(cadr exprs))))
(cond
((not next)
(loop (cdr exprs)))
merge two consecutive Resumes into one .
((isa? next Call/cc-Resume)
(set-car! exprs (resumes-merge! (list (car exprs) next)))
(set-cdr! exprs (cddr exprs))
(loop exprs))
((or (isa? next Continue)
(and (isa? next Break)
(not (with-access::Break next (val) val))))
(let ((label (if (isa? next Continue)
(with-access::Continue next (label) label)
(with-access::Break next (label) label))))
(unless (isa? label Call/cc-Label)
(widen!::Call/cc-Label label))
(with-access::Call/cc-Label label (resumes)
(cons-set! resumes expr)))
remove Resume from this Begin
(set-car! exprs (cadr exprs))
(set-cdr! exprs (cddr exprs))
(loop exprs))
(else
(loop (cdr exprs))))))
(else
(loop (cdr exprs))))))))
this)
(define-nmethod (Set!.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Set! this (val lvalue)
(let ((resume (resume-begin-split val)))
(if resume
(begin
(set! val (simplified-begin val))
;; before resuming the execution at our resume-point we need to
;; update the lvalue.
;; ex:
;; case 0:
index = 2 ;
;; x = call/cc();
case 2 :
;; ....
Here we need to update ' x ' before resuming at ' case 2 : ' .
(with-access::Call/cc-Resume resume (indices)
there could be several indices for one variable .
;; ex:
;; (set! a (if xxx
;; (call/cc..)
;; (call/cc..)))
(for-each (lambda (index)
(update-hoisted! surrounding-fun index
`(set! ,(with-access::Ref lvalue (var) var))))
indices)
(instantiate::Begin (exprs (list this resume)))))
this))))
(define-nmethod (Break.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Break this (val label)
(let ((resume (resume-begin-split val)))
(when resume
(set! val (simplified-begin val))
(unless (isa? label Call/cc-Label)
(widen!::Call/cc-Label label))
(with-access::Call/cc-Label label (resumes)
(cons-set! resumes resume)))))
this)
(define-nmethod (While.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::While this (body label)
(let ((body-resume (resume-begin-split body))
(continue-resumes (and (isa? label Call/cc-Label)
(with-access::Call/cc-Label label (resumes)
resumes))))
(when body-resume (set! body (simplified-begin body)))
;; a body-resume continues at the end of the while -> like a continue
;; We put it just before the loop.
;; a continue-resume initially was just before a
;; continue. We put it just before the loop now, too.
(let ((resume (cond
((and body-resume continue-resumes)
(resumes-merge! (cons body-resume
continue-resumes)))
(body-resume
body-resume)
(continue-resumes
(resumes-merge! continue-resumes))
(else #f))))
(when (isa? label Call/cc-Label) (shrink! label))
(if resume
;; note the 'resume' before the 'this'
(instantiate::Begin (exprs (list resume this)))
this)))))
(define-nmethod (Labeled.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Labeled this (body label)
(let ((body-resume (resume-begin-split body))
(label-resumes (and (isa? label Call/cc-Label)
(with-access::Call/cc-Label label (resumes)
resumes))))
(when body-resume (set! body (simplified-begin body)))
(let ((resume (cond
((and body-resume label-resumes)
(resumes-merge! (cons body-resume label-resumes)))
(body-resume
body-resume)
(label-resumes
(resumes-merge! label-resumes))
(else #f))))
(when (isa? label Call/cc-Label) (shrink! label))
(if resume
;; all resumes are after Labelled.
(instantiate::Begin (exprs (list this resume)))
this)))))
(define-nmethod (Return.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Return this (val)
(let ((return-resume (resume-begin-split val)))
;; if there is (are) actually a return-resume, then it must be a
;; resume assigning a variable. Otherwise the call would be in
;; tail-position and thus would not have any resume.
;; ex:
;; (return (if xyz
;; (set! a (call/cc..))
;; (set! b (if xxx
;; (call/cc..)
;; (call/cc..)))))
;;
;; all call/cc-calls are not in tail-position. but once the resume
;; has been pushed after the 'set!'s, the resumes are in
;; tail-position.
(when return-resume
(with-access::Call/cc-Resume return-resume (indices)
(for-each (lambda (index)
(update-hoisted! surrounding-fun index '(return)))
indices))
;; drop the resume-node, as it is not needed anymore
)))
this)
| null | https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/scheme2js/callcc_resume_push.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* */
* but WITHOUT ANY WARRANTY; without even the implied warranty of */
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
* LICENSE file for more details. */
*=====================================================================*/
When call/cc resumes, the instruction following the call/cc should be
executed.
Call/cc-Resume represents this location. These nodes are introduced here.
The Resume node is then (sometimes) pushed further, to push it to cheaper
locations. All skipped expressions are copied into the Resume-node and need
to be executed before jumping to the resume-point. At the moment only the
"Set!" node is skipped (and the copied expression currently is just the
skipped var).
first hoisting for variable
physically update the element
if n is a Begin:
returns #f or the last element of the begin, if it was a Call/cc-Resume
physically modifies the begin, so it does not contain the resume-node
anymore.
should never happen
returns #f if the list is empty.
first merge all the Resumes
add Resume node.
tail-call
TODO: implement Case-resume
merge nested Begins.
insert into our list.
otherwise we wouldn't have gotten a 'Begin'.
before resuming the execution at our resume-point we need to
update the lvalue.
ex:
case 0:
x = call/cc();
....
ex:
(set! a (if xxx
(call/cc..)
(call/cc..)))
a body-resume continues at the end of the while -> like a continue
We put it just before the loop.
a continue-resume initially was just before a
continue. We put it just before the loop now, too.
note the 'resume' before the 'this'
all resumes are after Labelled.
if there is (are) actually a return-resume, then it must be a
resume assigning a variable. Otherwise the call would be in
tail-position and thus would not have any resume.
ex:
(return (if xyz
(set! a (call/cc..))
(set! b (if xxx
(call/cc..)
(call/cc..)))))
all call/cc-calls are not in tail-position. but once the resume
has been pushed after the 'set!'s, the resumes are in
tail-position.
drop the resume-node, as it is not needed anymore | * Author : * /
* Copyright : 2007 - 11 , see LICENSE file * /
* This file is part of Scheme2Js . * /
* Scheme2Js is distributed in the hope that it will be useful , * /
(module callcc-resume-push
(import config
nodes
export-desc
walk
tail
mark-statements
verbose
tools)
(static (wide-class Call/cc-Label::Label
(resumes::pair-nil (default '()))))
(export (call/cc-resume-push! tree::Module)))
(define (call/cc-resume-push! tree)
(verbose " call/cc resume push")
(resume! tree #f #f))
(define (update-hoisted! fun index instr)
(with-access::Lambda fun (call/cc-hoisted)
(let ((rev-hoisted (assq index call/cc-hoisted)))
(cons-set! call/cc-hoisted `(,index ,instr))
(set-cdr! rev-hoisted (cons instr (cdr rev-hoisted)))))))
(define (resume-begin-split n)
(when (isa? n Begin)
(with-access::Begin n (exprs)
(let loop ((exprs exprs))
(cond
((null? (cdr exprs)) #f)
((and (null? (cddr exprs))
(isa? (cadr exprs) Call/cc-Resume))
(let ((resume (cadr exprs)))
(set-cdr! exprs '())
resume))
(else
(loop (cdr exprs))))))))
(define (simplified-begin bnode::Begin)
(with-access::Begin bnode (exprs)
(cond
((null? exprs) (instantiate::Const
(location (with-access::Node bnode (location) location))
(value #unspecified)))
((null? (cdr exprs)) (car exprs))
(else
bnode))))
merges all Resumes into the first of the list .
(define (resumes-merge! resumes)
(and resumes
(not (null? resumes))
(let ((first-resume (car resumes)))
(with-access::Call/cc-Resume first-resume (indices)
(let loop ((resumes (cdr resumes))
(inds indices))
(if (null? resumes)
(set! indices inds)
(loop (cdr resumes)
(append (with-access::Call/cc-Resume (car resumes) (indices) indices)
inds)))))
first-resume)))
(define-nmethod (Node.resume! surrounding-fun)
(default-walk! this surrounding-fun))
(define-nmethod (Lambda.resume! surrounding-fun)
(default-walk! this this))
(define-nmethod (Call.resume! surrounding-fun)
(with-access::Call this (call/cc? call/cc-index)
(if (or (not call/cc?)
(default-walk! this surrounding-fun)
(begin
(default-walk! this surrounding-fun)
(let ((resume-node (instantiate::Call/cc-Resume
(location (with-access::Node this (location) location))
(indices (list call/cc-index)))))
(instantiate::Begin
(exprs (list this resume-node))))))))
(define-nmethod (If.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::If this (then else)
(let ((then-resume (resume-begin-split then))
(else-resume (resume-begin-split else)))
(when then-resume
in case there is only one element left .
(set! then (simplified-begin then)))
(when else-resume
(set! else (simplified-begin else)))
(if (or then-resume else-resume)
(let* ((resume (cond
((and then-resume else-resume)
(resumes-merge! (list then-resume else-resume)))
(else
(or then-resume else-resume))))
(bnode (instantiate::Begin (exprs (list this resume)))))
bnode)
this))))
(define-nmethod (Case.resume! surrounding-fun)
(default-walk! this surrounding-fun))
(define-nmethod (Begin.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Begin this (exprs)
(let loop ((exprs exprs))
(unless (null? exprs)
(let ((expr (car exprs)))
(cond
((isa? expr Begin)
(let ((other-exprs (with-access::Begin expr (exprs) exprs))
(exprs-tail (cdr exprs)))
we know there must be at least 2 elements .
(set-car! exprs (car other-exprs))
(set-cdr! exprs (cdr other-exprs))
(set-cdr! (last-pair other-exprs) exprs-tail))
(loop exprs))
((isa? expr Call/cc-Resume)
(let ((next (and (not (null? (cdr exprs)))
(cadr exprs))))
(cond
((not next)
(loop (cdr exprs)))
merge two consecutive Resumes into one .
((isa? next Call/cc-Resume)
(set-car! exprs (resumes-merge! (list (car exprs) next)))
(set-cdr! exprs (cddr exprs))
(loop exprs))
((or (isa? next Continue)
(and (isa? next Break)
(not (with-access::Break next (val) val))))
(let ((label (if (isa? next Continue)
(with-access::Continue next (label) label)
(with-access::Break next (label) label))))
(unless (isa? label Call/cc-Label)
(widen!::Call/cc-Label label))
(with-access::Call/cc-Label label (resumes)
(cons-set! resumes expr)))
remove Resume from this Begin
(set-car! exprs (cadr exprs))
(set-cdr! exprs (cddr exprs))
(loop exprs))
(else
(loop (cdr exprs))))))
(else
(loop (cdr exprs))))))))
this)
(define-nmethod (Set!.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Set! this (val lvalue)
(let ((resume (resume-begin-split val)))
(if resume
(begin
(set! val (simplified-begin val))
case 2 :
Here we need to update ' x ' before resuming at ' case 2 : ' .
(with-access::Call/cc-Resume resume (indices)
there could be several indices for one variable .
(for-each (lambda (index)
(update-hoisted! surrounding-fun index
`(set! ,(with-access::Ref lvalue (var) var))))
indices)
(instantiate::Begin (exprs (list this resume)))))
this))))
(define-nmethod (Break.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Break this (val label)
(let ((resume (resume-begin-split val)))
(when resume
(set! val (simplified-begin val))
(unless (isa? label Call/cc-Label)
(widen!::Call/cc-Label label))
(with-access::Call/cc-Label label (resumes)
(cons-set! resumes resume)))))
this)
(define-nmethod (While.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::While this (body label)
(let ((body-resume (resume-begin-split body))
(continue-resumes (and (isa? label Call/cc-Label)
(with-access::Call/cc-Label label (resumes)
resumes))))
(when body-resume (set! body (simplified-begin body)))
(let ((resume (cond
((and body-resume continue-resumes)
(resumes-merge! (cons body-resume
continue-resumes)))
(body-resume
body-resume)
(continue-resumes
(resumes-merge! continue-resumes))
(else #f))))
(when (isa? label Call/cc-Label) (shrink! label))
(if resume
(instantiate::Begin (exprs (list resume this)))
this)))))
(define-nmethod (Labeled.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Labeled this (body label)
(let ((body-resume (resume-begin-split body))
(label-resumes (and (isa? label Call/cc-Label)
(with-access::Call/cc-Label label (resumes)
resumes))))
(when body-resume (set! body (simplified-begin body)))
(let ((resume (cond
((and body-resume label-resumes)
(resumes-merge! (cons body-resume label-resumes)))
(body-resume
body-resume)
(label-resumes
(resumes-merge! label-resumes))
(else #f))))
(when (isa? label Call/cc-Label) (shrink! label))
(if resume
(instantiate::Begin (exprs (list this resume)))
this)))))
(define-nmethod (Return.resume! surrounding-fun)
(default-walk! this surrounding-fun)
(with-access::Return this (val)
(let ((return-resume (resume-begin-split val)))
(when return-resume
(with-access::Call/cc-Resume return-resume (indices)
(for-each (lambda (index)
(update-hoisted! surrounding-fun index '(return)))
indices))
)))
this)
|
ccb8784013964a2b319b09c6968ac7abd31484994cce04a2c84ba934be31a1ca | ocaml/ocaml | location.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Lexing
type t = Warnings.loc =
{ loc_start: position; loc_end: position; loc_ghost: bool }
let in_file = Warnings.ghost_loc_in_file
let none = in_file "_none_"
let is_none l = (l = none)
let curr lexbuf = {
loc_start = lexbuf.lex_start_p;
loc_end = lexbuf.lex_curr_p;
loc_ghost = false
}
let init lexbuf fname =
lexbuf.lex_curr_p <- {
pos_fname = fname;
pos_lnum = 1;
pos_bol = 0;
pos_cnum = 0;
}
let symbol_rloc () = {
loc_start = Parsing.symbol_start_pos ();
loc_end = Parsing.symbol_end_pos ();
loc_ghost = false;
}
let symbol_gloc () = {
loc_start = Parsing.symbol_start_pos ();
loc_end = Parsing.symbol_end_pos ();
loc_ghost = true;
}
let rhs_loc n = {
loc_start = Parsing.rhs_start_pos n;
loc_end = Parsing.rhs_end_pos n;
loc_ghost = false;
}
let rhs_interval m n = {
loc_start = Parsing.rhs_start_pos m;
loc_end = Parsing.rhs_end_pos n;
loc_ghost = false;
}
(* return file, line, char from the given position *)
let get_pos_info pos =
(pos.pos_fname, pos.pos_lnum, pos.pos_cnum - pos.pos_bol)
type 'a loc = {
txt : 'a;
loc : t;
}
let mkloc txt loc = { txt ; loc }
let mknoloc txt = mkloc txt none
(******************************************************************************)
(* Input info *)
let input_name = ref "_none_"
let input_lexbuf = ref (None : lexbuf option)
let input_phrase_buffer = ref (None : Buffer.t option)
(******************************************************************************)
(* Terminal info *)
let status = ref Terminfo.Uninitialised
let setup_terminal () =
if !status = Terminfo.Uninitialised then
status := Terminfo.setup stdout
(* The number of lines already printed after input.
This is used by [highlight_terminfo] to identify the current position of the
input in the terminal. This would not be possible without this information,
since printing several warnings/errors adds text between the user input and
the bottom of the terminal.
We also use for {!is_first_report}, see below.
*)
let num_loc_lines = ref 0
We use [ num_loc_lines ] to determine if the report about to be
printed is the first or a follow - up report of the current
" batch " -- contiguous reports without user input in between , for
example for the current toplevel phrase . We use this to print
a blank line between messages of the same batch .
printed is the first or a follow-up report of the current
"batch" -- contiguous reports without user input in between, for
example for the current toplevel phrase. We use this to print
a blank line between messages of the same batch.
*)
let is_first_message () =
!num_loc_lines = 0
(* This is used by the toplevel to reset [num_loc_lines] before each phrase *)
let reset () =
num_loc_lines := 0
(* This is used by the toplevel *)
let echo_eof () =
print_newline ();
incr num_loc_lines
(* This is used by the toplevel and the report printers below. *)
let separate_new_message ppf =
if not (is_first_message ()) then begin
Format.pp_print_newline ppf ();
incr num_loc_lines
end
(* Code printing errors and warnings must be wrapped using this function, in
order to update [num_loc_lines].
[print_updating_num_loc_lines ppf f arg] is equivalent to calling [f ppf
arg], and additionally updates [num_loc_lines]. *)
let print_updating_num_loc_lines ppf f arg =
let open Format in
let out_functions = pp_get_formatter_out_functions ppf () in
let out_string str start len =
let rec count i c =
if i = start + len then c
else if String.get str i = '\n' then count (succ i) (succ c)
else count (succ i) c in
num_loc_lines := !num_loc_lines + count start 0 ;
out_functions.out_string str start len in
pp_set_formatter_out_functions ppf
{ out_functions with out_string } ;
f ppf arg ;
pp_print_flush ppf ();
pp_set_formatter_out_functions ppf out_functions
let setup_colors () =
Misc.Color.setup !Clflags.color
(******************************************************************************)
Printing locations , e.g. ' File " foo.ml " , line 3 , characters 10 - 12 '
let rewrite_absolute_path path =
match Misc.get_build_path_prefix_map () with
| None -> path
| Some map -> Build_path_prefix_map.rewrite map path
let absolute_path s = (* This function could go into Filename *)
let open Filename in
let s =
if not (is_relative s) then s
else (rewrite_absolute_path (concat (Sys.getcwd ()) s))
in
(* Now simplify . and .. components *)
let rec aux s =
let base = basename s in
let dir = dirname s in
if dir = s then dir
else if base = current_dir_name then aux dir
else if base = parent_dir_name then dirname (aux dir)
else concat (aux dir) base
in
aux s
let show_filename file =
if !Clflags.absname then absolute_path file else file
let print_filename ppf file =
Format.pp_print_string ppf (show_filename file)
Best - effort printing of the text describing a location , of the form
' File " foo.ml " , line 3 , characters 10 - 12 ' .
Some of the information ( filename , line number or characters numbers ) in the
location might be invalid ; in which case we do not print it .
'File "foo.ml", line 3, characters 10-12'.
Some of the information (filename, line number or characters numbers) in the
location might be invalid; in which case we do not print it.
*)
let print_loc ppf loc =
setup_colors ();
let file_valid = function
| "_none_" ->
This is a dummy placeholder , but we print it anyway to please editors
that parse locations in error messages ( e.g. Emacs ) .
that parse locations in error messages (e.g. Emacs). *)
true
| "" | "//toplevel//" -> false
| _ -> true
in
let line_valid line = line > 0 in
let chars_valid ~startchar ~endchar = startchar <> -1 && endchar <> -1 in
let file =
(* According to the comment in location.mli, if [pos_fname] is "", we must
use [!input_name]. *)
if loc.loc_start.pos_fname = "" then !input_name
else loc.loc_start.pos_fname
in
let startline = loc.loc_start.pos_lnum in
let endline = loc.loc_end.pos_lnum in
let startchar = loc.loc_start.pos_cnum - loc.loc_start.pos_bol in
let endchar = loc.loc_end.pos_cnum - loc.loc_end.pos_bol in
let first = ref true in
let capitalize s =
if !first then (first := false; String.capitalize_ascii s)
else s in
let comma () =
if !first then () else Format.fprintf ppf ", " in
Format.fprintf ppf "@{<loc>";
if file_valid file then
Format.fprintf ppf "%s \"%a\"" (capitalize "file") print_filename file;
Print " line 1 " in the case of a dummy line number . This is to please the
existing setup of editors that parse locations in error messages ( e.g.
Emacs ) .
existing setup of editors that parse locations in error messages (e.g.
Emacs). *)
comma ();
let startline = if line_valid startline then startline else 1 in
let endline = if line_valid endline then endline else startline in
begin if startline = endline then
Format.fprintf ppf "%s %i" (capitalize "line") startline
else
Format.fprintf ppf "%s %i-%i" (capitalize "lines") startline endline
end;
if chars_valid ~startchar ~endchar then (
comma ();
Format.fprintf ppf "%s %i-%i" (capitalize "characters") startchar endchar
);
Format.fprintf ppf "@}"
(* Print a comma-separated list of locations *)
let print_locs ppf locs =
Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf ",@ ")
print_loc ppf locs
(******************************************************************************)
(* An interval set structure; additionally, it stores user-provided information
at interval boundaries.
The implementation provided here is naive and assumes the number of intervals
to be small, but the interface would allow for a more efficient
implementation if needed.
Note: the structure only stores maximal intervals (that therefore do not
overlap).
*)
module ISet : sig
type 'a bound = 'a * int
type 'a t
(* bounds are included *)
val of_intervals : ('a bound * 'a bound) list -> 'a t
val mem : 'a t -> pos:int -> bool
val find_bound_in : 'a t -> range:(int * int) -> 'a bound option
val is_start : 'a t -> pos:int -> 'a option
val is_end : 'a t -> pos:int -> 'a option
val extrema : 'a t -> ('a bound * 'a bound) option
end
=
struct
type 'a bound = 'a * int
(* non overlapping intervals *)
type 'a t = ('a bound * 'a bound) list
let of_intervals intervals =
let pos =
List.map (fun ((a, x), (b, y)) ->
if x > y then [] else [((a, x), `S); ((b, y), `E)]
) intervals
|> List.flatten
|> List.sort (fun ((_, x), k) ((_, y), k') ->
(* Make `S come before `E so that consecutive intervals get merged
together in the fold below *)
let kn = function `S -> 0 | `E -> 1 in
compare (x, kn k) (y, kn k'))
in
let nesting, acc =
List.fold_left (fun (nesting, acc) (a, kind) ->
match kind, nesting with
| `S, `Outside -> `Inside (a, 0), acc
| `S, `Inside (s, n) -> `Inside (s, n+1), acc
| `E, `Outside -> assert false
| `E, `Inside (s, 0) -> `Outside, ((s, a) :: acc)
| `E, `Inside (s, n) -> `Inside (s, n-1), acc
) (`Outside, []) pos in
assert (nesting = `Outside);
List.rev acc
let mem iset ~pos =
List.exists (fun ((_, s), (_, e)) -> s <= pos && pos <= e) iset
let find_bound_in iset ~range:(start, end_) =
List.find_map (fun ((a, x), (b, y)) ->
if start <= x && x <= end_ then Some (a, x)
else if start <= y && y <= end_ then Some (b, y)
else None
) iset
let is_start iset ~pos =
List.find_map (fun ((a, x), _) ->
if pos = x then Some a else None
) iset
let is_end iset ~pos =
List.find_map (fun (_, (b, y)) ->
if pos = y then Some b else None
) iset
let extrema iset =
if iset = [] then None
else Some (fst (List.hd iset), snd (List.hd (List.rev iset)))
end
(******************************************************************************)
Toplevel : highlighting and quoting locations
(* Highlight the locations using standout mode.
If [locs] is empty, this function is a no-op.
*)
let highlight_terminfo lb ppf locs =
Format.pp_print_flush ppf (); (* avoid mixing Format and normal output *)
Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer .
let pos0 = -lb.lex_abs_pos in
(* Do nothing if the buffer does not contain the whole phrase. *)
if pos0 < 0 then raise Exit;
(* Count number of lines in phrase *)
let lines = ref !num_loc_lines in
for i = pos0 to lb.lex_buffer_len - 1 do
if Bytes.get lb.lex_buffer i = '\n' then incr lines
done;
(* If too many lines, give up *)
if !lines >= Terminfo.num_lines stdout - 2 then raise Exit;
(* Move cursor up that number of lines *)
flush stdout; Terminfo.backup stdout !lines;
(* Print the input, switching to standout for the location *)
let bol = ref false in
print_string "# ";
for pos = 0 to lb.lex_buffer_len - pos0 - 1 do
if !bol then (print_string " "; bol := false);
if List.exists (fun loc -> pos = loc.loc_start.pos_cnum) locs then
Terminfo.standout stdout true;
if List.exists (fun loc -> pos = loc.loc_end.pos_cnum) locs then
Terminfo.standout stdout false;
let c = Bytes.get lb.lex_buffer (pos + pos0) in
print_char c;
bol := (c = '\n')
done;
(* Make sure standout mode is over *)
Terminfo.standout stdout false;
(* Position cursor back to original location *)
Terminfo.resume stdout !num_loc_lines;
flush stdout
let highlight_terminfo lb ppf locs =
try highlight_terminfo lb ppf locs
with Exit -> ()
Highlight the location by printing it again .
There are two different styles for highlighting errors in " dumb " mode ,
depending if the error fits on a single line or spans across several lines .
For single - line errors ,
foo the_error bar
gets displayed as follows , where X is the line number :
X | foo the_error bar
^^^^^^^^^
For multi - line errors ,
foo the _
error bar
gets displayed as :
X1 | .... the _
X2 | error ....
An ellipsis hides the middle lines of the multi - line error if it has more
than [ max_lines ] lines .
If [ locs ] is empty then this function is a no - op .
There are two different styles for highlighting errors in "dumb" mode,
depending if the error fits on a single line or spans across several lines.
For single-line errors,
foo the_error bar
gets displayed as follows, where X is the line number:
X | foo the_error bar
^^^^^^^^^
For multi-line errors,
foo the_
error bar
gets displayed as:
X1 | ....the_
X2 | error....
An ellipsis hides the middle lines of the multi-line error if it has more
than [max_lines] lines.
If [locs] is empty then this function is a no-op.
*)
type input_line = {
text : string;
start_pos : int;
}
Takes a list of lines with possibly missing line numbers .
If the line numbers that are present are consistent with the number of lines
between them , then infer the intermediate line numbers .
This is not always the case , typically if lexer line directives are
involved ...
If the line numbers that are present are consistent with the number of lines
between them, then infer the intermediate line numbers.
This is not always the case, typically if lexer line directives are
involved... *)
let infer_line_numbers
(lines: (int option * input_line) list):
(int option * input_line) list
=
let (_, offset, consistent) =
List.fold_left (fun (i, offset, consistent) (lnum, _) ->
match lnum, offset with
| None, _ -> (i+1, offset, consistent)
| Some n, None -> (i+1, Some (n - i), consistent)
| Some n, Some m -> (i+1, offset, consistent && n = m + i)
) (0, None, true) lines
in
match offset, consistent with
| Some m, true ->
List.mapi (fun i (_, line) -> (Some (m + i), line)) lines
| _, _ ->
lines
(* [get_lines] must return the lines to highlight, given starting and ending
positions.
See [lines_around_from_current_input] below for an instantiation of
[get_lines] that reads from the current input.
*)
let highlight_quote ppf
~(get_lines: start_pos:position -> end_pos:position -> input_line list)
?(max_lines = 10)
highlight_tag
locs
=
let iset = ISet.of_intervals @@ List.filter_map (fun loc ->
let s, e = loc.loc_start, loc.loc_end in
if s.pos_cnum = -1 || e.pos_cnum = -1 then None
else Some ((s, s.pos_cnum), (e, e.pos_cnum - 1))
) locs in
match ISet.extrema iset with
| None -> ()
| Some ((leftmost, _), (rightmost, _)) ->
let lines =
get_lines ~start_pos:leftmost ~end_pos:rightmost
|> List.map (fun ({ text; start_pos } as line) ->
let end_pos = start_pos + String.length text - 1 in
let line_nb =
match ISet.find_bound_in iset ~range:(start_pos, end_pos) with
| None -> None
| Some (p, _) -> Some p.pos_lnum
in
(line_nb, line))
|> infer_line_numbers
|> List.map (fun (lnum, { text; start_pos }) ->
(text,
Option.fold ~some:Int.to_string ~none:"" lnum,
start_pos))
in
Format.fprintf ppf "@[<v>";
begin match lines with
| [] | [("", _, _)] -> ()
| [(line, line_nb, line_start_cnum)] ->
(* Single-line error *)
Format.fprintf ppf "%s | %s@," line_nb line;
Format.fprintf ppf "%*s " (String.length line_nb) "";
(* Iterate up to [rightmost], which can be larger than the length of
the line because we may point to a location after the end of the
last token on the line, for instance:
{[
token
^
Did you forget ...
]} *)
for i = 0 to rightmost.pos_cnum - line_start_cnum - 1 do
let pos = line_start_cnum + i in
if ISet.is_start iset ~pos <> None then
Format.fprintf ppf "@{<%s>" highlight_tag;
if ISet.mem iset ~pos then Format.pp_print_char ppf '^'
else if i < String.length line then begin
(* For alignment purposes, align using a tab for each tab in the
source code *)
if line.[i] = '\t' then Format.pp_print_char ppf '\t'
else Format.pp_print_char ppf ' '
end;
if ISet.is_end iset ~pos <> None then
Format.fprintf ppf "@}"
done;
Format.fprintf ppf "@}@,"
| _ ->
(* Multi-line error *)
Misc.pp_two_columns ~sep:"|" ~max_lines ppf
@@ List.map (fun (line, line_nb, line_start_cnum) ->
let line = String.mapi (fun i car ->
if ISet.mem iset ~pos:(line_start_cnum + i) then car else '.'
) line in
(line_nb, line)
) lines
end;
Format.fprintf ppf "@]"
let lines_around
~(start_pos: position) ~(end_pos: position)
~(seek: int -> unit)
~(read_char: unit -> char option):
input_line list
=
seek start_pos.pos_bol;
let lines = ref [] in
let bol = ref start_pos.pos_bol in
let cur = ref start_pos.pos_bol in
let b = Buffer.create 80 in
let add_line () =
if !bol < !cur then begin
let text = Buffer.contents b in
Buffer.clear b;
lines := { text; start_pos = !bol } :: !lines;
bol := !cur
end
in
let rec loop () =
if !bol >= end_pos.pos_cnum then ()
else begin
match read_char () with
| None ->
(* end of input *)
add_line ()
| Some c ->
incr cur;
match c with
| '\r' -> loop ()
| '\n' -> add_line (); loop ()
| _ -> Buffer.add_char b c; loop ()
end
in
loop ();
List.rev !lines
(* Try to get lines from a lexbuf *)
let lines_around_from_lexbuf
~(start_pos: position) ~(end_pos: position)
(lb: lexbuf):
input_line list
=
(* Converts a global position to one that is relative to the lexing buffer *)
let rel n = n - lb.lex_abs_pos in
if rel start_pos.pos_bol < 0 then begin
(* Do nothing if the buffer does not contain the input (because it has been
refilled while lexing it) *)
[]
end else begin
let pos = ref 0 in (* relative position *)
let seek n = pos := rel n in
let read_char () =
if !pos >= lb.lex_buffer_len then (* end of buffer *) None
else
let c = Bytes.get lb.lex_buffer !pos in
incr pos; Some c
in
lines_around ~start_pos ~end_pos ~seek ~read_char
end
(* Attempt to get lines from the phrase buffer *)
let lines_around_from_phrasebuf
~(start_pos: position) ~(end_pos: position)
(pb: Buffer.t):
input_line list
=
let pos = ref 0 in
let seek n = pos := n in
let read_char () =
if !pos >= Buffer.length pb then None
else begin
let c = Buffer.nth pb !pos in
incr pos; Some c
end
in
lines_around ~start_pos ~end_pos ~seek ~read_char
(* Get lines from a file *)
let lines_around_from_file
~(start_pos: position) ~(end_pos: position)
(filename: string):
input_line list
=
try
let cin = open_in_bin filename in
let read_char () =
try Some (input_char cin) with End_of_file -> None
in
let lines =
lines_around ~start_pos ~end_pos ~seek:(seek_in cin) ~read_char
in
close_in cin;
lines
with Sys_error _ -> []
A [ get_lines ] function for [ highlight_quote ] that reads from the current
input .
It first tries to read from [ ! input_lexbuf ] , then if that fails ( because the
lexbuf no longer contains the input we want ) , it reads from [ ! input_name ]
directly
input.
It first tries to read from [!input_lexbuf], then if that fails (because the
lexbuf no longer contains the input we want), it reads from [!input_name]
directly *)
let lines_around_from_current_input ~start_pos ~end_pos =
(* Be a bit defensive, and do not try to open one of the possible
[!input_name] values that we know do not denote valid filenames. *)
let file_valid = function
| "//toplevel//" | "_none_" | "" -> false
| _ -> true
in
let from_file () =
if file_valid !input_name then
lines_around_from_file !input_name ~start_pos ~end_pos
else
[]
in
match !input_lexbuf, !input_phrase_buffer, !input_name with
| _, Some pb, "//toplevel//" ->
begin match lines_around_from_phrasebuf pb ~start_pos ~end_pos with
| [] -> (* Could not read the input from the phrase buffer. This is likely
a sign that we were given a buggy location. *)
[]
| lines ->
lines
end
| Some lb, _, _ ->
begin match lines_around_from_lexbuf lb ~start_pos ~end_pos with
| [] -> (* The input is likely not in the lexbuf anymore *)
from_file ()
| lines ->
lines
end
| None, _, _ ->
from_file ()
(******************************************************************************)
(* Reporting errors and warnings *)
type msg = (Format.formatter -> unit) loc
let msg ?(loc = none) fmt =
Format.kdprintf (fun txt -> { loc; txt }) fmt
type report_kind =
| Report_error
| Report_warning of string
| Report_warning_as_error of string
| Report_alert of string
| Report_alert_as_error of string
type report = {
kind : report_kind;
main : msg;
sub : msg list;
}
type report_printer = {
(* The entry point *)
pp : report_printer ->
Format.formatter -> report -> unit;
pp_report_kind : report_printer -> report ->
Format.formatter -> report_kind -> unit;
pp_main_loc : report_printer -> report ->
Format.formatter -> t -> unit;
pp_main_txt : report_printer -> report ->
Format.formatter -> (Format.formatter -> unit) -> unit;
pp_submsgs : report_printer -> report ->
Format.formatter -> msg list -> unit;
pp_submsg : report_printer -> report ->
Format.formatter -> msg -> unit;
pp_submsg_loc : report_printer -> report ->
Format.formatter -> t -> unit;
pp_submsg_txt : report_printer -> report ->
Format.formatter -> (Format.formatter -> unit) -> unit;
}
let is_dummy_loc loc =
: this should be just [ loc.loc_ghost ] and the function should be
inlined below . However , currently , the compiler emits in some places ghost
locations with valid ranges that should still be printed . These locations
should be made non - ghost -- in the meantime we just check if the ranges are
valid .
inlined below. However, currently, the compiler emits in some places ghost
locations with valid ranges that should still be printed. These locations
should be made non-ghost -- in the meantime we just check if the ranges are
valid. *)
loc.loc_start.pos_cnum = -1 || loc.loc_end.pos_cnum = -1
It only makes sense to highlight ( i.e. quote or underline the corresponding
source code ) locations that originate from the current input .
As of now , this should only happen in the following cases :
- if dummy locs or ghost locs leak out of the compiler or a buggy ppx ;
- more generally , if some code uses the compiler - libs API and feeds it
locations that do not match the current values of [ ! Location.input_name ] ,
[ ! Location.input_lexbuf ] ;
- when calling the compiler on a .ml file that contains lexer line directives
indicating an other file . This should happen relatively rarely in practice --
in particular this is not what happens when using -pp or -ppx or a ppx
driver .
source code) locations that originate from the current input.
As of now, this should only happen in the following cases:
- if dummy locs or ghost locs leak out of the compiler or a buggy ppx;
- more generally, if some code uses the compiler-libs API and feeds it
locations that do not match the current values of [!Location.input_name],
[!Location.input_lexbuf];
- when calling the compiler on a .ml file that contains lexer line directives
indicating an other file. This should happen relatively rarely in practice --
in particular this is not what happens when using -pp or -ppx or a ppx
driver.
*)
let is_quotable_loc loc =
not (is_dummy_loc loc)
&& loc.loc_start.pos_fname = !input_name
&& loc.loc_end.pos_fname = !input_name
let error_style () =
match !Clflags.error_style with
| Some setting -> setting
| None -> Misc.Error_style.default_setting
let batch_mode_printer : report_printer =
let pp_loc _self report ppf loc =
let tag = match report.kind with
| Report_warning_as_error _
| Report_alert_as_error _
| Report_error -> "error"
| Report_warning _
| Report_alert _ -> "warning"
in
let highlight ppf loc =
match error_style () with
| Misc.Error_style.Contextual ->
if is_quotable_loc loc then
highlight_quote ppf
~get_lines:lines_around_from_current_input
tag [loc]
| Misc.Error_style.Short ->
()
in
Format.fprintf ppf "@[<v>%a:@ %a@]" print_loc loc highlight loc
in
let pp_txt ppf txt = Format.fprintf ppf "@[%t@]" txt in
let pp self ppf report =
setup_colors ();
separate_new_message ppf;
(* Make sure we keep [num_loc_lines] updated.
The tabulation box is here to give submessage the option
to be aligned with the main message box
*)
print_updating_num_loc_lines ppf (fun ppf () ->
Format.fprintf ppf "@[<v>%a%a%a: %a%a%a%a@]@."
Format.pp_open_tbox ()
(self.pp_main_loc self report) report.main.loc
(self.pp_report_kind self report) report.kind
Format.pp_set_tab ()
(self.pp_main_txt self report) report.main.txt
(self.pp_submsgs self report) report.sub
Format.pp_close_tbox ()
) ()
in
let pp_report_kind _self _ ppf = function
| Report_error -> Format.fprintf ppf "@{<error>Error@}"
| Report_warning w -> Format.fprintf ppf "@{<warning>Warning@} %s" w
| Report_warning_as_error w ->
Format.fprintf ppf "@{<error>Error@} (warning %s)" w
| Report_alert w -> Format.fprintf ppf "@{<warning>Alert@} %s" w
| Report_alert_as_error w ->
Format.fprintf ppf "@{<error>Error@} (alert %s)" w
in
let pp_main_loc self report ppf loc =
pp_loc self report ppf loc
in
let pp_main_txt _self _ ppf txt =
pp_txt ppf txt
in
let pp_submsgs self report ppf msgs =
List.iter (fun msg ->
Format.fprintf ppf "@,%a" (self.pp_submsg self report) msg
) msgs
in
let pp_submsg self report ppf { loc; txt } =
Format.fprintf ppf "@[%a %a@]"
(self.pp_submsg_loc self report) loc
(self.pp_submsg_txt self report) txt
in
let pp_submsg_loc self report ppf loc =
if not loc.loc_ghost then
pp_loc self report ppf loc
in
let pp_submsg_txt _self _ ppf loc =
pp_txt ppf loc
in
{ pp; pp_report_kind; pp_main_loc; pp_main_txt;
pp_submsgs; pp_submsg; pp_submsg_loc; pp_submsg_txt }
let terminfo_toplevel_printer (lb: lexbuf): report_printer =
let pp self ppf err =
setup_colors ();
(* Highlight all toplevel locations of the report, instead of displaying
the main location. Do it now instead of in [pp_main_loc], to avoid
messing with Format boxes. *)
let sub_locs = List.map (fun { loc; _ } -> loc) err.sub in
let all_locs = err.main.loc :: sub_locs in
let locs_highlighted = List.filter is_quotable_loc all_locs in
highlight_terminfo lb ppf locs_highlighted;
batch_mode_printer.pp self ppf err
in
let pp_main_loc _ _ _ _ = () in
let pp_submsg_loc _ _ ppf loc =
if not loc.loc_ghost then
Format.fprintf ppf "%a:@ " print_loc loc in
{ batch_mode_printer with pp; pp_main_loc; pp_submsg_loc }
let best_toplevel_printer () =
setup_terminal ();
match !status, !input_lexbuf with
| Terminfo.Good_term, Some lb ->
terminfo_toplevel_printer lb
| _, _ ->
batch_mode_printer
(* Creates a printer for the current input *)
let default_report_printer () : report_printer =
if !input_name = "//toplevel//" then
best_toplevel_printer ()
else
batch_mode_printer
let report_printer = ref default_report_printer
let print_report ppf report =
let printer = !report_printer () in
printer.pp printer ppf report
(******************************************************************************)
(* Reporting errors *)
type error = report
let report_error ppf err =
print_report ppf err
let mkerror loc sub txt =
{ kind = Report_error; main = { loc; txt }; sub }
let errorf ?(loc = none) ?(sub = []) =
Format.kdprintf (mkerror loc sub)
let error ?(loc = none) ?(sub = []) msg_str =
mkerror loc sub (fun ppf -> Format.pp_print_string ppf msg_str)
let error_of_printer ?(loc = none) ?(sub = []) pp x =
mkerror loc sub (fun ppf -> pp ppf x)
let error_of_printer_file print x =
error_of_printer ~loc:(in_file !input_name) print x
(******************************************************************************)
(* Reporting warnings: generating a report from a warning number using the
information in [Warnings] + convenience functions. *)
let default_warning_alert_reporter report mk (loc: t) w : report option =
match report w with
| `Inactive -> None
| `Active { Warnings.id; message; is_error; sub_locs } ->
let msg_of_str str = fun ppf -> Format.pp_print_string ppf str in
let kind = mk is_error id in
let main = { loc; txt = msg_of_str message } in
let sub = List.map (fun (loc, sub_message) ->
{ loc; txt = msg_of_str sub_message }
) sub_locs in
Some { kind; main; sub }
let default_warning_reporter =
default_warning_alert_reporter
Warnings.report
(fun is_error id ->
if is_error then Report_warning_as_error id
else Report_warning id
)
let warning_reporter = ref default_warning_reporter
let report_warning loc w = !warning_reporter loc w
let formatter_for_warnings = ref Format.err_formatter
let print_warning loc ppf w =
match report_warning loc w with
| None -> ()
| Some report -> print_report ppf report
let prerr_warning loc w = print_warning loc !formatter_for_warnings w
let default_alert_reporter =
default_warning_alert_reporter
Warnings.report_alert
(fun is_error id ->
if is_error then Report_alert_as_error id
else Report_alert id
)
let alert_reporter = ref default_alert_reporter
let report_alert loc w = !alert_reporter loc w
let print_alert loc ppf w =
match report_alert loc w with
| None -> ()
| Some report -> print_report ppf report
let prerr_alert loc w = print_alert loc !formatter_for_warnings w
let alert ?(def = none) ?(use = none) ~kind loc message =
prerr_alert loc {Warnings.kind; message; def; use}
let deprecated ?def ?use loc message =
alert ?def ?use ~kind:"deprecated" loc message
let auto_include_alert lib =
let message = Printf.sprintf "\
OCaml's lib directory layout changed in 5.0. The %s subdirectory has been \
automatically added to the search path, but you should add -I +%s to the \
command-line to silence this alert (e.g. by adding %s to the list of \
libraries in your dune file, or adding use_%s to your _tags file for \
ocamlbuild, or using -package %s for ocamlfind)." lib lib lib lib lib in
let alert =
{Warnings.kind="ocaml_deprecated_auto_include"; use=none; def=none;
message = Format.asprintf "@[@\n%a@]" Format.pp_print_text message}
in
prerr_alert none alert
let deprecated_script_alert program =
let message = Printf.sprintf "\
Running %s where the first argument is an implicit basename with no \
extension (e.g. %s script-file) is deprecated. Either rename the script \
(%s script-file.ml) or qualify the basename (%s ./script-file)"
program program program program
in
let alert =
{Warnings.kind="ocaml_deprecated_cli"; use=none; def=none;
message = Format.asprintf "@[@\n%a@]" Format.pp_print_text message}
in
prerr_alert none alert
(******************************************************************************)
(* Reporting errors on exceptions *)
let error_of_exn : (exn -> error option) list ref = ref []
let register_error_of_exn f = error_of_exn := f :: !error_of_exn
exception Already_displayed_error = Warnings.Errors
let error_of_exn exn =
match exn with
| Already_displayed_error -> Some `Already_displayed
| _ ->
let rec loop = function
| [] -> None
| f :: rest ->
match f exn with
| Some error -> Some (`Ok error)
| None -> loop rest
in
loop !error_of_exn
let () =
register_error_of_exn
(function
| Sys_error msg ->
Some (errorf ~loc:(in_file !input_name) "I/O error: %s" msg)
| _ -> None
)
external reraise : exn -> 'a = "%reraise"
let report_exception ppf exn =
let rec loop n exn =
match error_of_exn exn with
| None -> reraise exn
| Some `Already_displayed -> ()
| Some (`Ok err) -> report_error ppf err
| exception exn when n > 0 -> loop (n-1) exn
in
loop 5 exn
exception Error of error
let () =
register_error_of_exn
(function
| Error e -> Some e
| _ -> None
)
let raise_errorf ?(loc = none) ?(sub = []) =
Format.kdprintf (fun txt -> raise (Error (mkerror loc sub txt)))
| null | https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/parsing/location.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
return file, line, char from the given position
****************************************************************************
Input info
****************************************************************************
Terminal info
The number of lines already printed after input.
This is used by [highlight_terminfo] to identify the current position of the
input in the terminal. This would not be possible without this information,
since printing several warnings/errors adds text between the user input and
the bottom of the terminal.
We also use for {!is_first_report}, see below.
This is used by the toplevel to reset [num_loc_lines] before each phrase
This is used by the toplevel
This is used by the toplevel and the report printers below.
Code printing errors and warnings must be wrapped using this function, in
order to update [num_loc_lines].
[print_updating_num_loc_lines ppf f arg] is equivalent to calling [f ppf
arg], and additionally updates [num_loc_lines].
****************************************************************************
This function could go into Filename
Now simplify . and .. components
According to the comment in location.mli, if [pos_fname] is "", we must
use [!input_name].
Print a comma-separated list of locations
****************************************************************************
An interval set structure; additionally, it stores user-provided information
at interval boundaries.
The implementation provided here is naive and assumes the number of intervals
to be small, but the interface would allow for a more efficient
implementation if needed.
Note: the structure only stores maximal intervals (that therefore do not
overlap).
bounds are included
non overlapping intervals
Make `S come before `E so that consecutive intervals get merged
together in the fold below
****************************************************************************
Highlight the locations using standout mode.
If [locs] is empty, this function is a no-op.
avoid mixing Format and normal output
Do nothing if the buffer does not contain the whole phrase.
Count number of lines in phrase
If too many lines, give up
Move cursor up that number of lines
Print the input, switching to standout for the location
Make sure standout mode is over
Position cursor back to original location
[get_lines] must return the lines to highlight, given starting and ending
positions.
See [lines_around_from_current_input] below for an instantiation of
[get_lines] that reads from the current input.
Single-line error
Iterate up to [rightmost], which can be larger than the length of
the line because we may point to a location after the end of the
last token on the line, for instance:
{[
token
^
Did you forget ...
]}
For alignment purposes, align using a tab for each tab in the
source code
Multi-line error
end of input
Try to get lines from a lexbuf
Converts a global position to one that is relative to the lexing buffer
Do nothing if the buffer does not contain the input (because it has been
refilled while lexing it)
relative position
end of buffer
Attempt to get lines from the phrase buffer
Get lines from a file
Be a bit defensive, and do not try to open one of the possible
[!input_name] values that we know do not denote valid filenames.
Could not read the input from the phrase buffer. This is likely
a sign that we were given a buggy location.
The input is likely not in the lexbuf anymore
****************************************************************************
Reporting errors and warnings
The entry point
Make sure we keep [num_loc_lines] updated.
The tabulation box is here to give submessage the option
to be aligned with the main message box
Highlight all toplevel locations of the report, instead of displaying
the main location. Do it now instead of in [pp_main_loc], to avoid
messing with Format boxes.
Creates a printer for the current input
****************************************************************************
Reporting errors
****************************************************************************
Reporting warnings: generating a report from a warning number using the
information in [Warnings] + convenience functions.
****************************************************************************
Reporting errors on exceptions | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Lexing
type t = Warnings.loc =
{ loc_start: position; loc_end: position; loc_ghost: bool }
let in_file = Warnings.ghost_loc_in_file
let none = in_file "_none_"
let is_none l = (l = none)
let curr lexbuf = {
loc_start = lexbuf.lex_start_p;
loc_end = lexbuf.lex_curr_p;
loc_ghost = false
}
let init lexbuf fname =
lexbuf.lex_curr_p <- {
pos_fname = fname;
pos_lnum = 1;
pos_bol = 0;
pos_cnum = 0;
}
let symbol_rloc () = {
loc_start = Parsing.symbol_start_pos ();
loc_end = Parsing.symbol_end_pos ();
loc_ghost = false;
}
let symbol_gloc () = {
loc_start = Parsing.symbol_start_pos ();
loc_end = Parsing.symbol_end_pos ();
loc_ghost = true;
}
let rhs_loc n = {
loc_start = Parsing.rhs_start_pos n;
loc_end = Parsing.rhs_end_pos n;
loc_ghost = false;
}
let rhs_interval m n = {
loc_start = Parsing.rhs_start_pos m;
loc_end = Parsing.rhs_end_pos n;
loc_ghost = false;
}
let get_pos_info pos =
(pos.pos_fname, pos.pos_lnum, pos.pos_cnum - pos.pos_bol)
type 'a loc = {
txt : 'a;
loc : t;
}
let mkloc txt loc = { txt ; loc }
let mknoloc txt = mkloc txt none
let input_name = ref "_none_"
let input_lexbuf = ref (None : lexbuf option)
let input_phrase_buffer = ref (None : Buffer.t option)
let status = ref Terminfo.Uninitialised
let setup_terminal () =
if !status = Terminfo.Uninitialised then
status := Terminfo.setup stdout
let num_loc_lines = ref 0
We use [ num_loc_lines ] to determine if the report about to be
printed is the first or a follow - up report of the current
" batch " -- contiguous reports without user input in between , for
example for the current toplevel phrase . We use this to print
a blank line between messages of the same batch .
printed is the first or a follow-up report of the current
"batch" -- contiguous reports without user input in between, for
example for the current toplevel phrase. We use this to print
a blank line between messages of the same batch.
*)
let is_first_message () =
!num_loc_lines = 0
let reset () =
num_loc_lines := 0
let echo_eof () =
print_newline ();
incr num_loc_lines
let separate_new_message ppf =
if not (is_first_message ()) then begin
Format.pp_print_newline ppf ();
incr num_loc_lines
end
let print_updating_num_loc_lines ppf f arg =
let open Format in
let out_functions = pp_get_formatter_out_functions ppf () in
let out_string str start len =
let rec count i c =
if i = start + len then c
else if String.get str i = '\n' then count (succ i) (succ c)
else count (succ i) c in
num_loc_lines := !num_loc_lines + count start 0 ;
out_functions.out_string str start len in
pp_set_formatter_out_functions ppf
{ out_functions with out_string } ;
f ppf arg ;
pp_print_flush ppf ();
pp_set_formatter_out_functions ppf out_functions
let setup_colors () =
Misc.Color.setup !Clflags.color
Printing locations , e.g. ' File " foo.ml " , line 3 , characters 10 - 12 '
let rewrite_absolute_path path =
match Misc.get_build_path_prefix_map () with
| None -> path
| Some map -> Build_path_prefix_map.rewrite map path
let open Filename in
let s =
if not (is_relative s) then s
else (rewrite_absolute_path (concat (Sys.getcwd ()) s))
in
let rec aux s =
let base = basename s in
let dir = dirname s in
if dir = s then dir
else if base = current_dir_name then aux dir
else if base = parent_dir_name then dirname (aux dir)
else concat (aux dir) base
in
aux s
let show_filename file =
if !Clflags.absname then absolute_path file else file
let print_filename ppf file =
Format.pp_print_string ppf (show_filename file)
Best - effort printing of the text describing a location , of the form
' File " foo.ml " , line 3 , characters 10 - 12 ' .
Some of the information ( filename , line number or characters numbers ) in the
location might be invalid ; in which case we do not print it .
'File "foo.ml", line 3, characters 10-12'.
Some of the information (filename, line number or characters numbers) in the
location might be invalid; in which case we do not print it.
*)
let print_loc ppf loc =
setup_colors ();
let file_valid = function
| "_none_" ->
This is a dummy placeholder , but we print it anyway to please editors
that parse locations in error messages ( e.g. Emacs ) .
that parse locations in error messages (e.g. Emacs). *)
true
| "" | "//toplevel//" -> false
| _ -> true
in
let line_valid line = line > 0 in
let chars_valid ~startchar ~endchar = startchar <> -1 && endchar <> -1 in
let file =
if loc.loc_start.pos_fname = "" then !input_name
else loc.loc_start.pos_fname
in
let startline = loc.loc_start.pos_lnum in
let endline = loc.loc_end.pos_lnum in
let startchar = loc.loc_start.pos_cnum - loc.loc_start.pos_bol in
let endchar = loc.loc_end.pos_cnum - loc.loc_end.pos_bol in
let first = ref true in
let capitalize s =
if !first then (first := false; String.capitalize_ascii s)
else s in
let comma () =
if !first then () else Format.fprintf ppf ", " in
Format.fprintf ppf "@{<loc>";
if file_valid file then
Format.fprintf ppf "%s \"%a\"" (capitalize "file") print_filename file;
Print " line 1 " in the case of a dummy line number . This is to please the
existing setup of editors that parse locations in error messages ( e.g.
Emacs ) .
existing setup of editors that parse locations in error messages (e.g.
Emacs). *)
comma ();
let startline = if line_valid startline then startline else 1 in
let endline = if line_valid endline then endline else startline in
begin if startline = endline then
Format.fprintf ppf "%s %i" (capitalize "line") startline
else
Format.fprintf ppf "%s %i-%i" (capitalize "lines") startline endline
end;
if chars_valid ~startchar ~endchar then (
comma ();
Format.fprintf ppf "%s %i-%i" (capitalize "characters") startchar endchar
);
Format.fprintf ppf "@}"
let print_locs ppf locs =
Format.pp_print_list ~pp_sep:(fun ppf () -> Format.fprintf ppf ",@ ")
print_loc ppf locs
module ISet : sig
type 'a bound = 'a * int
type 'a t
val of_intervals : ('a bound * 'a bound) list -> 'a t
val mem : 'a t -> pos:int -> bool
val find_bound_in : 'a t -> range:(int * int) -> 'a bound option
val is_start : 'a t -> pos:int -> 'a option
val is_end : 'a t -> pos:int -> 'a option
val extrema : 'a t -> ('a bound * 'a bound) option
end
=
struct
type 'a bound = 'a * int
type 'a t = ('a bound * 'a bound) list
let of_intervals intervals =
let pos =
List.map (fun ((a, x), (b, y)) ->
if x > y then [] else [((a, x), `S); ((b, y), `E)]
) intervals
|> List.flatten
|> List.sort (fun ((_, x), k) ((_, y), k') ->
let kn = function `S -> 0 | `E -> 1 in
compare (x, kn k) (y, kn k'))
in
let nesting, acc =
List.fold_left (fun (nesting, acc) (a, kind) ->
match kind, nesting with
| `S, `Outside -> `Inside (a, 0), acc
| `S, `Inside (s, n) -> `Inside (s, n+1), acc
| `E, `Outside -> assert false
| `E, `Inside (s, 0) -> `Outside, ((s, a) :: acc)
| `E, `Inside (s, n) -> `Inside (s, n-1), acc
) (`Outside, []) pos in
assert (nesting = `Outside);
List.rev acc
let mem iset ~pos =
List.exists (fun ((_, s), (_, e)) -> s <= pos && pos <= e) iset
let find_bound_in iset ~range:(start, end_) =
List.find_map (fun ((a, x), (b, y)) ->
if start <= x && x <= end_ then Some (a, x)
else if start <= y && y <= end_ then Some (b, y)
else None
) iset
let is_start iset ~pos =
List.find_map (fun ((a, x), _) ->
if pos = x then Some a else None
) iset
let is_end iset ~pos =
List.find_map (fun (_, (b, y)) ->
if pos = y then Some b else None
) iset
let extrema iset =
if iset = [] then None
else Some (fst (List.hd iset), snd (List.hd (List.rev iset)))
end
Toplevel : highlighting and quoting locations
let highlight_terminfo lb ppf locs =
Char 0 is at offset -lb.lex_abs_pos in lb.lex_buffer .
let pos0 = -lb.lex_abs_pos in
if pos0 < 0 then raise Exit;
let lines = ref !num_loc_lines in
for i = pos0 to lb.lex_buffer_len - 1 do
if Bytes.get lb.lex_buffer i = '\n' then incr lines
done;
if !lines >= Terminfo.num_lines stdout - 2 then raise Exit;
flush stdout; Terminfo.backup stdout !lines;
let bol = ref false in
print_string "# ";
for pos = 0 to lb.lex_buffer_len - pos0 - 1 do
if !bol then (print_string " "; bol := false);
if List.exists (fun loc -> pos = loc.loc_start.pos_cnum) locs then
Terminfo.standout stdout true;
if List.exists (fun loc -> pos = loc.loc_end.pos_cnum) locs then
Terminfo.standout stdout false;
let c = Bytes.get lb.lex_buffer (pos + pos0) in
print_char c;
bol := (c = '\n')
done;
Terminfo.standout stdout false;
Terminfo.resume stdout !num_loc_lines;
flush stdout
let highlight_terminfo lb ppf locs =
try highlight_terminfo lb ppf locs
with Exit -> ()
Highlight the location by printing it again .
There are two different styles for highlighting errors in " dumb " mode ,
depending if the error fits on a single line or spans across several lines .
For single - line errors ,
foo the_error bar
gets displayed as follows , where X is the line number :
X | foo the_error bar
^^^^^^^^^
For multi - line errors ,
foo the _
error bar
gets displayed as :
X1 | .... the _
X2 | error ....
An ellipsis hides the middle lines of the multi - line error if it has more
than [ max_lines ] lines .
If [ locs ] is empty then this function is a no - op .
There are two different styles for highlighting errors in "dumb" mode,
depending if the error fits on a single line or spans across several lines.
For single-line errors,
foo the_error bar
gets displayed as follows, where X is the line number:
X | foo the_error bar
^^^^^^^^^
For multi-line errors,
foo the_
error bar
gets displayed as:
X1 | ....the_
X2 | error....
An ellipsis hides the middle lines of the multi-line error if it has more
than [max_lines] lines.
If [locs] is empty then this function is a no-op.
*)
type input_line = {
text : string;
start_pos : int;
}
Takes a list of lines with possibly missing line numbers .
If the line numbers that are present are consistent with the number of lines
between them , then infer the intermediate line numbers .
This is not always the case , typically if lexer line directives are
involved ...
If the line numbers that are present are consistent with the number of lines
between them, then infer the intermediate line numbers.
This is not always the case, typically if lexer line directives are
involved... *)
let infer_line_numbers
(lines: (int option * input_line) list):
(int option * input_line) list
=
let (_, offset, consistent) =
List.fold_left (fun (i, offset, consistent) (lnum, _) ->
match lnum, offset with
| None, _ -> (i+1, offset, consistent)
| Some n, None -> (i+1, Some (n - i), consistent)
| Some n, Some m -> (i+1, offset, consistent && n = m + i)
) (0, None, true) lines
in
match offset, consistent with
| Some m, true ->
List.mapi (fun i (_, line) -> (Some (m + i), line)) lines
| _, _ ->
lines
let highlight_quote ppf
~(get_lines: start_pos:position -> end_pos:position -> input_line list)
?(max_lines = 10)
highlight_tag
locs
=
let iset = ISet.of_intervals @@ List.filter_map (fun loc ->
let s, e = loc.loc_start, loc.loc_end in
if s.pos_cnum = -1 || e.pos_cnum = -1 then None
else Some ((s, s.pos_cnum), (e, e.pos_cnum - 1))
) locs in
match ISet.extrema iset with
| None -> ()
| Some ((leftmost, _), (rightmost, _)) ->
let lines =
get_lines ~start_pos:leftmost ~end_pos:rightmost
|> List.map (fun ({ text; start_pos } as line) ->
let end_pos = start_pos + String.length text - 1 in
let line_nb =
match ISet.find_bound_in iset ~range:(start_pos, end_pos) with
| None -> None
| Some (p, _) -> Some p.pos_lnum
in
(line_nb, line))
|> infer_line_numbers
|> List.map (fun (lnum, { text; start_pos }) ->
(text,
Option.fold ~some:Int.to_string ~none:"" lnum,
start_pos))
in
Format.fprintf ppf "@[<v>";
begin match lines with
| [] | [("", _, _)] -> ()
| [(line, line_nb, line_start_cnum)] ->
Format.fprintf ppf "%s | %s@," line_nb line;
Format.fprintf ppf "%*s " (String.length line_nb) "";
for i = 0 to rightmost.pos_cnum - line_start_cnum - 1 do
let pos = line_start_cnum + i in
if ISet.is_start iset ~pos <> None then
Format.fprintf ppf "@{<%s>" highlight_tag;
if ISet.mem iset ~pos then Format.pp_print_char ppf '^'
else if i < String.length line then begin
if line.[i] = '\t' then Format.pp_print_char ppf '\t'
else Format.pp_print_char ppf ' '
end;
if ISet.is_end iset ~pos <> None then
Format.fprintf ppf "@}"
done;
Format.fprintf ppf "@}@,"
| _ ->
Misc.pp_two_columns ~sep:"|" ~max_lines ppf
@@ List.map (fun (line, line_nb, line_start_cnum) ->
let line = String.mapi (fun i car ->
if ISet.mem iset ~pos:(line_start_cnum + i) then car else '.'
) line in
(line_nb, line)
) lines
end;
Format.fprintf ppf "@]"
let lines_around
~(start_pos: position) ~(end_pos: position)
~(seek: int -> unit)
~(read_char: unit -> char option):
input_line list
=
seek start_pos.pos_bol;
let lines = ref [] in
let bol = ref start_pos.pos_bol in
let cur = ref start_pos.pos_bol in
let b = Buffer.create 80 in
let add_line () =
if !bol < !cur then begin
let text = Buffer.contents b in
Buffer.clear b;
lines := { text; start_pos = !bol } :: !lines;
bol := !cur
end
in
let rec loop () =
if !bol >= end_pos.pos_cnum then ()
else begin
match read_char () with
| None ->
add_line ()
| Some c ->
incr cur;
match c with
| '\r' -> loop ()
| '\n' -> add_line (); loop ()
| _ -> Buffer.add_char b c; loop ()
end
in
loop ();
List.rev !lines
let lines_around_from_lexbuf
~(start_pos: position) ~(end_pos: position)
(lb: lexbuf):
input_line list
=
let rel n = n - lb.lex_abs_pos in
if rel start_pos.pos_bol < 0 then begin
[]
end else begin
let seek n = pos := rel n in
let read_char () =
else
let c = Bytes.get lb.lex_buffer !pos in
incr pos; Some c
in
lines_around ~start_pos ~end_pos ~seek ~read_char
end
let lines_around_from_phrasebuf
~(start_pos: position) ~(end_pos: position)
(pb: Buffer.t):
input_line list
=
let pos = ref 0 in
let seek n = pos := n in
let read_char () =
if !pos >= Buffer.length pb then None
else begin
let c = Buffer.nth pb !pos in
incr pos; Some c
end
in
lines_around ~start_pos ~end_pos ~seek ~read_char
let lines_around_from_file
~(start_pos: position) ~(end_pos: position)
(filename: string):
input_line list
=
try
let cin = open_in_bin filename in
let read_char () =
try Some (input_char cin) with End_of_file -> None
in
let lines =
lines_around ~start_pos ~end_pos ~seek:(seek_in cin) ~read_char
in
close_in cin;
lines
with Sys_error _ -> []
A [ get_lines ] function for [ highlight_quote ] that reads from the current
input .
It first tries to read from [ ! input_lexbuf ] , then if that fails ( because the
lexbuf no longer contains the input we want ) , it reads from [ ! input_name ]
directly
input.
It first tries to read from [!input_lexbuf], then if that fails (because the
lexbuf no longer contains the input we want), it reads from [!input_name]
directly *)
let lines_around_from_current_input ~start_pos ~end_pos =
let file_valid = function
| "//toplevel//" | "_none_" | "" -> false
| _ -> true
in
let from_file () =
if file_valid !input_name then
lines_around_from_file !input_name ~start_pos ~end_pos
else
[]
in
match !input_lexbuf, !input_phrase_buffer, !input_name with
| _, Some pb, "//toplevel//" ->
begin match lines_around_from_phrasebuf pb ~start_pos ~end_pos with
[]
| lines ->
lines
end
| Some lb, _, _ ->
begin match lines_around_from_lexbuf lb ~start_pos ~end_pos with
from_file ()
| lines ->
lines
end
| None, _, _ ->
from_file ()
type msg = (Format.formatter -> unit) loc
let msg ?(loc = none) fmt =
Format.kdprintf (fun txt -> { loc; txt }) fmt
type report_kind =
| Report_error
| Report_warning of string
| Report_warning_as_error of string
| Report_alert of string
| Report_alert_as_error of string
type report = {
kind : report_kind;
main : msg;
sub : msg list;
}
type report_printer = {
pp : report_printer ->
Format.formatter -> report -> unit;
pp_report_kind : report_printer -> report ->
Format.formatter -> report_kind -> unit;
pp_main_loc : report_printer -> report ->
Format.formatter -> t -> unit;
pp_main_txt : report_printer -> report ->
Format.formatter -> (Format.formatter -> unit) -> unit;
pp_submsgs : report_printer -> report ->
Format.formatter -> msg list -> unit;
pp_submsg : report_printer -> report ->
Format.formatter -> msg -> unit;
pp_submsg_loc : report_printer -> report ->
Format.formatter -> t -> unit;
pp_submsg_txt : report_printer -> report ->
Format.formatter -> (Format.formatter -> unit) -> unit;
}
let is_dummy_loc loc =
: this should be just [ loc.loc_ghost ] and the function should be
inlined below . However , currently , the compiler emits in some places ghost
locations with valid ranges that should still be printed . These locations
should be made non - ghost -- in the meantime we just check if the ranges are
valid .
inlined below. However, currently, the compiler emits in some places ghost
locations with valid ranges that should still be printed. These locations
should be made non-ghost -- in the meantime we just check if the ranges are
valid. *)
loc.loc_start.pos_cnum = -1 || loc.loc_end.pos_cnum = -1
It only makes sense to highlight ( i.e. quote or underline the corresponding
source code ) locations that originate from the current input .
As of now , this should only happen in the following cases :
- if dummy locs or ghost locs leak out of the compiler or a buggy ppx ;
- more generally , if some code uses the compiler - libs API and feeds it
locations that do not match the current values of [ ! Location.input_name ] ,
[ ! Location.input_lexbuf ] ;
- when calling the compiler on a .ml file that contains lexer line directives
indicating an other file . This should happen relatively rarely in practice --
in particular this is not what happens when using -pp or -ppx or a ppx
driver .
source code) locations that originate from the current input.
As of now, this should only happen in the following cases:
- if dummy locs or ghost locs leak out of the compiler or a buggy ppx;
- more generally, if some code uses the compiler-libs API and feeds it
locations that do not match the current values of [!Location.input_name],
[!Location.input_lexbuf];
- when calling the compiler on a .ml file that contains lexer line directives
indicating an other file. This should happen relatively rarely in practice --
in particular this is not what happens when using -pp or -ppx or a ppx
driver.
*)
let is_quotable_loc loc =
not (is_dummy_loc loc)
&& loc.loc_start.pos_fname = !input_name
&& loc.loc_end.pos_fname = !input_name
let error_style () =
match !Clflags.error_style with
| Some setting -> setting
| None -> Misc.Error_style.default_setting
let batch_mode_printer : report_printer =
let pp_loc _self report ppf loc =
let tag = match report.kind with
| Report_warning_as_error _
| Report_alert_as_error _
| Report_error -> "error"
| Report_warning _
| Report_alert _ -> "warning"
in
let highlight ppf loc =
match error_style () with
| Misc.Error_style.Contextual ->
if is_quotable_loc loc then
highlight_quote ppf
~get_lines:lines_around_from_current_input
tag [loc]
| Misc.Error_style.Short ->
()
in
Format.fprintf ppf "@[<v>%a:@ %a@]" print_loc loc highlight loc
in
let pp_txt ppf txt = Format.fprintf ppf "@[%t@]" txt in
let pp self ppf report =
setup_colors ();
separate_new_message ppf;
print_updating_num_loc_lines ppf (fun ppf () ->
Format.fprintf ppf "@[<v>%a%a%a: %a%a%a%a@]@."
Format.pp_open_tbox ()
(self.pp_main_loc self report) report.main.loc
(self.pp_report_kind self report) report.kind
Format.pp_set_tab ()
(self.pp_main_txt self report) report.main.txt
(self.pp_submsgs self report) report.sub
Format.pp_close_tbox ()
) ()
in
let pp_report_kind _self _ ppf = function
| Report_error -> Format.fprintf ppf "@{<error>Error@}"
| Report_warning w -> Format.fprintf ppf "@{<warning>Warning@} %s" w
| Report_warning_as_error w ->
Format.fprintf ppf "@{<error>Error@} (warning %s)" w
| Report_alert w -> Format.fprintf ppf "@{<warning>Alert@} %s" w
| Report_alert_as_error w ->
Format.fprintf ppf "@{<error>Error@} (alert %s)" w
in
let pp_main_loc self report ppf loc =
pp_loc self report ppf loc
in
let pp_main_txt _self _ ppf txt =
pp_txt ppf txt
in
let pp_submsgs self report ppf msgs =
List.iter (fun msg ->
Format.fprintf ppf "@,%a" (self.pp_submsg self report) msg
) msgs
in
let pp_submsg self report ppf { loc; txt } =
Format.fprintf ppf "@[%a %a@]"
(self.pp_submsg_loc self report) loc
(self.pp_submsg_txt self report) txt
in
let pp_submsg_loc self report ppf loc =
if not loc.loc_ghost then
pp_loc self report ppf loc
in
let pp_submsg_txt _self _ ppf loc =
pp_txt ppf loc
in
{ pp; pp_report_kind; pp_main_loc; pp_main_txt;
pp_submsgs; pp_submsg; pp_submsg_loc; pp_submsg_txt }
let terminfo_toplevel_printer (lb: lexbuf): report_printer =
let pp self ppf err =
setup_colors ();
let sub_locs = List.map (fun { loc; _ } -> loc) err.sub in
let all_locs = err.main.loc :: sub_locs in
let locs_highlighted = List.filter is_quotable_loc all_locs in
highlight_terminfo lb ppf locs_highlighted;
batch_mode_printer.pp self ppf err
in
let pp_main_loc _ _ _ _ = () in
let pp_submsg_loc _ _ ppf loc =
if not loc.loc_ghost then
Format.fprintf ppf "%a:@ " print_loc loc in
{ batch_mode_printer with pp; pp_main_loc; pp_submsg_loc }
let best_toplevel_printer () =
setup_terminal ();
match !status, !input_lexbuf with
| Terminfo.Good_term, Some lb ->
terminfo_toplevel_printer lb
| _, _ ->
batch_mode_printer
let default_report_printer () : report_printer =
if !input_name = "//toplevel//" then
best_toplevel_printer ()
else
batch_mode_printer
let report_printer = ref default_report_printer
let print_report ppf report =
let printer = !report_printer () in
printer.pp printer ppf report
type error = report
let report_error ppf err =
print_report ppf err
let mkerror loc sub txt =
{ kind = Report_error; main = { loc; txt }; sub }
let errorf ?(loc = none) ?(sub = []) =
Format.kdprintf (mkerror loc sub)
let error ?(loc = none) ?(sub = []) msg_str =
mkerror loc sub (fun ppf -> Format.pp_print_string ppf msg_str)
let error_of_printer ?(loc = none) ?(sub = []) pp x =
mkerror loc sub (fun ppf -> pp ppf x)
let error_of_printer_file print x =
error_of_printer ~loc:(in_file !input_name) print x
let default_warning_alert_reporter report mk (loc: t) w : report option =
match report w with
| `Inactive -> None
| `Active { Warnings.id; message; is_error; sub_locs } ->
let msg_of_str str = fun ppf -> Format.pp_print_string ppf str in
let kind = mk is_error id in
let main = { loc; txt = msg_of_str message } in
let sub = List.map (fun (loc, sub_message) ->
{ loc; txt = msg_of_str sub_message }
) sub_locs in
Some { kind; main; sub }
let default_warning_reporter =
default_warning_alert_reporter
Warnings.report
(fun is_error id ->
if is_error then Report_warning_as_error id
else Report_warning id
)
let warning_reporter = ref default_warning_reporter
let report_warning loc w = !warning_reporter loc w
let formatter_for_warnings = ref Format.err_formatter
let print_warning loc ppf w =
match report_warning loc w with
| None -> ()
| Some report -> print_report ppf report
let prerr_warning loc w = print_warning loc !formatter_for_warnings w
let default_alert_reporter =
default_warning_alert_reporter
Warnings.report_alert
(fun is_error id ->
if is_error then Report_alert_as_error id
else Report_alert id
)
let alert_reporter = ref default_alert_reporter
let report_alert loc w = !alert_reporter loc w
let print_alert loc ppf w =
match report_alert loc w with
| None -> ()
| Some report -> print_report ppf report
let prerr_alert loc w = print_alert loc !formatter_for_warnings w
let alert ?(def = none) ?(use = none) ~kind loc message =
prerr_alert loc {Warnings.kind; message; def; use}
let deprecated ?def ?use loc message =
alert ?def ?use ~kind:"deprecated" loc message
let auto_include_alert lib =
let message = Printf.sprintf "\
OCaml's lib directory layout changed in 5.0. The %s subdirectory has been \
automatically added to the search path, but you should add -I +%s to the \
command-line to silence this alert (e.g. by adding %s to the list of \
libraries in your dune file, or adding use_%s to your _tags file for \
ocamlbuild, or using -package %s for ocamlfind)." lib lib lib lib lib in
let alert =
{Warnings.kind="ocaml_deprecated_auto_include"; use=none; def=none;
message = Format.asprintf "@[@\n%a@]" Format.pp_print_text message}
in
prerr_alert none alert
let deprecated_script_alert program =
let message = Printf.sprintf "\
Running %s where the first argument is an implicit basename with no \
extension (e.g. %s script-file) is deprecated. Either rename the script \
(%s script-file.ml) or qualify the basename (%s ./script-file)"
program program program program
in
let alert =
{Warnings.kind="ocaml_deprecated_cli"; use=none; def=none;
message = Format.asprintf "@[@\n%a@]" Format.pp_print_text message}
in
prerr_alert none alert
let error_of_exn : (exn -> error option) list ref = ref []
let register_error_of_exn f = error_of_exn := f :: !error_of_exn
exception Already_displayed_error = Warnings.Errors
let error_of_exn exn =
match exn with
| Already_displayed_error -> Some `Already_displayed
| _ ->
let rec loop = function
| [] -> None
| f :: rest ->
match f exn with
| Some error -> Some (`Ok error)
| None -> loop rest
in
loop !error_of_exn
let () =
register_error_of_exn
(function
| Sys_error msg ->
Some (errorf ~loc:(in_file !input_name) "I/O error: %s" msg)
| _ -> None
)
external reraise : exn -> 'a = "%reraise"
let report_exception ppf exn =
let rec loop n exn =
match error_of_exn exn with
| None -> reraise exn
| Some `Already_displayed -> ()
| Some (`Ok err) -> report_error ppf err
| exception exn when n > 0 -> loop (n-1) exn
in
loop 5 exn
exception Error of error
let () =
register_error_of_exn
(function
| Error e -> Some e
| _ -> None
)
let raise_errorf ?(loc = none) ?(sub = []) =
Format.kdprintf (fun txt -> raise (Error (mkerror loc sub txt)))
|
d6530b329e5bf272a7b613675c29006c68a4039dc9ef03edf809a3fd26aec04b | hasktorch/hasktorch | AlexNet.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
module AlexNet where
import GHC.Generics
import Torch.Functional
import qualified Torch.Functional.Internal as I
import Torch.NN
import Torch.Tensor
data AlexNetBBSpec = AlexNetBBSpec
{ conv1 :: Conv2dSpec,
conv2 :: Conv2dSpec,
conv3 :: Conv2dSpec,
conv4 :: Conv2dSpec,
conv5 :: Conv2dSpec,
fc1 :: LinearSpec,
fc2 :: LinearSpec
}
deriving (Show, Eq)
alexnetBackBoneSpec =
AlexNetBBSpec
(Conv2dSpec 3 64 11 11)
(Conv2dSpec 64 192 5 5)
(Conv2dSpec 192 384 3 3)
(Conv2dSpec 384 256 3 3)
(Conv2dSpec 256 256 3 3)
(LinearSpec (6 * 6 * 256) 4096)
(LinearSpec 4096 4096)
data AlexNetBB = AlexNetBB
{ c1 :: Conv2d,
c2 :: Conv2d,
c3 :: Conv2d,
c4 :: Conv2d,
c5 :: Conv2d,
l1 :: Linear,
l2 :: Linear
}
deriving (Generic, Show)
instance Parameterized AlexNetBB
instance Randomizable AlexNetBBSpec AlexNetBB where
sample AlexNetBBSpec {..} =
AlexNetBB
<$> sample (conv1)
<*> sample (conv2)
<*> sample (conv3)
<*> sample (conv4)
<*> sample (conv5)
<*> sample (fc1)
<*> sample (fc2)
alexnetBBForward :: AlexNetBB -> Tensor -> Tensor
alexnetBBForward AlexNetBB {..} input =
linear l2
. relu
. linear l1
. flatten (Dim 1) (Dim (-1))
. adaptiveAvgPool2d (6, 6)
. maxPool2d (3, 3) (2, 2) (0, 0) (1, 1) Floor
. relu
. conv2dForward c5 (1, 1) (1, 1)
. relu
. conv2dForward c4 (1, 1) (1, 1)
. relu
. conv2dForward c3 (1, 1) (1, 1)
. maxPool2d (3, 3) (2, 2) (0, 0) (1, 1) Floor
. relu
. conv2dForward c2 (1, 1) (2, 2)
. maxPool2d (3, 3) (2, 2) (0, 0) (1, 1) Floor
. relu
. conv2dForward c1 (4, 4) (2, 2)
$ input
| null | https://raw.githubusercontent.com/hasktorch/hasktorch/8fa4d2a6cdb7f144484f7d24d8d4924fb0faecd2/examples/alexNet/AlexNet.hs | haskell | # LANGUAGE DeriveGeneric #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
module AlexNet where
import GHC.Generics
import Torch.Functional
import qualified Torch.Functional.Internal as I
import Torch.NN
import Torch.Tensor
data AlexNetBBSpec = AlexNetBBSpec
{ conv1 :: Conv2dSpec,
conv2 :: Conv2dSpec,
conv3 :: Conv2dSpec,
conv4 :: Conv2dSpec,
conv5 :: Conv2dSpec,
fc1 :: LinearSpec,
fc2 :: LinearSpec
}
deriving (Show, Eq)
alexnetBackBoneSpec =
AlexNetBBSpec
(Conv2dSpec 3 64 11 11)
(Conv2dSpec 64 192 5 5)
(Conv2dSpec 192 384 3 3)
(Conv2dSpec 384 256 3 3)
(Conv2dSpec 256 256 3 3)
(LinearSpec (6 * 6 * 256) 4096)
(LinearSpec 4096 4096)
data AlexNetBB = AlexNetBB
{ c1 :: Conv2d,
c2 :: Conv2d,
c3 :: Conv2d,
c4 :: Conv2d,
c5 :: Conv2d,
l1 :: Linear,
l2 :: Linear
}
deriving (Generic, Show)
instance Parameterized AlexNetBB
instance Randomizable AlexNetBBSpec AlexNetBB where
sample AlexNetBBSpec {..} =
AlexNetBB
<$> sample (conv1)
<*> sample (conv2)
<*> sample (conv3)
<*> sample (conv4)
<*> sample (conv5)
<*> sample (fc1)
<*> sample (fc2)
alexnetBBForward :: AlexNetBB -> Tensor -> Tensor
alexnetBBForward AlexNetBB {..} input =
linear l2
. relu
. linear l1
. flatten (Dim 1) (Dim (-1))
. adaptiveAvgPool2d (6, 6)
. maxPool2d (3, 3) (2, 2) (0, 0) (1, 1) Floor
. relu
. conv2dForward c5 (1, 1) (1, 1)
. relu
. conv2dForward c4 (1, 1) (1, 1)
. relu
. conv2dForward c3 (1, 1) (1, 1)
. maxPool2d (3, 3) (2, 2) (0, 0) (1, 1) Floor
. relu
. conv2dForward c2 (1, 1) (2, 2)
. maxPool2d (3, 3) (2, 2) (0, 0) (1, 1) Floor
. relu
. conv2dForward c1 (4, 4) (2, 2)
$ input
| |
4c12495cced95e112e46c9363f86ab064c74fa499831a9e4468f14573a268f4d | tolysz/prepare-ghcjs | PathsModule.hs | -----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Build.Macros
Copyright : 2003 - 2005 ,
2006 ,
2007 - 2008
--
-- Maintainer :
-- Portability : portable
--
-- Generating the Paths_pkgname module.
--
This is a module that Cabal generates for the benefit of packages . It
-- enables them to find their version number and find any installed data files
-- at runtime. This code should probably be split off into another module.
--
module Distribution.Simple.Build.PathsModule (
generate, pkgPathEnvVar
) where
import Distribution.System
import Distribution.Simple.Compiler
import Distribution.Package
import Distribution.PackageDescription
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.BuildPaths
import Distribution.Simple.Utils
import Distribution.Text
import Distribution.Version
import System.FilePath
( pathSeparator )
import Data.Maybe
( fromJust, isNothing )
-- ------------------------------------------------------------
-- * Building Paths_<pkg>.hs
-- ------------------------------------------------------------
generate :: PackageDescription -> LocalBuildInfo -> String
generate pkg_descr lbi =
let pragmas = cpp_pragma ++ ffi_pragmas ++ warning_pragmas
cpp_pragma | supports_cpp = "{-# LANGUAGE CPP #-}\n"
| otherwise = ""
ffi_pragmas
| absolute = ""
| supports_language_pragma =
"{-# LANGUAGE ForeignFunctionInterface #-}\n"
| otherwise =
"{-# OPTIONS_GHC -fffi #-}\n"++
"{-# OPTIONS_JHC -fffi #-}\n"
warning_pragmas =
"{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}\n"++
"{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}\n"
foreign_imports
| absolute = ""
| otherwise =
"import Foreign\n"++
"import Foreign.C\n"
reloc_imports
| reloc =
"import System.Environment (getExecutablePath)\n"
| otherwise = ""
header =
pragmas++
"module " ++ display paths_modulename ++ " (\n"++
" version,\n"++
" getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir,\n"++
" getDataFileName, getSysconfDir\n"++
" ) where\n"++
"\n"++
foreign_imports++
"import qualified Control.Exception as Exception\n"++
"import Data.Version (Version(..))\n"++
"import System.Environment (getEnv)\n"++
reloc_imports ++
"import Prelude\n"++
"\n"++
(if supports_cpp
then
("#if defined(VERSION_base)\n"++
"\n"++
"#if MIN_VERSION_base(4,0,0)\n"++
"catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a\n"++
"#else\n"++
"catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a\n"++
"#endif\n"++
"\n"++
"#else\n"++
"catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a\n"++
"#endif\n")
else
"catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a\n")++
"catchIO = Exception.catch\n" ++
"\n"++
"version :: Version"++
"\nversion = Version " ++ show branch ++ " " ++ show tags
where Version branch tags = packageVersion pkg_descr
body
| reloc =
"\n\nbindirrel :: FilePath\n" ++
"bindirrel = " ++ show flat_bindirreloc ++
"\n"++
"\ngetBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath\n"++
"getBinDir = "++mkGetEnvOrReloc "bindir" flat_bindirreloc++"\n"++
"getLibDir = "++mkGetEnvOrReloc "libdir" flat_libdirreloc++"\n"++
"getDynLibDir = "++mkGetEnvOrReloc "dynlibdir" flat_dynlibdirreloc++"\n"++
"getDataDir = "++mkGetEnvOrReloc "datadir" flat_datadirreloc++"\n"++
"getLibexecDir = "++mkGetEnvOrReloc "libexecdir" flat_libexecdirreloc++"\n"++
"getSysconfDir = "++mkGetEnvOrReloc "sysconfdir" flat_sysconfdirreloc++"\n"++
"\n"++
"getDataFileName :: FilePath -> IO FilePath\n"++
"getDataFileName name = do\n"++
" dir <- getDataDir\n"++
" return (dir `joinFileName` name)\n"++
"\n"++
get_prefix_reloc_stuff++
"\n"++
filename_stuff
| absolute =
"\nbindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath\n"++
"\nbindir = " ++ show flat_bindir ++
"\nlibdir = " ++ show flat_libdir ++
"\ndynlibdir = " ++ show flat_dynlibdir ++
"\ndatadir = " ++ show flat_datadir ++
"\nlibexecdir = " ++ show flat_libexecdir ++
"\nsysconfdir = " ++ show flat_sysconfdir ++
"\n"++
"\ngetBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath\n"++
"getBinDir = "++mkGetEnvOr "bindir" "return bindir"++"\n"++
"getLibDir = "++mkGetEnvOr "libdir" "return libdir"++"\n"++
"getDynLibDir = "++mkGetEnvOr "dynlibdir" "return dynlibdir"++"\n"++
"getDataDir = "++mkGetEnvOr "datadir" "return datadir"++"\n"++
"getLibexecDir = "++mkGetEnvOr "libexecdir" "return libexecdir"++"\n"++
"getSysconfDir = "++mkGetEnvOr "sysconfdir" "return sysconfdir"++"\n"++
"\n"++
"getDataFileName :: FilePath -> IO FilePath\n"++
"getDataFileName name = do\n"++
" dir <- getDataDir\n"++
" return (dir ++ "++path_sep++" ++ name)\n"
| otherwise =
"\nprefix, bindirrel :: FilePath" ++
"\nprefix = " ++ show flat_prefix ++
"\nbindirrel = " ++ show (fromJust flat_bindirrel) ++
"\n\n"++
"getBinDir :: IO FilePath\n"++
"getBinDir = getPrefixDirRel bindirrel\n\n"++
"getLibDir :: IO FilePath\n"++
"getLibDir = "++mkGetDir flat_libdir flat_libdirrel++"\n\n"++
"getDynLibDir :: IO FilePath\n"++
"getDynLibDir = "++mkGetDir flat_dynlibdir flat_dynlibdirrel++"\n\n"++
"getDataDir :: IO FilePath\n"++
"getDataDir = "++ mkGetEnvOr "datadir"
(mkGetDir flat_datadir flat_datadirrel)++"\n\n"++
"getLibexecDir :: IO FilePath\n"++
"getLibexecDir = "++mkGetDir flat_libexecdir flat_libexecdirrel++"\n\n"++
"getSysconfDir :: IO FilePath\n"++
"getSysconfDir = "++mkGetDir flat_sysconfdir flat_sysconfdirrel++"\n\n"++
"getDataFileName :: FilePath -> IO FilePath\n"++
"getDataFileName name = do\n"++
" dir <- getDataDir\n"++
" return (dir `joinFileName` name)\n"++
"\n"++
get_prefix_stuff++
"\n"++
filename_stuff
in header++body
where
InstallDirs {
prefix = flat_prefix,
bindir = flat_bindir,
libdir = flat_libdir,
dynlibdir = flat_dynlibdir,
datadir = flat_datadir,
libexecdir = flat_libexecdir,
sysconfdir = flat_sysconfdir
} = absoluteInstallDirs pkg_descr lbi NoCopyDest
InstallDirs {
bindir = flat_bindirrel,
libdir = flat_libdirrel,
dynlibdir = flat_dynlibdirrel,
datadir = flat_datadirrel,
libexecdir = flat_libexecdirrel,
sysconfdir = flat_sysconfdirrel
} = prefixRelativeInstallDirs (packageId pkg_descr) lbi
flat_bindirreloc = shortRelativePath flat_prefix flat_bindir
flat_libdirreloc = shortRelativePath flat_prefix flat_libdir
flat_dynlibdirreloc = shortRelativePath flat_prefix flat_dynlibdir
flat_datadirreloc = shortRelativePath flat_prefix flat_datadir
flat_libexecdirreloc = shortRelativePath flat_prefix flat_libexecdir
flat_sysconfdirreloc = shortRelativePath flat_prefix flat_sysconfdir
mkGetDir _ (Just dirrel) = "getPrefixDirRel " ++ show dirrel
mkGetDir dir Nothing = "return " ++ show dir
mkGetEnvOrReloc var dirrel = "catchIO (getEnv \""++var'++"\")" ++
" (\\_ -> getPrefixDirReloc \"" ++ dirrel ++
"\")"
where var' = pkgPathEnvVar pkg_descr var
mkGetEnvOr var expr = "catchIO (getEnv \""++var'++"\")"++
" (\\_ -> "++expr++")"
where var' = pkgPathEnvVar pkg_descr var
-- In several cases we cannot make relocatable installations
absolute =
hasLibs pkg_descr -- we can only make progs relocatable
if is an absolute path
|| not (supportsRelocatableProgs (compilerFlavor (compiler lbi)))
reloc = relocatable lbi
supportsRelocatableProgs GHC = case buildOS of
Windows -> True
_ -> False
supportsRelocatableProgs GHCJS = case buildOS of
Windows -> True
_ -> False
supportsRelocatableProgs _ = False
paths_modulename = autogenModuleName pkg_descr
get_prefix_stuff = get_prefix_win32 buildArch
path_sep = show [pathSeparator]
supports_cpp = compilerFlavor (compiler lbi) == GHC
supports_language_pragma =
(compilerFlavor (compiler lbi) == GHC &&
(compilerVersion (compiler lbi)
`withinRange` orLaterVersion (Version [6,6,1] []))) ||
compilerFlavor (compiler lbi) == GHCJS
-- | Generates the name of the environment variable controlling the path
-- component of interest.
pkgPathEnvVar :: PackageDescription
^ path component ; one of \"bindir\ " , \"libdir\ " ,
\"datadir\ " , \"libexecdir\ " , or \"sysconfdir\ "
-> String -- ^ environment variable name
pkgPathEnvVar pkg_descr var =
showPkgName (packageName pkg_descr) ++ "_" ++ var
where
showPkgName = map fixchar . display
fixchar '-' = '_'
fixchar c = c
get_prefix_reloc_stuff :: String
get_prefix_reloc_stuff =
"getPrefixDirReloc :: FilePath -> IO FilePath\n"++
"getPrefixDirReloc dirRel = do\n"++
" exePath <- getExecutablePath\n"++
" let (bindir,_) = splitFileName exePath\n"++
" return ((bindir `minusFileName` bindirrel) `joinFileName` dirRel)\n"
get_prefix_win32 :: Arch -> String
get_prefix_win32 arch =
"getPrefixDirRel :: FilePath -> IO FilePath\n"++
"getPrefixDirRel dirRel = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.\n"++
" where\n"++
" try_size size = allocaArray (fromIntegral size) $ \\buf -> do\n"++
" ret <- c_GetModuleFileName nullPtr buf size\n"++
" case ret of\n"++
" 0 -> return (prefix `joinFileName` dirRel)\n"++
" _ | ret < size -> do\n"++
" exePath <- peekCWString buf\n"++
" let (bindir,_) = splitFileName exePath\n"++
" return ((bindir `minusFileName` bindirrel) `joinFileName` dirRel)\n"++
" | otherwise -> try_size (size * 2)\n"++
"\n"++
"foreign import " ++ cconv ++ " unsafe \"windows.h GetModuleFileNameW\"\n"++
" c_GetModuleFileName :: Ptr () -> CWString -> Int32 -> IO Int32\n"
where cconv = case arch of
I386 -> "stdcall"
X86_64 -> "ccall"
_ -> error "win32 supported only with I386, X86_64"
filename_stuff :: String
filename_stuff =
"minusFileName :: FilePath -> String -> FilePath\n"++
"minusFileName dir \"\" = dir\n"++
"minusFileName dir \".\" = dir\n"++
"minusFileName dir suffix =\n"++
" minusFileName (fst (splitFileName dir)) (fst (splitFileName suffix))\n"++
"\n"++
"joinFileName :: String -> String -> FilePath\n"++
"joinFileName \"\" fname = fname\n"++
"joinFileName \".\" fname = fname\n"++
"joinFileName dir \"\" = dir\n"++
"joinFileName dir fname\n"++
" | isPathSeparator (last dir) = dir++fname\n"++
" | otherwise = dir++pathSeparator:fname\n"++
"\n"++
"splitFileName :: FilePath -> (String, String)\n"++
"splitFileName p = (reverse (path2++drive), reverse fname)\n"++
" where\n"++
" (path,drive) = case p of\n"++
" (c:':':p') -> (reverse p',[':',c])\n"++
" _ -> (reverse p ,\"\")\n"++
" (fname,path1) = break isPathSeparator path\n"++
" path2 = case path1 of\n"++
" [] -> \".\"\n"++
" [_] -> path1 -- don't remove the trailing slash if \n"++
" -- there is only one character\n"++
" (c:path') | isPathSeparator c -> path'\n"++
" _ -> path1\n"++
"\n"++
"pathSeparator :: Char\n"++
(case buildOS of
Windows -> "pathSeparator = '\\\\'\n"
_ -> "pathSeparator = '/'\n") ++
"\n"++
"isPathSeparator :: Char -> Bool\n"++
(case buildOS of
Windows -> "isPathSeparator c = c == '/' || c == '\\\\'\n"
_ -> "isPathSeparator c = c == '/'\n")
| null | https://raw.githubusercontent.com/tolysz/prepare-ghcjs/8499e14e27854a366e98f89fab0af355056cf055/spec-lts/cabal/Cabal/Distribution/Simple/Build/PathsModule.hs | haskell | ---------------------------------------------------------------------------
|
Module : Distribution.Simple.Build.Macros
Maintainer :
Portability : portable
Generating the Paths_pkgname module.
enables them to find their version number and find any installed data files
at runtime. This code should probably be split off into another module.
------------------------------------------------------------
* Building Paths_<pkg>.hs
------------------------------------------------------------
In several cases we cannot make relocatable installations
we can only make progs relocatable
| Generates the name of the environment variable controlling the path
component of interest.
^ environment variable name | Copyright : 2003 - 2005 ,
2006 ,
2007 - 2008
This is a module that Cabal generates for the benefit of packages . It
module Distribution.Simple.Build.PathsModule (
generate, pkgPathEnvVar
) where
import Distribution.System
import Distribution.Simple.Compiler
import Distribution.Package
import Distribution.PackageDescription
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.BuildPaths
import Distribution.Simple.Utils
import Distribution.Text
import Distribution.Version
import System.FilePath
( pathSeparator )
import Data.Maybe
( fromJust, isNothing )
generate :: PackageDescription -> LocalBuildInfo -> String
generate pkg_descr lbi =
let pragmas = cpp_pragma ++ ffi_pragmas ++ warning_pragmas
cpp_pragma | supports_cpp = "{-# LANGUAGE CPP #-}\n"
| otherwise = ""
ffi_pragmas
| absolute = ""
| supports_language_pragma =
"{-# LANGUAGE ForeignFunctionInterface #-}\n"
| otherwise =
"{-# OPTIONS_GHC -fffi #-}\n"++
"{-# OPTIONS_JHC -fffi #-}\n"
warning_pragmas =
"{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}\n"++
"{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}\n"
foreign_imports
| absolute = ""
| otherwise =
"import Foreign\n"++
"import Foreign.C\n"
reloc_imports
| reloc =
"import System.Environment (getExecutablePath)\n"
| otherwise = ""
header =
pragmas++
"module " ++ display paths_modulename ++ " (\n"++
" version,\n"++
" getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir,\n"++
" getDataFileName, getSysconfDir\n"++
" ) where\n"++
"\n"++
foreign_imports++
"import qualified Control.Exception as Exception\n"++
"import Data.Version (Version(..))\n"++
"import System.Environment (getEnv)\n"++
reloc_imports ++
"import Prelude\n"++
"\n"++
(if supports_cpp
then
("#if defined(VERSION_base)\n"++
"\n"++
"#if MIN_VERSION_base(4,0,0)\n"++
"catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a\n"++
"#else\n"++
"catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a\n"++
"#endif\n"++
"\n"++
"#else\n"++
"catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a\n"++
"#endif\n")
else
"catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a\n")++
"catchIO = Exception.catch\n" ++
"\n"++
"version :: Version"++
"\nversion = Version " ++ show branch ++ " " ++ show tags
where Version branch tags = packageVersion pkg_descr
body
| reloc =
"\n\nbindirrel :: FilePath\n" ++
"bindirrel = " ++ show flat_bindirreloc ++
"\n"++
"\ngetBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath\n"++
"getBinDir = "++mkGetEnvOrReloc "bindir" flat_bindirreloc++"\n"++
"getLibDir = "++mkGetEnvOrReloc "libdir" flat_libdirreloc++"\n"++
"getDynLibDir = "++mkGetEnvOrReloc "dynlibdir" flat_dynlibdirreloc++"\n"++
"getDataDir = "++mkGetEnvOrReloc "datadir" flat_datadirreloc++"\n"++
"getLibexecDir = "++mkGetEnvOrReloc "libexecdir" flat_libexecdirreloc++"\n"++
"getSysconfDir = "++mkGetEnvOrReloc "sysconfdir" flat_sysconfdirreloc++"\n"++
"\n"++
"getDataFileName :: FilePath -> IO FilePath\n"++
"getDataFileName name = do\n"++
" dir <- getDataDir\n"++
" return (dir `joinFileName` name)\n"++
"\n"++
get_prefix_reloc_stuff++
"\n"++
filename_stuff
| absolute =
"\nbindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath\n"++
"\nbindir = " ++ show flat_bindir ++
"\nlibdir = " ++ show flat_libdir ++
"\ndynlibdir = " ++ show flat_dynlibdir ++
"\ndatadir = " ++ show flat_datadir ++
"\nlibexecdir = " ++ show flat_libexecdir ++
"\nsysconfdir = " ++ show flat_sysconfdir ++
"\n"++
"\ngetBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath\n"++
"getBinDir = "++mkGetEnvOr "bindir" "return bindir"++"\n"++
"getLibDir = "++mkGetEnvOr "libdir" "return libdir"++"\n"++
"getDynLibDir = "++mkGetEnvOr "dynlibdir" "return dynlibdir"++"\n"++
"getDataDir = "++mkGetEnvOr "datadir" "return datadir"++"\n"++
"getLibexecDir = "++mkGetEnvOr "libexecdir" "return libexecdir"++"\n"++
"getSysconfDir = "++mkGetEnvOr "sysconfdir" "return sysconfdir"++"\n"++
"\n"++
"getDataFileName :: FilePath -> IO FilePath\n"++
"getDataFileName name = do\n"++
" dir <- getDataDir\n"++
" return (dir ++ "++path_sep++" ++ name)\n"
| otherwise =
"\nprefix, bindirrel :: FilePath" ++
"\nprefix = " ++ show flat_prefix ++
"\nbindirrel = " ++ show (fromJust flat_bindirrel) ++
"\n\n"++
"getBinDir :: IO FilePath\n"++
"getBinDir = getPrefixDirRel bindirrel\n\n"++
"getLibDir :: IO FilePath\n"++
"getLibDir = "++mkGetDir flat_libdir flat_libdirrel++"\n\n"++
"getDynLibDir :: IO FilePath\n"++
"getDynLibDir = "++mkGetDir flat_dynlibdir flat_dynlibdirrel++"\n\n"++
"getDataDir :: IO FilePath\n"++
"getDataDir = "++ mkGetEnvOr "datadir"
(mkGetDir flat_datadir flat_datadirrel)++"\n\n"++
"getLibexecDir :: IO FilePath\n"++
"getLibexecDir = "++mkGetDir flat_libexecdir flat_libexecdirrel++"\n\n"++
"getSysconfDir :: IO FilePath\n"++
"getSysconfDir = "++mkGetDir flat_sysconfdir flat_sysconfdirrel++"\n\n"++
"getDataFileName :: FilePath -> IO FilePath\n"++
"getDataFileName name = do\n"++
" dir <- getDataDir\n"++
" return (dir `joinFileName` name)\n"++
"\n"++
get_prefix_stuff++
"\n"++
filename_stuff
in header++body
where
InstallDirs {
prefix = flat_prefix,
bindir = flat_bindir,
libdir = flat_libdir,
dynlibdir = flat_dynlibdir,
datadir = flat_datadir,
libexecdir = flat_libexecdir,
sysconfdir = flat_sysconfdir
} = absoluteInstallDirs pkg_descr lbi NoCopyDest
InstallDirs {
bindir = flat_bindirrel,
libdir = flat_libdirrel,
dynlibdir = flat_dynlibdirrel,
datadir = flat_datadirrel,
libexecdir = flat_libexecdirrel,
sysconfdir = flat_sysconfdirrel
} = prefixRelativeInstallDirs (packageId pkg_descr) lbi
flat_bindirreloc = shortRelativePath flat_prefix flat_bindir
flat_libdirreloc = shortRelativePath flat_prefix flat_libdir
flat_dynlibdirreloc = shortRelativePath flat_prefix flat_dynlibdir
flat_datadirreloc = shortRelativePath flat_prefix flat_datadir
flat_libexecdirreloc = shortRelativePath flat_prefix flat_libexecdir
flat_sysconfdirreloc = shortRelativePath flat_prefix flat_sysconfdir
mkGetDir _ (Just dirrel) = "getPrefixDirRel " ++ show dirrel
mkGetDir dir Nothing = "return " ++ show dir
mkGetEnvOrReloc var dirrel = "catchIO (getEnv \""++var'++"\")" ++
" (\\_ -> getPrefixDirReloc \"" ++ dirrel ++
"\")"
where var' = pkgPathEnvVar pkg_descr var
mkGetEnvOr var expr = "catchIO (getEnv \""++var'++"\")"++
" (\\_ -> "++expr++")"
where var' = pkgPathEnvVar pkg_descr var
absolute =
if is an absolute path
|| not (supportsRelocatableProgs (compilerFlavor (compiler lbi)))
reloc = relocatable lbi
supportsRelocatableProgs GHC = case buildOS of
Windows -> True
_ -> False
supportsRelocatableProgs GHCJS = case buildOS of
Windows -> True
_ -> False
supportsRelocatableProgs _ = False
paths_modulename = autogenModuleName pkg_descr
get_prefix_stuff = get_prefix_win32 buildArch
path_sep = show [pathSeparator]
supports_cpp = compilerFlavor (compiler lbi) == GHC
supports_language_pragma =
(compilerFlavor (compiler lbi) == GHC &&
(compilerVersion (compiler lbi)
`withinRange` orLaterVersion (Version [6,6,1] []))) ||
compilerFlavor (compiler lbi) == GHCJS
pkgPathEnvVar :: PackageDescription
^ path component ; one of \"bindir\ " , \"libdir\ " ,
\"datadir\ " , \"libexecdir\ " , or \"sysconfdir\ "
pkgPathEnvVar pkg_descr var =
showPkgName (packageName pkg_descr) ++ "_" ++ var
where
showPkgName = map fixchar . display
fixchar '-' = '_'
fixchar c = c
get_prefix_reloc_stuff :: String
get_prefix_reloc_stuff =
"getPrefixDirReloc :: FilePath -> IO FilePath\n"++
"getPrefixDirReloc dirRel = do\n"++
" exePath <- getExecutablePath\n"++
" let (bindir,_) = splitFileName exePath\n"++
" return ((bindir `minusFileName` bindirrel) `joinFileName` dirRel)\n"
get_prefix_win32 :: Arch -> String
get_prefix_win32 arch =
"getPrefixDirRel :: FilePath -> IO FilePath\n"++
"getPrefixDirRel dirRel = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.\n"++
" where\n"++
" try_size size = allocaArray (fromIntegral size) $ \\buf -> do\n"++
" ret <- c_GetModuleFileName nullPtr buf size\n"++
" case ret of\n"++
" 0 -> return (prefix `joinFileName` dirRel)\n"++
" _ | ret < size -> do\n"++
" exePath <- peekCWString buf\n"++
" let (bindir,_) = splitFileName exePath\n"++
" return ((bindir `minusFileName` bindirrel) `joinFileName` dirRel)\n"++
" | otherwise -> try_size (size * 2)\n"++
"\n"++
"foreign import " ++ cconv ++ " unsafe \"windows.h GetModuleFileNameW\"\n"++
" c_GetModuleFileName :: Ptr () -> CWString -> Int32 -> IO Int32\n"
where cconv = case arch of
I386 -> "stdcall"
X86_64 -> "ccall"
_ -> error "win32 supported only with I386, X86_64"
filename_stuff :: String
filename_stuff =
"minusFileName :: FilePath -> String -> FilePath\n"++
"minusFileName dir \"\" = dir\n"++
"minusFileName dir \".\" = dir\n"++
"minusFileName dir suffix =\n"++
" minusFileName (fst (splitFileName dir)) (fst (splitFileName suffix))\n"++
"\n"++
"joinFileName :: String -> String -> FilePath\n"++
"joinFileName \"\" fname = fname\n"++
"joinFileName \".\" fname = fname\n"++
"joinFileName dir \"\" = dir\n"++
"joinFileName dir fname\n"++
" | isPathSeparator (last dir) = dir++fname\n"++
" | otherwise = dir++pathSeparator:fname\n"++
"\n"++
"splitFileName :: FilePath -> (String, String)\n"++
"splitFileName p = (reverse (path2++drive), reverse fname)\n"++
" where\n"++
" (path,drive) = case p of\n"++
" (c:':':p') -> (reverse p',[':',c])\n"++
" _ -> (reverse p ,\"\")\n"++
" (fname,path1) = break isPathSeparator path\n"++
" path2 = case path1 of\n"++
" [] -> \".\"\n"++
" [_] -> path1 -- don't remove the trailing slash if \n"++
" -- there is only one character\n"++
" (c:path') | isPathSeparator c -> path'\n"++
" _ -> path1\n"++
"\n"++
"pathSeparator :: Char\n"++
(case buildOS of
Windows -> "pathSeparator = '\\\\'\n"
_ -> "pathSeparator = '/'\n") ++
"\n"++
"isPathSeparator :: Char -> Bool\n"++
(case buildOS of
Windows -> "isPathSeparator c = c == '/' || c == '\\\\'\n"
_ -> "isPathSeparator c = c == '/'\n")
|
54e50c8543bd01005604565dcd6ad22d084fa7090afd704b70df98f3b28ae2aa | mflatt/not-a-box | schemify.rkt | #lang racket/base
(require "wrap.rkt"
"match.rkt"
"known.rkt"
"import.rkt"
"struct-type-info.rkt"
"simple.rkt"
"find-definition.rkt"
"mutated.rkt"
"mutated-state.rkt"
"left-to-right.rkt")
(provide schemify-linklet
schemify-body
(all-from-out "known.rkt"))
;; Convert a linklet to a Scheme `lambda`, dealing with several
;; issues:
;;
;; - imports and exports are represented by `variable` objects that
;; are passed to the function; to avoid obscuring the program to
;; the optimizer, though, refer to the definitions of exported
;; variables instead of going through the `variable`, whenever
;; possible, and accept values instead of `variable`s for constant
;; imports;
;;
;; - wrap expressions in a sequence of definitions plus expressions
;; so that the result body is a sequence of definitions followed
;; by a single expression;
;;
;; - convert function calls and `let` forms to enforce left-to-right
;; evaluation;
;;
;; - convert function calls to support applicable structs, using
` # % app ` whenever a call might go through something other than a
;; plain function;
;;
- convert ` make - struct - type ` bindings to a pattern that Chez can
;; recognize;
;;
;; - optimize away `variable-reference-constant?` uses, which is
;; important to make keyword-argument function calls work directly
;; without keywords;
;;
;; - simplify `define-values` and `let-values` to `define` and
;; `let`, when possible, and generally avoid `let-values`.
;; The given linklet can have parts wrapped as `syntax?` objects.
;; When called from the Racket expander, those syntax objects
;; will be "correlated" objects that just support source locations.
;; The job of `annotate` is to take an original term (which might
;; be `syntax?`) and a schemified term an potentially make it
;; an annotatation. The `unannotate` function should return a
stripped S - expression back ; it 's used for post - Schemify checks ,
;; and `unannotate` is expected to be constant time.
;; Returns (values schemified-linklet import-abi export-info)
An import ABI is a list of list of booleans , parallel to the
;; linklet imports, where #t to means that a value is expected, and #f
;; means that a variable (which boxes a value) is expected
(define (schemify-linklet lk annotate unannotate prim-knowns get-import-knowns)
(define (im-int-id id) (unwrap (if (pair? id) (cadr id) id)))
(define (im-ext-id id) (unwrap (if (pair? id) (car id) id)))
(define (ex-int-id id) (unwrap (if (pair? id) (car id) id)))
(define (ex-ext-id id) (unwrap (if (pair? id) (cadr id) id)))
;; Assume no wraps unless the level of an id or expression
(match lk
[`(linklet ,im-idss ,ex-ids . ,bodys)
;; For imports, map symbols to gensymed `variable` argument names:
(define imports
(for/fold ([imports (hasheq)]) ([im-ids (in-list im-idss)]
[index (in-naturals)])
(define grp (import-group (lambda () (get-import-knowns index))))
(for/fold ([imports imports]) ([im-id (in-list im-ids)])
(define id (im-int-id im-id))
(define ext-id (im-ext-id im-id))
(hash-set imports id (import grp (gensym (symbol->string id)) ext-id)))))
;; Ditto for exports:
(define exports
(for/fold ([exports (hasheq)]) ([ex-id (in-list ex-ids)])
(define id (ex-int-id ex-id))
(hash-set exports id (gensym (symbol->string id)))))
;; Schemify the body, collecting information about defined names:
(define-values (new-body defn-info mutated)
(schemify-body* bodys annotate unannotate prim-knowns imports exports))
(values
;; Build `lambda` with schemified body:
`(lambda (instance-variable-reference
,@(for*/list ([im-ids (in-list im-idss)]
[im-id (in-list im-ids)])
(import-id (hash-ref imports (im-int-id im-id))))
,@(for/list ([ex-id (in-list ex-ids)])
(hash-ref exports (ex-int-id ex-id))))
,@new-body)
;; Import ABI: request values for constants, `variable`s otherwise
(for/list ([im-ids (in-list im-idss)])
(define im-knowns (and (pair? (unwrap im-ids))
(let ([k/t (import-group-knowns/thunk
(import-grp
(hash-ref imports (im-int-id (wrap-car im-ids)))))])
(if (procedure? k/t) #f k/t))))
(for/list ([im-id (in-list im-ids)])
(and im-knowns
(known-constant? (hash-ref im-knowns (im-ext-id im-id) #f)))))
Convert internal to external identifiers
(for/fold ([knowns (hasheq)]) ([ex-id (in-list ex-ids)])
(define id (ex-int-id ex-id))
(define v (hash-ref defn-info id #f))
(cond
[(and v
(not (set!ed-mutated-state? (hash-ref mutated id #f))))
(define ext-id (ex-ext-id ex-id))
(hash-set knowns ext-id v)]
[else knowns])))]))
;; ----------------------------------------
(define (schemify-body l annotate unannotate prim-knowns imports exports)
(define-values (new-body defn-info mutated)
(schemify-body* l annotate unannotate prim-knowns imports exports))
new-body)
(define (schemify-body* l annotate unannotate prim-knowns imports exports)
;; Various conversion steps need information about mutated variables,
;; where "mutated" here includes visible implicit mutation, such as
;; a variable that might be used before it is defined:
(define mutated (mutated-in-body l exports prim-knowns (hasheq) imports))
;; Make another pass to gather known-binding information:
(define knowns
(for/fold ([knowns (hasheq)]) ([form (in-list l)])
(define-values (new-knowns info)
(find-definitions form prim-knowns knowns imports mutated))
new-knowns))
;; While schemifying, add calls to install exported values in to the
;; corresponding exported `variable` records, but delay those
;; installs to the end, if possible
(define schemified
(let loop ([l l] [accum-exprs null] [accum-ids null])
(cond
[(null? l)
(define set-vars
(for/list ([id (in-list accum-ids)]
#:when (hash-ref exports id #f))
(make-set-variable id exports)))
(cond
[(null? set-vars)
(cond
[(null? accum-exprs) '((void))]
[else (reverse accum-exprs)])]
[else (append
(make-expr-defns accum-exprs)
set-vars)])]
[else
(define form (car l))
(define schemified (schemify form annotate unannotate
prim-knowns knowns mutated imports exports))
(match form
[`(define-values ,ids ,_)
(append
(make-expr-defns accum-exprs)
(cons
schemified
(let id-loop ([ids ids] [accum-exprs null] [accum-ids accum-ids])
(cond
[(wrap-null? ids) (loop (wrap-cdr l) accum-exprs accum-ids)]
[(via-variable-mutated-state? (hash-ref mutated (unwrap (wrap-car ids)) #f))
(define id (unwrap (wrap-car ids)))
(cond
[(hash-ref exports id #f)
(id-loop (wrap-cdr ids)
(cons (make-set-variable id exports)
accum-exprs)
accum-ids)]
[else
(id-loop (wrap-cdr ids) accum-exprs accum-ids)])]
[else
(id-loop (wrap-cdr ids) accum-exprs (cons (unwrap (wrap-car ids)) accum-ids))]))))]
[`,_
(loop (wrap-cdr l) (cons schemified accum-exprs) accum-ids)])])))
;; Return both schemified and known-binding information, where
;; the later is used for cross-linklet optimization
(values schemified knowns mutated))
(define (make-set-variable id exports)
(define ex-var (hash-ref exports (unwrap id)))
`(variable-set! ,ex-var ,id))
(define (make-expr-defns accum-exprs)
(for/list ([expr (in-list (reverse accum-exprs))])
`(define ,(gensym) ,expr)))
;; ----------------------------------------
;; Schemify `let-values` to `let`, etc., and
;; reorganize struct bindings.
(define (schemify v annotate unannotate prim-knowns knowns mutated imports exports)
(let schemify/knowns ([knowns knowns] [v v])
(let schemify ([v v])
(annotate
v
(match v
[`(lambda ,formals ,body ...)
`(lambda ,formals ,@(map schemify body))]
[`(case-lambda [,formalss ,bodys ...] ...)
`(case-lambda ,@(for/list ([formals (in-list formalss)]
[body (in-list bodys)])
`[,formals ,@(map schemify body)]))]
[`(define-values (,struct:s ,make-s ,s? ,acc/muts ...)
(let-values (((,struct: ,make ,?1 ,-ref ,-set!) ,mk))
(values ,struct:2
,make2
,?2
,make-acc/muts ...)))
;; Convert a `make-struct-type` binding into a
set of bindings that Chez 's cp0 recognizes ,
;; and push the struct-specific extra work into
;; `struct-type-install-properties!`
(define sti (and (wrap-eq? struct: struct:2)
(wrap-eq? make make2)
(wrap-eq? ?1 ?2)
(make-struct-type-info mk prim-knowns knowns imports mutated)))
(cond
[(and sti
;; make sure `struct:` isn't used too early, since we're
;; reordering it's definition with respect to some arguments
;; of `make-struct-type`:
(simple-mutated-state? (hash-ref mutated (unwrap struct:) #f)))
`(begin
(define ,struct:s (make-record-type-descriptor ',(struct-type-info-name sti)
,(schemify (struct-type-info-parent sti))
#f #f #f
',(for/vector ([i (in-range (struct-type-info-immediate-field-count sti))])
`(mutable ,(string->symbol (format "f~a" i))))))
,@(if (null? (struct-type-info-rest sti))
null
`((define ,(gensym)
(struct-type-install-properties! ,struct:s
',(struct-type-info-name sti)
,(struct-type-info-immediate-field-count sti)
0
,(schemify (struct-type-info-parent sti))
,@(map schemify (struct-type-info-rest sti))))))
(define ,make-s (record-constructor
(make-record-constructor-descriptor ,struct:s #f #f)))
(define ,s? (record-predicate ,struct:s))
,@(for/list ([acc/mut (in-list acc/muts)]
[make-acc/mut (in-list make-acc/muts)])
`(define ,acc/mut
,(match make-acc/mut
[`(make-struct-field-accessor ,(? (lambda (v) (wrap-eq? v -ref))) ,pos ,_)
`(record-accessor ,struct:s ,pos)]
[`(make-struct-field-mutator ,(? (lambda (v) (wrap-eq? v -set!))) ,pos ,_)
`(record-mutator ,struct:s ,pos)]
[`,_ (error "oops")]))))]
[else
(match v
[`(,_ ,ids ,rhs)
`(define-values ,ids ,(schemify rhs))])])]
[`(define-values (,id) ,rhs)
`(define ,id ,(schemify rhs))]
[`(define-values ,ids ,rhs)
`(define-values ,ids ,(schemify rhs))]
[`(quote ,_) v]
[`(let-values () ,body)
(schemify body)]
[`(let-values () ,bodys ...)
`(begin ,@(map schemify bodys))]
[`(let-values ([(,ids) ,rhss] ...) ,bodys ...)
(define new-knowns
(for/fold ([knowns knowns]) ([id (in-list ids)]
[rhs (in-list rhss)])
(if (lambda? rhs)
(hash-set knowns (unwrap id) a-known-procedure)
knowns)))
(left-to-right/let ids
(for/list ([rhs (in-list rhss)])
(schemify rhs))
(for/list ([body (in-list bodys)])
(schemify/knowns new-knowns body))
unannotate prim-knowns knowns imports mutated)]
[`(let-values ([() (begin ,rhss ... (values))]) ,bodys ...)
`(begin ,@(map schemify rhss) ,@(map schemify bodys))]
[`(let-values ([,idss ,rhss] ...) ,bodys ...)
(left-to-right/let-values idss
(for/list ([rhs (in-list rhss)])
(schemify rhs))
(map schemify bodys)
mutated)]
[`(letrec-values ([(,ids) ,rhss] ...) ,bodys ...)
(define new-knowns
(for/fold ([knowns knowns]) ([id (in-list ids)]
[rhs (in-list rhss)])
(if (lambda? rhs)
(hash-set knowns (unwrap id) a-known-procedure)
knowns)))
`(letrec* ,(for/list ([id (in-list ids)]
[rhs (in-list rhss)])
`[,id ,(schemify/knowns new-knowns rhs)])
,@(for/list ([body (in-list bodys)])
(schemify/knowns new-knowns body)))]
[`(letrec-values ([,idss ,rhss] ...) ,bodys ...)
Convert
;; (letrec*-values ([(id ...) rhs] ...) ....)
;; to
( letrec * ( [ ( call - with - values rhs vector ) ]
;; [id (vector-ref vec 0)]
;; ... ...)
;; ....)
`(letrec* ,(apply
append
(for/list ([ids (in-wrap-list idss)]
[rhs (in-list rhss)])
(let ([rhs (schemify rhs)])
(cond
[(null? ids)
`([,(gensym "lr")
,(make-let-values null rhs '(void))])]
[(and (pair? ids) (null? (cdr ids)))
`([,(car ids) ,rhs])]
[else
(define lr (gensym "lr"))
`([,lr ,(make-let-values ids rhs `(vector . ,ids))]
,@(for/list ([id (in-list ids)]
[pos (in-naturals)])
`[,id (vector-ref ,lr ,pos)]))]))))
,@(map schemify bodys))]
[`(if ,tst ,thn ,els)
`(if ,(schemify tst) ,(schemify thn) ,(schemify els))]
[`(with-continuation-mark ,key ,val ,body)
`(with-continuation-mark ,(schemify key) ,(schemify val) ,(schemify body))]
[`(begin ,exps ...)
`(begin . ,(map schemify exps))]
[`(begin0 ,exps ...)
`(begin0 . ,(map schemify exps))]
[`(set! ,id ,rhs)
(let ([ex-id (hash-ref exports (unwrap id) #f)])
(if ex-id
`(variable-set! ,ex-id ,(schemify rhs))
`(set! ,id ,(schemify rhs))))]
[`(variable-reference-constant? (#%variable-reference ,id))
(let ([id (unwrap id)])
(and (not (hash-ref mutated id #f))
(let ([im (hash-ref imports id #f)])
(or (not im)
(known-constant? (import-lookup im))))))]
[`(#%variable-reference)
'instance-variable-reference]
[`(#%variable-reference ,id)
(define e (hash-ref exports (unwrap id) #f))
(if e
`(make-instance-variable-reference
instance-variable-reference
,e)
`(make-instance-variable-reference
instance-variable-reference
,(if (hash-ref mutated (unwrap id) #f)
'mutable
'immutable)))]
[`(,rator ,exps ...)
(let ([s-rator (schemify rator)]
[args (map schemify exps)]
[u-rator (unwrap rator)])
(let ([plain-app?
(or (and (known-procedure? (hash-ref-either knowns imports u-rator))
(not (hash-ref mutated u-rator #f)))
(known-procedure? (hash-ref prim-knowns u-rator #f))
(lambda? rator))])
(left-to-right/app s-rator
args
plain-app?
unannotate prim-knowns knowns imports mutated)))]
[`,_
(let ([u-v (unwrap v)])
(cond
[(and (symbol? u-v)
(via-variable-mutated-state? (hash-ref mutated u-v #f))
(hash-ref exports u-v #f))
=> (lambda (ex-id) `(variable-ref ,ex-id))]
[(and (symbol? u-v)
(hash-ref imports u-v #f))
=> (lambda (im)
(if (known-constant? (import-lookup im))
;; Not boxed:
(import-id im)
;; Will be boxed, but won't be undefined (because the
;; module system won't link to an instance whose
;; definitions didn't complete):
`(variable-ref/no-check ,(import-id im))))]
[else v]))])))))
| null | https://raw.githubusercontent.com/mflatt/not-a-box/b6c1af4fb0eb877610a3a20b5265a8c8d2dd28e9/schemify/schemify.rkt | racket | Convert a linklet to a Scheme `lambda`, dealing with several
issues:
- imports and exports are represented by `variable` objects that
are passed to the function; to avoid obscuring the program to
the optimizer, though, refer to the definitions of exported
variables instead of going through the `variable`, whenever
possible, and accept values instead of `variable`s for constant
imports;
- wrap expressions in a sequence of definitions plus expressions
so that the result body is a sequence of definitions followed
by a single expression;
- convert function calls and `let` forms to enforce left-to-right
evaluation;
- convert function calls to support applicable structs, using
plain function;
recognize;
- optimize away `variable-reference-constant?` uses, which is
important to make keyword-argument function calls work directly
without keywords;
- simplify `define-values` and `let-values` to `define` and
`let`, when possible, and generally avoid `let-values`.
The given linklet can have parts wrapped as `syntax?` objects.
When called from the Racket expander, those syntax objects
will be "correlated" objects that just support source locations.
The job of `annotate` is to take an original term (which might
be `syntax?`) and a schemified term an potentially make it
an annotatation. The `unannotate` function should return a
it 's used for post - Schemify checks ,
and `unannotate` is expected to be constant time.
Returns (values schemified-linklet import-abi export-info)
linklet imports, where #t to means that a value is expected, and #f
means that a variable (which boxes a value) is expected
Assume no wraps unless the level of an id or expression
For imports, map symbols to gensymed `variable` argument names:
Ditto for exports:
Schemify the body, collecting information about defined names:
Build `lambda` with schemified body:
Import ABI: request values for constants, `variable`s otherwise
----------------------------------------
Various conversion steps need information about mutated variables,
where "mutated" here includes visible implicit mutation, such as
a variable that might be used before it is defined:
Make another pass to gather known-binding information:
While schemifying, add calls to install exported values in to the
corresponding exported `variable` records, but delay those
installs to the end, if possible
Return both schemified and known-binding information, where
the later is used for cross-linklet optimization
----------------------------------------
Schemify `let-values` to `let`, etc., and
reorganize struct bindings.
Convert a `make-struct-type` binding into a
and push the struct-specific extra work into
`struct-type-install-properties!`
make sure `struct:` isn't used too early, since we're
reordering it's definition with respect to some arguments
of `make-struct-type`:
(letrec*-values ([(id ...) rhs] ...) ....)
to
[id (vector-ref vec 0)]
... ...)
....)
Not boxed:
Will be boxed, but won't be undefined (because the
module system won't link to an instance whose
definitions didn't complete): | #lang racket/base
(require "wrap.rkt"
"match.rkt"
"known.rkt"
"import.rkt"
"struct-type-info.rkt"
"simple.rkt"
"find-definition.rkt"
"mutated.rkt"
"mutated-state.rkt"
"left-to-right.rkt")
(provide schemify-linklet
schemify-body
(all-from-out "known.rkt"))
` # % app ` whenever a call might go through something other than a
- convert ` make - struct - type ` bindings to a pattern that Chez can
An import ABI is a list of list of booleans , parallel to the
(define (schemify-linklet lk annotate unannotate prim-knowns get-import-knowns)
(define (im-int-id id) (unwrap (if (pair? id) (cadr id) id)))
(define (im-ext-id id) (unwrap (if (pair? id) (car id) id)))
(define (ex-int-id id) (unwrap (if (pair? id) (car id) id)))
(define (ex-ext-id id) (unwrap (if (pair? id) (cadr id) id)))
(match lk
[`(linklet ,im-idss ,ex-ids . ,bodys)
(define imports
(for/fold ([imports (hasheq)]) ([im-ids (in-list im-idss)]
[index (in-naturals)])
(define grp (import-group (lambda () (get-import-knowns index))))
(for/fold ([imports imports]) ([im-id (in-list im-ids)])
(define id (im-int-id im-id))
(define ext-id (im-ext-id im-id))
(hash-set imports id (import grp (gensym (symbol->string id)) ext-id)))))
(define exports
(for/fold ([exports (hasheq)]) ([ex-id (in-list ex-ids)])
(define id (ex-int-id ex-id))
(hash-set exports id (gensym (symbol->string id)))))
(define-values (new-body defn-info mutated)
(schemify-body* bodys annotate unannotate prim-knowns imports exports))
(values
`(lambda (instance-variable-reference
,@(for*/list ([im-ids (in-list im-idss)]
[im-id (in-list im-ids)])
(import-id (hash-ref imports (im-int-id im-id))))
,@(for/list ([ex-id (in-list ex-ids)])
(hash-ref exports (ex-int-id ex-id))))
,@new-body)
(for/list ([im-ids (in-list im-idss)])
(define im-knowns (and (pair? (unwrap im-ids))
(let ([k/t (import-group-knowns/thunk
(import-grp
(hash-ref imports (im-int-id (wrap-car im-ids)))))])
(if (procedure? k/t) #f k/t))))
(for/list ([im-id (in-list im-ids)])
(and im-knowns
(known-constant? (hash-ref im-knowns (im-ext-id im-id) #f)))))
Convert internal to external identifiers
(for/fold ([knowns (hasheq)]) ([ex-id (in-list ex-ids)])
(define id (ex-int-id ex-id))
(define v (hash-ref defn-info id #f))
(cond
[(and v
(not (set!ed-mutated-state? (hash-ref mutated id #f))))
(define ext-id (ex-ext-id ex-id))
(hash-set knowns ext-id v)]
[else knowns])))]))
(define (schemify-body l annotate unannotate prim-knowns imports exports)
(define-values (new-body defn-info mutated)
(schemify-body* l annotate unannotate prim-knowns imports exports))
new-body)
(define (schemify-body* l annotate unannotate prim-knowns imports exports)
(define mutated (mutated-in-body l exports prim-knowns (hasheq) imports))
(define knowns
(for/fold ([knowns (hasheq)]) ([form (in-list l)])
(define-values (new-knowns info)
(find-definitions form prim-knowns knowns imports mutated))
new-knowns))
(define schemified
(let loop ([l l] [accum-exprs null] [accum-ids null])
(cond
[(null? l)
(define set-vars
(for/list ([id (in-list accum-ids)]
#:when (hash-ref exports id #f))
(make-set-variable id exports)))
(cond
[(null? set-vars)
(cond
[(null? accum-exprs) '((void))]
[else (reverse accum-exprs)])]
[else (append
(make-expr-defns accum-exprs)
set-vars)])]
[else
(define form (car l))
(define schemified (schemify form annotate unannotate
prim-knowns knowns mutated imports exports))
(match form
[`(define-values ,ids ,_)
(append
(make-expr-defns accum-exprs)
(cons
schemified
(let id-loop ([ids ids] [accum-exprs null] [accum-ids accum-ids])
(cond
[(wrap-null? ids) (loop (wrap-cdr l) accum-exprs accum-ids)]
[(via-variable-mutated-state? (hash-ref mutated (unwrap (wrap-car ids)) #f))
(define id (unwrap (wrap-car ids)))
(cond
[(hash-ref exports id #f)
(id-loop (wrap-cdr ids)
(cons (make-set-variable id exports)
accum-exprs)
accum-ids)]
[else
(id-loop (wrap-cdr ids) accum-exprs accum-ids)])]
[else
(id-loop (wrap-cdr ids) accum-exprs (cons (unwrap (wrap-car ids)) accum-ids))]))))]
[`,_
(loop (wrap-cdr l) (cons schemified accum-exprs) accum-ids)])])))
(values schemified knowns mutated))
(define (make-set-variable id exports)
(define ex-var (hash-ref exports (unwrap id)))
`(variable-set! ,ex-var ,id))
(define (make-expr-defns accum-exprs)
(for/list ([expr (in-list (reverse accum-exprs))])
`(define ,(gensym) ,expr)))
(define (schemify v annotate unannotate prim-knowns knowns mutated imports exports)
(let schemify/knowns ([knowns knowns] [v v])
(let schemify ([v v])
(annotate
v
(match v
[`(lambda ,formals ,body ...)
`(lambda ,formals ,@(map schemify body))]
[`(case-lambda [,formalss ,bodys ...] ...)
`(case-lambda ,@(for/list ([formals (in-list formalss)]
[body (in-list bodys)])
`[,formals ,@(map schemify body)]))]
[`(define-values (,struct:s ,make-s ,s? ,acc/muts ...)
(let-values (((,struct: ,make ,?1 ,-ref ,-set!) ,mk))
(values ,struct:2
,make2
,?2
,make-acc/muts ...)))
set of bindings that Chez 's cp0 recognizes ,
(define sti (and (wrap-eq? struct: struct:2)
(wrap-eq? make make2)
(wrap-eq? ?1 ?2)
(make-struct-type-info mk prim-knowns knowns imports mutated)))
(cond
[(and sti
(simple-mutated-state? (hash-ref mutated (unwrap struct:) #f)))
`(begin
(define ,struct:s (make-record-type-descriptor ',(struct-type-info-name sti)
,(schemify (struct-type-info-parent sti))
#f #f #f
',(for/vector ([i (in-range (struct-type-info-immediate-field-count sti))])
`(mutable ,(string->symbol (format "f~a" i))))))
,@(if (null? (struct-type-info-rest sti))
null
`((define ,(gensym)
(struct-type-install-properties! ,struct:s
',(struct-type-info-name sti)
,(struct-type-info-immediate-field-count sti)
0
,(schemify (struct-type-info-parent sti))
,@(map schemify (struct-type-info-rest sti))))))
(define ,make-s (record-constructor
(make-record-constructor-descriptor ,struct:s #f #f)))
(define ,s? (record-predicate ,struct:s))
,@(for/list ([acc/mut (in-list acc/muts)]
[make-acc/mut (in-list make-acc/muts)])
`(define ,acc/mut
,(match make-acc/mut
[`(make-struct-field-accessor ,(? (lambda (v) (wrap-eq? v -ref))) ,pos ,_)
`(record-accessor ,struct:s ,pos)]
[`(make-struct-field-mutator ,(? (lambda (v) (wrap-eq? v -set!))) ,pos ,_)
`(record-mutator ,struct:s ,pos)]
[`,_ (error "oops")]))))]
[else
(match v
[`(,_ ,ids ,rhs)
`(define-values ,ids ,(schemify rhs))])])]
[`(define-values (,id) ,rhs)
`(define ,id ,(schemify rhs))]
[`(define-values ,ids ,rhs)
`(define-values ,ids ,(schemify rhs))]
[`(quote ,_) v]
[`(let-values () ,body)
(schemify body)]
[`(let-values () ,bodys ...)
`(begin ,@(map schemify bodys))]
[`(let-values ([(,ids) ,rhss] ...) ,bodys ...)
(define new-knowns
(for/fold ([knowns knowns]) ([id (in-list ids)]
[rhs (in-list rhss)])
(if (lambda? rhs)
(hash-set knowns (unwrap id) a-known-procedure)
knowns)))
(left-to-right/let ids
(for/list ([rhs (in-list rhss)])
(schemify rhs))
(for/list ([body (in-list bodys)])
(schemify/knowns new-knowns body))
unannotate prim-knowns knowns imports mutated)]
[`(let-values ([() (begin ,rhss ... (values))]) ,bodys ...)
`(begin ,@(map schemify rhss) ,@(map schemify bodys))]
[`(let-values ([,idss ,rhss] ...) ,bodys ...)
(left-to-right/let-values idss
(for/list ([rhs (in-list rhss)])
(schemify rhs))
(map schemify bodys)
mutated)]
[`(letrec-values ([(,ids) ,rhss] ...) ,bodys ...)
(define new-knowns
(for/fold ([knowns knowns]) ([id (in-list ids)]
[rhs (in-list rhss)])
(if (lambda? rhs)
(hash-set knowns (unwrap id) a-known-procedure)
knowns)))
`(letrec* ,(for/list ([id (in-list ids)]
[rhs (in-list rhss)])
`[,id ,(schemify/knowns new-knowns rhs)])
,@(for/list ([body (in-list bodys)])
(schemify/knowns new-knowns body)))]
[`(letrec-values ([,idss ,rhss] ...) ,bodys ...)
Convert
( letrec * ( [ ( call - with - values rhs vector ) ]
`(letrec* ,(apply
append
(for/list ([ids (in-wrap-list idss)]
[rhs (in-list rhss)])
(let ([rhs (schemify rhs)])
(cond
[(null? ids)
`([,(gensym "lr")
,(make-let-values null rhs '(void))])]
[(and (pair? ids) (null? (cdr ids)))
`([,(car ids) ,rhs])]
[else
(define lr (gensym "lr"))
`([,lr ,(make-let-values ids rhs `(vector . ,ids))]
,@(for/list ([id (in-list ids)]
[pos (in-naturals)])
`[,id (vector-ref ,lr ,pos)]))]))))
,@(map schemify bodys))]
[`(if ,tst ,thn ,els)
`(if ,(schemify tst) ,(schemify thn) ,(schemify els))]
[`(with-continuation-mark ,key ,val ,body)
`(with-continuation-mark ,(schemify key) ,(schemify val) ,(schemify body))]
[`(begin ,exps ...)
`(begin . ,(map schemify exps))]
[`(begin0 ,exps ...)
`(begin0 . ,(map schemify exps))]
[`(set! ,id ,rhs)
(let ([ex-id (hash-ref exports (unwrap id) #f)])
(if ex-id
`(variable-set! ,ex-id ,(schemify rhs))
`(set! ,id ,(schemify rhs))))]
[`(variable-reference-constant? (#%variable-reference ,id))
(let ([id (unwrap id)])
(and (not (hash-ref mutated id #f))
(let ([im (hash-ref imports id #f)])
(or (not im)
(known-constant? (import-lookup im))))))]
[`(#%variable-reference)
'instance-variable-reference]
[`(#%variable-reference ,id)
(define e (hash-ref exports (unwrap id) #f))
(if e
`(make-instance-variable-reference
instance-variable-reference
,e)
`(make-instance-variable-reference
instance-variable-reference
,(if (hash-ref mutated (unwrap id) #f)
'mutable
'immutable)))]
[`(,rator ,exps ...)
(let ([s-rator (schemify rator)]
[args (map schemify exps)]
[u-rator (unwrap rator)])
(let ([plain-app?
(or (and (known-procedure? (hash-ref-either knowns imports u-rator))
(not (hash-ref mutated u-rator #f)))
(known-procedure? (hash-ref prim-knowns u-rator #f))
(lambda? rator))])
(left-to-right/app s-rator
args
plain-app?
unannotate prim-knowns knowns imports mutated)))]
[`,_
(let ([u-v (unwrap v)])
(cond
[(and (symbol? u-v)
(via-variable-mutated-state? (hash-ref mutated u-v #f))
(hash-ref exports u-v #f))
=> (lambda (ex-id) `(variable-ref ,ex-id))]
[(and (symbol? u-v)
(hash-ref imports u-v #f))
=> (lambda (im)
(if (known-constant? (import-lookup im))
(import-id im)
`(variable-ref/no-check ,(import-id im))))]
[else v]))])))))
|
3e281f40c6498c55bb93e4bc462e91b0ee40df05c4ee9aa33fb8fb40ad524a37 | deadtrickster/rebar3_elvis_plugin | elvis_config.erl | -module(elvis_config).
-export([
default/0,
load_file/1,
load/1,
validate/1,
normalize/1,
Geters
dirs/1,
ignore/1,
filter/1,
files/1,
rules/1,
%% Files
resolve_files/1,
resolve_files/2,
apply_to_files/2
]).
-export_type([
config/0
]).
-type config() :: [map()].
-define(DEFAULT_CONFIG_PATH, "./elvis.config").
-define(DEFAULT_REBAR_CONFIG_PATH, "./rebar.config").
-define(DEFAULT_FILTER, "*.erl").
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Public
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec default() -> config().
default() ->
case file:consult(?DEFAULT_CONFIG_PATH) of
{ok, [Config]} ->
load(Config);
{error, enoent} ->
case file:consult(?DEFAULT_REBAR_CONFIG_PATH) of
{ok, Config} ->
load(Config);
{error, enoent} ->
Config = application:get_env(elvis, config, []),
ensure_config_list(Config);
{error, Reason} ->
throw(Reason)
end;
{error, Reason} ->
throw(Reason)
end.
-spec load_file(string()) -> config().
load_file(Path) ->
case file:consult(Path) of
{ok, [Config]} ->
load(Config);
{error, Reason} ->
throw(Reason)
end.
-spec load(term()) -> config().
load(AppConfig) ->
ElvisConfig = proplists:get_value(elvis, AppConfig, []),
Config = proplists:get_value(config, ElvisConfig, []),
ensure_config_list(Config).
ensure_config_list(Config) when is_map(Config) ->
[Config];
ensure_config_list(Config) ->
Config.
-spec validate(Config::config()) -> ok.
validate([]) ->
throw({invalid_config, empty_config});
validate(Config) ->
lists:foreach(fun do_validate/1, Config).
do_validate(RuleGroup) ->
case maps:is_key(src_dirs, RuleGroup) or maps:is_key(dirs, RuleGroup) of
false -> throw({invalid_config, {missing_dirs, RuleGroup}});
true -> ok
end,
case maps:is_key(dirs, RuleGroup) of
true ->
case maps:is_key(filter, RuleGroup) of
false -> throw({invalid_config, {missing_filter, RuleGroup}});
true -> ok
end;
false -> ok
end,
case maps:is_key(rules, RuleGroup) orelse maps:is_key(ruleset, RuleGroup) of
false -> throw({invalid_config, {missing_rules, RuleGroup}});
true -> ok
end.
-spec normalize(config()) -> config().
normalize(Config) when is_list(Config) ->
lists:map(fun do_normalize/1, Config).
@private
do_normalize(Config = #{src_dirs := Dirs}) ->
%% NOTE: Provided for backwards compatibility.
Rename ' ' key to ' dirs ' .
Config1 = maps:remove(src_dirs, Config),
Config1#{dirs => Dirs};
do_normalize(Config) ->
Config.
-spec dirs(Config::config() | map()) -> [string()].
dirs(Config) when is_list(Config) ->
lists:flatmap(fun dirs/1, Config);
dirs(_RuleGroup = #{dirs := Dirs}) ->
Dirs;
dirs(#{}) ->
[].
-spec ignore(config() | map()) -> [string()].
ignore(Config) when is_list(Config) ->
lists:flatmap(fun ignore/1, Config);
ignore(_RuleGroup = #{ignore := Ignore}) ->
lists:map(fun ignore_to_regexp/1, Ignore);
ignore(#{}) ->
[].
-spec filter(config() | map()) -> [string()].
filter(Config) when is_list(Config) ->
lists:flatmap(fun filter/1, Config);
filter(_RuleGroup = #{filter := Filter}) ->
Filter;
filter(#{}) ->
?DEFAULT_FILTER.
-spec files(RuleGroup::config() | map()) -> [elvis_file:file()] | undefined.
files(RuleGroup) when is_list(RuleGroup) ->
lists:map(fun files/1, RuleGroup);
files(_RuleGroup = #{files := Files}) ->
Files;
files(#{}) ->
undefined.
-spec rules(Rules::config() | map()) -> [string()] | undefined.
rules(Rules) when is_list(Rules) ->
lists:map(fun rules/1, Rules);
rules(#{rules := UserRules, ruleset := RuleSet}) ->
DefaultRules = elvis_rulesets:rules(RuleSet),
merge_rules(UserRules, DefaultRules);
rules(#{rules := Rules}) -> Rules;
rules(#{ruleset := RuleSet}) ->
elvis_rulesets:rules(RuleSet);
rules(#{}) ->
undefined.
%% @doc Takes a configuration and a list of files, filtering some
%% of them according to the 'filter' key, or if not specified
%% uses '*.erl'.
%% @end
%% resolve_files/2 with a config() type is used in elvis project
-spec resolve_files(Config::config() | map(), Files::[elvis_file:file()]) ->
config() | map().
resolve_files(Config, Files) when is_list(Config) ->
Fun = fun(RuleGroup) -> resolve_files(RuleGroup, Files) end,
lists:map(Fun, Config);
resolve_files(RuleGroup, Files) ->
Filter = filter(RuleGroup),
Dirs = dirs(RuleGroup),
Ignore = ignore(RuleGroup),
FilteredFiles = elvis_file:filter_files(Files, Dirs, Filter, Ignore),
RuleGroup#{files => FilteredFiles}.
%% @doc Takes a configuration and finds all files according to its 'dirs'
%% end 'filter' key, or if not specified uses '*.erl'.
%% @end
-spec resolve_files(map()) -> map().
resolve_files(RuleGroup = #{files := _Files}) ->
RuleGroup;
resolve_files(RuleGroup = #{dirs := Dirs}) ->
Filter = filter(RuleGroup),
Files = elvis_file:find_files(Dirs, Filter),
resolve_files(RuleGroup, Files).
%% @doc Takes a function and configuration and applies the function to all
%% file in the configuration.
%% @end
-spec apply_to_files(Fun::fun(), Config::config() | map()) -> config() | map().
apply_to_files(Fun, Config) when is_list(Config) ->
ApplyFun = fun(RuleGroup) -> apply_to_files(Fun, RuleGroup) end,
lists:map(ApplyFun, Config);
apply_to_files(Fun, RuleGroup = #{files := Files}) ->
NewFiles = lists:map(Fun, Files),
RuleGroup#{files => NewFiles}.
%% @doc Ensures the ignore is a regexp, this is used
%% to allow using 'module name' atoms in the ignore
list by taking advantage of the fact that erlang
%% enforces the module and the file name to be the
%% same.
%% @end
-spec ignore_to_regexp(string() | atom()) -> string().
ignore_to_regexp(R) when is_list(R) ->
R;
ignore_to_regexp(A) when is_atom(A) ->
"/" ++ atom_to_list(A) ++ "\\.erl$".
%% @doc Merge user rules (override) with elvis default rules.
-spec merge_rules(UserRules::list(), DefaultRules::list()) -> list().
merge_rules(UserRules, DefaultRules) ->
UnduplicatedRules =
% Drops repeated rules
lists:filter(
If any default rule is in UserRules it means the user
% wants to override the rule.
fun({FileName, RuleName}) ->
not is_rule_override(FileName, RuleName, UserRules);
({FileName, RuleName, _}) ->
not is_rule_override(FileName, RuleName, UserRules);
(_) -> false
end,
DefaultRules
),
OverrideRules =
% Remove the rules that the user wants to "disable" and after that,
% remains just the rules the user wants to override.
lists:filter(
fun({_FileName, _RuleName, OverrideOptions}) ->
disable /= OverrideOptions;
(_) -> false end,
UserRules
),
UnduplicatedRules ++ OverrideRules.
-spec is_rule_override(FileName::atom(), RuleName::atom(), UserRules::list()) ->
boolean().
is_rule_override(FileName, RuleName, UserRules) ->
lists:any(
fun(UserRule) ->
case UserRule of
{FileName, RuleName, _} -> true;
_ -> false
end
end,
UserRules
).
| null | https://raw.githubusercontent.com/deadtrickster/rebar3_elvis_plugin/0b7dd1a3808dbe2e2e916ecf3afd1ff24e723021/src/elvis_config.erl | erlang | Files
Public
NOTE: Provided for backwards compatibility.
@doc Takes a configuration and a list of files, filtering some
of them according to the 'filter' key, or if not specified
uses '*.erl'.
@end
resolve_files/2 with a config() type is used in elvis project
@doc Takes a configuration and finds all files according to its 'dirs'
end 'filter' key, or if not specified uses '*.erl'.
@end
@doc Takes a function and configuration and applies the function to all
file in the configuration.
@end
@doc Ensures the ignore is a regexp, this is used
to allow using 'module name' atoms in the ignore
enforces the module and the file name to be the
same.
@end
@doc Merge user rules (override) with elvis default rules.
Drops repeated rules
wants to override the rule.
Remove the rules that the user wants to "disable" and after that,
remains just the rules the user wants to override. | -module(elvis_config).
-export([
default/0,
load_file/1,
load/1,
validate/1,
normalize/1,
Geters
dirs/1,
ignore/1,
filter/1,
files/1,
rules/1,
resolve_files/1,
resolve_files/2,
apply_to_files/2
]).
-export_type([
config/0
]).
-type config() :: [map()].
-define(DEFAULT_CONFIG_PATH, "./elvis.config").
-define(DEFAULT_REBAR_CONFIG_PATH, "./rebar.config").
-define(DEFAULT_FILTER, "*.erl").
-spec default() -> config().
default() ->
case file:consult(?DEFAULT_CONFIG_PATH) of
{ok, [Config]} ->
load(Config);
{error, enoent} ->
case file:consult(?DEFAULT_REBAR_CONFIG_PATH) of
{ok, Config} ->
load(Config);
{error, enoent} ->
Config = application:get_env(elvis, config, []),
ensure_config_list(Config);
{error, Reason} ->
throw(Reason)
end;
{error, Reason} ->
throw(Reason)
end.
-spec load_file(string()) -> config().
load_file(Path) ->
case file:consult(Path) of
{ok, [Config]} ->
load(Config);
{error, Reason} ->
throw(Reason)
end.
-spec load(term()) -> config().
load(AppConfig) ->
ElvisConfig = proplists:get_value(elvis, AppConfig, []),
Config = proplists:get_value(config, ElvisConfig, []),
ensure_config_list(Config).
ensure_config_list(Config) when is_map(Config) ->
[Config];
ensure_config_list(Config) ->
Config.
-spec validate(Config::config()) -> ok.
validate([]) ->
throw({invalid_config, empty_config});
validate(Config) ->
lists:foreach(fun do_validate/1, Config).
do_validate(RuleGroup) ->
case maps:is_key(src_dirs, RuleGroup) or maps:is_key(dirs, RuleGroup) of
false -> throw({invalid_config, {missing_dirs, RuleGroup}});
true -> ok
end,
case maps:is_key(dirs, RuleGroup) of
true ->
case maps:is_key(filter, RuleGroup) of
false -> throw({invalid_config, {missing_filter, RuleGroup}});
true -> ok
end;
false -> ok
end,
case maps:is_key(rules, RuleGroup) orelse maps:is_key(ruleset, RuleGroup) of
false -> throw({invalid_config, {missing_rules, RuleGroup}});
true -> ok
end.
-spec normalize(config()) -> config().
normalize(Config) when is_list(Config) ->
lists:map(fun do_normalize/1, Config).
@private
do_normalize(Config = #{src_dirs := Dirs}) ->
Rename ' ' key to ' dirs ' .
Config1 = maps:remove(src_dirs, Config),
Config1#{dirs => Dirs};
do_normalize(Config) ->
Config.
-spec dirs(Config::config() | map()) -> [string()].
dirs(Config) when is_list(Config) ->
lists:flatmap(fun dirs/1, Config);
dirs(_RuleGroup = #{dirs := Dirs}) ->
Dirs;
dirs(#{}) ->
[].
-spec ignore(config() | map()) -> [string()].
ignore(Config) when is_list(Config) ->
lists:flatmap(fun ignore/1, Config);
ignore(_RuleGroup = #{ignore := Ignore}) ->
lists:map(fun ignore_to_regexp/1, Ignore);
ignore(#{}) ->
[].
-spec filter(config() | map()) -> [string()].
filter(Config) when is_list(Config) ->
lists:flatmap(fun filter/1, Config);
filter(_RuleGroup = #{filter := Filter}) ->
Filter;
filter(#{}) ->
?DEFAULT_FILTER.
-spec files(RuleGroup::config() | map()) -> [elvis_file:file()] | undefined.
files(RuleGroup) when is_list(RuleGroup) ->
lists:map(fun files/1, RuleGroup);
files(_RuleGroup = #{files := Files}) ->
Files;
files(#{}) ->
undefined.
-spec rules(Rules::config() | map()) -> [string()] | undefined.
rules(Rules) when is_list(Rules) ->
lists:map(fun rules/1, Rules);
rules(#{rules := UserRules, ruleset := RuleSet}) ->
DefaultRules = elvis_rulesets:rules(RuleSet),
merge_rules(UserRules, DefaultRules);
rules(#{rules := Rules}) -> Rules;
rules(#{ruleset := RuleSet}) ->
elvis_rulesets:rules(RuleSet);
rules(#{}) ->
undefined.
-spec resolve_files(Config::config() | map(), Files::[elvis_file:file()]) ->
config() | map().
resolve_files(Config, Files) when is_list(Config) ->
Fun = fun(RuleGroup) -> resolve_files(RuleGroup, Files) end,
lists:map(Fun, Config);
resolve_files(RuleGroup, Files) ->
Filter = filter(RuleGroup),
Dirs = dirs(RuleGroup),
Ignore = ignore(RuleGroup),
FilteredFiles = elvis_file:filter_files(Files, Dirs, Filter, Ignore),
RuleGroup#{files => FilteredFiles}.
-spec resolve_files(map()) -> map().
resolve_files(RuleGroup = #{files := _Files}) ->
RuleGroup;
resolve_files(RuleGroup = #{dirs := Dirs}) ->
Filter = filter(RuleGroup),
Files = elvis_file:find_files(Dirs, Filter),
resolve_files(RuleGroup, Files).
-spec apply_to_files(Fun::fun(), Config::config() | map()) -> config() | map().
apply_to_files(Fun, Config) when is_list(Config) ->
ApplyFun = fun(RuleGroup) -> apply_to_files(Fun, RuleGroup) end,
lists:map(ApplyFun, Config);
apply_to_files(Fun, RuleGroup = #{files := Files}) ->
NewFiles = lists:map(Fun, Files),
RuleGroup#{files => NewFiles}.
list by taking advantage of the fact that erlang
-spec ignore_to_regexp(string() | atom()) -> string().
ignore_to_regexp(R) when is_list(R) ->
R;
ignore_to_regexp(A) when is_atom(A) ->
"/" ++ atom_to_list(A) ++ "\\.erl$".
-spec merge_rules(UserRules::list(), DefaultRules::list()) -> list().
merge_rules(UserRules, DefaultRules) ->
UnduplicatedRules =
lists:filter(
If any default rule is in UserRules it means the user
fun({FileName, RuleName}) ->
not is_rule_override(FileName, RuleName, UserRules);
({FileName, RuleName, _}) ->
not is_rule_override(FileName, RuleName, UserRules);
(_) -> false
end,
DefaultRules
),
OverrideRules =
lists:filter(
fun({_FileName, _RuleName, OverrideOptions}) ->
disable /= OverrideOptions;
(_) -> false end,
UserRules
),
UnduplicatedRules ++ OverrideRules.
-spec is_rule_override(FileName::atom(), RuleName::atom(), UserRules::list()) ->
boolean().
is_rule_override(FileName, RuleName, UserRules) ->
lists:any(
fun(UserRule) ->
case UserRule of
{FileName, RuleName, _} -> true;
_ -> false
end
end,
UserRules
).
|
8b01029f02aa6c5408316b1146804e2f6ab236f325307b91df70cd338b40f51e | MercuryTechnologies/moat | SumOfProductSpec.hs | module SumOfProductSpec where
import Common
import Data.Text (Text)
import Moat
import Test.Hspec
import Test.Hspec.Golden
import Prelude hiding (Enum)
data Enum
= DataCons0 {enumField0 :: Int, enumField1 :: Int}
| DataCons1 {enumField2 :: Text, enumField3 :: Text}
mobileGenWith
( defaultOptions
{ dataAnnotations = [Parcelize, Serializable],
dataInterfaces = [Parcelable],
dataProtocols = [OtherProtocol "CaseIterable", Hashable, Codable]
}
)
''Enum
spec :: Spec
spec =
describe "stays golden" $ do
let moduleName = "SumOfProductSpec"
it "swift" $
defaultGolden ("swiftEnum" <> moduleName) (showSwift @Enum)
it "kotlin" $
defaultGolden ("kotlinEnum" <> moduleName) (showKotlin @Enum)
| null | https://raw.githubusercontent.com/MercuryTechnologies/moat/0217e7abe6bb045e5ea4c33d5dae9d636d3e6159/test/SumOfProductSpec.hs | haskell | module SumOfProductSpec where
import Common
import Data.Text (Text)
import Moat
import Test.Hspec
import Test.Hspec.Golden
import Prelude hiding (Enum)
data Enum
= DataCons0 {enumField0 :: Int, enumField1 :: Int}
| DataCons1 {enumField2 :: Text, enumField3 :: Text}
mobileGenWith
( defaultOptions
{ dataAnnotations = [Parcelize, Serializable],
dataInterfaces = [Parcelable],
dataProtocols = [OtherProtocol "CaseIterable", Hashable, Codable]
}
)
''Enum
spec :: Spec
spec =
describe "stays golden" $ do
let moduleName = "SumOfProductSpec"
it "swift" $
defaultGolden ("swiftEnum" <> moduleName) (showSwift @Enum)
it "kotlin" $
defaultGolden ("kotlinEnum" <> moduleName) (showKotlin @Enum)
| |
c67e6c4126a58acc448ac8f556155b72c9ac6c0dc48fda1870de4f75f10536d6 | roosta/tincture | spec_test.cljs | (ns tincture.spec-test
(:require [cljs.test :refer-macros [deftest testing is]]
[tincture.spec :as sp]
[clojure.spec.alpha :as s]))
(s/def ::test-boolean boolean?)
(s/def ::test-pos-int pos-int?)
(deftest check-spec
(testing "Checking a spec, and check return value"
(is (sp/check-spec true ::test-boolean))
(is (= (sp/check-spec 1 ::test-pos-int) 1))
(try (sp/check-spec :test ::test-boolean)
(catch js/Error e
(is (= (.-message e)
"Invalid value"))))
(try (sp/check-spec -1 ::test-pos-int "test message")
(catch js/Error e
(is (= (.-message e)
"test message"))))))
(deftest email-spec
(testing "Passing emails through the :tincture.spec/email spec"
(is (s/valid? :tincture.spec/email ""))
(is (s/valid? :tincture.spec/email ""))
(is (not (s/valid? :tincture.spec/email "test")))
(is (not (s/valid? :tincture.spec/email "test@example")))
(is (not (s/valid? :tincture.spec/email "example.com")))
(is (not (s/valid? :tincture.spec/email "test.example.com")))
)
)
| null | https://raw.githubusercontent.com/roosta/tincture/587e68248dae09616942dc23bbd97cb9a1a4caa2/test/tincture/spec_test.cljs | clojure | (ns tincture.spec-test
(:require [cljs.test :refer-macros [deftest testing is]]
[tincture.spec :as sp]
[clojure.spec.alpha :as s]))
(s/def ::test-boolean boolean?)
(s/def ::test-pos-int pos-int?)
(deftest check-spec
(testing "Checking a spec, and check return value"
(is (sp/check-spec true ::test-boolean))
(is (= (sp/check-spec 1 ::test-pos-int) 1))
(try (sp/check-spec :test ::test-boolean)
(catch js/Error e
(is (= (.-message e)
"Invalid value"))))
(try (sp/check-spec -1 ::test-pos-int "test message")
(catch js/Error e
(is (= (.-message e)
"test message"))))))
(deftest email-spec
(testing "Passing emails through the :tincture.spec/email spec"
(is (s/valid? :tincture.spec/email ""))
(is (s/valid? :tincture.spec/email ""))
(is (not (s/valid? :tincture.spec/email "test")))
(is (not (s/valid? :tincture.spec/email "test@example")))
(is (not (s/valid? :tincture.spec/email "example.com")))
(is (not (s/valid? :tincture.spec/email "test.example.com")))
)
)
| |
80fe97a1c65581eb0decf8a12c1890711e44a83f746c40c450601632ce2986ba | parapluu/Concuerror | concuerror_deps.erl | %%%----------------------------------------------------------------------
Copyright ( c ) 2013 , < > ,
< >
and < > .
%%% All rights reserved.
%%%
This file is distributed under the Simplified BSD License .
%%% Details can be found in the LICENSE file.
%%%----------------------------------------------------------------------
Authors : < >
Description : Dependency relation for Erlang
%%%----------------------------------------------------------------------
-module(concuerror_deps).
-export([may_have_dependencies/1,
dependent/2,
lock_release_atom/0]).
-spec may_have_dependencies(concuerror_sched:transition()) -> boolean().
may_have_dependencies({_Lid, {error, _}, []}) -> false;
may_have_dependencies({_Lid, {Spawn, _}, []})
when Spawn =:= spawn; Spawn =:= spawn_link; Spawn =:= spawn_monitor;
Spawn =:= spawn_opt -> false;
may_have_dependencies({_Lid, {'receive', {unblocked, _, _}}, []}) -> false;
may_have_dependencies({_Lid, exited, []}) -> false;
may_have_dependencies(_Else) -> true.
-spec lock_release_atom() -> '_._concuerror_lock_release'.
lock_release_atom() -> '_._concuerror_lock_release'.
-define( ONLY_INITIALLY, true).
-define( SYMMETRIC, true).
-define( CHECK_MSG, true).
-define( ALLOW_SWAP, true).
-define(DONT_ALLOW_SWAP, false).
-define(ONLY_AFTER_SWAP, false).
-define( DONT_CHECK_MSG, false).
-spec dependent(concuerror_sched:transition(),
concuerror_sched:transition()) -> boolean().
dependent(A, B) ->
dependent(A, B, ?CHECK_MSG, ?ALLOW_SWAP).
%%==============================================================================
%% Instructions from the same process are always dependent
dependent({Lid, _Instr1, _Msgs1},
{Lid, _Instr2, _Msgs2}, ?ONLY_INITIALLY, ?ONLY_INITIALLY) ->
true;
%%==============================================================================
%% XXX: This should be fixed in sched:recent_dependency_cv and removed
dependent({_Lid1, _Instr1, _Msgs1},
{_Lid2, 'init', _Msgs2}, ?ONLY_INITIALLY, ?ONLY_INITIALLY) ->
false;
%%==============================================================================
%% Decisions depending on send and receive statements:
%%==============================================================================
%% Sending to the same process:
dependent({ Lid1, Instr1, PreMsgs1} = Trans1,
{ Lid2, Instr2, PreMsgs2} = Trans2,
?CHECK_MSG, AllowSwap) ->
ProcEvidence = [ { P , L } || { P , { _ M , L } } < - PreMsgs2 ] ,
%% Msgs2 = [{P, M} || {P, {M, _L}} <- PreMsgs2],
Msgs1 = add_missing_messages(Lid1 , Instr1 , PreMsgs1 , ProcEvidence ) ,
ProcEvidence1 = [{P, L, M} || {P, {_M, L, M}} <- PreMsgs1],
ProcEvidence2 = [{P, L, M} || {P, {_M, L, M}} <- PreMsgs2],
Msgs1 = add_missing_messages(Lid1, Instr1, PreMsgs1, ProcEvidence2),
Msgs2 = add_missing_messages(Lid2, Instr2, PreMsgs2, ProcEvidence1),
case Msgs1 =:= [] orelse Msgs2 =:= [] of
true -> dependent(Trans1, Trans2, ?DONT_CHECK_MSG, AllowSwap);
false ->
Lids1 = ordsets:from_list(orddict:fetch_keys(Msgs1)),
Lids2 = ordsets:from_list(orddict:fetch_keys(Msgs2)),
case ordsets:intersection(Lids1, Lids2) of
[] ->
dependent(Trans1, Trans2, ?DONT_CHECK_MSG, AllowSwap);
[Key] ->
%% XXX: Can be refined
case {orddict:fetch(Key, Msgs1), orddict:fetch(Key, Msgs2)} of
{[V1], [V2]} ->
LockReleaseAtom = lock_release_atom(),
V1 =/= LockReleaseAtom andalso V2 =/= LockReleaseAtom;
_Else -> true
end;
_ -> true %% XXX: Can be refined
end
end;
%%==============================================================================
%% Sending to an activated after clause depends on that receive's patterns OR
%% Sending the message that triggered a receive's 'had_after'
dependent({Lid1, Instr1, PreMsgs1} = Trans1,
{Lid2, {Receive, Info}, _Msgs2} = Trans2,
_CheckMsg, AllowSwap) when
Receive =:= 'after';
(Receive =:= 'receive' andalso
element(1, Info) =:= had_after) ->
ProcEvidence =
case Receive =:= 'after' of
true -> [{Lid2, element(2, Info), element(3, Info)}];
false -> []
end,
Msgs1 = add_missing_messages(Lid1, Instr1, PreMsgs1, ProcEvidence),
Dependent =
case orddict:find(Lid2, Msgs1) of
{ok, MsgsToLid2} ->
Fun =
case Receive of
'after' -> element(1, Info);
'receive' ->
Target = element(3, Info),
OLid = element(2, Info),
fun(X) -> X =:= Target andalso OLid =:= Lid1 end
end,
lists:any(Fun, MsgsToLid2);
error -> false
end,
Dependent orelse (AllowSwap andalso
dependent(Trans2, Trans1, ?CHECK_MSG, ?DONT_ALLOW_SWAP));
%%==============================================================================
%% Other instructions are not in race with receive or after, if not caught by
%% the message checking part.
dependent({_Lid1, { _Any, _Details1}, _Msgs1},
{_Lid2, {Receive, _Details2}, _Msgs2},
_CheckMsg, ?ONLY_AFTER_SWAP) when
Receive =:= 'after';
Receive =:= 'receive' ->
false;
%% Swapped version, as the message checking code can force a swap.
dependent({_Lid1, {Receive, _Details1}, _Msgs1},
{_Lid2, { _Any, _Details2}, _Msgs2},
_CheckMsg, ?ONLY_AFTER_SWAP) when
Receive =:= 'after';
Receive =:= 'receive' ->
false;
%%==============================================================================
%% From here onwards, we have taken care of messaging races.
%%==============================================================================
%% ETS operations live in their own small world.
dependent({_Lid1, {ets, Op1}, _Msgs1},
{_Lid2, {ets, Op2}, _Msgs2},
_CheckMsg, ?SYMMETRIC) ->
dependent_ets(Op1, Op2);
%%==============================================================================
%% Registering a table with the same name as an existing one.
dependent({_Lid1, { ets, { new, [_Table, Name, Options]}}, _Msgs1},
{_Lid2, {exit, {normal, {{_Heirs, Tables}, _Na, _Li, _Mo}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
NamedTables = [N || {_Lid, {ok, N}} <- Tables],
lists:member(named_table, Options) andalso
lists:member(Name, NamedTables);
%% Table owners exits race with any ets operation on the same table.
dependent({_Lid1, { ets, { _Op, [Table|_Rest]}}, _Msgs1},
{_Lid2, {exit, {normal, {{_Heirs, Tables}, _Na, _Li, _Mo}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
lists:keymember(Table, 1, Tables);
%% %% Covered by next
%% dependent({_Lid1, { ets, _Details1}, _Msgs1},
{ _ , { exit , _ Details2 } , _ Msgs2 } ,
_ CheckMsg , _ ) - >
%% false;
%%==============================================================================
%% No other operations race with ets operations.
dependent({_Lid1, { ets, _Details1}, _Msgs1},
{_Lid2, {_Any, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
%% Exits with heirs, links, monitors induce messages that create dependencies
%% XXX: Should be removed when tracking reversals accurately.
dependent({Lid1, {exit, {normal, {{Heirs1, _Tbls1}, _N1, L1, M1}}}, _Msgs1},
{Lid2, {exit, {normal, {{Heirs2, _Tbls2}, _N2, L2, M2}}}, _Msgs2},
_CheckMsg, ?SYMMETRIC) ->
lists:member(Lid1, Heirs2) orelse lists:member(Lid2, Heirs1) orelse
lists:member(Lid1, L2) orelse lists:member(Lid2, L1) orelse
lists:member(Lid1, M2) orelse lists:member(Lid2, M1);
%%==============================================================================
%% Registered processes:
%% Sending using name to a process that may exit and unregister.
dependent({_Lid1, {send, {TName, _TLid, _Msg}}, _Msgs1},
{_Lid2, {exit, {normal, {_Tables, {ok, TName}, _L, _M}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
dependent({_Lid1, {send, _Details1}, _Msgs1},
{_Lid2, {exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
Register and unregister have the same dependencies .
Use a unique value for the Pid to avoid checks there .
dependent({Lid, {unregister, RegName}, Msgs}, B, CheckMsg, AllowSwap) ->
dependent({Lid, {register, {RegName, make_ref()}}, Msgs}, B,
CheckMsg, AllowSwap);
dependent(A, {Lid, {unregister, RegName}, Msgs}, CheckMsg, AllowSwap) ->
dependent(A, {Lid, {register, {RegName, make_ref()}}, Msgs},
CheckMsg, AllowSwap);
%%==============================================================================
%% Send using name before process has registered itself (or after unregistering).
dependent({_Lid1, {register, {RegName, _TLid}}, _Msgs1},
{_Lid2, { send, {RegName, _Lid, _Msg}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
%% No other races between register and send.
dependent({_Lid1, {register, _Details1}, _Msgs1},
{_Lid2, { send, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
Two registers using the same name or the same process .
dependent({_Lid1, {register, {RegName1, TLid1}}, _Msgs1},
{_Lid2, {register, {RegName2, TLid2}}, _Msgs2},
_CheckMsg, ?SYMMETRIC) ->
RegName1 =:= RegName2 orelse TLid1 =:= TLid2;
%%==============================================================================
%% Register a process that may exit.
dependent({_Lid1, {register, {_RegName, TLid}}, _Msgs1},
{ TLid, { exit, {normal, _Info}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
%% Register for a name that might be in use.
dependent({_Lid1, {register, {Name, _TLid}}, _Msgs1},
{_Lid2, { exit, {normal, {_Tables, {ok, Name}, _L, _M}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
%% No other races between register and exit.
dependent({_Lid1, {register, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
Whereis using name before process has registered itself .
dependent({_Lid1, {register, {RegName, _TLid1}}, _Msgs1},
{_Lid2, { whereis, {RegName, _TLid2}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
No other races between register and whereis .
dependent({_Lid1, {register, _Details1}, _Msgs1},
{_Lid2, { whereis, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
%% Process alive and exits.
dependent({_Lid1, {is_process_alive, TLid}, _Msgs1},
{ TLid, { exit, {normal, _Info}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
%% No other races between is_process_alive and exit.
dependent({_Lid1, {is_process_alive, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
%% Process registered and exits.
dependent({_Lid1, {whereis, {Name, _TLid1}}, _Msgs1},
{_Lid2, { exit, {normal, {_Tables, {ok, Name}, _L, _M}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
No other races between whereis and exit .
dependent({_Lid1, {whereis, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
%% Demonitor/link/unlink and exit.
dependent({_Lid, {Linker, TLid}, _Msgs1},
{TLid, { exit, {normal, _Info}}, _Msgs2},
_CheckMsg, _AllowSwap)
when Linker =:= demonitor; Linker =:= link; Linker =:= unlink ->
true;
%% No other races between demonitor/link/unlink and exit.
dependent({_Lid1, {Linker, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap)
when Linker =:= demonitor; Linker =:= link; Linker =:= unlink ->
false;
%%==============================================================================
%% Depending on the order, monitor's Info is different.
dependent({_Lid, {monitor, {TLid, _MonRef}}, _Msgs1},
{TLid, { exit, {normal, _Info}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
dependent({_Lid1, {monitor, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
%% Trap exits flag and linked process exiting.
dependent({Lid1, {process_flag, {trap_exit, _Value, Links1}}, _Msgs1},
{Lid2, { exit, {normal, {_Tables, _N, Links2, _M}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
lists:member(Lid2, Links1) orelse lists:member(Lid1, Links2);
%% Trap exits flag and explicit exit signals.
dependent({ Lid1, {process_flag, {trap_exit, _Value, _Links1}}, _Msgs1},
{_Lid2, { exit_2, {TLid, _Reason}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
Lid1 =:= TLid;
%% No other races between setting a process flag and exiting.
dependent({_Lid1, {process_flag, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
%%==============================================================================
%% Setting a process_flag is not in race with linking. Happening together, they
%% can cause other races, however.
dependent({_Lid1, {process_flag, _Details1}, _Msgs1},
{_Lid2, {LinkOrUnlink, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap)
when LinkOrUnlink =:= link; LinkOrUnlink =:= unlink ->
false;
%%==============================================================================
%% Spawning is independent with everything else.
dependent({_Lid1, {Spawn, _Details1}, _Msgs1},
{_Lid2, { _Any, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap)
when Spawn =:= spawn; Spawn =:= spawn_link; Spawn =:= spawn_monitor;
Spawn =:= spawn_opt ->
false;
%%==============================================================================
Swap the two arguments if the test is not symmetric by itself .
dependent(TransitionA, TransitionB, _CheckMsg, ?ALLOW_SWAP) ->
dependent(TransitionB, TransitionA, ?CHECK_MSG, ?DONT_ALLOW_SWAP);
dependent(TransitionA, TransitionB, _CheckMsg, ?DONT_ALLOW_SWAP) ->
case independent(TransitionA, TransitionB) of
true -> false;
maybe ->
io:format("ALERT! Not certainly independent:\n ~p\n ~p\n",
[TransitionA, TransitionB]),
true
end.
%%==============================================================================
%%==============================================================================
-spec independent(concuerror_sched:transition(),
concuerror_sched:transition()) -> 'true' | 'maybe'.
independent({_Lid1, {Op1, _}, _Msgs1}, {_Lid2, {Op2, _}, _Msgs2}) ->
Independent =
[
{ monitor, demonitor},
{ monitor, send},
{ demonitor, send},
{ whereis, send},
{ link, send},
{ unlink, send},
{process_flag, send},
{process_flag, monitor},
{ unlink, monitor},
{ register, monitor},
{ whereis, unlink},
{ unlink, register},
{ whereis, monitor},
{ whereis, demonitor},
{ unlink, demonitor},
{ register, demonitor},
{process_flag, register},
{ whereis, is_process_alive},
{ demonitor, is_process_alive},
{ monitor, is_process_alive},
{ send, is_process_alive},
{ link, monitor}
],
%% XXX: This should probably be removed.
Solo = [send_after,exit_2],
case
%% Assuming that all the races of an instruction with another instance
%% of itself have already been caught.
Op1 =:= Op2
orelse lists:member({Op1, Op2},Independent)
orelse lists:member({Op2, Op1},Independent)
orelse lists:member(Op1, Solo)
orelse lists:member(Op2, Solo)
of
true -> true;
false -> maybe
end.
add_missing_messages(Lid, Instr, PreMsgs, ProcEvidence) ->
Msgs = [{P, M} || {P, {M, _L, _M}} <- PreMsgs],
case Instr of
{send, {_RegName, Lid2, Msg}} ->
add_missing_message(Lid2, Msg, Msgs);
{exit, _} ->
LMsg = {'EXIT', Lid, normal},
%% XXX: Dummy could be problematic
MMsg = {'DOWN', dummy, process, Lid, normal},
LAdder = fun(P, M) -> add_missing_message(P, LMsg, M) end,
MAdder = fun(P, M) -> add_missing_message(P, MMsg, M) end,
Fold =
fun({P, Links, Monitors}, Acc) ->
Acc1 =
case lists:member(Lid, Links) of
true -> LAdder(P, Acc);
false -> Acc
end,
Acc2 =
case lists:member(Lid, Monitors) of
true -> MAdder(P, Acc1);
false -> Acc1
end,
Acc2
end,
lists:foldl(Fold, Msgs, ProcEvidence);
{exit_2, {To, Msg}} ->
%% XXX: Too strong.
add_missing_message(To, Msg, Msgs);
_ -> Msgs
end.
%% XXX: Not accurate for monitor DOWN messages due to dummy
add_missing_message(Lid, Msg, Msgs) ->
try true = lists:member(Msg, orddict:fetch(Lid, Msgs)) of
_ -> Msgs
catch
_:_ -> orddict:append(Lid, Msg, Msgs)
end.
%% ETS table dependencies:
dependent_ets(Op1, Op2) ->
dependent_ets(Op1, Op2, ?ALLOW_SWAP).
%%==============================================================================
dependent_ets({MajorOp, [Tid1, Name1|_]}, {_, [Tid2, Name2|_]}, _AllowSwap)
when MajorOp =:= info; MajorOp =:= delete ->
(Tid1 =:= Tid2) orelse (Name1 =:= Name2);
%%==============================================================================
dependent_ets({insert, [T, _, Keys1, KP, Objects1, true]},
{insert, [T, _, Keys2, KP, Objects2, true]}, ?SYMMETRIC) ->
case ordsets:intersection(Keys1, Keys2) of
[] -> false;
Keys ->
Fold =
fun(_K, true) -> true;
(K, false) ->
lists:keyfind(K, KP, Objects1) =/=
lists:keyfind(K, KP, Objects2)
end,
lists:foldl(Fold, false, Keys)
end;
dependent_ets({insert, _Details1},
{insert, _Details2}, ?SYMMETRIC) ->
false;
%%==============================================================================
dependent_ets({insert_new, [_, _, _, _, _, false]},
{insert_new, [_, _, _, _, _, false]}, ?SYMMETRIC) ->
false;
dependent_ets({insert_new, [T, _, Keys1, KP, _Objects1, _Status1]},
{insert_new, [T, _, Keys2, KP, _Objects2, _Status2]},
?SYMMETRIC) ->
ordsets:intersection(Keys1, Keys2) =/= [];
dependent_ets({insert_new, _Details1},
{insert_new, _Details2}, ?SYMMETRIC) ->
false;
%%==============================================================================
dependent_ets({insert_new, [T, _, Keys1, KP, _Objects1, _Status1]},
{ insert, [T, _, Keys2, KP, _Objects2, true]},
_AllowSwap) ->
ordsets:intersection(Keys1, Keys2) =/= [];
dependent_ets({insert_new, _Details1},
{ insert, _Details2},
_AllowSwap) ->
false;
%%==============================================================================
dependent_ets({Insert, [T, _, Keys, _KP, _Objects1, true]},
{lookup, [T, _, K]}, _AllowSwap)
when Insert =:= insert; Insert =:= insert_new ->
ordsets:is_element(K, Keys);
dependent_ets({Insert, _Details1},
{lookup, _Details2}, _AllowSwap)
when Insert =:= insert; Insert =:= insert_new ->
false;
%%==============================================================================
dependent_ets({lookup, _Details1}, {lookup, _Details2}, ?SYMMETRIC) ->
false;
%%==============================================================================
dependent_ets({new, [_Tid1, Name, Options1]},
{new, [_Tid2, Name, Options2]}, ?SYMMETRIC) ->
lists:member(named_table, Options1) andalso
lists:member(named_table, Options2);
%%==============================================================================
dependent_ets({ new, _Details1}, {_Any, _Details2}, ?DONT_ALLOW_SWAP) ->
false;
dependent_ets({_Any, _Details1}, { new, _Details2}, ?DONT_ALLOW_SWAP) ->
false;
%%==============================================================================
dependent_ets(Op1, Op2, ?ALLOW_SWAP) ->
dependent_ets(Op2, Op1, ?DONT_ALLOW_SWAP);
dependent_ets(Op1, Op2, ?DONT_ALLOW_SWAP) ->
concuerror_log:log(3, "Not certainly independent (ETS):\n ~p\n ~p\n",
[Op1, Op2]),
true.
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/resources/old_source/concuerror_deps.erl | erlang | ----------------------------------------------------------------------
All rights reserved.
Details can be found in the LICENSE file.
----------------------------------------------------------------------
----------------------------------------------------------------------
==============================================================================
Instructions from the same process are always dependent
==============================================================================
XXX: This should be fixed in sched:recent_dependency_cv and removed
==============================================================================
Decisions depending on send and receive statements:
==============================================================================
Sending to the same process:
Msgs2 = [{P, M} || {P, {M, _L}} <- PreMsgs2],
XXX: Can be refined
XXX: Can be refined
==============================================================================
Sending to an activated after clause depends on that receive's patterns OR
Sending the message that triggered a receive's 'had_after'
==============================================================================
Other instructions are not in race with receive or after, if not caught by
the message checking part.
Swapped version, as the message checking code can force a swap.
==============================================================================
From here onwards, we have taken care of messaging races.
==============================================================================
ETS operations live in their own small world.
==============================================================================
Registering a table with the same name as an existing one.
Table owners exits race with any ets operation on the same table.
%% Covered by next
dependent({_Lid1, { ets, _Details1}, _Msgs1},
false;
==============================================================================
No other operations race with ets operations.
==============================================================================
Exits with heirs, links, monitors induce messages that create dependencies
XXX: Should be removed when tracking reversals accurately.
==============================================================================
Registered processes:
Sending using name to a process that may exit and unregister.
==============================================================================
==============================================================================
Send using name before process has registered itself (or after unregistering).
No other races between register and send.
==============================================================================
==============================================================================
Register a process that may exit.
Register for a name that might be in use.
No other races between register and exit.
==============================================================================
==============================================================================
Process alive and exits.
No other races between is_process_alive and exit.
==============================================================================
Process registered and exits.
==============================================================================
Demonitor/link/unlink and exit.
No other races between demonitor/link/unlink and exit.
==============================================================================
Depending on the order, monitor's Info is different.
==============================================================================
Trap exits flag and linked process exiting.
Trap exits flag and explicit exit signals.
No other races between setting a process flag and exiting.
==============================================================================
Setting a process_flag is not in race with linking. Happening together, they
can cause other races, however.
==============================================================================
Spawning is independent with everything else.
==============================================================================
==============================================================================
==============================================================================
XXX: This should probably be removed.
Assuming that all the races of an instruction with another instance
of itself have already been caught.
XXX: Dummy could be problematic
XXX: Too strong.
XXX: Not accurate for monitor DOWN messages due to dummy
ETS table dependencies:
==============================================================================
==============================================================================
==============================================================================
==============================================================================
==============================================================================
==============================================================================
==============================================================================
==============================================================================
============================================================================== | Copyright ( c ) 2013 , < > ,
< >
and < > .
This file is distributed under the Simplified BSD License .
Authors : < >
Description : Dependency relation for Erlang
-module(concuerror_deps).
-export([may_have_dependencies/1,
dependent/2,
lock_release_atom/0]).
-spec may_have_dependencies(concuerror_sched:transition()) -> boolean().
may_have_dependencies({_Lid, {error, _}, []}) -> false;
may_have_dependencies({_Lid, {Spawn, _}, []})
when Spawn =:= spawn; Spawn =:= spawn_link; Spawn =:= spawn_monitor;
Spawn =:= spawn_opt -> false;
may_have_dependencies({_Lid, {'receive', {unblocked, _, _}}, []}) -> false;
may_have_dependencies({_Lid, exited, []}) -> false;
may_have_dependencies(_Else) -> true.
-spec lock_release_atom() -> '_._concuerror_lock_release'.
lock_release_atom() -> '_._concuerror_lock_release'.
-define( ONLY_INITIALLY, true).
-define( SYMMETRIC, true).
-define( CHECK_MSG, true).
-define( ALLOW_SWAP, true).
-define(DONT_ALLOW_SWAP, false).
-define(ONLY_AFTER_SWAP, false).
-define( DONT_CHECK_MSG, false).
-spec dependent(concuerror_sched:transition(),
concuerror_sched:transition()) -> boolean().
dependent(A, B) ->
dependent(A, B, ?CHECK_MSG, ?ALLOW_SWAP).
dependent({Lid, _Instr1, _Msgs1},
{Lid, _Instr2, _Msgs2}, ?ONLY_INITIALLY, ?ONLY_INITIALLY) ->
true;
dependent({_Lid1, _Instr1, _Msgs1},
{_Lid2, 'init', _Msgs2}, ?ONLY_INITIALLY, ?ONLY_INITIALLY) ->
false;
dependent({ Lid1, Instr1, PreMsgs1} = Trans1,
{ Lid2, Instr2, PreMsgs2} = Trans2,
?CHECK_MSG, AllowSwap) ->
ProcEvidence = [ { P , L } || { P , { _ M , L } } < - PreMsgs2 ] ,
Msgs1 = add_missing_messages(Lid1 , Instr1 , PreMsgs1 , ProcEvidence ) ,
ProcEvidence1 = [{P, L, M} || {P, {_M, L, M}} <- PreMsgs1],
ProcEvidence2 = [{P, L, M} || {P, {_M, L, M}} <- PreMsgs2],
Msgs1 = add_missing_messages(Lid1, Instr1, PreMsgs1, ProcEvidence2),
Msgs2 = add_missing_messages(Lid2, Instr2, PreMsgs2, ProcEvidence1),
case Msgs1 =:= [] orelse Msgs2 =:= [] of
true -> dependent(Trans1, Trans2, ?DONT_CHECK_MSG, AllowSwap);
false ->
Lids1 = ordsets:from_list(orddict:fetch_keys(Msgs1)),
Lids2 = ordsets:from_list(orddict:fetch_keys(Msgs2)),
case ordsets:intersection(Lids1, Lids2) of
[] ->
dependent(Trans1, Trans2, ?DONT_CHECK_MSG, AllowSwap);
[Key] ->
case {orddict:fetch(Key, Msgs1), orddict:fetch(Key, Msgs2)} of
{[V1], [V2]} ->
LockReleaseAtom = lock_release_atom(),
V1 =/= LockReleaseAtom andalso V2 =/= LockReleaseAtom;
_Else -> true
end;
end
end;
dependent({Lid1, Instr1, PreMsgs1} = Trans1,
{Lid2, {Receive, Info}, _Msgs2} = Trans2,
_CheckMsg, AllowSwap) when
Receive =:= 'after';
(Receive =:= 'receive' andalso
element(1, Info) =:= had_after) ->
ProcEvidence =
case Receive =:= 'after' of
true -> [{Lid2, element(2, Info), element(3, Info)}];
false -> []
end,
Msgs1 = add_missing_messages(Lid1, Instr1, PreMsgs1, ProcEvidence),
Dependent =
case orddict:find(Lid2, Msgs1) of
{ok, MsgsToLid2} ->
Fun =
case Receive of
'after' -> element(1, Info);
'receive' ->
Target = element(3, Info),
OLid = element(2, Info),
fun(X) -> X =:= Target andalso OLid =:= Lid1 end
end,
lists:any(Fun, MsgsToLid2);
error -> false
end,
Dependent orelse (AllowSwap andalso
dependent(Trans2, Trans1, ?CHECK_MSG, ?DONT_ALLOW_SWAP));
dependent({_Lid1, { _Any, _Details1}, _Msgs1},
{_Lid2, {Receive, _Details2}, _Msgs2},
_CheckMsg, ?ONLY_AFTER_SWAP) when
Receive =:= 'after';
Receive =:= 'receive' ->
false;
dependent({_Lid1, {Receive, _Details1}, _Msgs1},
{_Lid2, { _Any, _Details2}, _Msgs2},
_CheckMsg, ?ONLY_AFTER_SWAP) when
Receive =:= 'after';
Receive =:= 'receive' ->
false;
dependent({_Lid1, {ets, Op1}, _Msgs1},
{_Lid2, {ets, Op2}, _Msgs2},
_CheckMsg, ?SYMMETRIC) ->
dependent_ets(Op1, Op2);
dependent({_Lid1, { ets, { new, [_Table, Name, Options]}}, _Msgs1},
{_Lid2, {exit, {normal, {{_Heirs, Tables}, _Na, _Li, _Mo}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
NamedTables = [N || {_Lid, {ok, N}} <- Tables],
lists:member(named_table, Options) andalso
lists:member(Name, NamedTables);
dependent({_Lid1, { ets, { _Op, [Table|_Rest]}}, _Msgs1},
{_Lid2, {exit, {normal, {{_Heirs, Tables}, _Na, _Li, _Mo}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
lists:keymember(Table, 1, Tables);
{ _ , { exit , _ Details2 } , _ Msgs2 } ,
_ CheckMsg , _ ) - >
dependent({_Lid1, { ets, _Details1}, _Msgs1},
{_Lid2, {_Any, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
dependent({Lid1, {exit, {normal, {{Heirs1, _Tbls1}, _N1, L1, M1}}}, _Msgs1},
{Lid2, {exit, {normal, {{Heirs2, _Tbls2}, _N2, L2, M2}}}, _Msgs2},
_CheckMsg, ?SYMMETRIC) ->
lists:member(Lid1, Heirs2) orelse lists:member(Lid2, Heirs1) orelse
lists:member(Lid1, L2) orelse lists:member(Lid2, L1) orelse
lists:member(Lid1, M2) orelse lists:member(Lid2, M1);
dependent({_Lid1, {send, {TName, _TLid, _Msg}}, _Msgs1},
{_Lid2, {exit, {normal, {_Tables, {ok, TName}, _L, _M}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
dependent({_Lid1, {send, _Details1}, _Msgs1},
{_Lid2, {exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
Register and unregister have the same dependencies .
Use a unique value for the Pid to avoid checks there .
dependent({Lid, {unregister, RegName}, Msgs}, B, CheckMsg, AllowSwap) ->
dependent({Lid, {register, {RegName, make_ref()}}, Msgs}, B,
CheckMsg, AllowSwap);
dependent(A, {Lid, {unregister, RegName}, Msgs}, CheckMsg, AllowSwap) ->
dependent(A, {Lid, {register, {RegName, make_ref()}}, Msgs},
CheckMsg, AllowSwap);
dependent({_Lid1, {register, {RegName, _TLid}}, _Msgs1},
{_Lid2, { send, {RegName, _Lid, _Msg}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
dependent({_Lid1, {register, _Details1}, _Msgs1},
{_Lid2, { send, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
Two registers using the same name or the same process .
dependent({_Lid1, {register, {RegName1, TLid1}}, _Msgs1},
{_Lid2, {register, {RegName2, TLid2}}, _Msgs2},
_CheckMsg, ?SYMMETRIC) ->
RegName1 =:= RegName2 orelse TLid1 =:= TLid2;
dependent({_Lid1, {register, {_RegName, TLid}}, _Msgs1},
{ TLid, { exit, {normal, _Info}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
dependent({_Lid1, {register, {Name, _TLid}}, _Msgs1},
{_Lid2, { exit, {normal, {_Tables, {ok, Name}, _L, _M}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
dependent({_Lid1, {register, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
Whereis using name before process has registered itself .
dependent({_Lid1, {register, {RegName, _TLid1}}, _Msgs1},
{_Lid2, { whereis, {RegName, _TLid2}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
No other races between register and whereis .
dependent({_Lid1, {register, _Details1}, _Msgs1},
{_Lid2, { whereis, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
dependent({_Lid1, {is_process_alive, TLid}, _Msgs1},
{ TLid, { exit, {normal, _Info}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
dependent({_Lid1, {is_process_alive, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
dependent({_Lid1, {whereis, {Name, _TLid1}}, _Msgs1},
{_Lid2, { exit, {normal, {_Tables, {ok, Name}, _L, _M}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
No other races between whereis and exit .
dependent({_Lid1, {whereis, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
dependent({_Lid, {Linker, TLid}, _Msgs1},
{TLid, { exit, {normal, _Info}}, _Msgs2},
_CheckMsg, _AllowSwap)
when Linker =:= demonitor; Linker =:= link; Linker =:= unlink ->
true;
dependent({_Lid1, {Linker, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap)
when Linker =:= demonitor; Linker =:= link; Linker =:= unlink ->
false;
dependent({_Lid, {monitor, {TLid, _MonRef}}, _Msgs1},
{TLid, { exit, {normal, _Info}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
true;
dependent({_Lid1, {monitor, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
dependent({Lid1, {process_flag, {trap_exit, _Value, Links1}}, _Msgs1},
{Lid2, { exit, {normal, {_Tables, _N, Links2, _M}}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
lists:member(Lid2, Links1) orelse lists:member(Lid1, Links2);
dependent({ Lid1, {process_flag, {trap_exit, _Value, _Links1}}, _Msgs1},
{_Lid2, { exit_2, {TLid, _Reason}}, _Msgs2},
_CheckMsg, _AllowSwap) ->
Lid1 =:= TLid;
dependent({_Lid1, {process_flag, _Details1}, _Msgs1},
{_Lid2, { exit, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap) ->
false;
dependent({_Lid1, {process_flag, _Details1}, _Msgs1},
{_Lid2, {LinkOrUnlink, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap)
when LinkOrUnlink =:= link; LinkOrUnlink =:= unlink ->
false;
dependent({_Lid1, {Spawn, _Details1}, _Msgs1},
{_Lid2, { _Any, _Details2}, _Msgs2},
_CheckMsg, _AllowSwap)
when Spawn =:= spawn; Spawn =:= spawn_link; Spawn =:= spawn_monitor;
Spawn =:= spawn_opt ->
false;
Swap the two arguments if the test is not symmetric by itself .
dependent(TransitionA, TransitionB, _CheckMsg, ?ALLOW_SWAP) ->
dependent(TransitionB, TransitionA, ?CHECK_MSG, ?DONT_ALLOW_SWAP);
dependent(TransitionA, TransitionB, _CheckMsg, ?DONT_ALLOW_SWAP) ->
case independent(TransitionA, TransitionB) of
true -> false;
maybe ->
io:format("ALERT! Not certainly independent:\n ~p\n ~p\n",
[TransitionA, TransitionB]),
true
end.
-spec independent(concuerror_sched:transition(),
concuerror_sched:transition()) -> 'true' | 'maybe'.
independent({_Lid1, {Op1, _}, _Msgs1}, {_Lid2, {Op2, _}, _Msgs2}) ->
Independent =
[
{ monitor, demonitor},
{ monitor, send},
{ demonitor, send},
{ whereis, send},
{ link, send},
{ unlink, send},
{process_flag, send},
{process_flag, monitor},
{ unlink, monitor},
{ register, monitor},
{ whereis, unlink},
{ unlink, register},
{ whereis, monitor},
{ whereis, demonitor},
{ unlink, demonitor},
{ register, demonitor},
{process_flag, register},
{ whereis, is_process_alive},
{ demonitor, is_process_alive},
{ monitor, is_process_alive},
{ send, is_process_alive},
{ link, monitor}
],
Solo = [send_after,exit_2],
case
Op1 =:= Op2
orelse lists:member({Op1, Op2},Independent)
orelse lists:member({Op2, Op1},Independent)
orelse lists:member(Op1, Solo)
orelse lists:member(Op2, Solo)
of
true -> true;
false -> maybe
end.
add_missing_messages(Lid, Instr, PreMsgs, ProcEvidence) ->
Msgs = [{P, M} || {P, {M, _L, _M}} <- PreMsgs],
case Instr of
{send, {_RegName, Lid2, Msg}} ->
add_missing_message(Lid2, Msg, Msgs);
{exit, _} ->
LMsg = {'EXIT', Lid, normal},
MMsg = {'DOWN', dummy, process, Lid, normal},
LAdder = fun(P, M) -> add_missing_message(P, LMsg, M) end,
MAdder = fun(P, M) -> add_missing_message(P, MMsg, M) end,
Fold =
fun({P, Links, Monitors}, Acc) ->
Acc1 =
case lists:member(Lid, Links) of
true -> LAdder(P, Acc);
false -> Acc
end,
Acc2 =
case lists:member(Lid, Monitors) of
true -> MAdder(P, Acc1);
false -> Acc1
end,
Acc2
end,
lists:foldl(Fold, Msgs, ProcEvidence);
{exit_2, {To, Msg}} ->
add_missing_message(To, Msg, Msgs);
_ -> Msgs
end.
add_missing_message(Lid, Msg, Msgs) ->
try true = lists:member(Msg, orddict:fetch(Lid, Msgs)) of
_ -> Msgs
catch
_:_ -> orddict:append(Lid, Msg, Msgs)
end.
dependent_ets(Op1, Op2) ->
dependent_ets(Op1, Op2, ?ALLOW_SWAP).
dependent_ets({MajorOp, [Tid1, Name1|_]}, {_, [Tid2, Name2|_]}, _AllowSwap)
when MajorOp =:= info; MajorOp =:= delete ->
(Tid1 =:= Tid2) orelse (Name1 =:= Name2);
dependent_ets({insert, [T, _, Keys1, KP, Objects1, true]},
{insert, [T, _, Keys2, KP, Objects2, true]}, ?SYMMETRIC) ->
case ordsets:intersection(Keys1, Keys2) of
[] -> false;
Keys ->
Fold =
fun(_K, true) -> true;
(K, false) ->
lists:keyfind(K, KP, Objects1) =/=
lists:keyfind(K, KP, Objects2)
end,
lists:foldl(Fold, false, Keys)
end;
dependent_ets({insert, _Details1},
{insert, _Details2}, ?SYMMETRIC) ->
false;
dependent_ets({insert_new, [_, _, _, _, _, false]},
{insert_new, [_, _, _, _, _, false]}, ?SYMMETRIC) ->
false;
dependent_ets({insert_new, [T, _, Keys1, KP, _Objects1, _Status1]},
{insert_new, [T, _, Keys2, KP, _Objects2, _Status2]},
?SYMMETRIC) ->
ordsets:intersection(Keys1, Keys2) =/= [];
dependent_ets({insert_new, _Details1},
{insert_new, _Details2}, ?SYMMETRIC) ->
false;
dependent_ets({insert_new, [T, _, Keys1, KP, _Objects1, _Status1]},
{ insert, [T, _, Keys2, KP, _Objects2, true]},
_AllowSwap) ->
ordsets:intersection(Keys1, Keys2) =/= [];
dependent_ets({insert_new, _Details1},
{ insert, _Details2},
_AllowSwap) ->
false;
dependent_ets({Insert, [T, _, Keys, _KP, _Objects1, true]},
{lookup, [T, _, K]}, _AllowSwap)
when Insert =:= insert; Insert =:= insert_new ->
ordsets:is_element(K, Keys);
dependent_ets({Insert, _Details1},
{lookup, _Details2}, _AllowSwap)
when Insert =:= insert; Insert =:= insert_new ->
false;
dependent_ets({lookup, _Details1}, {lookup, _Details2}, ?SYMMETRIC) ->
false;
dependent_ets({new, [_Tid1, Name, Options1]},
{new, [_Tid2, Name, Options2]}, ?SYMMETRIC) ->
lists:member(named_table, Options1) andalso
lists:member(named_table, Options2);
dependent_ets({ new, _Details1}, {_Any, _Details2}, ?DONT_ALLOW_SWAP) ->
false;
dependent_ets({_Any, _Details1}, { new, _Details2}, ?DONT_ALLOW_SWAP) ->
false;
dependent_ets(Op1, Op2, ?ALLOW_SWAP) ->
dependent_ets(Op2, Op1, ?DONT_ALLOW_SWAP);
dependent_ets(Op1, Op2, ?DONT_ALLOW_SWAP) ->
concuerror_log:log(3, "Not certainly independent (ETS):\n ~p\n ~p\n",
[Op1, Op2]),
true.
|
d249ba128ba46e4a119b2a01d54d889fc42e16db12fbc2ec2aaa0a11b8317d13 | sunshineclt/Racket-Helper | 4-SICP2.36.rkt | #lang racket
(define (accumulate op init seq)
(if (null? seq)
init
(op (car seq) (accumulate op init (cdr seq)))))
(define (accumulate-n op init seqs)
(if (null? seqs)
'()
(cons (accumulate op init (map (lambda (s) (if(null? s)'()(car s))) seqs))
(if(null? (cdar seqs))
'()
(accumulate-n op init (map cdr seqs))))))
(define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12)))
(display (accumulate-n + 10 s)) (newline)
(display (accumulate-n * 1 s)) (newline)
(display (accumulate-n cons '() s)) (newline)
(display "******") (newline)
(define (myloop)
(let ((lst (read)))
(if (eq? lst eof)
(void)
(begin (display (accumulate-n + 0 lst)) (newline)
(display (accumulate-n cons '(a) lst)) (newline)
(myloop)))))
(myloop) | null | https://raw.githubusercontent.com/sunshineclt/Racket-Helper/bf85f38dd8d084db68265bb98d8c38bada6494ec/%E5%BE%90%E7%8E%89%E9%BA%9F/%E4%BD%9C%E4%B8%9A3/4-SICP2.36.rkt | racket | #lang racket
(define (accumulate op init seq)
(if (null? seq)
init
(op (car seq) (accumulate op init (cdr seq)))))
(define (accumulate-n op init seqs)
(if (null? seqs)
'()
(cons (accumulate op init (map (lambda (s) (if(null? s)'()(car s))) seqs))
(if(null? (cdar seqs))
'()
(accumulate-n op init (map cdr seqs))))))
(define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12)))
(display (accumulate-n + 10 s)) (newline)
(display (accumulate-n * 1 s)) (newline)
(display (accumulate-n cons '() s)) (newline)
(display "******") (newline)
(define (myloop)
(let ((lst (read)))
(if (eq? lst eof)
(void)
(begin (display (accumulate-n + 0 lst)) (newline)
(display (accumulate-n cons '(a) lst)) (newline)
(myloop)))))
(myloop) | |
a60734a039b1d0671ae5f1bf3ea240fb96805757376bf7157df69f2714ffe598 | faber-lang/faber | ParseSpec.hs | module ParseSpec (spec) where
import Operators
import Parse
import Test.Hspec
-- helpers
parse :: String -> Expr
parse s = case parseCode "" code of
Left (ParseError err) -> error err
Right t -> destruct t
where
code = "name main = " ++ s
destruct [Name (NameDef _ [] body [])] = body
parseTy :: String -> TypeScheme
parseTy s = case parseCode "" code of
Left (ParseError err) -> error err
Right t -> destruct t
where
code = "name main :: " ++ s
destruct [Name (TypeAnnot _ body)] = body
add :: Expr -> Expr -> Expr
add = BinaryOp Add
mul :: Expr -> Expr -> Expr
mul = BinaryOp Mul
pos :: Expr -> Expr
pos = SingleOp Positive
neg :: Expr -> Expr
neg = SingleOp Negative
int :: Int -> Expr
int = Integer
var :: String -> Expr
var = Variable
-- tests
spec :: Spec
spec = do
describe "skip" $ do
it "skip spaces" $ do
parse "24 " `shouldBe` int 24
parse " 2 + 5 " `shouldBe` int 2 `add` int 5
parse "- 4" `shouldBe` neg (int 4)
parse " ( 24 + 12 )" `shouldBe` int 24 `add` int 12
parse "\\a b c => 1+a*3 " `shouldBe` Lambda ["a", "b", "c"] (int 1 `add` (var "a" `mul` int 3))
parse "( 1 ,2 ,3 ) " `shouldBe` Tuple [int 1, int 2, int 3]
it "skip comments" $ do
parse "24 /* comment */ + 23" `shouldBe` int 24 `add` int 23
parse "1+ /* comment */ (/*comment*/2+3)" `shouldBe` int 1 `add` (int 2 `add` int 3)
parse "\\abc=>\n//comment\n\\x//comment2\n=>/*comment*/x*abc" `shouldBe` Lambda ["abc"] (Lambda ["x"] (var "x" `mul` var "abc"))
describe "expression" $ do
it "parse integers" $ do
parse "1" `shouldBe` int 1
parse "24" `shouldBe` int 24
parse "312" `shouldBe` int 312
it "parse variables" $ do
parse "a" `shouldBe` var "a"
parse "abc" `shouldBe` var "abc"
parse "x1" `shouldBe` var "x1"
it "parse binary operators" $ do
parse "2+5" `shouldBe` int 2 `add` int 5
parse "12*35" `shouldBe` int 12 `mul` int 35
it "binop precedence" $ do
parse "2+5*10" `shouldBe` int 2 `add` (int 5 `mul` int 10)
parse "1*2+3" `shouldBe` (int 1 `mul` int 2) `add` int 3
parse "2+5*10+3" `shouldBe` (int 2 `add` (int 5 `mul` int 10)) `add` int 3
it "binop associativity" $ do
parse "1+2+3+4+5" `shouldBe` (((int 1 `add` int 2) `add` int 3) `add` int 4) `add` int 5
parse "1*2*3*4*5" `shouldBe` (((int 1 `mul` int 2) `mul` int 3) `mul` int 4) `mul` int 5
it "parse single operators" $ do
parse "+5" `shouldBe` pos (int 5)
parse "-4" `shouldBe` neg (int 4)
parse "-x" `shouldBe` neg (var "x")
it "parse parentheses" $ do
parse "1+(2+3)" `shouldBe` int 1 `add` (int 2 `add` int 3)
parse "3*(4+5)" `shouldBe` int 3 `mul` (int 4 `add` int 5)
parse "(12)" `shouldBe` int 12
parse "(24+12)" `shouldBe` int 24 `add` int 12
parse "3*((4+5)*6)" `shouldBe` int 3 `mul` ((int 4 `add` int 5) `mul` int 6)
it "parse lambdas" $ do
parse "\\x=>x" `shouldBe` Lambda ["x"] (var "x")
parse "\\a b c=>1+a*3" `shouldBe` Lambda ["a", "b", "c"] (int 1 `add` (var "a" `mul` int 3))
parse "\\abc=>\\x=>x*abc" `shouldBe` Lambda ["abc"] (Lambda ["x"] (var "x" `mul` var "abc"))
it "parse tuples" $ do
parse "(1,2,3)" `shouldBe` Tuple [int 1, int 2, int 3]
parse "(1+2,3+4)" `shouldBe` Tuple [int 1 `add` int 2, int 3 `add` int 4]
parse "(0,)" `shouldBe` Tuple [int 0]
parse "()" `shouldBe` Tuple []
it "parse let-in" $ do
parse "let a = 1 in a" `shouldBe` LetIn [NameDef "a" [] (int 1) []] (var "a")
parse "let\n - a = 1\n - b = 2 in a" `shouldBe` LetIn [NameDef "a" [] (int 1) [], NameDef "b" [] (int 2) []] (var "a")
it "parse nested let-in" $ do
parse "let a = 1 in let b = 1 in a + b" `shouldBe` LetIn [NameDef "a" [] (int 1) []] (LetIn [NameDef "b" [] (int 1) []] (var "a" `add` var "b"))
it "parse let-in with where clause" $ do
parse "let a = b where b = 1 in a" `shouldBe` LetIn [NameDef "a" [] (var "b") [NameDef "b" [] (int 1) []]] (var "a")
it "parse if-then-else" $ do
parse "if 1 then a + 1 else b + 1" `shouldBe` If (int 1) (var "a" `add` int 1) (var "b" `add` int 1)
parse "if 1 then if 0 then 1 else 2 else if 1 then 1 else 2" `shouldBe` If (int 1) (If (int 0) (int 1) (int 2)) (If (int 1) (int 1) (int 2))
describe "type" $ do
it "parse type identifiers" $ do
parseTy "Int" `shouldBe` Forall [] (Ident "Int")
parseTy "if" `shouldBe` Forall [] (Ident "if")
it "parse function types" $ do
parseTy "a -> b" `shouldBe` Forall [] (Function (Ident "a") (Ident "b"))
parseTy "a -> a -> a" `shouldBe` Forall [] (Function (Ident "a") (Function (Ident "a") (Ident "a")))
it "parse product types" $ do
parseTy "(a, b)" `shouldBe` Forall [] (Product [Ident "a", Ident "b"])
parseTy "(a,)" `shouldBe` Forall [] (Product [Ident "a"])
parseTy "()" `shouldBe` Forall [] (Product [])
it "parse parentheses" $ do
parseTy "(a -> b) -> c" `shouldBe` Forall [] (Function (Function (Ident "a") (Ident "b")) (Ident "c"))
parseTy "(a)" `shouldBe` Forall [] (Ident "a")
it "parse quantifiers" $ do
parseTy "forall a. a -> a" `shouldBe` Forall ["a"] (Function (Ident "a") (Ident "a"))
parseTy "forall a b c. a" `shouldBe` Forall ["a", "b", "c"] (Ident "a")
describe "definition" $ do
it "parse simple name definitions" $ do
parseCode "" "name def x y = x + y\nname main = 1" `shouldBe` Right [Name (NameDef "def" ["x", "y"] (add (var "x") (var "y")) []), Name (NameDef "main" [] (int 1) [])]
it "parse name definitions with where" $ do
parseCode "" "name def x = y where y = x" `shouldBe` Right [Name (NameDef "def" ["x"] (var "y") [NameDef "y" [] (var "x") []])]
parseCode "" "name def x = y where\n - y = x\n - z = x" `shouldBe` Right [Name (NameDef "def" ["x"] (var "y") [NameDef "y" [] (var "x") [], NameDef "z" [] (var "x") []])]
it "parse type annotation syntax" $ do
parseCode "" "name a :: Int" `shouldBe` Right [Name $ TypeAnnot "a" $ Forall [] $ Ident "Int"]
parseCode "" "name a = f where\n- f :: Int\n- f = 1" `shouldBe` Right [Name $ NameDef "a" [] (var "f") [TypeAnnot "f" (Forall [] $ Ident "Int"), NameDef "f" [] (int 1) []]]
| null | https://raw.githubusercontent.com/faber-lang/faber/d022f52b22f209f1f10609949495b689e886c75f/test/ParseSpec.hs | haskell | helpers
tests | module ParseSpec (spec) where
import Operators
import Parse
import Test.Hspec
parse :: String -> Expr
parse s = case parseCode "" code of
Left (ParseError err) -> error err
Right t -> destruct t
where
code = "name main = " ++ s
destruct [Name (NameDef _ [] body [])] = body
parseTy :: String -> TypeScheme
parseTy s = case parseCode "" code of
Left (ParseError err) -> error err
Right t -> destruct t
where
code = "name main :: " ++ s
destruct [Name (TypeAnnot _ body)] = body
add :: Expr -> Expr -> Expr
add = BinaryOp Add
mul :: Expr -> Expr -> Expr
mul = BinaryOp Mul
pos :: Expr -> Expr
pos = SingleOp Positive
neg :: Expr -> Expr
neg = SingleOp Negative
int :: Int -> Expr
int = Integer
var :: String -> Expr
var = Variable
spec :: Spec
spec = do
describe "skip" $ do
it "skip spaces" $ do
parse "24 " `shouldBe` int 24
parse " 2 + 5 " `shouldBe` int 2 `add` int 5
parse "- 4" `shouldBe` neg (int 4)
parse " ( 24 + 12 )" `shouldBe` int 24 `add` int 12
parse "\\a b c => 1+a*3 " `shouldBe` Lambda ["a", "b", "c"] (int 1 `add` (var "a" `mul` int 3))
parse "( 1 ,2 ,3 ) " `shouldBe` Tuple [int 1, int 2, int 3]
it "skip comments" $ do
parse "24 /* comment */ + 23" `shouldBe` int 24 `add` int 23
parse "1+ /* comment */ (/*comment*/2+3)" `shouldBe` int 1 `add` (int 2 `add` int 3)
parse "\\abc=>\n//comment\n\\x//comment2\n=>/*comment*/x*abc" `shouldBe` Lambda ["abc"] (Lambda ["x"] (var "x" `mul` var "abc"))
describe "expression" $ do
it "parse integers" $ do
parse "1" `shouldBe` int 1
parse "24" `shouldBe` int 24
parse "312" `shouldBe` int 312
it "parse variables" $ do
parse "a" `shouldBe` var "a"
parse "abc" `shouldBe` var "abc"
parse "x1" `shouldBe` var "x1"
it "parse binary operators" $ do
parse "2+5" `shouldBe` int 2 `add` int 5
parse "12*35" `shouldBe` int 12 `mul` int 35
it "binop precedence" $ do
parse "2+5*10" `shouldBe` int 2 `add` (int 5 `mul` int 10)
parse "1*2+3" `shouldBe` (int 1 `mul` int 2) `add` int 3
parse "2+5*10+3" `shouldBe` (int 2 `add` (int 5 `mul` int 10)) `add` int 3
it "binop associativity" $ do
parse "1+2+3+4+5" `shouldBe` (((int 1 `add` int 2) `add` int 3) `add` int 4) `add` int 5
parse "1*2*3*4*5" `shouldBe` (((int 1 `mul` int 2) `mul` int 3) `mul` int 4) `mul` int 5
it "parse single operators" $ do
parse "+5" `shouldBe` pos (int 5)
parse "-4" `shouldBe` neg (int 4)
parse "-x" `shouldBe` neg (var "x")
it "parse parentheses" $ do
parse "1+(2+3)" `shouldBe` int 1 `add` (int 2 `add` int 3)
parse "3*(4+5)" `shouldBe` int 3 `mul` (int 4 `add` int 5)
parse "(12)" `shouldBe` int 12
parse "(24+12)" `shouldBe` int 24 `add` int 12
parse "3*((4+5)*6)" `shouldBe` int 3 `mul` ((int 4 `add` int 5) `mul` int 6)
it "parse lambdas" $ do
parse "\\x=>x" `shouldBe` Lambda ["x"] (var "x")
parse "\\a b c=>1+a*3" `shouldBe` Lambda ["a", "b", "c"] (int 1 `add` (var "a" `mul` int 3))
parse "\\abc=>\\x=>x*abc" `shouldBe` Lambda ["abc"] (Lambda ["x"] (var "x" `mul` var "abc"))
it "parse tuples" $ do
parse "(1,2,3)" `shouldBe` Tuple [int 1, int 2, int 3]
parse "(1+2,3+4)" `shouldBe` Tuple [int 1 `add` int 2, int 3 `add` int 4]
parse "(0,)" `shouldBe` Tuple [int 0]
parse "()" `shouldBe` Tuple []
it "parse let-in" $ do
parse "let a = 1 in a" `shouldBe` LetIn [NameDef "a" [] (int 1) []] (var "a")
parse "let\n - a = 1\n - b = 2 in a" `shouldBe` LetIn [NameDef "a" [] (int 1) [], NameDef "b" [] (int 2) []] (var "a")
it "parse nested let-in" $ do
parse "let a = 1 in let b = 1 in a + b" `shouldBe` LetIn [NameDef "a" [] (int 1) []] (LetIn [NameDef "b" [] (int 1) []] (var "a" `add` var "b"))
it "parse let-in with where clause" $ do
parse "let a = b where b = 1 in a" `shouldBe` LetIn [NameDef "a" [] (var "b") [NameDef "b" [] (int 1) []]] (var "a")
it "parse if-then-else" $ do
parse "if 1 then a + 1 else b + 1" `shouldBe` If (int 1) (var "a" `add` int 1) (var "b" `add` int 1)
parse "if 1 then if 0 then 1 else 2 else if 1 then 1 else 2" `shouldBe` If (int 1) (If (int 0) (int 1) (int 2)) (If (int 1) (int 1) (int 2))
describe "type" $ do
it "parse type identifiers" $ do
parseTy "Int" `shouldBe` Forall [] (Ident "Int")
parseTy "if" `shouldBe` Forall [] (Ident "if")
it "parse function types" $ do
parseTy "a -> b" `shouldBe` Forall [] (Function (Ident "a") (Ident "b"))
parseTy "a -> a -> a" `shouldBe` Forall [] (Function (Ident "a") (Function (Ident "a") (Ident "a")))
it "parse product types" $ do
parseTy "(a, b)" `shouldBe` Forall [] (Product [Ident "a", Ident "b"])
parseTy "(a,)" `shouldBe` Forall [] (Product [Ident "a"])
parseTy "()" `shouldBe` Forall [] (Product [])
it "parse parentheses" $ do
parseTy "(a -> b) -> c" `shouldBe` Forall [] (Function (Function (Ident "a") (Ident "b")) (Ident "c"))
parseTy "(a)" `shouldBe` Forall [] (Ident "a")
it "parse quantifiers" $ do
parseTy "forall a. a -> a" `shouldBe` Forall ["a"] (Function (Ident "a") (Ident "a"))
parseTy "forall a b c. a" `shouldBe` Forall ["a", "b", "c"] (Ident "a")
describe "definition" $ do
it "parse simple name definitions" $ do
parseCode "" "name def x y = x + y\nname main = 1" `shouldBe` Right [Name (NameDef "def" ["x", "y"] (add (var "x") (var "y")) []), Name (NameDef "main" [] (int 1) [])]
it "parse name definitions with where" $ do
parseCode "" "name def x = y where y = x" `shouldBe` Right [Name (NameDef "def" ["x"] (var "y") [NameDef "y" [] (var "x") []])]
parseCode "" "name def x = y where\n - y = x\n - z = x" `shouldBe` Right [Name (NameDef "def" ["x"] (var "y") [NameDef "y" [] (var "x") [], NameDef "z" [] (var "x") []])]
it "parse type annotation syntax" $ do
parseCode "" "name a :: Int" `shouldBe` Right [Name $ TypeAnnot "a" $ Forall [] $ Ident "Int"]
parseCode "" "name a = f where\n- f :: Int\n- f = 1" `shouldBe` Right [Name $ NameDef "a" [] (var "f") [TypeAnnot "f" (Forall [] $ Ident "Int"), NameDef "f" [] (int 1) []]]
|
7b0abad1b9fd0e8b293ee55957138a2da5b1960fae234cfdd966843a4febe5ef | babashka/process | quickdoc.clj | (ns quickdoc
(:require [pod.borkdude.clj-kondo :as clj-kondo]))
(defn quickdoc [{:keys [branch outfile
github/repo]
:or {branch "main"
outfile "API.md"}}]
(let [var-defs
(-> (clj-kondo/run! {:lint ["src"]
:config {:output {:analysis {:arglists true
:var-definitions {:meta [:no-doc]}}}}})
:analysis :var-definitions)
nss (group-by :ns var-defs)
docs
(with-out-str
(doseq [[ns ana] nss
:let [_ (println "##" ns)]
var (sort-by :name ana)
:when (and (not (:no-doc (:meta var)))
(not (:private var))
(not (= 'clojure.core/defrecord (:defined-by var))))]
;; (.println System/err (:defined-by var))
(println "###" (format "`%s`" (:name var)))
;; (.println System/err (keys var))
(when-let [arg-lists (seq (:arglist-strs var))]
(doseq [arglist arg-lists]
(println (format "<code>%s</code><br>" arglist))))
(when-let [doc (:doc var)]
(println)
(when (:macro var)
(println "Macro.\n\n"))
(println doc))
(println)
(println
(format
"[Source](%s/blob/%s/%s#L%s-L%s)"
repo
branch
(:filename var)
(:row var)
(:end-row var)))))]
(spit outfile docs)))
(quickdoc {:branch "master"
:github/repo ""})
| null | https://raw.githubusercontent.com/babashka/process/c99fbe294b9da5185ece64b5fee8283f6d2a3827/script/quickdoc.clj | clojure | (.println System/err (:defined-by var))
(.println System/err (keys var)) | (ns quickdoc
(:require [pod.borkdude.clj-kondo :as clj-kondo]))
(defn quickdoc [{:keys [branch outfile
github/repo]
:or {branch "main"
outfile "API.md"}}]
(let [var-defs
(-> (clj-kondo/run! {:lint ["src"]
:config {:output {:analysis {:arglists true
:var-definitions {:meta [:no-doc]}}}}})
:analysis :var-definitions)
nss (group-by :ns var-defs)
docs
(with-out-str
(doseq [[ns ana] nss
:let [_ (println "##" ns)]
var (sort-by :name ana)
:when (and (not (:no-doc (:meta var)))
(not (:private var))
(not (= 'clojure.core/defrecord (:defined-by var))))]
(println "###" (format "`%s`" (:name var)))
(when-let [arg-lists (seq (:arglist-strs var))]
(doseq [arglist arg-lists]
(println (format "<code>%s</code><br>" arglist))))
(when-let [doc (:doc var)]
(println)
(when (:macro var)
(println "Macro.\n\n"))
(println doc))
(println)
(println
(format
"[Source](%s/blob/%s/%s#L%s-L%s)"
repo
branch
(:filename var)
(:row var)
(:end-row var)))))]
(spit outfile docs)))
(quickdoc {:branch "master"
:github/repo ""})
|
d1a5dc3f0595e918667c93156419b5ac0200cbe4288f22002d1a8e8c942fea5c | dsheets/codoc | codocExtraction.ml |
* Copyright ( c ) 2015 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2015 David Sheets <>
*
* Permission to use, copy, modify, and 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.
*
*)
module StringSet = Set.Make(String)
module StringMap = Map.Make(String)
type 'a r = {
cmti : 'a;
cmi : 'a;
cmt : 'a;
}
type typ = Cmti | Cmi | Cmt
type file = {
typ : typ;
rel : string;
src : string;
hide : bool; (* cmt or packed *)
}
type 'a set = {
root : string;
set : 'a r;
}
type t = bool StringMap.t set
type env = StringSet.t set
let at root =
StringSet.({ root; set = { cmti = empty; cmi = empty; cmt = empty; }; })
let add_ map el = StringSet.add el map
let add_cmti ({ cmti } as x) path = { x with cmti = add_ cmti path }
let add_cmi ({ cmi } as x) path = { x with cmi = add_ cmi path }
let add_cmt ({ cmt } as x) path = { x with cmt = add_ cmt path }
let file ?(src="") rel_file = Filename.(
if check_suffix rel_file ".cmti"
then Some {
typ = Cmti; rel = chop_suffix rel_file ".cmti"; src; hide = false;
}
else if check_suffix rel_file ".cmi"
then Some {
typ = Cmi; rel = chop_suffix rel_file ".cmi"; src; hide = false;
}
else if check_suffix rel_file ".cmt"
then Some {
typ = Cmt; rel = chop_suffix rel_file ".cmt"; src; hide = true;
}
else None
)
let is_extractable path = Filename.(
check_suffix path ".cmti" ||
check_suffix path ".cmt" ||
check_suffix path ".cmi"
)
let is_cmti = function { typ = Cmti } -> true | { typ = Cmt | Cmi } -> false
let is_hidden { hide } = hide
let filter { root; set = { cmti; cmi; cmt }; } =
let cmt = StringSet.(fold (fun r ->
StringMap.add r true
) (diff (diff cmt cmti) cmi)) StringMap.empty in
let cmi_map = StringSet.(fold (fun r ->
StringMap.add r false
) (diff cmi cmti)) StringMap.empty in
let cmti = StringSet.fold (fun r ->
StringMap.add r (not (StringSet.mem r cmi))
) cmti StringMap.empty in
StringSet.({
root;
set = { cmti; cmi = cmi_map; cmt; };
})
let fold f acc { root; set = { cmti; cmi; cmt }; } =
let list = StringMap.fold (f.cmti root) cmti acc in
let list = StringMap.fold (f.cmi root) cmi list in
StringMap.fold (f.cmt root) cmt list
let map f = fold {
cmti = (fun root v hide list -> f.cmti root v hide :: list);
cmi = (fun root v hide list -> f.cmi root v hide :: list);
cmt = (fun root v hide list -> f.cmt root v hide :: list);
}
let apply f = function
| { typ = Cmti; src; rel; hide; } -> f.cmti src rel hide
| { typ = Cmt; src; rel; hide; } -> f.cmt src rel hide
| { typ = Cmi; src; rel; hide; } -> f.cmi src rel hide
let mapply a f = function
| { typ = Cmti; rel; } -> { a with cmti = f.cmti rel a.cmti }
| { typ = Cmt; rel; } -> { a with cmt = f.cmt rel a.cmt }
| { typ = Cmi; rel; } -> { a with cmi = f.cmi rel a.cmi }
let add_f = StringSet.({ cmti = add; cmt = add; cmi = add; })
let add extr next = match file next with
| None -> extr
| Some file -> { extr with set = mapply extr.set add_f file }
let rel_cmti _ path _hide = path ^ ".cmti"
let rel_cmt _ path _hide = path ^ ".cmt"
let rel_cmi _ path _hide = path ^ ".cmi"
let cmti root path hide = Filename.concat root (rel_cmti root path hide)
let cmt root path hide = Filename.concat root (rel_cmt root path hide)
let cmi root path hide = Filename.concat root (rel_cmi root path hide)
let rel_path_f = { cmti = rel_cmti; cmt = rel_cmt; cmi = rel_cmi; }
let path_f = { cmti; cmt; cmi; }
let uniform_cons f = {
cmti = (fun src rel hide -> f { typ = Cmti; rel; src; hide; });
cmi = (fun src rel hide -> f { typ = Cmi; rel; src; hide; });
cmt = (fun src rel hide -> f { typ = Cmt; rel; src; hide; });
}
let file_f = uniform_cons (fun x -> x)
let rel_xml_path _ p _hide =
let dir = match Filename.dirname p with "." -> "" | p -> p in
let xml = Filename.(concat (String.capitalize (basename p)) "index.xml") in
Filename.concat dir xml
let xml_path root p hide = Filename.concat root (rel_xml_path root p hide)
let uniform f = { cmti = f; cmi = f; cmt = f; }
let uapply f = apply (uniform_cons (fun file ->
let src, rel = f file.src file.rel in
{ file with src; rel }
))
let xml_f = uniform xml_path
let xml = apply xml_f
let rel_xml_f = uniform rel_xml_path
let rel_xml = apply rel_xml_f
let path = apply path_f
let rel_path = apply rel_path_f
let relocate src = apply (uniform_cons (fun x -> { x with src }))
let path_list = map path_f []
let file_list = map file_f []
let xml_list = map xml_f []
let summarize { root; set } =
let cmti_count = StringMap.cardinal set.cmti in
let cmi_count = StringMap.cardinal set.cmi in
let cmt_count = StringMap.cardinal set.cmt in
Printf.sprintf
"%4d cmti %4d cmi %4d cmt under %s" cmti_count cmi_count cmt_count root
let read root_fn file =
let read_fn = match file with
| { typ = Cmti } -> DocOck.read_cmti
| { typ = Cmi } -> DocOck.read_cmi
| { typ = Cmt } -> DocOck.read_cmt
in
read_fn root_fn (path file)
| null | https://raw.githubusercontent.com/dsheets/codoc/382077cf3e7e20e478bd97cc0b348e0b2ec926db/lib/codocExtraction.ml | ocaml | cmt or packed |
* Copyright ( c ) 2015 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2015 David Sheets <>
*
* Permission to use, copy, modify, and 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.
*
*)
module StringSet = Set.Make(String)
module StringMap = Map.Make(String)
type 'a r = {
cmti : 'a;
cmi : 'a;
cmt : 'a;
}
type typ = Cmti | Cmi | Cmt
type file = {
typ : typ;
rel : string;
src : string;
}
type 'a set = {
root : string;
set : 'a r;
}
type t = bool StringMap.t set
type env = StringSet.t set
let at root =
StringSet.({ root; set = { cmti = empty; cmi = empty; cmt = empty; }; })
let add_ map el = StringSet.add el map
let add_cmti ({ cmti } as x) path = { x with cmti = add_ cmti path }
let add_cmi ({ cmi } as x) path = { x with cmi = add_ cmi path }
let add_cmt ({ cmt } as x) path = { x with cmt = add_ cmt path }
let file ?(src="") rel_file = Filename.(
if check_suffix rel_file ".cmti"
then Some {
typ = Cmti; rel = chop_suffix rel_file ".cmti"; src; hide = false;
}
else if check_suffix rel_file ".cmi"
then Some {
typ = Cmi; rel = chop_suffix rel_file ".cmi"; src; hide = false;
}
else if check_suffix rel_file ".cmt"
then Some {
typ = Cmt; rel = chop_suffix rel_file ".cmt"; src; hide = true;
}
else None
)
let is_extractable path = Filename.(
check_suffix path ".cmti" ||
check_suffix path ".cmt" ||
check_suffix path ".cmi"
)
let is_cmti = function { typ = Cmti } -> true | { typ = Cmt | Cmi } -> false
let is_hidden { hide } = hide
let filter { root; set = { cmti; cmi; cmt }; } =
let cmt = StringSet.(fold (fun r ->
StringMap.add r true
) (diff (diff cmt cmti) cmi)) StringMap.empty in
let cmi_map = StringSet.(fold (fun r ->
StringMap.add r false
) (diff cmi cmti)) StringMap.empty in
let cmti = StringSet.fold (fun r ->
StringMap.add r (not (StringSet.mem r cmi))
) cmti StringMap.empty in
StringSet.({
root;
set = { cmti; cmi = cmi_map; cmt; };
})
let fold f acc { root; set = { cmti; cmi; cmt }; } =
let list = StringMap.fold (f.cmti root) cmti acc in
let list = StringMap.fold (f.cmi root) cmi list in
StringMap.fold (f.cmt root) cmt list
let map f = fold {
cmti = (fun root v hide list -> f.cmti root v hide :: list);
cmi = (fun root v hide list -> f.cmi root v hide :: list);
cmt = (fun root v hide list -> f.cmt root v hide :: list);
}
let apply f = function
| { typ = Cmti; src; rel; hide; } -> f.cmti src rel hide
| { typ = Cmt; src; rel; hide; } -> f.cmt src rel hide
| { typ = Cmi; src; rel; hide; } -> f.cmi src rel hide
let mapply a f = function
| { typ = Cmti; rel; } -> { a with cmti = f.cmti rel a.cmti }
| { typ = Cmt; rel; } -> { a with cmt = f.cmt rel a.cmt }
| { typ = Cmi; rel; } -> { a with cmi = f.cmi rel a.cmi }
let add_f = StringSet.({ cmti = add; cmt = add; cmi = add; })
let add extr next = match file next with
| None -> extr
| Some file -> { extr with set = mapply extr.set add_f file }
let rel_cmti _ path _hide = path ^ ".cmti"
let rel_cmt _ path _hide = path ^ ".cmt"
let rel_cmi _ path _hide = path ^ ".cmi"
let cmti root path hide = Filename.concat root (rel_cmti root path hide)
let cmt root path hide = Filename.concat root (rel_cmt root path hide)
let cmi root path hide = Filename.concat root (rel_cmi root path hide)
let rel_path_f = { cmti = rel_cmti; cmt = rel_cmt; cmi = rel_cmi; }
let path_f = { cmti; cmt; cmi; }
let uniform_cons f = {
cmti = (fun src rel hide -> f { typ = Cmti; rel; src; hide; });
cmi = (fun src rel hide -> f { typ = Cmi; rel; src; hide; });
cmt = (fun src rel hide -> f { typ = Cmt; rel; src; hide; });
}
let file_f = uniform_cons (fun x -> x)
let rel_xml_path _ p _hide =
let dir = match Filename.dirname p with "." -> "" | p -> p in
let xml = Filename.(concat (String.capitalize (basename p)) "index.xml") in
Filename.concat dir xml
let xml_path root p hide = Filename.concat root (rel_xml_path root p hide)
let uniform f = { cmti = f; cmi = f; cmt = f; }
let uapply f = apply (uniform_cons (fun file ->
let src, rel = f file.src file.rel in
{ file with src; rel }
))
let xml_f = uniform xml_path
let xml = apply xml_f
let rel_xml_f = uniform rel_xml_path
let rel_xml = apply rel_xml_f
let path = apply path_f
let rel_path = apply rel_path_f
let relocate src = apply (uniform_cons (fun x -> { x with src }))
let path_list = map path_f []
let file_list = map file_f []
let xml_list = map xml_f []
let summarize { root; set } =
let cmti_count = StringMap.cardinal set.cmti in
let cmi_count = StringMap.cardinal set.cmi in
let cmt_count = StringMap.cardinal set.cmt in
Printf.sprintf
"%4d cmti %4d cmi %4d cmt under %s" cmti_count cmi_count cmt_count root
let read root_fn file =
let read_fn = match file with
| { typ = Cmti } -> DocOck.read_cmti
| { typ = Cmi } -> DocOck.read_cmi
| { typ = Cmt } -> DocOck.read_cmt
in
read_fn root_fn (path file)
|
c96526efdce583c4b902dee2d7cafac57adf95baacfa54714c0f76b701faaf24 | JunSuzukiJapan/cl-reex | handmade-observable.lisp | (in-package :cl-user)
(defpackage cl-reex.macro.handmade-observable
(:use :cl)
(:import-from :cl-reex.observable
:subscribe
:observable
:observable-object
:is-active
:observable-state
:state
:active
:error
:completed
:disposed
:dispose
:observable-from
:on-next
:on-error
:on-completed
:disposable-do-nothing)
(:import-from :cl-reex.observer
:observer )
(:export :handmade-observable) )
(in-package :cl-reex.macro.handmade-observable)
(defclass handmade-observable-object (observable-object)
((source :initarg :source
:accessor source) ))
(defmethod subscribe ((observable handmade-observable-object) observer)
(handler-bind
((error #'(lambda (condition)
(on-error observer condition)
(return-from subscribe
(make-instance 'disposable-do-nothing
:observable observable
:observer observer )))))
(dolist (message (source observable))
(case (car message)
;; on-next
((on-next)
(when (is-active observable)
(on-next observer (cadr message)) ))
;; on-error
((on-error)
(when (is-active observable)
(setf (state observable) 'error)
(on-error observer (cadr message)) ))
;; on-completed
((on-completed)
(when (is-active observable)
(setf (state observable) 'completed)
(on-completed observer) ))))
(make-instance 'disposable-do-nothing
:observable observable
:observer observer ) ))
(defmacro handmade-observable (&rest body)
`(make-instance 'handmade-observable-object
:source ',body ))
| null | https://raw.githubusercontent.com/JunSuzukiJapan/cl-reex/94928c7949c235b41902138d9e4a5654b92d67eb/src/macro/handmade-observable.lisp | lisp | on-next
on-error
on-completed | (in-package :cl-user)
(defpackage cl-reex.macro.handmade-observable
(:use :cl)
(:import-from :cl-reex.observable
:subscribe
:observable
:observable-object
:is-active
:observable-state
:state
:active
:error
:completed
:disposed
:dispose
:observable-from
:on-next
:on-error
:on-completed
:disposable-do-nothing)
(:import-from :cl-reex.observer
:observer )
(:export :handmade-observable) )
(in-package :cl-reex.macro.handmade-observable)
(defclass handmade-observable-object (observable-object)
((source :initarg :source
:accessor source) ))
(defmethod subscribe ((observable handmade-observable-object) observer)
(handler-bind
((error #'(lambda (condition)
(on-error observer condition)
(return-from subscribe
(make-instance 'disposable-do-nothing
:observable observable
:observer observer )))))
(dolist (message (source observable))
(case (car message)
((on-next)
(when (is-active observable)
(on-next observer (cadr message)) ))
((on-error)
(when (is-active observable)
(setf (state observable) 'error)
(on-error observer (cadr message)) ))
((on-completed)
(when (is-active observable)
(setf (state observable) 'completed)
(on-completed observer) ))))
(make-instance 'disposable-do-nothing
:observable observable
:observer observer ) ))
(defmacro handmade-observable (&rest body)
`(make-instance 'handmade-observable-object
:source ',body ))
|
add280d4857653a78305e8a1588bc23735d9bf89ae9d2bb23e6f2692d6a9ec07 | yrashk/erlang | ets.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(ets).
Interface to the Term store BIF 's
%% ets == Erlang Term Store
-export([file2tab/1,
file2tab/2,
filter/3,
foldl/3, foldr/3,
match_delete/2,
tab2file/2,
tab2file/3,
tabfile_info/1,
from_dets/2,
to_dets/2,
init_table/2,
test_ms/2,
tab2list/1,
table/1,
table/2,
fun2ms/1,
match_spec_run/2,
repair_continuation/2]).
-export([i/0, i/1, i/2, i/3]).
%%------------------------------------------------------------------------------
-type tab() :: atom() | tid().
-type ext_info() :: 'md5sum' | 'object_count'.
-type protection() :: 'private' | 'protected' | 'public'.
-type type() :: 'bag' | 'duplicate_bag' | 'ordered_set' | 'set'.
-type table_info() :: {'name', atom()}
| {'type', type()}
| {'protection', protection()}
| {'named_table', bool()}
| {'keypos', non_neg_integer()}
| {'size', non_neg_integer()}
| {'extended_info', [ext_info()]}
| {'version', {non_neg_integer(), non_neg_integer()}}.
%% these ones are also defined in erl_bif_types
-type match_pattern() :: atom() | tuple().
-type match_specs() :: [{match_pattern(), [_], [_]}].
%%------------------------------------------------------------------------------
%% The following functions used to be found in this module, but
%% are now BIFs (i.e. implemented in C).
%%
%% all/0
%% delete/1
%% delete/2
%% first/1
info/1
%% info/2
%% safe_fixtable/2
%% lookup/2
%% lookup_element/3
insert/2
%% is_compiled_ms/1
%% last/1
next/2
%% prev/2
%% rename/2
%% slot/2
%% match/1
%% match/3
%% match_object/1
%% match_object/2
%% match_object/3
match_spec_compile/1
select/1
select/2
select/3
%% select_reverse/1
%% select_reverse/2
%% select_reverse/3
%% select_delete/2
update_counter/3
%%
-opaque comp_match_spec() :: any(). %% this one is REALLY opaque
-spec match_spec_run([tuple()], comp_match_spec()) -> [term()].
match_spec_run(List, CompiledMS) ->
lists:reverse(ets:match_spec_run_r(List, CompiledMS, [])).
-type continuation() :: '$end_of_table'
| {tab(),integer(),integer(),binary(),list(),integer()}
| {tab(),_,_,integer(),binary(),list(),integer(),integer()}.
-spec repair_continuation(continuation(), match_specs()) -> continuation().
%% $end_of_table is an allowed continuation in ets...
repair_continuation('$end_of_table', _) ->
'$end_of_table';
%% ordered_set
repair_continuation(Untouched = {Table,Lastkey,EndCondition,N2,Bin,L2,N3,N4}, MS)
when %% (is_atom(Table) or is_integer(Table)),
is_integer(N2),
byte_size(Bin) =:= 0,
is_list(L2),
is_integer(N3),
is_integer(N4) ->
case ets:is_compiled_ms(Bin) of
true ->
Untouched;
false ->
{Table,Lastkey,EndCondition,N2,ets:match_spec_compile(MS),L2,N3,N4}
end;
%% set/bag/duplicate_bag
repair_continuation(Untouched = {Table,N1,N2,Bin,L,N3}, MS)
when %% (is_atom(Table) or is_integer(Table)),
is_integer(N1),
is_integer(N2),
byte_size(Bin) =:= 0,
is_list(L),
is_integer(N3) ->
case ets:is_compiled_ms(Bin) of
true ->
Untouched;
false ->
{Table,N1,N2,ets:match_spec_compile(MS),L,N3}
end.
-spec fun2ms(function()) -> match_specs().
fun2ms(ShellFun) when is_function(ShellFun) ->
%% Check that this is really a shell fun...
case erl_eval:fun_data(ShellFun) of
{fun_data,ImportList,Clauses} ->
case ms_transform:transform_from_shell(
?MODULE,Clauses,ImportList) of
{error,[{_,[{_,_,Code}|_]}|_],_} ->
io:format("Error: ~s~n",
[ms_transform:format_error(Code)]),
{error,transform_error};
Else ->
Else
end;
false ->
exit({badarg,{?MODULE,fun2ms,
[function,called,with,real,'fun',
should,be,transformed,with,
parse_transform,'or',called,with,
a,'fun',generated,in,the,
shell]}})
end.
-spec foldl(fun((_, term()) -> term()), term(), tab()) -> term().
foldl(F, Accu, T) ->
ets:safe_fixtable(T, true),
First = ets:first(T),
try
do_foldl(F, Accu, First, T)
after
ets:safe_fixtable(T, false)
end.
do_foldl(F, Accu0, Key, T) ->
case Key of
'$end_of_table' ->
Accu0;
_ ->
do_foldl(F,
lists:foldl(F, Accu0, ets:lookup(T, Key)),
ets:next(T, Key), T)
end.
-spec foldr(fun((_, term()) -> term()), term(), tab()) -> term().
foldr(F, Accu, T) ->
ets:safe_fixtable(T, true),
Last = ets:last(T),
try
do_foldr(F, Accu, Last, T)
after
ets:safe_fixtable(T, false)
end.
do_foldr(F, Accu0, Key, T) ->
case Key of
'$end_of_table' ->
Accu0;
_ ->
do_foldr(F,
lists:foldr(F, Accu0, ets:lookup(T, Key)),
ets:prev(T, Key), T)
end.
-spec from_dets(tab(), dets:tab_name()) -> 'true'.
from_dets(EtsTable, DetsTable) ->
case (catch dets:to_ets(DetsTable, EtsTable)) of
{error, Reason} ->
erlang:error(Reason, [EtsTable,DetsTable]);
{'EXIT', {Reason1, _Stack1}} ->
erlang:error(Reason1,[EtsTable,DetsTable]);
{'EXIT', EReason} ->
erlang:error(EReason,[EtsTable,DetsTable]);
EtsTable ->
true;
Unexpected -> %% Dets bug?
erlang:error(Unexpected,[EtsTable,DetsTable])
end.
-spec to_dets(tab(), dets:tab_name()) -> tab().
to_dets(EtsTable, DetsTable) ->
case (catch dets:from_ets(DetsTable, EtsTable)) of
{error, Reason} ->
erlang:error(Reason, [EtsTable,DetsTable]);
{'EXIT', {Reason1, _Stack1}} ->
erlang:error(Reason1,[EtsTable,DetsTable]);
{'EXIT', EReason} ->
erlang:error(EReason,[EtsTable,DetsTable]);
ok ->
DetsTable;
Unexpected -> %% Dets bug?
erlang:error(Unexpected,[EtsTable,DetsTable])
end.
-spec test_ms(tuple(), match_specs()) ->
{'ok', term()} | {'error', [{'warning'|'error', string()}]}.
test_ms(Term, MS) ->
case erlang:match_spec_test(Term, MS, table) of
{ok, Result, _Flags, _Messages} ->
{ok, Result};
{error, _Errors} = Error ->
Error
end.
-spec init_table(tab(), fun(('read' | 'close') -> term())) -> 'true'.
init_table(Table, Fun) ->
ets:delete_all_objects(Table),
init_table_continue(Table, Fun(read)).
init_table_continue(_Table, end_of_input) ->
true;
init_table_continue(Table, {List, Fun}) when is_list(List), is_function(Fun) ->
case (catch init_table_sub(Table, List)) of
{'EXIT', Reason} ->
(catch Fun(close)),
exit(Reason);
true ->
init_table_continue(Table, Fun(read))
end;
init_table_continue(_Table, Error) ->
exit(Error).
init_table_sub(_Table, []) ->
true;
init_table_sub(Table, [H|T]) ->
ets:insert(Table, H),
init_table_sub(Table, T).
-spec match_delete(tab(), match_pattern()) -> 'true'.
match_delete(Table, Pattern) ->
ets:select_delete(Table, [{Pattern,[],[true]}]),
true.
%% Produce a list of tuples from a table
-spec tab2list(tab()) -> [tuple()].
tab2list(T) ->
ets:match_object(T, '_').
-spec filter(tab(), function(), [term()]) -> [term()].
filter(Tn, F, A) when is_atom(Tn) ; is_integer(Tn) ->
do_filter(Tn, ets:first(Tn), F, A, []).
do_filter(_Tab, '$end_of_table', _, _, Ack) ->
Ack;
do_filter(Tab, Key, F, A, Ack) ->
case apply(F, [ets:lookup(Tab, Key)|A]) of
false ->
do_filter(Tab, ets:next(Tab, Key), F, A, Ack);
true ->
Ack2 = ets:lookup(Tab, Key) ++ Ack,
do_filter(Tab, ets:next(Tab, Key), F, A, Ack2);
{true, Value} ->
do_filter(Tab, ets:next(Tab, Key), F, A, [Value|Ack])
end.
Dump a table to a file using the disk_log facility
%% Options := [Option]
%% Option := {extended_info,[ExtInfo]}
%% ExtInfo := object_count | md5sum
-define(MAJOR_F2T_VERSION,1).
-define(MINOR_F2T_VERSION,0).
-record(filetab_options,
{
object_count = false :: bool(),
md5sum = false :: bool()
}).
-type fname() :: string() | atom().
-type t2f_option() :: {'extended_info', [ext_info()]}.
-spec tab2file(tab(), fname()) -> 'ok' | {'error', term()}.
tab2file(Tab, File) ->
tab2file(Tab, File, []).
-spec tab2file(tab(), fname(), [t2f_option()]) -> 'ok' | {'error', term()}.
tab2file(Tab, File, Options) ->
try
{ok, FtOptions} = parse_ft_options(Options),
file:delete(File),
case file:read_file_info(File) of
{error, enoent} -> ok;
_ -> throw(eaccess)
end,
Name = make_ref(),
case disk_log:open([{name, Name}, {file, File}]) of
{ok, Name} ->
ok;
{error, Reason} ->
throw(Reason)
end,
try
Info0 = case ets:info(Tab) of
undefined ->
erlang : error(badarg , [ Tab , File , Options ] ) ;
throw(badtab);
I ->
I
end,
Info = [list_to_tuple(Info0 ++
[{major_version,?MAJOR_F2T_VERSION},
{minor_version,?MINOR_F2T_VERSION},
{extended_info,
ft_options_to_list(FtOptions)}])],
{LogFun, InitState} =
case FtOptions#filetab_options.md5sum of
true ->
{fun(Oldstate,Termlist) ->
{NewState,BinList} =
md5terms(Oldstate,Termlist),
disk_log:blog_terms(Name,BinList),
NewState
end,
erlang:md5_init()};
false ->
{fun(_,Termlist) ->
disk_log:log_terms(Name,Termlist),
true
end,
true}
end,
ets:safe_fixtable(Tab,true),
{NewState1,Num} = try
NewState = LogFun(InitState,Info),
dump_file(
ets:select(Tab,[{'_',[],['$_']}],100),
LogFun, NewState, 0)
after
(catch ets:safe_fixtable(Tab,false))
end,
EndInfo =
case FtOptions#filetab_options.object_count of
true ->
[{count,Num}];
false ->
[]
end ++
case FtOptions#filetab_options.md5sum of
true ->
[{md5,erlang:md5_final(NewState1)}];
false ->
[]
end,
case EndInfo of
[] ->
ok;
List ->
LogFun(NewState1,[['$end_of_table',List]])
end,
disk_log:close(Name)
catch
throw:TReason ->
disk_log:close(Name),
file:delete(File),
throw(TReason);
exit:ExReason ->
disk_log:close(Name),
file:delete(File),
exit(ExReason);
error:ErReason ->
disk_log:close(Name),
file:delete(File),
erlang:raise(error,ErReason,erlang:get_stacktrace())
end
catch
throw:TReason2 ->
{error,TReason2};
exit:ExReason2 ->
{error,ExReason2}
end.
dump_file('$end_of_table', _LogFun, State, Num) ->
{State,Num};
dump_file({Terms, Context}, LogFun, State, Num) ->
Count = length(Terms),
NewState = LogFun(State, Terms),
dump_file(ets:select(Context), LogFun, NewState, Num + Count).
ft_options_to_list(#filetab_options{md5sum = MD5, object_count = PS}) ->
case PS of
true ->
[object_count];
_ ->
[]
end ++
case MD5 of
true ->
[md5sum];
_ ->
[]
end.
md5terms(State, []) ->
{State, []};
md5terms(State, [H|T]) ->
B = term_to_binary(H),
NewState = erlang:md5_update(State, B),
{FinState, TL} = md5terms(NewState, T),
{FinState, [B|TL]}.
parse_ft_options(Options) when is_list(Options) ->
{Opt,Rest} = case (catch lists:keytake(extended_info,1,Options)) of
false ->
{[],Options};
{value,{extended_info,L},R} when is_list(L) ->
{L,R}
end,
case Rest of
[] ->
parse_ft_info_options(#filetab_options{}, Opt);
Other ->
throw({unknown_option, Other})
end;
parse_ft_options(Malformed) ->
throw({malformed_option, Malformed}).
parse_ft_info_options(FtOpt,[]) ->
{ok,FtOpt};
parse_ft_info_options(FtOpt,[object_count | T]) ->
parse_ft_info_options(FtOpt#filetab_options{object_count = true}, T);
parse_ft_info_options(FtOpt,[md5sum | T]) ->
parse_ft_info_options(FtOpt#filetab_options{md5sum = true}, T);
parse_ft_info_options(_,[Unexpected | _]) ->
throw({unknown_option,[{extended_info,[Unexpected]}]});
parse_ft_info_options(_,Malformed) ->
throw({malformed_option,Malformed}).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Read a dumped file from disk and create a corresponding table
%% Opts := [Opt]
%% Opt := {verify,bool()}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-type f2t_option() :: {'verify', bool()}.
-spec file2tab(fname()) -> {'ok', tab()} | {'error', term()}.
file2tab(File) ->
file2tab(File, []).
-spec file2tab(fname(), [f2t_option()]) -> {'ok', tab()} | {'error', term()}.
file2tab(File, Opts) ->
try
{ok,Verify} = parse_f2t_opts(Opts,false),
Name = make_ref(),
{ok, Major, Minor, FtOptions, MD5State, FullHeader, DLContext} =
case disk_log:open([{name, Name},
{file, File},
{mode, read_only}]) of
{ok, Name} ->
get_header_data(Name,Verify);
{repaired, Name, _,_} -> %Uh? cannot happen?
case Verify of
true ->
disk_log:close(Name),
throw(badfile);
false ->
get_header_data(Name,Verify)
end;
{error, Other1} ->
throw({read_error, Other1});
Other2 ->
throw(Other2)
end,
try
if
Major > ?MAJOR_F2T_VERSION ->
throw({unsupported_file_version,{Major,Minor}});
true ->
ok
end,
{ok, Tab, HeadCount} = create_tab(FullHeader),
StrippedOptions =
case Verify of
true ->
FtOptions;
false ->
#filetab_options{}
end,
{ReadFun,InitState} =
case StrippedOptions#filetab_options.md5sum of
true ->
{fun({OldMD5State,OldCount,_OL,ODLContext} = OS) ->
case wrap_bchunk(Name,ODLContext,100,Verify) of
eof ->
{OS,[]};
{NDLContext,Blist} ->
{Termlist, NewMD5State,
NewCount,NewLast} =
md5_and_convert(Blist,
OldMD5State,
OldCount),
{{NewMD5State, NewCount,
NewLast,NDLContext},
Termlist}
end
end,
{MD5State,0,[],DLContext}};
false ->
{fun({_,OldCount,_OL,ODLContext} = OS) ->
case wrap_chunk(Name,ODLContext,100,Verify) of
eof ->
{OS,[]};
{NDLContext,List} ->
{NewLast,NewCount,NewList} =
scan_for_endinfo(List, OldCount),
{{false,NewCount,NewLast,NDLContext},
NewList}
end
end,
{false,0,[],DLContext}}
end,
try
do_read_and_verify(ReadFun,InitState,Tab,
StrippedOptions,HeadCount,Verify)
catch
throw:TReason ->
ets:delete(Tab),
throw(TReason);
exit:ExReason ->
ets:delete(Tab),
exit(ExReason);
error:ErReason ->
ets:delete(Tab),
erlang:raise(error,ErReason,erlang:get_stacktrace())
end
after
disk_log:close(Name)
end
catch
throw:TReason2 ->
{error,TReason2};
exit:ExReason2 ->
{error,ExReason2}
end.
do_read_and_verify(ReadFun,InitState,Tab,FtOptions,HeadCount,Verify) ->
case load_table(ReadFun,InitState,Tab) of
{ok,{_,FinalCount,[],_}} ->
case {FtOptions#filetab_options.md5sum,
FtOptions#filetab_options.object_count} of
{false,false} ->
case Verify of
false ->
ok;
true ->
case FinalCount of
HeadCount ->
ok;
_ ->
throw(invalid_object_count)
end
end;
_ ->
throw(badfile)
end,
{ok,Tab};
{ok,{FinalMD5State,FinalCount,['$end_of_table',LastInfo],_}} ->
ECount = case lists:keysearch(count,1,LastInfo) of
{value,{count,N}} ->
N;
_ ->
false
end,
EMD5 = case lists:keysearch(md5,1,LastInfo) of
{value,{md5,M}} ->
M;
_ ->
false
end,
case FtOptions#filetab_options.md5sum of
true ->
case erlang:md5_final(FinalMD5State) of
EMD5 ->
ok;
_MD5MisM ->
throw(checksum_error)
end;
false ->
ok
end,
case FtOptions#filetab_options.object_count of
true ->
case FinalCount of
ECount ->
ok;
_Other ->
throw(invalid_object_count)
end;
false ->
%% Only use header count if no extended info
%% at all is present and verification is requested.
case {Verify,FtOptions#filetab_options.md5sum} of
{true,false} ->
case FinalCount of
HeadCount ->
ok;
_Other2 ->
throw(invalid_object_count)
end;
_ ->
ok
end
end,
{ok,Tab}
end.
parse_f2t_opts([],Verify) ->
{ok,Verify};
parse_f2t_opts([{verify, true}|T],_OV) ->
parse_f2t_opts(T,true);
parse_f2t_opts([{verify,false}|T],OV) ->
parse_f2t_opts(T,OV);
parse_f2t_opts([Unexpected|_],_) ->
throw({unknown_option,Unexpected});
parse_f2t_opts(Malformed,_) ->
throw({malformed_option,Malformed}).
count_mandatory([]) ->
0;
count_mandatory([{Tag,_}|T]) when Tag =:= name;
Tag =:= type;
Tag =:= protection;
Tag =:= named_table;
Tag =:= keypos;
Tag =:= size ->
1+count_mandatory(T);
count_mandatory([_|T]) ->
count_mandatory(T).
verify_header_mandatory(L) ->
count_mandatory(L) =:= 6.
wrap_bchunk(Name,C,N,true) ->
case disk_log:bchunk(Name,C,N) of
{_,_,X} when X > 0 ->
throw(badfile);
{NC,Bin,_} ->
{NC,Bin};
Y ->
Y
end;
wrap_bchunk(Name,C,N,false) ->
case disk_log:bchunk(Name,C,N) of
{NC,Bin,_} ->
{NC,Bin};
Y ->
Y
end.
wrap_chunk(Name,C,N,true) ->
case disk_log:chunk(Name,C,N) of
{_,_,X} when X > 0 ->
throw(badfile);
{NC,TL,_} ->
{NC,TL};
Y ->
Y
end;
wrap_chunk(Name,C,N,false) ->
case disk_log:chunk(Name,C,N) of
{NC,TL,_} ->
{NC,TL};
Y ->
Y
end.
get_header_data(Name,true) ->
case wrap_bchunk(Name,start,1,true) of
{C,[Bin]} when is_binary(Bin) ->
T = binary_to_term(Bin),
case T of
Tup when is_tuple(Tup) ->
L = tuple_to_list(Tup),
case verify_header_mandatory(L) of
false ->
throw(badfile);
true ->
Major = case lists:keysearch(major,1,L) of
{value,{major,Maj}} ->
Maj;
_ ->
0
end,
Minor = case lists:keysearch(minor,1,L) of
{value,{minor,Min}} ->
Min;
_ ->
0
end,
FtOptions =
case lists:keysearch(extended_info,1,L) of
{value,{extended_info,I}}
when is_list(I) ->
#filetab_options
{
object_count =
lists:member(object_count,I),
md5sum =
lists:member(md5sum,I)
};
_ ->
#filetab_options{}
end,
MD5Initial =
case FtOptions#filetab_options.md5sum of
true ->
X = erlang:md5_init(),
erlang:md5_update(X,Bin);
false ->
false
end,
{ok, Major, Minor, FtOptions, MD5Initial, L, C}
end;
_X ->
throw(badfile)
end;
_Y ->
throw(badfile)
end;
get_header_data(Name, false) ->
case wrap_chunk(Name,start,1,false) of
{C,[Tup]} when is_tuple(Tup) ->
L = tuple_to_list(Tup),
case verify_header_mandatory(L) of
false ->
throw(badfile);
true ->
Major = case lists:keysearch(major_version,1,L) of
{value,{major_version,Maj}} ->
Maj;
_ ->
0
end,
Minor = case lists:keysearch(minor_version,1,L) of
{value,{minor_version,Min}} ->
Min;
_ ->
0
end,
FtOptions =
case lists:keysearch(extended_info,1,L) of
{value,{extended_info,I}}
when is_list(I) ->
#filetab_options
{
object_count =
lists:member(object_count,I),
md5sum =
lists:member(md5sum,I)
};
_ ->
#filetab_options{}
end,
{ok, Major, Minor, FtOptions, false, L, C}
end;
_ ->
throw(badfile)
end.
md5_and_convert([],MD5State,Count) ->
{[],MD5State,Count,[]};
md5_and_convert([H|T],MD5State,Count) when is_binary(H) ->
case (catch binary_to_term(H)) of
{'EXIT', _} ->
md5_and_convert(T,MD5State,Count);
['$end_of_table',Dat] ->
{[],MD5State,Count,['$end_of_table',Dat]};
Term ->
X = erlang:md5_update(MD5State,H),
{Rest,NewMD5,NewCount,NewLast} = md5_and_convert(T,X,Count+1),
{[Term | Rest],NewMD5,NewCount,NewLast}
end.
scan_for_endinfo([],Count) ->
{[],Count,[]};
scan_for_endinfo([['$end_of_table',Dat]],Count) ->
{['$end_of_table',Dat],Count,[]};
scan_for_endinfo([Term|T],Count) ->
{NewLast,NCount,Rest} = scan_for_endinfo(T,Count+1),
{NewLast,NCount,[Term | Rest]}.
load_table(ReadFun, State, Tab) ->
{NewState,NewData} = ReadFun(State),
case NewData of
[] ->
{ok,NewState};
List ->
ets:insert(Tab,List),
load_table(ReadFun,NewState,Tab)
end.
create_tab(I) ->
{value, {name, Name}} = lists:keysearch(name, 1, I),
{value, {type, Type}} = lists:keysearch(type, 1, I),
{value, {protection, P}} = lists:keysearch(protection, 1, I),
{value, {named_table, Val}} = lists:keysearch(named_table, 1, I),
{value, {keypos, Kp}} = lists:keysearch(keypos, 1, I),
{value, {size, Sz}} = lists:keysearch(size, 1, I),
try
Tab = ets:new(Name, [Type, P, {keypos, Kp} | named_table(Val)]),
{ok, Tab, Sz}
catch
_:_ ->
throw(cannot_create_table)
end.
named_table(true) -> [named_table];
named_table(false) -> [].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% tabfile_info/1 reads the head information in an ets table dumped to
%% disk by means of file2tab and returns a list of the relevant table
%% information
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec tabfile_info(fname()) -> {'ok', [table_info()]} | {'error', term()}.
tabfile_info(File) when is_list(File) ; is_atom(File) ->
try
Name = make_ref(),
{ok, Major, Minor, _FtOptions, _MD5State, FullHeader, _DLContext} =
case disk_log:open([{name, Name},
{file, File},
{mode, read_only}]) of
{ok, Name} ->
get_header_data(Name,false);
{repaired, Name, _,_} -> %Uh? cannot happen?
get_header_data(Name,false);
{error, Other1} ->
throw({read_error, Other1});
Other2 ->
throw(Other2)
end,
disk_log:close(Name),
{value, N} = lists:keysearch(name, 1, FullHeader),
{value, Type} = lists:keysearch(type, 1, FullHeader),
{value, P} = lists:keysearch(protection, 1, FullHeader),
{value, Val} = lists:keysearch(named_table, 1, FullHeader),
{value, Kp} = lists:keysearch(keypos, 1, FullHeader),
{value, Sz} = lists:keysearch(size, 1, FullHeader),
Ei = case lists:keysearch(extended_info, 1, FullHeader) of
{value, Ei0} -> Ei0;
_ -> {extended_info, []}
end,
{ok, [N,Type,P,Val,Kp,Sz,Ei,{version,{Major,Minor}}]}
catch
throw:TReason ->
{error,TReason};
exit:ExReason ->
{error,ExReason}
end.
-type qlc__query_handle() :: term(). %% XXX: belongs in 'qlc'
-type num_objects() :: 'default' | pos_integer().
-type trav_method() :: 'first_next' | 'last_prev'
| 'select' | {'select', match_specs()}.
-type table_option() :: {'n_objects', num_objects()}
| {'traverse', trav_method()}.
-spec table(tab()) -> qlc__query_handle().
table(Tab) ->
table(Tab, []).
-spec table(tab(), table_option() | [table_option()]) -> qlc__query_handle().
table(Tab, Opts) ->
case options(Opts, [traverse, n_objects]) of
{badarg,_} ->
erlang:error(badarg, [Tab, Opts]);
[[Traverse, NObjs], QlcOptions] ->
TF = case Traverse of
first_next ->
fun() -> qlc_next(Tab, ets:first(Tab)) end;
last_prev ->
fun() -> qlc_prev(Tab, ets:last(Tab)) end;
select ->
fun(MS) -> qlc_select(ets:select(Tab, MS, NObjs)) end;
{select, MS} ->
fun() -> qlc_select(ets:select(Tab, MS, NObjs)) end
end,
PreFun = fun(_) -> ets:safe_fixtable(Tab, true) end,
PostFun = fun() -> ets:safe_fixtable(Tab, false) end,
InfoFun = fun(Tag) -> table_info(Tab, Tag) end,
KeyEquality = case ets:info(Tab, type) of
ordered_set -> '==';
_ -> '=:='
end,
LookupFun =
case Traverse of
{select, _MS} ->
undefined;
_ ->
fun(_Pos, [K]) ->
ets:lookup(Tab, K);
(_Pos, Ks) ->
lists:flatmap(fun(K) -> ets:lookup(Tab, K)
end, Ks)
end
end,
FormatFun =
fun({all, _NElements, _ElementFun}) ->
As = [Tab | [Opts || _ <- [[]], Opts =/= []]],
{?MODULE, table, As};
({match_spec, MS}) ->
{?MODULE, table,
[Tab, [{traverse, {select, MS}} |
listify(Opts)]]};
({lookup, _KeyPos, [Value], _NElements, ElementFun}) ->
io_lib:format("~w:lookup(~w, ~w)",
[?MODULE, Tab, ElementFun(Value)]);
({lookup, _KeyPos, Values, _NElements, ElementFun}) ->
Vals = [ElementFun(V) || V <- Values],
io_lib:format("lists:flatmap(fun(V) -> "
"~w:lookup(~w, V) end, ~w)",
[?MODULE, Tab, Vals])
end,
qlc:table(TF, [{pre_fun, PreFun}, {post_fun, PostFun},
{info_fun, InfoFun}, {format_fun, FormatFun},
{key_equality, KeyEquality},
{lookup_fun, LookupFun}] ++ QlcOptions)
end.
table_info(Tab, num_of_objects) ->
ets:info(Tab, size);
table_info(Tab, keypos) ->
ets:info(Tab, keypos);
table_info(Tab, is_unique_objects) ->
ets:info(Tab, type) =/= duplicate_bag;
table_info(Tab, is_sorted_key) ->
ets:info(Tab, type) =:= ordered_set;
table_info(_Tab, _) ->
undefined.
qlc_next(_Tab, '$end_of_table') ->
[];
qlc_next(Tab, Key) ->
ets:lookup(Tab, Key) ++ fun() -> qlc_next(Tab, ets:next(Tab, Key)) end.
qlc_prev(_Tab, '$end_of_table') ->
[];
qlc_prev(Tab, Key) ->
ets:lookup(Tab, Key) ++ fun() -> qlc_prev(Tab, ets:prev(Tab, Key)) end.
qlc_select('$end_of_table') ->
[];
qlc_select({Objects, Cont}) ->
Objects ++ fun() -> qlc_select(ets:select(Cont)) end.
options(Options, Keys) when is_list(Options) ->
options(Options, Keys, []);
options(Option, Keys) ->
options([Option], Keys, []).
options(Options, [Key | Keys], L) when is_list(Options) ->
V = case lists:keysearch(Key, 1, Options) of
{value, {n_objects, default}} ->
{ok, default_option(Key)};
{value, {n_objects, NObjs}} when is_integer(NObjs),
NObjs >= 1 ->
{ok, NObjs};
{value, {traverse, select}} ->
{ok, select};
{value, {traverse, {select, MS}}} ->
{ok, {select, MS}};
{value, {traverse, first_next}} ->
{ok, first_next};
{value, {traverse, last_prev}} ->
{ok, last_prev};
{value, {Key, _}} ->
badarg;
false ->
Default = default_option(Key),
{ok, Default}
end,
case V of
badarg ->
{badarg, Key};
{ok,Value} ->
NewOptions = lists:keydelete(Key, 1, Options),
options(NewOptions, Keys, [Value | L])
end;
options(Options, [], L) ->
[lists:reverse(L), Options].
default_option(traverse) -> select;
default_option(n_objects) -> 100.
listify(L) when is_list(L) ->
L;
listify(T) ->
[T].
%% End of table/2.
%% Print info about all tabs on the tty
-spec i() -> 'ok'.
i() ->
hform('id', 'name', 'type', 'size', 'mem', 'owner'),
io:format(" -------------------------------------"
"---------------------------------------\n"),
lists:foreach(fun prinfo/1, tabs()),
ok.
tabs() ->
lists:sort(ets:all()).
prinfo(Tab) ->
case catch prinfo2(Tab) of
{'EXIT', _} ->
io:format("~-10s ... unreadable \n", [to_string(Tab)]);
ok ->
ok
end.
prinfo2(Tab) ->
Name = ets:info(Tab, name),
Type = ets:info(Tab, type),
Size = ets:info(Tab, size),
Mem = ets:info(Tab, memory),
Owner = ets:info(Tab, owner),
hform(Tab, Name, Type, Size, Mem, is_reg(Owner)).
is_reg(Owner) ->
case process_info(Owner, registered_name) of
{registered_name, Name} -> Name;
_ -> Owner
end.
: this code used to truncate over - sized fields . Now it
%%% pushes the remaining entries to the right instead, rather than
%%% losing information.
hform(A0, B0, C0, D0, E0, F0) ->
[A,B,C,D,E,F] = [to_string(T) || T <- [A0,B0,C0,D0,E0,F0]],
A1 = pad_right(A, 15),
B1 = pad_right(B, 17),
C1 = pad_right(C, 5),
D1 = pad_right(D, 6),
E1 = pad_right(E, 8),
%% no need to pad the last entry on the line
io:format(" ~s ~s ~s ~s ~s ~s\n", [A1,B1,C1,D1,E1,F]).
pad_right(String, Len) ->
if
length(String) >= Len ->
String;
true ->
[Space] = " ",
String ++ lists:duplicate(Len - length(String), Space)
end.
to_string(X) ->
lists:flatten(io_lib:format("~p", [X])).
%% view a specific table
-spec i(tab()) -> 'ok'.
i(Tab) ->
i(Tab, 40).
-spec i(tab(), pos_integer()) -> 'ok'.
i(Tab, Height) ->
i(Tab, Height, 80).
-spec i(tab(), pos_integer(), pos_integer()) -> 'ok'.
i(Tab, Height, Width) ->
First = ets:first(Tab),
display_items(Height, Width, Tab, First, 1, 1).
display_items(Height, Width, Tab, '$end_of_table', Turn, Opos) ->
P = 'EOT (q)uit (p)Digits (k)ill /Regexp -->',
choice(Height, Width, P, eot, Tab, '$end_of_table', Turn, Opos);
display_items(Height, Width, Tab, Key, Turn, Opos) when Turn < Height ->
do_display(Height, Width, Tab, Key, Turn, Opos);
display_items(Height, Width, Tab, Key, Turn, Opos) when Turn >= Height ->
P = '(c)ontinue (q)uit (p)Digits (k)ill /Regexp -->',
choice(Height, Width, P, normal, Tab, Key, Turn, Opos).
choice(Height, Width, P, Mode, Tab, Key, Turn, Opos) ->
case get_line(P, "c\n") of
"c\n" when Mode =:= normal ->
do_display(Height, Width, Tab, Key, 1, Opos);
"c\n" when is_tuple(Mode), element(1, Mode) =:= re ->
{re, Re} = Mode,
re_search(Height, Width, Tab, Key, Re, 1, Opos);
"q\n" ->
ok;
"k\n" ->
ets:delete(Tab),
ok;
[$p|Digs] ->
catch case catch list_to_integer(nonl(Digs)) of
{'EXIT', _} ->
io:put_chars("Bad digits\n");
Number when Mode =:= normal ->
print_number(Tab, ets:first(Tab), Number);
Number when Mode =:= eot ->
print_number(Tab, ets:first(Tab), Number);
Number -> %% regexp
{re, Re} = Mode,
print_re_num(Tab, ets:first(Tab), Number, Re)
end,
choice(Height, Width, P, Mode, Tab, Key, Turn, Opos);
[$/|Regexp] -> %% from regexp
case re:compile(nonl(Regexp)) of
{ok,Re} ->
re_search(Height, Width, Tab, ets:first(Tab), Re, 1, 1);
{error,{ErrorString,_Pos}} ->
io:format("~s\n", [ErrorString]),
choice(Height, Width, P, Mode, Tab, Key, Turn, Opos)
end;
_ ->
choice(Height, Width, P, Mode, Tab, Key, Turn, Opos)
end.
get_line(P, Default) ->
case io:get_line(P) of
"\n" ->
Default;
L ->
L
end.
nonl(S) -> string:strip(S, right, $\n).
print_number(Tab, Key, Num) ->
Os = ets:lookup(Tab, Key),
Len = length(Os),
if
(Num - Len) < 1 ->
O = lists:nth(Num, Os),
io:format("~p~n", [O]); %% use ppterm here instead
true ->
print_number(Tab, ets:next(Tab, Key), Num - Len)
end.
do_display(Height, Width, Tab, Key, Turn, Opos) ->
Objs = ets:lookup(Tab, Key),
do_display_items(Height, Width, Objs, Opos),
Len = length(Objs),
display_items(Height, Width, Tab, ets:next(Tab, Key), Turn+Len, Opos+Len).
do_display_items(Height, Width, [Obj|Tail], Opos) ->
do_display_item(Height, Width, Obj, Opos),
do_display_items(Height, Width, Tail, Opos+1);
do_display_items(_Height, _Width, [], Opos) ->
Opos.
do_display_item(_Height, Width, I, Opos) ->
L = to_string(I),
L2 = if
length(L) > Width - 8 ->
string:substr(L, 1, Width-13) ++ " ...";
true ->
L
end,
io:format("<~-4w> ~s~n", [Opos,L2]).
re_search(Height, Width, Tab, '$end_of_table', Re, Turn, Opos) ->
P = 'EOT (q)uit (p)Digits (k)ill /Regexp -->',
choice(Height, Width, P, {re, Re}, Tab, '$end_of_table', Turn, Opos);
re_search(Height, Width, Tab, Key, Re, Turn, Opos) when Turn < Height ->
re_display(Height, Width, Tab, Key, ets:lookup(Tab, Key), Re, Turn, Opos);
re_search(Height, Width, Tab, Key, Re, Turn, Opos) ->
P = '(c)ontinue (q)uit (p)Digits (k)ill /Regexp -->',
choice(Height, Width, P, {re, Re}, Tab, Key, Turn, Opos).
re_display(Height, Width, Tab, Key, [], Re, Turn, Opos) ->
re_search(Height, Width, Tab, ets:next(Tab, Key), Re, Turn, Opos);
re_display(Height, Width, Tab, Key, [H|T], Re, Turn, Opos) ->
Str = to_string(H),
case re:run(Str, Re, [{capture,none}]) of
match ->
do_display_item(Height, Width, H, Opos),
re_display(Height, Width, Tab, Key, T, Re, Turn+1, Opos+1);
nomatch ->
re_display(Height, Width, Tab, Key, T, Re, Turn, Opos)
end.
print_re_num(_,'$end_of_table',_,_) -> ok;
print_re_num(Tab, Key, Num, Re) ->
Os = re_match(ets:lookup(Tab, Key), Re),
Len = length(Os),
if
(Num - Len) < 1 ->
O = lists:nth(Num, Os),
io:format("~p~n", [O]); %% use ppterm here instead
true ->
print_re_num(Tab, ets:next(Tab, Key), Num - Len, Re)
end.
re_match([], _) -> [];
re_match([H|T], Re) ->
case re:run(to_string(H), Re, [{capture,none}]) of
match ->
[H|re_match(T,Re)];
nomatch ->
re_match(T, Re)
end.
| null | https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/stdlib/src/ets.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%
ets == Erlang Term Store
------------------------------------------------------------------------------
these ones are also defined in erl_bif_types
------------------------------------------------------------------------------
The following functions used to be found in this module, but
are now BIFs (i.e. implemented in C).
all/0
delete/1
delete/2
first/1
info/2
safe_fixtable/2
lookup/2
lookup_element/3
is_compiled_ms/1
last/1
prev/2
rename/2
slot/2
match/1
match/3
match_object/1
match_object/2
match_object/3
select_reverse/1
select_reverse/2
select_reverse/3
select_delete/2
this one is REALLY opaque
$end_of_table is an allowed continuation in ets...
ordered_set
(is_atom(Table) or is_integer(Table)),
set/bag/duplicate_bag
(is_atom(Table) or is_integer(Table)),
Check that this is really a shell fun...
Dets bug?
Dets bug?
Produce a list of tuples from a table
Options := [Option]
Option := {extended_info,[ExtInfo]}
ExtInfo := object_count | md5sum
Read a dumped file from disk and create a corresponding table
Opts := [Opt]
Opt := {verify,bool()}
Uh? cannot happen?
Only use header count if no extended info
at all is present and verification is requested.
tabfile_info/1 reads the head information in an ets table dumped to
disk by means of file2tab and returns a list of the relevant table
information
Uh? cannot happen?
XXX: belongs in 'qlc'
End of table/2.
Print info about all tabs on the tty
pushes the remaining entries to the right instead, rather than
losing information.
no need to pad the last entry on the line
view a specific table
regexp
from regexp
use ppterm here instead
use ppterm here instead | Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(ets).
Interface to the Term store BIF 's
-export([file2tab/1,
file2tab/2,
filter/3,
foldl/3, foldr/3,
match_delete/2,
tab2file/2,
tab2file/3,
tabfile_info/1,
from_dets/2,
to_dets/2,
init_table/2,
test_ms/2,
tab2list/1,
table/1,
table/2,
fun2ms/1,
match_spec_run/2,
repair_continuation/2]).
-export([i/0, i/1, i/2, i/3]).
-type tab() :: atom() | tid().
-type ext_info() :: 'md5sum' | 'object_count'.
-type protection() :: 'private' | 'protected' | 'public'.
-type type() :: 'bag' | 'duplicate_bag' | 'ordered_set' | 'set'.
-type table_info() :: {'name', atom()}
| {'type', type()}
| {'protection', protection()}
| {'named_table', bool()}
| {'keypos', non_neg_integer()}
| {'size', non_neg_integer()}
| {'extended_info', [ext_info()]}
| {'version', {non_neg_integer(), non_neg_integer()}}.
-type match_pattern() :: atom() | tuple().
-type match_specs() :: [{match_pattern(), [_], [_]}].
info/1
insert/2
next/2
match_spec_compile/1
select/1
select/2
select/3
update_counter/3
-spec match_spec_run([tuple()], comp_match_spec()) -> [term()].
match_spec_run(List, CompiledMS) ->
lists:reverse(ets:match_spec_run_r(List, CompiledMS, [])).
-type continuation() :: '$end_of_table'
| {tab(),integer(),integer(),binary(),list(),integer()}
| {tab(),_,_,integer(),binary(),list(),integer(),integer()}.
-spec repair_continuation(continuation(), match_specs()) -> continuation().
repair_continuation('$end_of_table', _) ->
'$end_of_table';
repair_continuation(Untouched = {Table,Lastkey,EndCondition,N2,Bin,L2,N3,N4}, MS)
is_integer(N2),
byte_size(Bin) =:= 0,
is_list(L2),
is_integer(N3),
is_integer(N4) ->
case ets:is_compiled_ms(Bin) of
true ->
Untouched;
false ->
{Table,Lastkey,EndCondition,N2,ets:match_spec_compile(MS),L2,N3,N4}
end;
repair_continuation(Untouched = {Table,N1,N2,Bin,L,N3}, MS)
is_integer(N1),
is_integer(N2),
byte_size(Bin) =:= 0,
is_list(L),
is_integer(N3) ->
case ets:is_compiled_ms(Bin) of
true ->
Untouched;
false ->
{Table,N1,N2,ets:match_spec_compile(MS),L,N3}
end.
-spec fun2ms(function()) -> match_specs().
fun2ms(ShellFun) when is_function(ShellFun) ->
case erl_eval:fun_data(ShellFun) of
{fun_data,ImportList,Clauses} ->
case ms_transform:transform_from_shell(
?MODULE,Clauses,ImportList) of
{error,[{_,[{_,_,Code}|_]}|_],_} ->
io:format("Error: ~s~n",
[ms_transform:format_error(Code)]),
{error,transform_error};
Else ->
Else
end;
false ->
exit({badarg,{?MODULE,fun2ms,
[function,called,with,real,'fun',
should,be,transformed,with,
parse_transform,'or',called,with,
a,'fun',generated,in,the,
shell]}})
end.
-spec foldl(fun((_, term()) -> term()), term(), tab()) -> term().
foldl(F, Accu, T) ->
ets:safe_fixtable(T, true),
First = ets:first(T),
try
do_foldl(F, Accu, First, T)
after
ets:safe_fixtable(T, false)
end.
do_foldl(F, Accu0, Key, T) ->
case Key of
'$end_of_table' ->
Accu0;
_ ->
do_foldl(F,
lists:foldl(F, Accu0, ets:lookup(T, Key)),
ets:next(T, Key), T)
end.
-spec foldr(fun((_, term()) -> term()), term(), tab()) -> term().
foldr(F, Accu, T) ->
ets:safe_fixtable(T, true),
Last = ets:last(T),
try
do_foldr(F, Accu, Last, T)
after
ets:safe_fixtable(T, false)
end.
do_foldr(F, Accu0, Key, T) ->
case Key of
'$end_of_table' ->
Accu0;
_ ->
do_foldr(F,
lists:foldr(F, Accu0, ets:lookup(T, Key)),
ets:prev(T, Key), T)
end.
-spec from_dets(tab(), dets:tab_name()) -> 'true'.
from_dets(EtsTable, DetsTable) ->
case (catch dets:to_ets(DetsTable, EtsTable)) of
{error, Reason} ->
erlang:error(Reason, [EtsTable,DetsTable]);
{'EXIT', {Reason1, _Stack1}} ->
erlang:error(Reason1,[EtsTable,DetsTable]);
{'EXIT', EReason} ->
erlang:error(EReason,[EtsTable,DetsTable]);
EtsTable ->
true;
erlang:error(Unexpected,[EtsTable,DetsTable])
end.
-spec to_dets(tab(), dets:tab_name()) -> tab().
to_dets(EtsTable, DetsTable) ->
case (catch dets:from_ets(DetsTable, EtsTable)) of
{error, Reason} ->
erlang:error(Reason, [EtsTable,DetsTable]);
{'EXIT', {Reason1, _Stack1}} ->
erlang:error(Reason1,[EtsTable,DetsTable]);
{'EXIT', EReason} ->
erlang:error(EReason,[EtsTable,DetsTable]);
ok ->
DetsTable;
erlang:error(Unexpected,[EtsTable,DetsTable])
end.
-spec test_ms(tuple(), match_specs()) ->
{'ok', term()} | {'error', [{'warning'|'error', string()}]}.
test_ms(Term, MS) ->
case erlang:match_spec_test(Term, MS, table) of
{ok, Result, _Flags, _Messages} ->
{ok, Result};
{error, _Errors} = Error ->
Error
end.
-spec init_table(tab(), fun(('read' | 'close') -> term())) -> 'true'.
init_table(Table, Fun) ->
ets:delete_all_objects(Table),
init_table_continue(Table, Fun(read)).
init_table_continue(_Table, end_of_input) ->
true;
init_table_continue(Table, {List, Fun}) when is_list(List), is_function(Fun) ->
case (catch init_table_sub(Table, List)) of
{'EXIT', Reason} ->
(catch Fun(close)),
exit(Reason);
true ->
init_table_continue(Table, Fun(read))
end;
init_table_continue(_Table, Error) ->
exit(Error).
init_table_sub(_Table, []) ->
true;
init_table_sub(Table, [H|T]) ->
ets:insert(Table, H),
init_table_sub(Table, T).
-spec match_delete(tab(), match_pattern()) -> 'true'.
match_delete(Table, Pattern) ->
ets:select_delete(Table, [{Pattern,[],[true]}]),
true.
-spec tab2list(tab()) -> [tuple()].
tab2list(T) ->
ets:match_object(T, '_').
-spec filter(tab(), function(), [term()]) -> [term()].
filter(Tn, F, A) when is_atom(Tn) ; is_integer(Tn) ->
do_filter(Tn, ets:first(Tn), F, A, []).
do_filter(_Tab, '$end_of_table', _, _, Ack) ->
Ack;
do_filter(Tab, Key, F, A, Ack) ->
case apply(F, [ets:lookup(Tab, Key)|A]) of
false ->
do_filter(Tab, ets:next(Tab, Key), F, A, Ack);
true ->
Ack2 = ets:lookup(Tab, Key) ++ Ack,
do_filter(Tab, ets:next(Tab, Key), F, A, Ack2);
{true, Value} ->
do_filter(Tab, ets:next(Tab, Key), F, A, [Value|Ack])
end.
Dump a table to a file using the disk_log facility
-define(MAJOR_F2T_VERSION,1).
-define(MINOR_F2T_VERSION,0).
-record(filetab_options,
{
object_count = false :: bool(),
md5sum = false :: bool()
}).
-type fname() :: string() | atom().
-type t2f_option() :: {'extended_info', [ext_info()]}.
-spec tab2file(tab(), fname()) -> 'ok' | {'error', term()}.
tab2file(Tab, File) ->
tab2file(Tab, File, []).
-spec tab2file(tab(), fname(), [t2f_option()]) -> 'ok' | {'error', term()}.
tab2file(Tab, File, Options) ->
try
{ok, FtOptions} = parse_ft_options(Options),
file:delete(File),
case file:read_file_info(File) of
{error, enoent} -> ok;
_ -> throw(eaccess)
end,
Name = make_ref(),
case disk_log:open([{name, Name}, {file, File}]) of
{ok, Name} ->
ok;
{error, Reason} ->
throw(Reason)
end,
try
Info0 = case ets:info(Tab) of
undefined ->
erlang : error(badarg , [ Tab , File , Options ] ) ;
throw(badtab);
I ->
I
end,
Info = [list_to_tuple(Info0 ++
[{major_version,?MAJOR_F2T_VERSION},
{minor_version,?MINOR_F2T_VERSION},
{extended_info,
ft_options_to_list(FtOptions)}])],
{LogFun, InitState} =
case FtOptions#filetab_options.md5sum of
true ->
{fun(Oldstate,Termlist) ->
{NewState,BinList} =
md5terms(Oldstate,Termlist),
disk_log:blog_terms(Name,BinList),
NewState
end,
erlang:md5_init()};
false ->
{fun(_,Termlist) ->
disk_log:log_terms(Name,Termlist),
true
end,
true}
end,
ets:safe_fixtable(Tab,true),
{NewState1,Num} = try
NewState = LogFun(InitState,Info),
dump_file(
ets:select(Tab,[{'_',[],['$_']}],100),
LogFun, NewState, 0)
after
(catch ets:safe_fixtable(Tab,false))
end,
EndInfo =
case FtOptions#filetab_options.object_count of
true ->
[{count,Num}];
false ->
[]
end ++
case FtOptions#filetab_options.md5sum of
true ->
[{md5,erlang:md5_final(NewState1)}];
false ->
[]
end,
case EndInfo of
[] ->
ok;
List ->
LogFun(NewState1,[['$end_of_table',List]])
end,
disk_log:close(Name)
catch
throw:TReason ->
disk_log:close(Name),
file:delete(File),
throw(TReason);
exit:ExReason ->
disk_log:close(Name),
file:delete(File),
exit(ExReason);
error:ErReason ->
disk_log:close(Name),
file:delete(File),
erlang:raise(error,ErReason,erlang:get_stacktrace())
end
catch
throw:TReason2 ->
{error,TReason2};
exit:ExReason2 ->
{error,ExReason2}
end.
dump_file('$end_of_table', _LogFun, State, Num) ->
{State,Num};
dump_file({Terms, Context}, LogFun, State, Num) ->
Count = length(Terms),
NewState = LogFun(State, Terms),
dump_file(ets:select(Context), LogFun, NewState, Num + Count).
ft_options_to_list(#filetab_options{md5sum = MD5, object_count = PS}) ->
case PS of
true ->
[object_count];
_ ->
[]
end ++
case MD5 of
true ->
[md5sum];
_ ->
[]
end.
md5terms(State, []) ->
{State, []};
md5terms(State, [H|T]) ->
B = term_to_binary(H),
NewState = erlang:md5_update(State, B),
{FinState, TL} = md5terms(NewState, T),
{FinState, [B|TL]}.
parse_ft_options(Options) when is_list(Options) ->
{Opt,Rest} = case (catch lists:keytake(extended_info,1,Options)) of
false ->
{[],Options};
{value,{extended_info,L},R} when is_list(L) ->
{L,R}
end,
case Rest of
[] ->
parse_ft_info_options(#filetab_options{}, Opt);
Other ->
throw({unknown_option, Other})
end;
parse_ft_options(Malformed) ->
throw({malformed_option, Malformed}).
parse_ft_info_options(FtOpt,[]) ->
{ok,FtOpt};
parse_ft_info_options(FtOpt,[object_count | T]) ->
parse_ft_info_options(FtOpt#filetab_options{object_count = true}, T);
parse_ft_info_options(FtOpt,[md5sum | T]) ->
parse_ft_info_options(FtOpt#filetab_options{md5sum = true}, T);
parse_ft_info_options(_,[Unexpected | _]) ->
throw({unknown_option,[{extended_info,[Unexpected]}]});
parse_ft_info_options(_,Malformed) ->
throw({malformed_option,Malformed}).
-type f2t_option() :: {'verify', bool()}.
-spec file2tab(fname()) -> {'ok', tab()} | {'error', term()}.
file2tab(File) ->
file2tab(File, []).
-spec file2tab(fname(), [f2t_option()]) -> {'ok', tab()} | {'error', term()}.
file2tab(File, Opts) ->
try
{ok,Verify} = parse_f2t_opts(Opts,false),
Name = make_ref(),
{ok, Major, Minor, FtOptions, MD5State, FullHeader, DLContext} =
case disk_log:open([{name, Name},
{file, File},
{mode, read_only}]) of
{ok, Name} ->
get_header_data(Name,Verify);
case Verify of
true ->
disk_log:close(Name),
throw(badfile);
false ->
get_header_data(Name,Verify)
end;
{error, Other1} ->
throw({read_error, Other1});
Other2 ->
throw(Other2)
end,
try
if
Major > ?MAJOR_F2T_VERSION ->
throw({unsupported_file_version,{Major,Minor}});
true ->
ok
end,
{ok, Tab, HeadCount} = create_tab(FullHeader),
StrippedOptions =
case Verify of
true ->
FtOptions;
false ->
#filetab_options{}
end,
{ReadFun,InitState} =
case StrippedOptions#filetab_options.md5sum of
true ->
{fun({OldMD5State,OldCount,_OL,ODLContext} = OS) ->
case wrap_bchunk(Name,ODLContext,100,Verify) of
eof ->
{OS,[]};
{NDLContext,Blist} ->
{Termlist, NewMD5State,
NewCount,NewLast} =
md5_and_convert(Blist,
OldMD5State,
OldCount),
{{NewMD5State, NewCount,
NewLast,NDLContext},
Termlist}
end
end,
{MD5State,0,[],DLContext}};
false ->
{fun({_,OldCount,_OL,ODLContext} = OS) ->
case wrap_chunk(Name,ODLContext,100,Verify) of
eof ->
{OS,[]};
{NDLContext,List} ->
{NewLast,NewCount,NewList} =
scan_for_endinfo(List, OldCount),
{{false,NewCount,NewLast,NDLContext},
NewList}
end
end,
{false,0,[],DLContext}}
end,
try
do_read_and_verify(ReadFun,InitState,Tab,
StrippedOptions,HeadCount,Verify)
catch
throw:TReason ->
ets:delete(Tab),
throw(TReason);
exit:ExReason ->
ets:delete(Tab),
exit(ExReason);
error:ErReason ->
ets:delete(Tab),
erlang:raise(error,ErReason,erlang:get_stacktrace())
end
after
disk_log:close(Name)
end
catch
throw:TReason2 ->
{error,TReason2};
exit:ExReason2 ->
{error,ExReason2}
end.
do_read_and_verify(ReadFun,InitState,Tab,FtOptions,HeadCount,Verify) ->
case load_table(ReadFun,InitState,Tab) of
{ok,{_,FinalCount,[],_}} ->
case {FtOptions#filetab_options.md5sum,
FtOptions#filetab_options.object_count} of
{false,false} ->
case Verify of
false ->
ok;
true ->
case FinalCount of
HeadCount ->
ok;
_ ->
throw(invalid_object_count)
end
end;
_ ->
throw(badfile)
end,
{ok,Tab};
{ok,{FinalMD5State,FinalCount,['$end_of_table',LastInfo],_}} ->
ECount = case lists:keysearch(count,1,LastInfo) of
{value,{count,N}} ->
N;
_ ->
false
end,
EMD5 = case lists:keysearch(md5,1,LastInfo) of
{value,{md5,M}} ->
M;
_ ->
false
end,
case FtOptions#filetab_options.md5sum of
true ->
case erlang:md5_final(FinalMD5State) of
EMD5 ->
ok;
_MD5MisM ->
throw(checksum_error)
end;
false ->
ok
end,
case FtOptions#filetab_options.object_count of
true ->
case FinalCount of
ECount ->
ok;
_Other ->
throw(invalid_object_count)
end;
false ->
case {Verify,FtOptions#filetab_options.md5sum} of
{true,false} ->
case FinalCount of
HeadCount ->
ok;
_Other2 ->
throw(invalid_object_count)
end;
_ ->
ok
end
end,
{ok,Tab}
end.
parse_f2t_opts([],Verify) ->
{ok,Verify};
parse_f2t_opts([{verify, true}|T],_OV) ->
parse_f2t_opts(T,true);
parse_f2t_opts([{verify,false}|T],OV) ->
parse_f2t_opts(T,OV);
parse_f2t_opts([Unexpected|_],_) ->
throw({unknown_option,Unexpected});
parse_f2t_opts(Malformed,_) ->
throw({malformed_option,Malformed}).
count_mandatory([]) ->
0;
count_mandatory([{Tag,_}|T]) when Tag =:= name;
Tag =:= type;
Tag =:= protection;
Tag =:= named_table;
Tag =:= keypos;
Tag =:= size ->
1+count_mandatory(T);
count_mandatory([_|T]) ->
count_mandatory(T).
verify_header_mandatory(L) ->
count_mandatory(L) =:= 6.
wrap_bchunk(Name,C,N,true) ->
case disk_log:bchunk(Name,C,N) of
{_,_,X} when X > 0 ->
throw(badfile);
{NC,Bin,_} ->
{NC,Bin};
Y ->
Y
end;
wrap_bchunk(Name,C,N,false) ->
case disk_log:bchunk(Name,C,N) of
{NC,Bin,_} ->
{NC,Bin};
Y ->
Y
end.
wrap_chunk(Name,C,N,true) ->
case disk_log:chunk(Name,C,N) of
{_,_,X} when X > 0 ->
throw(badfile);
{NC,TL,_} ->
{NC,TL};
Y ->
Y
end;
wrap_chunk(Name,C,N,false) ->
case disk_log:chunk(Name,C,N) of
{NC,TL,_} ->
{NC,TL};
Y ->
Y
end.
get_header_data(Name,true) ->
case wrap_bchunk(Name,start,1,true) of
{C,[Bin]} when is_binary(Bin) ->
T = binary_to_term(Bin),
case T of
Tup when is_tuple(Tup) ->
L = tuple_to_list(Tup),
case verify_header_mandatory(L) of
false ->
throw(badfile);
true ->
Major = case lists:keysearch(major,1,L) of
{value,{major,Maj}} ->
Maj;
_ ->
0
end,
Minor = case lists:keysearch(minor,1,L) of
{value,{minor,Min}} ->
Min;
_ ->
0
end,
FtOptions =
case lists:keysearch(extended_info,1,L) of
{value,{extended_info,I}}
when is_list(I) ->
#filetab_options
{
object_count =
lists:member(object_count,I),
md5sum =
lists:member(md5sum,I)
};
_ ->
#filetab_options{}
end,
MD5Initial =
case FtOptions#filetab_options.md5sum of
true ->
X = erlang:md5_init(),
erlang:md5_update(X,Bin);
false ->
false
end,
{ok, Major, Minor, FtOptions, MD5Initial, L, C}
end;
_X ->
throw(badfile)
end;
_Y ->
throw(badfile)
end;
get_header_data(Name, false) ->
case wrap_chunk(Name,start,1,false) of
{C,[Tup]} when is_tuple(Tup) ->
L = tuple_to_list(Tup),
case verify_header_mandatory(L) of
false ->
throw(badfile);
true ->
Major = case lists:keysearch(major_version,1,L) of
{value,{major_version,Maj}} ->
Maj;
_ ->
0
end,
Minor = case lists:keysearch(minor_version,1,L) of
{value,{minor_version,Min}} ->
Min;
_ ->
0
end,
FtOptions =
case lists:keysearch(extended_info,1,L) of
{value,{extended_info,I}}
when is_list(I) ->
#filetab_options
{
object_count =
lists:member(object_count,I),
md5sum =
lists:member(md5sum,I)
};
_ ->
#filetab_options{}
end,
{ok, Major, Minor, FtOptions, false, L, C}
end;
_ ->
throw(badfile)
end.
md5_and_convert([],MD5State,Count) ->
{[],MD5State,Count,[]};
md5_and_convert([H|T],MD5State,Count) when is_binary(H) ->
case (catch binary_to_term(H)) of
{'EXIT', _} ->
md5_and_convert(T,MD5State,Count);
['$end_of_table',Dat] ->
{[],MD5State,Count,['$end_of_table',Dat]};
Term ->
X = erlang:md5_update(MD5State,H),
{Rest,NewMD5,NewCount,NewLast} = md5_and_convert(T,X,Count+1),
{[Term | Rest],NewMD5,NewCount,NewLast}
end.
scan_for_endinfo([],Count) ->
{[],Count,[]};
scan_for_endinfo([['$end_of_table',Dat]],Count) ->
{['$end_of_table',Dat],Count,[]};
scan_for_endinfo([Term|T],Count) ->
{NewLast,NCount,Rest} = scan_for_endinfo(T,Count+1),
{NewLast,NCount,[Term | Rest]}.
load_table(ReadFun, State, Tab) ->
{NewState,NewData} = ReadFun(State),
case NewData of
[] ->
{ok,NewState};
List ->
ets:insert(Tab,List),
load_table(ReadFun,NewState,Tab)
end.
create_tab(I) ->
{value, {name, Name}} = lists:keysearch(name, 1, I),
{value, {type, Type}} = lists:keysearch(type, 1, I),
{value, {protection, P}} = lists:keysearch(protection, 1, I),
{value, {named_table, Val}} = lists:keysearch(named_table, 1, I),
{value, {keypos, Kp}} = lists:keysearch(keypos, 1, I),
{value, {size, Sz}} = lists:keysearch(size, 1, I),
try
Tab = ets:new(Name, [Type, P, {keypos, Kp} | named_table(Val)]),
{ok, Tab, Sz}
catch
_:_ ->
throw(cannot_create_table)
end.
named_table(true) -> [named_table];
named_table(false) -> [].
-spec tabfile_info(fname()) -> {'ok', [table_info()]} | {'error', term()}.
tabfile_info(File) when is_list(File) ; is_atom(File) ->
try
Name = make_ref(),
{ok, Major, Minor, _FtOptions, _MD5State, FullHeader, _DLContext} =
case disk_log:open([{name, Name},
{file, File},
{mode, read_only}]) of
{ok, Name} ->
get_header_data(Name,false);
get_header_data(Name,false);
{error, Other1} ->
throw({read_error, Other1});
Other2 ->
throw(Other2)
end,
disk_log:close(Name),
{value, N} = lists:keysearch(name, 1, FullHeader),
{value, Type} = lists:keysearch(type, 1, FullHeader),
{value, P} = lists:keysearch(protection, 1, FullHeader),
{value, Val} = lists:keysearch(named_table, 1, FullHeader),
{value, Kp} = lists:keysearch(keypos, 1, FullHeader),
{value, Sz} = lists:keysearch(size, 1, FullHeader),
Ei = case lists:keysearch(extended_info, 1, FullHeader) of
{value, Ei0} -> Ei0;
_ -> {extended_info, []}
end,
{ok, [N,Type,P,Val,Kp,Sz,Ei,{version,{Major,Minor}}]}
catch
throw:TReason ->
{error,TReason};
exit:ExReason ->
{error,ExReason}
end.
-type num_objects() :: 'default' | pos_integer().
-type trav_method() :: 'first_next' | 'last_prev'
| 'select' | {'select', match_specs()}.
-type table_option() :: {'n_objects', num_objects()}
| {'traverse', trav_method()}.
-spec table(tab()) -> qlc__query_handle().
table(Tab) ->
table(Tab, []).
-spec table(tab(), table_option() | [table_option()]) -> qlc__query_handle().
table(Tab, Opts) ->
case options(Opts, [traverse, n_objects]) of
{badarg,_} ->
erlang:error(badarg, [Tab, Opts]);
[[Traverse, NObjs], QlcOptions] ->
TF = case Traverse of
first_next ->
fun() -> qlc_next(Tab, ets:first(Tab)) end;
last_prev ->
fun() -> qlc_prev(Tab, ets:last(Tab)) end;
select ->
fun(MS) -> qlc_select(ets:select(Tab, MS, NObjs)) end;
{select, MS} ->
fun() -> qlc_select(ets:select(Tab, MS, NObjs)) end
end,
PreFun = fun(_) -> ets:safe_fixtable(Tab, true) end,
PostFun = fun() -> ets:safe_fixtable(Tab, false) end,
InfoFun = fun(Tag) -> table_info(Tab, Tag) end,
KeyEquality = case ets:info(Tab, type) of
ordered_set -> '==';
_ -> '=:='
end,
LookupFun =
case Traverse of
{select, _MS} ->
undefined;
_ ->
fun(_Pos, [K]) ->
ets:lookup(Tab, K);
(_Pos, Ks) ->
lists:flatmap(fun(K) -> ets:lookup(Tab, K)
end, Ks)
end
end,
FormatFun =
fun({all, _NElements, _ElementFun}) ->
As = [Tab | [Opts || _ <- [[]], Opts =/= []]],
{?MODULE, table, As};
({match_spec, MS}) ->
{?MODULE, table,
[Tab, [{traverse, {select, MS}} |
listify(Opts)]]};
({lookup, _KeyPos, [Value], _NElements, ElementFun}) ->
io_lib:format("~w:lookup(~w, ~w)",
[?MODULE, Tab, ElementFun(Value)]);
({lookup, _KeyPos, Values, _NElements, ElementFun}) ->
Vals = [ElementFun(V) || V <- Values],
io_lib:format("lists:flatmap(fun(V) -> "
"~w:lookup(~w, V) end, ~w)",
[?MODULE, Tab, Vals])
end,
qlc:table(TF, [{pre_fun, PreFun}, {post_fun, PostFun},
{info_fun, InfoFun}, {format_fun, FormatFun},
{key_equality, KeyEquality},
{lookup_fun, LookupFun}] ++ QlcOptions)
end.
table_info(Tab, num_of_objects) ->
ets:info(Tab, size);
table_info(Tab, keypos) ->
ets:info(Tab, keypos);
table_info(Tab, is_unique_objects) ->
ets:info(Tab, type) =/= duplicate_bag;
table_info(Tab, is_sorted_key) ->
ets:info(Tab, type) =:= ordered_set;
table_info(_Tab, _) ->
undefined.
qlc_next(_Tab, '$end_of_table') ->
[];
qlc_next(Tab, Key) ->
ets:lookup(Tab, Key) ++ fun() -> qlc_next(Tab, ets:next(Tab, Key)) end.
qlc_prev(_Tab, '$end_of_table') ->
[];
qlc_prev(Tab, Key) ->
ets:lookup(Tab, Key) ++ fun() -> qlc_prev(Tab, ets:prev(Tab, Key)) end.
qlc_select('$end_of_table') ->
[];
qlc_select({Objects, Cont}) ->
Objects ++ fun() -> qlc_select(ets:select(Cont)) end.
options(Options, Keys) when is_list(Options) ->
options(Options, Keys, []);
options(Option, Keys) ->
options([Option], Keys, []).
options(Options, [Key | Keys], L) when is_list(Options) ->
V = case lists:keysearch(Key, 1, Options) of
{value, {n_objects, default}} ->
{ok, default_option(Key)};
{value, {n_objects, NObjs}} when is_integer(NObjs),
NObjs >= 1 ->
{ok, NObjs};
{value, {traverse, select}} ->
{ok, select};
{value, {traverse, {select, MS}}} ->
{ok, {select, MS}};
{value, {traverse, first_next}} ->
{ok, first_next};
{value, {traverse, last_prev}} ->
{ok, last_prev};
{value, {Key, _}} ->
badarg;
false ->
Default = default_option(Key),
{ok, Default}
end,
case V of
badarg ->
{badarg, Key};
{ok,Value} ->
NewOptions = lists:keydelete(Key, 1, Options),
options(NewOptions, Keys, [Value | L])
end;
options(Options, [], L) ->
[lists:reverse(L), Options].
default_option(traverse) -> select;
default_option(n_objects) -> 100.
listify(L) when is_list(L) ->
L;
listify(T) ->
[T].
-spec i() -> 'ok'.
i() ->
hform('id', 'name', 'type', 'size', 'mem', 'owner'),
io:format(" -------------------------------------"
"---------------------------------------\n"),
lists:foreach(fun prinfo/1, tabs()),
ok.
tabs() ->
lists:sort(ets:all()).
prinfo(Tab) ->
case catch prinfo2(Tab) of
{'EXIT', _} ->
io:format("~-10s ... unreadable \n", [to_string(Tab)]);
ok ->
ok
end.
prinfo2(Tab) ->
Name = ets:info(Tab, name),
Type = ets:info(Tab, type),
Size = ets:info(Tab, size),
Mem = ets:info(Tab, memory),
Owner = ets:info(Tab, owner),
hform(Tab, Name, Type, Size, Mem, is_reg(Owner)).
is_reg(Owner) ->
case process_info(Owner, registered_name) of
{registered_name, Name} -> Name;
_ -> Owner
end.
: this code used to truncate over - sized fields . Now it
hform(A0, B0, C0, D0, E0, F0) ->
[A,B,C,D,E,F] = [to_string(T) || T <- [A0,B0,C0,D0,E0,F0]],
A1 = pad_right(A, 15),
B1 = pad_right(B, 17),
C1 = pad_right(C, 5),
D1 = pad_right(D, 6),
E1 = pad_right(E, 8),
io:format(" ~s ~s ~s ~s ~s ~s\n", [A1,B1,C1,D1,E1,F]).
pad_right(String, Len) ->
if
length(String) >= Len ->
String;
true ->
[Space] = " ",
String ++ lists:duplicate(Len - length(String), Space)
end.
to_string(X) ->
lists:flatten(io_lib:format("~p", [X])).
-spec i(tab()) -> 'ok'.
i(Tab) ->
i(Tab, 40).
-spec i(tab(), pos_integer()) -> 'ok'.
i(Tab, Height) ->
i(Tab, Height, 80).
-spec i(tab(), pos_integer(), pos_integer()) -> 'ok'.
i(Tab, Height, Width) ->
First = ets:first(Tab),
display_items(Height, Width, Tab, First, 1, 1).
display_items(Height, Width, Tab, '$end_of_table', Turn, Opos) ->
P = 'EOT (q)uit (p)Digits (k)ill /Regexp -->',
choice(Height, Width, P, eot, Tab, '$end_of_table', Turn, Opos);
display_items(Height, Width, Tab, Key, Turn, Opos) when Turn < Height ->
do_display(Height, Width, Tab, Key, Turn, Opos);
display_items(Height, Width, Tab, Key, Turn, Opos) when Turn >= Height ->
P = '(c)ontinue (q)uit (p)Digits (k)ill /Regexp -->',
choice(Height, Width, P, normal, Tab, Key, Turn, Opos).
choice(Height, Width, P, Mode, Tab, Key, Turn, Opos) ->
case get_line(P, "c\n") of
"c\n" when Mode =:= normal ->
do_display(Height, Width, Tab, Key, 1, Opos);
"c\n" when is_tuple(Mode), element(1, Mode) =:= re ->
{re, Re} = Mode,
re_search(Height, Width, Tab, Key, Re, 1, Opos);
"q\n" ->
ok;
"k\n" ->
ets:delete(Tab),
ok;
[$p|Digs] ->
catch case catch list_to_integer(nonl(Digs)) of
{'EXIT', _} ->
io:put_chars("Bad digits\n");
Number when Mode =:= normal ->
print_number(Tab, ets:first(Tab), Number);
Number when Mode =:= eot ->
print_number(Tab, ets:first(Tab), Number);
{re, Re} = Mode,
print_re_num(Tab, ets:first(Tab), Number, Re)
end,
choice(Height, Width, P, Mode, Tab, Key, Turn, Opos);
case re:compile(nonl(Regexp)) of
{ok,Re} ->
re_search(Height, Width, Tab, ets:first(Tab), Re, 1, 1);
{error,{ErrorString,_Pos}} ->
io:format("~s\n", [ErrorString]),
choice(Height, Width, P, Mode, Tab, Key, Turn, Opos)
end;
_ ->
choice(Height, Width, P, Mode, Tab, Key, Turn, Opos)
end.
get_line(P, Default) ->
case io:get_line(P) of
"\n" ->
Default;
L ->
L
end.
nonl(S) -> string:strip(S, right, $\n).
print_number(Tab, Key, Num) ->
Os = ets:lookup(Tab, Key),
Len = length(Os),
if
(Num - Len) < 1 ->
O = lists:nth(Num, Os),
true ->
print_number(Tab, ets:next(Tab, Key), Num - Len)
end.
do_display(Height, Width, Tab, Key, Turn, Opos) ->
Objs = ets:lookup(Tab, Key),
do_display_items(Height, Width, Objs, Opos),
Len = length(Objs),
display_items(Height, Width, Tab, ets:next(Tab, Key), Turn+Len, Opos+Len).
do_display_items(Height, Width, [Obj|Tail], Opos) ->
do_display_item(Height, Width, Obj, Opos),
do_display_items(Height, Width, Tail, Opos+1);
do_display_items(_Height, _Width, [], Opos) ->
Opos.
do_display_item(_Height, Width, I, Opos) ->
L = to_string(I),
L2 = if
length(L) > Width - 8 ->
string:substr(L, 1, Width-13) ++ " ...";
true ->
L
end,
io:format("<~-4w> ~s~n", [Opos,L2]).
re_search(Height, Width, Tab, '$end_of_table', Re, Turn, Opos) ->
P = 'EOT (q)uit (p)Digits (k)ill /Regexp -->',
choice(Height, Width, P, {re, Re}, Tab, '$end_of_table', Turn, Opos);
re_search(Height, Width, Tab, Key, Re, Turn, Opos) when Turn < Height ->
re_display(Height, Width, Tab, Key, ets:lookup(Tab, Key), Re, Turn, Opos);
re_search(Height, Width, Tab, Key, Re, Turn, Opos) ->
P = '(c)ontinue (q)uit (p)Digits (k)ill /Regexp -->',
choice(Height, Width, P, {re, Re}, Tab, Key, Turn, Opos).
re_display(Height, Width, Tab, Key, [], Re, Turn, Opos) ->
re_search(Height, Width, Tab, ets:next(Tab, Key), Re, Turn, Opos);
re_display(Height, Width, Tab, Key, [H|T], Re, Turn, Opos) ->
Str = to_string(H),
case re:run(Str, Re, [{capture,none}]) of
match ->
do_display_item(Height, Width, H, Opos),
re_display(Height, Width, Tab, Key, T, Re, Turn+1, Opos+1);
nomatch ->
re_display(Height, Width, Tab, Key, T, Re, Turn, Opos)
end.
print_re_num(_,'$end_of_table',_,_) -> ok;
print_re_num(Tab, Key, Num, Re) ->
Os = re_match(ets:lookup(Tab, Key), Re),
Len = length(Os),
if
(Num - Len) < 1 ->
O = lists:nth(Num, Os),
true ->
print_re_num(Tab, ets:next(Tab, Key), Num - Len, Re)
end.
re_match([], _) -> [];
re_match([H|T], Re) ->
case re:run(to_string(H), Re, [{capture,none}]) of
match ->
[H|re_match(T,Re)];
nomatch ->
re_match(T, Re)
end.
|
3aecc9cb569a3668b60771164174311dd9cf4f7e25126d5dab62e8958c179681 | binaryage/clearcut | messages.cljs | (ns clearcut.messages
"A subsystem for printing runtime warnings and errors."
(:require-macros [clearcut.messages :refer [gen-clearcut-message-prefix]]))
; -- helpers ----------------------------------------------------------------------------------------------------------------
(defn ^:dynamic post-process-message [msg]
(str (gen-clearcut-message-prefix) ", " msg))
; -- runtime error/warning messages -----------------------------------------------------------------------------------------
(defmulti runtime-message (fn [type & _] type))
( defmethod runtime - message : unexpected - soft - selector [ _ type ]
; (post-process-message (str "Unexpected soft selector (\"?\" does not make sense with oset!)")))
| null | https://raw.githubusercontent.com/binaryage/clearcut/7f44705cd8743f8679199cb78a215487eb411ed4/src/lib/clearcut/messages.cljs | clojure | -- helpers ----------------------------------------------------------------------------------------------------------------
-- runtime error/warning messages -----------------------------------------------------------------------------------------
(post-process-message (str "Unexpected soft selector (\"?\" does not make sense with oset!)"))) | (ns clearcut.messages
"A subsystem for printing runtime warnings and errors."
(:require-macros [clearcut.messages :refer [gen-clearcut-message-prefix]]))
(defn ^:dynamic post-process-message [msg]
(str (gen-clearcut-message-prefix) ", " msg))
(defmulti runtime-message (fn [type & _] type))
( defmethod runtime - message : unexpected - soft - selector [ _ type ]
|
1bc546cc99b9f74129f5852a5e5fc2b39f9f6d782997a876699bde312615f06c | robert-strandh/CLIMatis | graphics-packages.lisp | (defpackage #:clim3-graphics
(:use #:common-lisp)
(:export
))
| null | https://raw.githubusercontent.com/robert-strandh/CLIMatis/4949ddcc46d3f81596f956d12f64035e04589b29/Graphics/graphics-packages.lisp | lisp | (defpackage #:clim3-graphics
(:use #:common-lisp)
(:export
))
| |
5aceb21a53df2419f94a15753f34ba67543557f474fdf29e0fe1d146e83dbd4f | Holworth/SICP_Solutions | square-list-iter.rkt | #lang sicp
(define (square-list items)
(define (iter things ans)
(if (null? things)
ans
(iter (cdr things)
(append ans
(list (* (car things) (car things)))))
))
(iter items nil)
)
(square-list (list 1 2 3 4 5)) | null | https://raw.githubusercontent.com/Holworth/SICP_Solutions/c5c893545e6cd21d835a000dd226923c55475588/solutions/chap2/code/square-list-iter.rkt | racket | #lang sicp
(define (square-list items)
(define (iter things ans)
(if (null? things)
ans
(iter (cdr things)
(append ans
(list (* (car things) (car things)))))
))
(iter items nil)
)
(square-list (list 1 2 3 4 5)) | |
3c2d788f53330abf22ae730811f2a7e545b55c4e21fb06001173d71d1339730b | tolysz/prepare-ghcjs | Common.hs | # LANGUAGE CPP #
{-# LANGUAGE PackageImports #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module Typed.Common (load) where
import Prelude ()
import Prelude.Compat
import Data.ByteString.Lazy as L
import System.Exit
import System.IO
#ifndef HAS_BOTH_AESON_AND_BENCHMARKS
import Data.Aeson hiding (Result)
#else
import "aeson" Data.Aeson hiding (Result)
import qualified "aeson-benchmarks" Data.Aeson as B
#endif
load :: FromJSON a => FilePath -> IO a
load fileName = do
mv <- eitherDecode' <$> L.readFile fileName
case mv of
Right v -> return v
Left err -> do
hPutStrLn stderr $ fileName ++ ": JSON decode failed - " ++ err
exitWith (ExitFailure 1)
| null | https://raw.githubusercontent.com/tolysz/prepare-ghcjs/8499e14e27854a366e98f89fab0af355056cf055/spec-lts8/aeson/benchmarks/Typed/Common.hs | haskell | # LANGUAGE PackageImports # | # LANGUAGE CPP #
# OPTIONS_GHC -fno - warn - unused - imports #
module Typed.Common (load) where
import Prelude ()
import Prelude.Compat
import Data.ByteString.Lazy as L
import System.Exit
import System.IO
#ifndef HAS_BOTH_AESON_AND_BENCHMARKS
import Data.Aeson hiding (Result)
#else
import "aeson" Data.Aeson hiding (Result)
import qualified "aeson-benchmarks" Data.Aeson as B
#endif
load :: FromJSON a => FilePath -> IO a
load fileName = do
mv <- eitherDecode' <$> L.readFile fileName
case mv of
Right v -> return v
Left err -> do
hPutStrLn stderr $ fileName ++ ": JSON decode failed - " ++ err
exitWith (ExitFailure 1)
|
6d46d1a1d354e4355c5dc9cbe601bc372459c32b491ffa6cb1444ed47a255f49 | VisionsGlobalEmpowerment/webchange | state.cljs | (ns webchange.admin.pages.class-profile.state
(:require
[re-frame.core :as re-frame]
[re-frame.std-interceptors :as i]
[webchange.admin.routes :as routes]
[webchange.state.warehouse :as warehouse]))
(def path-to-db :page/class-profile)
(re-frame/reg-sub
path-to-db
(fn [db]
(get db path-to-db)))
;; Side Bar Content
(def side-bar-key :side-bar)
(defn- set-side-bar
([db component]
(assoc db side-bar-key {:component component}))
([db component props]
(assoc db side-bar-key {:component component
:props props})))
(re-frame/reg-sub
::side-bar
:<- [path-to-db]
#(get % side-bar-key {:component :class-form}))
(re-frame/reg-event-fx
::open-add-student-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :students-add)}))
(re-frame/reg-event-fx
::open-students-list
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :students-list)}))
(re-frame/reg-event-fx
::open-add-teacher-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :teachers-add)}))
(re-frame/reg-event-fx
::open-edit-teacher-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_ teacher-id]]
{:db (set-side-bar db :teacher-edit {:teacher-id teacher-id})}))
(re-frame/reg-event-fx
::open-teachers-list
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :teachers-list)}))
(re-frame/reg-event-fx
::open-class-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :class-form)}))
(re-frame/reg-event-fx
::open-assign-course-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :assign-course)}))
;; Class Form
(def form-editable-key :form-editable?)
(re-frame/reg-sub
::form-editable?
:<- [path-to-db]
#(get % form-editable-key false))
(defn- set-form-editable
[db value]
(assoc db form-editable-key value))
(re-frame/reg-event-fx
::set-form-editable
[(i/path path-to-db)]
(fn [{:keys [db]} [_ value]]
{:db (set-form-editable db value)}))
(re-frame/reg-event-fx
::handle-class-edit-cancel
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
(let [{:keys [on-edit-finished]} (:handlers db)]
{:dispatch-n (cond-> [[::set-form-editable false]]
(some? on-edit-finished) (conj on-edit-finished))})))
;; Class data
(re-frame/reg-sub
::class-data
:<- [path-to-db]
:class-data)
(defn- set-class-data
[db class-data]
(assoc db :class-data class-data))
(defn- update-class-data
[db class-data]
(update db :class-data merge class-data))
(re-frame/reg-event-fx
::update-class-data
[(i/path path-to-db)]
(fn [{:keys [db]} [_ data]]
(let [{:keys [on-edit-finished]} (:handlers db)]
(cond-> {:db (-> db
(update-class-data data)
(set-form-editable false))}
(some? on-edit-finished) (assoc :dispatch on-edit-finished)))))
;; school courses
(def school-courses-key :school-courses)
(defn- set-school-courses
[db data]
(assoc db school-courses-key data))
(re-frame/reg-sub
::school-courses
:<- [path-to-db]
#(get % school-courses-key []))
(re-frame/reg-sub
::school-courses-number
:<- [::school-courses]
#(count %))
;;
(re-frame/reg-event-fx
::init
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [class-id school-id params]}]]
(let [{:keys [action]} params]
{:db (-> db
(assoc :school-id school-id)
(assoc :class-id class-id)
(assoc :handlers (select-keys params [:on-edit-finished])))
:dispatch-n (cond-> [[::load-class]
[::warehouse/load-school-courses {:school-id school-id}
{:on-success [::load-school-courses-success]}]
[::warehouse/load-school {:school-id school-id}
{:on-success [::load-school-success]}]]
(= action "edit") (conj [::set-form-editable true])
(= action "manage-students") (conj [::open-students-list])
(= action "manage-teachers") (conj [::open-teachers-list]))})))
(re-frame/reg-event-fx
::load-class
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
(let [class-id (:class-id db)]
{:dispatch [::warehouse/load-class {:class-id class-id}
{:on-success [::load-class-success]}]})))
(re-frame/reg-event-fx
::load-class-success
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [class]}]]
{:db (set-class-data db class)}))
(re-frame/reg-event-fx
::load-school-courses-success
[(i/path path-to-db)]
(fn [{:keys [db]} [_ courses]]
{:db (set-school-courses db courses)}))
(re-frame/reg-event-fx
::load-school-success
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [school]}]]
{:db (assoc db :school-data school)}))
(re-frame/reg-sub
::readonly?
:<- [path-to-db]
#(get-in % [:school-data :readonly] false))
(re-frame/reg-sub
::class-stats
:<- [::class-data]
#(get % :stats {}))
(re-frame/reg-sub
::class-course
:<- [::class-data]
#(get % :course-info))
(re-frame/reg-event-fx
::handle-students-added
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [class]}]]
{:db (-> db
(update-class-data (select-keys class [:stats]))
(set-side-bar :class-form))}))
(re-frame/reg-event-fx
::handle-teachers-added
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [class]}]]
{:db (-> db
(update-class-data (select-keys class [:stats]))
(set-side-bar :class-form))}))
(re-frame/reg-event-fx
::open-students-activities
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
(let [{:keys [class-id school-id]} db]
{:dispatch [::routes/redirect :class-students :school-id school-id :class-id class-id]})))
(re-frame/reg-event-fx
::handle-class-deleted
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
(let [{:keys [school-id]} db]
{:dispatch [::routes/redirect :school-profile :school-id school-id]})))
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/2b14cfa0b116034312a382763e6aebd67e2f25a7/src/cljs/webchange/admin/pages/class_profile/state.cljs | clojure | Side Bar Content
Class Form
Class data
school courses
| (ns webchange.admin.pages.class-profile.state
(:require
[re-frame.core :as re-frame]
[re-frame.std-interceptors :as i]
[webchange.admin.routes :as routes]
[webchange.state.warehouse :as warehouse]))
(def path-to-db :page/class-profile)
(re-frame/reg-sub
path-to-db
(fn [db]
(get db path-to-db)))
(def side-bar-key :side-bar)
(defn- set-side-bar
([db component]
(assoc db side-bar-key {:component component}))
([db component props]
(assoc db side-bar-key {:component component
:props props})))
(re-frame/reg-sub
::side-bar
:<- [path-to-db]
#(get % side-bar-key {:component :class-form}))
(re-frame/reg-event-fx
::open-add-student-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :students-add)}))
(re-frame/reg-event-fx
::open-students-list
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :students-list)}))
(re-frame/reg-event-fx
::open-add-teacher-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :teachers-add)}))
(re-frame/reg-event-fx
::open-edit-teacher-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_ teacher-id]]
{:db (set-side-bar db :teacher-edit {:teacher-id teacher-id})}))
(re-frame/reg-event-fx
::open-teachers-list
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :teachers-list)}))
(re-frame/reg-event-fx
::open-class-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :class-form)}))
(re-frame/reg-event-fx
::open-assign-course-form
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
{:db (set-side-bar db :assign-course)}))
(def form-editable-key :form-editable?)
(re-frame/reg-sub
::form-editable?
:<- [path-to-db]
#(get % form-editable-key false))
(defn- set-form-editable
[db value]
(assoc db form-editable-key value))
(re-frame/reg-event-fx
::set-form-editable
[(i/path path-to-db)]
(fn [{:keys [db]} [_ value]]
{:db (set-form-editable db value)}))
(re-frame/reg-event-fx
::handle-class-edit-cancel
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
(let [{:keys [on-edit-finished]} (:handlers db)]
{:dispatch-n (cond-> [[::set-form-editable false]]
(some? on-edit-finished) (conj on-edit-finished))})))
(re-frame/reg-sub
::class-data
:<- [path-to-db]
:class-data)
(defn- set-class-data
[db class-data]
(assoc db :class-data class-data))
(defn- update-class-data
[db class-data]
(update db :class-data merge class-data))
(re-frame/reg-event-fx
::update-class-data
[(i/path path-to-db)]
(fn [{:keys [db]} [_ data]]
(let [{:keys [on-edit-finished]} (:handlers db)]
(cond-> {:db (-> db
(update-class-data data)
(set-form-editable false))}
(some? on-edit-finished) (assoc :dispatch on-edit-finished)))))
(def school-courses-key :school-courses)
(defn- set-school-courses
[db data]
(assoc db school-courses-key data))
(re-frame/reg-sub
::school-courses
:<- [path-to-db]
#(get % school-courses-key []))
(re-frame/reg-sub
::school-courses-number
:<- [::school-courses]
#(count %))
(re-frame/reg-event-fx
::init
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [class-id school-id params]}]]
(let [{:keys [action]} params]
{:db (-> db
(assoc :school-id school-id)
(assoc :class-id class-id)
(assoc :handlers (select-keys params [:on-edit-finished])))
:dispatch-n (cond-> [[::load-class]
[::warehouse/load-school-courses {:school-id school-id}
{:on-success [::load-school-courses-success]}]
[::warehouse/load-school {:school-id school-id}
{:on-success [::load-school-success]}]]
(= action "edit") (conj [::set-form-editable true])
(= action "manage-students") (conj [::open-students-list])
(= action "manage-teachers") (conj [::open-teachers-list]))})))
(re-frame/reg-event-fx
::load-class
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
(let [class-id (:class-id db)]
{:dispatch [::warehouse/load-class {:class-id class-id}
{:on-success [::load-class-success]}]})))
(re-frame/reg-event-fx
::load-class-success
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [class]}]]
{:db (set-class-data db class)}))
(re-frame/reg-event-fx
::load-school-courses-success
[(i/path path-to-db)]
(fn [{:keys [db]} [_ courses]]
{:db (set-school-courses db courses)}))
(re-frame/reg-event-fx
::load-school-success
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [school]}]]
{:db (assoc db :school-data school)}))
(re-frame/reg-sub
::readonly?
:<- [path-to-db]
#(get-in % [:school-data :readonly] false))
(re-frame/reg-sub
::class-stats
:<- [::class-data]
#(get % :stats {}))
(re-frame/reg-sub
::class-course
:<- [::class-data]
#(get % :course-info))
(re-frame/reg-event-fx
::handle-students-added
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [class]}]]
{:db (-> db
(update-class-data (select-keys class [:stats]))
(set-side-bar :class-form))}))
(re-frame/reg-event-fx
::handle-teachers-added
[(i/path path-to-db)]
(fn [{:keys [db]} [_ {:keys [class]}]]
{:db (-> db
(update-class-data (select-keys class [:stats]))
(set-side-bar :class-form))}))
(re-frame/reg-event-fx
::open-students-activities
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
(let [{:keys [class-id school-id]} db]
{:dispatch [::routes/redirect :class-students :school-id school-id :class-id class-id]})))
(re-frame/reg-event-fx
::handle-class-deleted
[(i/path path-to-db)]
(fn [{:keys [db]} [_]]
(let [{:keys [school-id]} db]
{:dispatch [::routes/redirect :school-profile :school-id school-id]})))
|
289b17826b8181f0b8453104b55a87dfc288e0df8a3c33623298351805ae0a80 | thlack/surfs | button.clj | (ns ^:no-doc thlack.surfs.elements.spec.button
(:require [clojure.spec.alpha :as s]
[thlack.surfs.composition.spec :as comp.spec]
[thlack.surfs.strings.spec :as strings.spec :refer [deftext]]))
(s/def ::type #{:button})
(deftext ::text ::comp.spec/plain-text 75)
(s/def ::action_id ::strings.spec/action_id)
(deftext ::url ::strings.spec/url-string 3000)
(deftext ::value ::strings.spec/string 2000)
(s/def ::style #{:primary :danger})
| null | https://raw.githubusercontent.com/thlack/surfs/e03d137d6d43c4b73a45a71984cf084d2904c4b0/src/thlack/surfs/elements/spec/button.clj | clojure | (ns ^:no-doc thlack.surfs.elements.spec.button
(:require [clojure.spec.alpha :as s]
[thlack.surfs.composition.spec :as comp.spec]
[thlack.surfs.strings.spec :as strings.spec :refer [deftext]]))
(s/def ::type #{:button})
(deftext ::text ::comp.spec/plain-text 75)
(s/def ::action_id ::strings.spec/action_id)
(deftext ::url ::strings.spec/url-string 3000)
(deftext ::value ::strings.spec/string 2000)
(s/def ::style #{:primary :danger})
| |
0f834ed9db9d0b1a9c4de8aa41f4edb1b3a09bb6d7240196e7776ae78a93c465 | jstrutz/hashids.clj | util.clj | (ns hashids.util
(:require [clojure.edn :as edn]))
(defmacro xor
([] nil)
([a] a)
([a b]
`(let [a# ~a
b# ~b]
(if a#
(if b# false a#)
(if b# b# false)))))
(defn expt
[b e]
(java.lang.Math/pow b e))
(defn long->hexstr [n] (format "%x" n))
(defn hexstr->long
[s]
(try
(edn/read-string (str "0x" s))
(catch java.lang.NumberFormatException e nil)))
(defn ceil
[v]
(long (java.lang.Math/ceil v)))
(defn positions
"Returns the indexes of the items in the collection whose items satisfy the predicate"
[pred coll]
(keep-indexed (fn [idx x]
(when (pred x)
idx))
coll))
(defn swap [v i1 i2]
(assoc v i2 (v i1) i1 (v i2)))
(defn strip-whitespace [s]
(apply str (remove clojure.string/blank? (map str s))))
(defn chars-intersection [str1 str2]
(keep (fn [c]
(some #{c} str2))
(distinct str1)))
(defn chars-difference [str1 str2]
(filter (fn [c] (xor (some #{c} str1)
(some #{c} str2)))
(distinct (str str1 str2))))
(defn chars-subtraction [str1 str2]
(remove #(some #{%} str2) str1))
(defn split-on-chars
[instr splitstr]
(map #(map second %)
(partition-by first
(second (reduce
(fn [[prev-chg letters] letter]
(let [is-sep (boolean (some #{letter} splitstr))
this-chg (xor prev-chg is-sep)]
[this-chg (if is-sep
letters
(conj letters [this-chg letter]))]))
[false []]
instr)))))
| null | https://raw.githubusercontent.com/jstrutz/hashids.clj/3811184c290319e9c7515ccee7a53713d9f700ab/src/hashids/util.clj | clojure | (ns hashids.util
(:require [clojure.edn :as edn]))
(defmacro xor
([] nil)
([a] a)
([a b]
`(let [a# ~a
b# ~b]
(if a#
(if b# false a#)
(if b# b# false)))))
(defn expt
[b e]
(java.lang.Math/pow b e))
(defn long->hexstr [n] (format "%x" n))
(defn hexstr->long
[s]
(try
(edn/read-string (str "0x" s))
(catch java.lang.NumberFormatException e nil)))
(defn ceil
[v]
(long (java.lang.Math/ceil v)))
(defn positions
"Returns the indexes of the items in the collection whose items satisfy the predicate"
[pred coll]
(keep-indexed (fn [idx x]
(when (pred x)
idx))
coll))
(defn swap [v i1 i2]
(assoc v i2 (v i1) i1 (v i2)))
(defn strip-whitespace [s]
(apply str (remove clojure.string/blank? (map str s))))
(defn chars-intersection [str1 str2]
(keep (fn [c]
(some #{c} str2))
(distinct str1)))
(defn chars-difference [str1 str2]
(filter (fn [c] (xor (some #{c} str1)
(some #{c} str2)))
(distinct (str str1 str2))))
(defn chars-subtraction [str1 str2]
(remove #(some #{%} str2) str1))
(defn split-on-chars
[instr splitstr]
(map #(map second %)
(partition-by first
(second (reduce
(fn [[prev-chg letters] letter]
(let [is-sep (boolean (some #{letter} splitstr))
this-chg (xor prev-chg is-sep)]
[this-chg (if is-sep
letters
(conj letters [this-chg letter]))]))
[false []]
instr)))))
| |
fad4dff6da8d93b76041edf2dc4f85401a18d690af8571e4ee562b225a5abccc | pitag-ha/ppx_fprint | test.expected.ml | let saludo = Printf.sprintf "Hi there."
let first_name = "O"
let last_name = "Caml"
let introduction = Printf.sprintf "My name is %s." first_name
let formal_intro = Printf.sprintf "My name is %s%s." first_name last_name
| null | https://raw.githubusercontent.com/pitag-ha/ppx_fprint/98506a3c8b3e3af04ab31a31fa5a4c1148c5a022/test/rewriter/test.expected.ml | ocaml | let saludo = Printf.sprintf "Hi there."
let first_name = "O"
let last_name = "Caml"
let introduction = Printf.sprintf "My name is %s." first_name
let formal_intro = Printf.sprintf "My name is %s%s." first_name last_name
| |
64bf23147dd252af4e867b302f33ebfffe5f9faf76e27bb9706ab74ccee7e052 | input-output-hk/plutus-apps | Constraints.hs | -- | Constraints for transactions
module Ledger.Tx.Constraints(
-- $constraints
TC.TxConstraints(..)
, TC.TxConstraint(..)
, TC.ScriptInputConstraint(..)
, TC.ScriptOutputConstraint(..)
-- * Defining constraints
, TC.mustPayToTheScriptWithDatumHash
, TC.mustPayToTheScriptWithDatumInTx
, TC.mustPayToTheScriptWithInlineDatum
, TC.mustPayToTheScriptWithReferenceScript
, TC.mustPayToAddress
, TC.mustPayToAddressWithDatumHash
, TC.mustPayToAddressWithDatumInTx
, TC.mustPayToAddressWithInlineDatum
, TC.mustPayToAddressWithReferenceScript
, TC.mustPayToAddressWithReferenceValidator
, TC.mustPayToAddressWithReferenceMintingPolicy
, TC.mustMintCurrency
, TC.mustMintCurrencyWithRedeemer
, TC.mustMintValue
, TC.mustMintValueWithRedeemer
, TC.mustSpendAtLeast
, TC.mustSpendPubKeyOutput
, TC.mustSpendOutputFromTheScript
, TC.mustSpendScriptOutput
, TC.mustSpendScriptOutputWithReference
, TC.mustSpendScriptOutputWithMatchingDatumAndValue
, TC.mustUseOutputAsCollateral
, TC.mustReferenceOutput
, TC.mustValidateInSlotRange
, TC.mustValidateInTimeRange
, TC.mustBeSignedBy
, TC.mustProduceAtLeast
, TC.mustIncludeDatumInTxWithHash
, TC.mustIncludeDatumInTx
, TC.mustSatisfyAnyOf
-- * Must-pay constraints for specific types of addresses
, TC.mustPayToPubKey
, TC.mustPayToPubKeyAddress
, TC.mustPayToPubKeyWithDatumHash
, TC.mustPayToPubKeyAddressWithDatumHash
, TC.mustPayToPubKeyWithDatumInTx
, TC.mustPayToPubKeyAddressWithDatumInTx
, TC.mustPayToPubKeyWithInlineDatum
, TC.mustPayToPubKeyAddressWithInlineDatum
, TC.mustPayToOtherScriptWithDatumHash
, TC.mustPayToOtherScriptWithDatumInTx
, TC.mustPayToOtherScriptWithInlineDatum
, TC.mustPayToOtherScriptAddressWithDatumHash
, TC.mustPayToOtherScriptAddressWithDatumInTx
, TC.mustPayToOtherScriptAddressWithInlineDatum
-- * Defining off-chain only constraints
, TC.collectFromPlutusV1Script
, TC.collectFromPlutusV1ScriptFilter
, TC.collectFromTheScriptFilter
, TC.collectFromTheScript
, TC.collectFromPlutusV2Script
, TC.collectFromPlutusV2ScriptFilter
-- * Queries on constraints
, TC.modifiesUtxoSet
, TC.isSatisfiable
-- * Off-chain transaction generation
, OC.UnbalancedTx(..)
, OC.MkTxError(..)
, OC.mkTx
, OC.adjustUnbalancedTx
* * Combining multiple typed scripts into one transaction
, OC.SomeLookupsAndConstraints(..)
, OC.mkSomeTx
, OC.mkTxWithParams
-- ** Lookups
, OC.ScriptLookups(..)
, OC.typedValidatorLookups
, OC.unspentOutputs
, OC.mintingPolicy
, OC.plutusV1MintingPolicy
, OC.plutusV2MintingPolicy
, OC.otherScript
, OC.plutusV1OtherScript
, OC.plutusV2OtherScript
, OC.otherData
, OC.paymentPubKey
, OC.paymentPubKeyHash
-- * Deprecated
, TC.mustPayToTheScript
, TC.mustPayToAddressWithDatum
, TC.mustPayWithDatumToPubKey
, TC.mustPayWithDatumToPubKeyAddress
, TC.mustPayWithDatumInTxToPubKey
, TC.mustPayWithDatumInTxToPubKeyAddress
, TC.mustPayWithInlineDatumToPubKey
, TC.mustPayWithInlineDatumToPubKeyAddress
, TC.mustPayToOtherScript
, TC.mustPayToOtherScriptAddress
, TC.mustValidateIn
) where
import Ledger.Tx.Constraints.OffChain qualified as OC
import Ledger.Tx.Constraints.TxConstraints qualified as TC
-- $constraints
This module defines ' Ledger . Tx . Constraints . . ' , a list
of constraints on transactions . To construct a value of ' Ledger . Tx . Constraints . . ' use
-- the 'Ledger.Tx.Constraints.TxConstraints.mustPayToTheScriptWithDatumHash',
-- 'Ledger.Tx.Constraints.TxConstraints.mustSpendAtLeast', etc functions. Once we have a
' Ledger . Tx . Constraints . . ' value it can be used both to generate a transaction that
satisfies the constraints ( off - chain , using ' Ledger . Tx . Constraints . . OffChain.mkTx ' ) and to check whether
-- a given pending transaction meets the constraints (on-chain, using
' Ledger . Constraints . OnChain . V1.checkScriptContext ' , ' Ledger . Constraints . OnChain . V2.checkScriptContext ' ) .
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/006f4ae4461094d3e9405a445b0c9cf48727fa81/plutus-tx-constraints/src/Ledger/Tx/Constraints.hs | haskell | | Constraints for transactions
$constraints
* Defining constraints
* Must-pay constraints for specific types of addresses
* Defining off-chain only constraints
* Queries on constraints
* Off-chain transaction generation
** Lookups
* Deprecated
$constraints
the 'Ledger.Tx.Constraints.TxConstraints.mustPayToTheScriptWithDatumHash',
'Ledger.Tx.Constraints.TxConstraints.mustSpendAtLeast', etc functions. Once we have a
a given pending transaction meets the constraints (on-chain, using | module Ledger.Tx.Constraints(
TC.TxConstraints(..)
, TC.TxConstraint(..)
, TC.ScriptInputConstraint(..)
, TC.ScriptOutputConstraint(..)
, TC.mustPayToTheScriptWithDatumHash
, TC.mustPayToTheScriptWithDatumInTx
, TC.mustPayToTheScriptWithInlineDatum
, TC.mustPayToTheScriptWithReferenceScript
, TC.mustPayToAddress
, TC.mustPayToAddressWithDatumHash
, TC.mustPayToAddressWithDatumInTx
, TC.mustPayToAddressWithInlineDatum
, TC.mustPayToAddressWithReferenceScript
, TC.mustPayToAddressWithReferenceValidator
, TC.mustPayToAddressWithReferenceMintingPolicy
, TC.mustMintCurrency
, TC.mustMintCurrencyWithRedeemer
, TC.mustMintValue
, TC.mustMintValueWithRedeemer
, TC.mustSpendAtLeast
, TC.mustSpendPubKeyOutput
, TC.mustSpendOutputFromTheScript
, TC.mustSpendScriptOutput
, TC.mustSpendScriptOutputWithReference
, TC.mustSpendScriptOutputWithMatchingDatumAndValue
, TC.mustUseOutputAsCollateral
, TC.mustReferenceOutput
, TC.mustValidateInSlotRange
, TC.mustValidateInTimeRange
, TC.mustBeSignedBy
, TC.mustProduceAtLeast
, TC.mustIncludeDatumInTxWithHash
, TC.mustIncludeDatumInTx
, TC.mustSatisfyAnyOf
, TC.mustPayToPubKey
, TC.mustPayToPubKeyAddress
, TC.mustPayToPubKeyWithDatumHash
, TC.mustPayToPubKeyAddressWithDatumHash
, TC.mustPayToPubKeyWithDatumInTx
, TC.mustPayToPubKeyAddressWithDatumInTx
, TC.mustPayToPubKeyWithInlineDatum
, TC.mustPayToPubKeyAddressWithInlineDatum
, TC.mustPayToOtherScriptWithDatumHash
, TC.mustPayToOtherScriptWithDatumInTx
, TC.mustPayToOtherScriptWithInlineDatum
, TC.mustPayToOtherScriptAddressWithDatumHash
, TC.mustPayToOtherScriptAddressWithDatumInTx
, TC.mustPayToOtherScriptAddressWithInlineDatum
, TC.collectFromPlutusV1Script
, TC.collectFromPlutusV1ScriptFilter
, TC.collectFromTheScriptFilter
, TC.collectFromTheScript
, TC.collectFromPlutusV2Script
, TC.collectFromPlutusV2ScriptFilter
, TC.modifiesUtxoSet
, TC.isSatisfiable
, OC.UnbalancedTx(..)
, OC.MkTxError(..)
, OC.mkTx
, OC.adjustUnbalancedTx
* * Combining multiple typed scripts into one transaction
, OC.SomeLookupsAndConstraints(..)
, OC.mkSomeTx
, OC.mkTxWithParams
, OC.ScriptLookups(..)
, OC.typedValidatorLookups
, OC.unspentOutputs
, OC.mintingPolicy
, OC.plutusV1MintingPolicy
, OC.plutusV2MintingPolicy
, OC.otherScript
, OC.plutusV1OtherScript
, OC.plutusV2OtherScript
, OC.otherData
, OC.paymentPubKey
, OC.paymentPubKeyHash
, TC.mustPayToTheScript
, TC.mustPayToAddressWithDatum
, TC.mustPayWithDatumToPubKey
, TC.mustPayWithDatumToPubKeyAddress
, TC.mustPayWithDatumInTxToPubKey
, TC.mustPayWithDatumInTxToPubKeyAddress
, TC.mustPayWithInlineDatumToPubKey
, TC.mustPayWithInlineDatumToPubKeyAddress
, TC.mustPayToOtherScript
, TC.mustPayToOtherScriptAddress
, TC.mustValidateIn
) where
import Ledger.Tx.Constraints.OffChain qualified as OC
import Ledger.Tx.Constraints.TxConstraints qualified as TC
This module defines ' Ledger . Tx . Constraints . . ' , a list
of constraints on transactions . To construct a value of ' Ledger . Tx . Constraints . . ' use
' Ledger . Tx . Constraints . . ' value it can be used both to generate a transaction that
satisfies the constraints ( off - chain , using ' Ledger . Tx . Constraints . . OffChain.mkTx ' ) and to check whether
' Ledger . Constraints . OnChain . V1.checkScriptContext ' , ' Ledger . Constraints . OnChain . V2.checkScriptContext ' ) .
|
3a72b3a583560a82fba325009602c0fffb7b826080c1e90aa3d8a037ab42246a | haskell/cabal | Progress.hs | module Distribution.Solver.Types.Progress
( Progress(..)
, foldProgress
) where
import Prelude ()
import Distribution.Solver.Compat.Prelude hiding (fail)
-- | A type to represent the unfolding of an expensive long running
-- calculation that may fail. We may get intermediate steps before the final
-- result which may be used to indicate progress and\/or logging messages.
--
data Progress step fail done = Step step (Progress step fail done)
| Fail fail
| Done done
This Functor instance works around a bug in GHC 7.6.3 .
See /-/issues/7436#note_66637 .
-- The derived functor instance caused a space leak in the solver.
instance Functor (Progress step fail) where
fmap f (Step s p) = Step s (fmap f p)
fmap _ (Fail x) = Fail x
fmap f (Done r) = Done (f r)
| Consume a ' Progress ' calculation . Much like ' foldr ' for lists but with two
base cases , one for a final result and one for failure .
--
Eg to convert into a simple ' Either ' result use :
--
-- > foldProgress (flip const) Left Right
--
foldProgress :: (step -> a -> a) -> (fail -> a) -> (done -> a)
-> Progress step fail done -> a
foldProgress step fail done = fold
where fold (Step s p) = step s (fold p)
fold (Fail f) = fail f
fold (Done r) = done r
instance Monad (Progress step fail) where
return = pure
p >>= f = foldProgress Step Fail f p
instance Applicative (Progress step fail) where
pure a = Done a
p <*> x = foldProgress Step Fail (flip fmap x) p
instance Monoid fail => Alternative (Progress step fail) where
empty = Fail mempty
p <|> q = foldProgress Step (const q) Done p
| null | https://raw.githubusercontent.com/haskell/cabal/6896c6aa0e4804913aaba0bbbe00649e18f17bb8/cabal-install-solver/src/Distribution/Solver/Types/Progress.hs | haskell | | A type to represent the unfolding of an expensive long running
calculation that may fail. We may get intermediate steps before the final
result which may be used to indicate progress and\/or logging messages.
The derived functor instance caused a space leak in the solver.
> foldProgress (flip const) Left Right
| module Distribution.Solver.Types.Progress
( Progress(..)
, foldProgress
) where
import Prelude ()
import Distribution.Solver.Compat.Prelude hiding (fail)
data Progress step fail done = Step step (Progress step fail done)
| Fail fail
| Done done
This Functor instance works around a bug in GHC 7.6.3 .
See /-/issues/7436#note_66637 .
instance Functor (Progress step fail) where
fmap f (Step s p) = Step s (fmap f p)
fmap _ (Fail x) = Fail x
fmap f (Done r) = Done (f r)
| Consume a ' Progress ' calculation . Much like ' foldr ' for lists but with two
base cases , one for a final result and one for failure .
Eg to convert into a simple ' Either ' result use :
foldProgress :: (step -> a -> a) -> (fail -> a) -> (done -> a)
-> Progress step fail done -> a
foldProgress step fail done = fold
where fold (Step s p) = step s (fold p)
fold (Fail f) = fail f
fold (Done r) = done r
instance Monad (Progress step fail) where
return = pure
p >>= f = foldProgress Step Fail f p
instance Applicative (Progress step fail) where
pure a = Done a
p <*> x = foldProgress Step Fail (flip fmap x) p
instance Monoid fail => Alternative (Progress step fail) where
empty = Fail mempty
p <|> q = foldProgress Step (const q) Done p
|
8ff7b7d1c421d482a8612b751e78d7201ccee2ae46a7109a7057e0b371100fdd | nodew/haskell-realworld-example | Article.hs | # LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
module Conduit.Core.Article where
import RIO
import Rel8
import Data.Aeson
import Data.Time
import qualified Data.Text as T
import Servant
import Crypto.Random ( MonadRandom(getRandomBytes) )
import Crypto.Hash ( hashWith, SHA256(SHA256) )
import Conduit.Core.User
data Article = Article
{ articleId :: ArticleId
, articleAuthorId :: UserId
, articleTitle :: Text
, articleSlug :: Slug
, articleDescription :: Text
, articleBody :: Text
, articleTags :: [Text]
, articleCreatedAt :: UTCTime
, articleUpdatedAt :: UTCTime
}
newtype ArticleId = ArticleId { getArticleId :: Int64 }
deriving newtype (Eq, Show, Read, FromJSON, ToJSON, DBEq, DBType)
newtype Slug = Slug { getSlug :: Text }
deriving newtype (Eq, Show, Read, FromJSON, ToJSON, FromHttpApiData, DBEq, DBType)
newtype TagId = TagId { getTagId :: Int64 }
deriving newtype (Eq, Show, Read, FromJSON, ToJSON, DBEq, DBType)
mkSlug :: MonadIO m => Text -> m Slug
mkSlug title = do
rnd <- liftIO $ getRandomBytes 32
let hash = T.pack $ show $ hashWith SHA256 (rnd :: ByteString)
let slugText = T.intercalate "-" $ (T.words . T.toLower $ title) ++ [T.take 8 hash]
return $ Slug slugText
| null | https://raw.githubusercontent.com/nodew/haskell-realworld-example/3401dcf9ee9cd04ed3417b37d05348c204f0607b/src/Conduit/Core/Article.hs | haskell | # LANGUAGE DerivingStrategies #
# LANGUAGE GeneralizedNewtypeDeriving #
module Conduit.Core.Article where
import RIO
import Rel8
import Data.Aeson
import Data.Time
import qualified Data.Text as T
import Servant
import Crypto.Random ( MonadRandom(getRandomBytes) )
import Crypto.Hash ( hashWith, SHA256(SHA256) )
import Conduit.Core.User
data Article = Article
{ articleId :: ArticleId
, articleAuthorId :: UserId
, articleTitle :: Text
, articleSlug :: Slug
, articleDescription :: Text
, articleBody :: Text
, articleTags :: [Text]
, articleCreatedAt :: UTCTime
, articleUpdatedAt :: UTCTime
}
newtype ArticleId = ArticleId { getArticleId :: Int64 }
deriving newtype (Eq, Show, Read, FromJSON, ToJSON, DBEq, DBType)
newtype Slug = Slug { getSlug :: Text }
deriving newtype (Eq, Show, Read, FromJSON, ToJSON, FromHttpApiData, DBEq, DBType)
newtype TagId = TagId { getTagId :: Int64 }
deriving newtype (Eq, Show, Read, FromJSON, ToJSON, DBEq, DBType)
mkSlug :: MonadIO m => Text -> m Slug
mkSlug title = do
rnd <- liftIO $ getRandomBytes 32
let hash = T.pack $ show $ hashWith SHA256 (rnd :: ByteString)
let slugText = T.intercalate "-" $ (T.words . T.toLower $ title) ++ [T.take 8 hash]
return $ Slug slugText
| |
629afe0d08397502d83623550488c85766871dfd7b6f1f030c30091430a9a5b8 | freizl/dive-into-haskell | fizzbuzz.hs | # LANGUAGE MonadComprehensions #
module Main where
import Data.Monoid
import Data.Maybe
test :: Int -> String -> Int -> Maybe String
test x str n = listToMaybe [ str | n `mod` x == 0 ]
fizz :: Int -> Maybe String
fizz = test 3 "fizz"
buzz :: Int -> Maybe String
buzz = test 5 "buzz"
fz :: Int -> String
fz n = fromMaybe (show n) $ mconcat $ [fizz n, buzz n]
fz2 :: Int -> String
fz2 i = fromMaybe (show i) $ mappend ["fizz" | i `rem` 3 == 0]
["buzz" | i `rem` 5 == 0]
main :: IO ()
main = mapM_ print [(x, fz x, fzhh x) | x <- [1..20] ++ [70..80] ++ [1150..1160]]
hiss, howl :: Int -> Maybe String
hiss = test 7 "hiss"
howl = test 11 "howl"
fzhh :: Int -> String
fzhh n = fromMaybe (show n) $ mconcat $ [fizz n, buzz n, hiss n, howl n]
| null | https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/problems/fizzbuzz.hs | haskell | # LANGUAGE MonadComprehensions #
module Main where
import Data.Monoid
import Data.Maybe
test :: Int -> String -> Int -> Maybe String
test x str n = listToMaybe [ str | n `mod` x == 0 ]
fizz :: Int -> Maybe String
fizz = test 3 "fizz"
buzz :: Int -> Maybe String
buzz = test 5 "buzz"
fz :: Int -> String
fz n = fromMaybe (show n) $ mconcat $ [fizz n, buzz n]
fz2 :: Int -> String
fz2 i = fromMaybe (show i) $ mappend ["fizz" | i `rem` 3 == 0]
["buzz" | i `rem` 5 == 0]
main :: IO ()
main = mapM_ print [(x, fz x, fzhh x) | x <- [1..20] ++ [70..80] ++ [1150..1160]]
hiss, howl :: Int -> Maybe String
hiss = test 7 "hiss"
howl = test 11 "howl"
fzhh :: Int -> String
fzhh n = fromMaybe (show n) $ mconcat $ [fizz n, buzz n, hiss n, howl n]
| |
9a4f1eca57eadd8defa8cd7d7068fb0df96566484b7608e5f304fd3a066d5465 | jlongster/schemeray | schemeray.scm | ;;; Scheme Raytracer v0.1
;;;
;;; Performs sphere/plane/triangle intersection tests, loads
.obj files as a list of triangles , applies
;;; illumination and reflections.
;;;
;;; The math here hasn't been optimized at all, and there's
;;; a good deal that could be done. However, I simply wanted
to build a prototype . Optimization will come in the
;;; next version.
;;;
;;; This outputs to a file 'image.ppm' which is of the format
Portable Pixmap . provides nice tools to convert
;;; ppm's to other file formats if you need it.
;;;
;;; 10/04/2007
;;;
;;; Roughly ported for Chicken
;;; 10/08/2007
( For Chicken )
(require-extension syntax-case)
(declare (standard-bindings)
(extended-bindings)
(block)
(mostly-flonum)
(not safe))
;;; Utility
(define-syntax when
(syntax-rules ()
((when cond do ...)
(if cond
(begin do ...)))))
(define-syntax unless
(syntax-rules ()
((when cond do ...)
(if (not cond)
(begin do ...)))))
(define current-log-port
(make-parameter (current-error-port)))
; Prints all of its args like 'print', but without the serious bug of named parameters
(define (display-args . rest)
(for-each (lambda (s) (display s)) rest))
JJS : Renamed to print - log to prevent collisions in Chicken
;; All references to log have been updated.
(define (print-log . rest)
(with-output-to-port (current-log-port)
(lambda ()
(apply display-args (append rest '("\n"))))))
(define (real->u8 n)
(inexact->exact
(max 0
(min 255
(if (integer? n)
n
(floor n))))))
(define (real->percentage n)
(inexact->exact (floor (* 100 n))))
: Definition for Chicken
(define write-u8 write-byte)
(define (write-color v1)
(write-u8 (real->u8 (* (vec3d-x v1) 255)))
(write-u8 (real->u8 (* (vec3d-y v1) 255)))
(write-u8 (real->u8 (* (vec3d-z v1) 255))))
;;; Utility stuff to help with math
JL : For Gambit
;; (define-structure vec2d x y)
;; (define-structure vec3d x y z)
: For Chicken
(define-record vec2d x y)
(define-record vec3d x y z)
(define (vec3d-op v1 v2 op)
(make-vec3d (op (vec3d-x v1) (vec3d-x v2))
(op (vec3d-y v1) (vec3d-y v2))
(op (vec3d-z v1) (vec3d-z v2))))
(define (vec3d-add v1 v2)
(vec3d-op v1 v2 +))
(define (vec3d-sub v1 v2)
(vec3d-op v1 v2 -))
(define (vec3d-component-mul v1 v2)
(make-vec3d (* (vec3d-x v1) (vec3d-x v2))
(* (vec3d-y v1) (vec3d-y v2))
(* (vec3d-z v1) (vec3d-z v2))))
(define (vec3d-scalar-mul v1 f)
(make-vec3d (* (vec3d-x v1) f)
(* (vec3d-y v1) f)
(* (vec3d-z v1) f)))
(define (vec3d-inverse v1)
(vec3d-scalar-mul v1 -1))
(define (vec3d-length v1)
(sqrt (vec3d-dot v1 v1)))
(define (vec3d-unit v1)
(let ((l (vec3d-length v1)))
(make-vec3d (/ (vec3d-x v1) l)
(/ (vec3d-y v1) l)
(/ (vec3d-z v1) l))))
(define (vec3d-dot v1 v2)
(+ (* (vec3d-x v1) (vec3d-x v2))
(* (vec3d-y v1) (vec3d-y v2))
(* (vec3d-z v1) (vec3d-z v2))))
(define (vec3d-cross v1 v2)
(make-vec3d (- (* (vec3d-y v1) (vec3d-z v2))
(* (vec3d-z v1) (vec3d-y v2)))
(- (* (vec3d-z v1) (vec3d-x v2))
(* (vec3d-x v1) (vec3d-z v2)))
(- (* (vec3d-x v1) (vec3d-y v2))
(* (vec3d-y v1) (vec3d-x v2)))))
(define (saturate n)
(min 1.0 (max 0.0 n)))
(include "obj-file-parser.scm")
;;; Config constants
(define screenDimen (make-vec2d 8 6))
(define res (make-vec2d 600 450))
(define eye (make-vec3d 0 0 -5))
(define depth 10000)
(define backColor (make-vec3d 0 0 0))
(define ambient (make-vec3d .1 .1 .1))
(define maxsteps 3)
(define coptix (delay (load-obj "coptix_slim")))
(define box (delay (load-obj "box")))
(define (generate-spheres)
(let ((start (make-vec3d 0 0 65))
(dX (make-vec3d -1 -.25 .5))
(dY (make-vec3d 0 -1 0)))
(let loop ((num 0)
(acc '()))
(if (< num 25)
(loop (+ num 1) (cons `(sphere ,(make-vec3d .8 (+ .2 (/ num 50)) .2)
,(vec3d-add
(vec3d-add start
(vec3d-scalar-mul
(vec3d-scalar-mul dX 10)
(remainder num 5)))
(vec3d-scalar-mul
(vec3d-scalar-mul dY 10)
(quotient num 5)))
5)
acc))
acc))))
(define scene `(,@(generate-spheres)
( sphere , ( make - vec3d .4 .6 .5 ) , ( make - vec3d -15 0 90 ) 20 )
( sphere , ( make - vec3d .75 .95 .92 ) , ( make - vec3d 20 -20 65 ) 5 )
(plane ,(make-vec3d .7 .7 1.0) 10 ,(make-vec3d .25 -1 0))
(mesh #f ,(make-vec3d 23 0 50) ,coptix)
(light ,(make-vec3d .7 .9 .9) ,(make-vec3d -40 -15 60) 1)))
;;; Types
(define-syntax obj-dispatch
(syntax-rules (else)
((obj-dispatch obj (else body ...))
(begin body ...))
((obj-dispatch obj (type body ...) almost last ...)
(if (eq? 'type (obj-type obj))
(begin body ...)
(obj-dispatch obj almost last ...)))
((obj-dispatch obj (type body ...) last ...)
(if (eq? 'type (obj-type obj))
(begin body ...)))))
(define (obj-type obj)
(car obj))
(define (obj-color obj)
(cadr obj))
(define (obj-normal obj point)
(obj-dispatch obj
(sphere (sphere-normal obj point))
(light (sphere-normal obj point))
(plane (plane-normal obj))
(triangle (triangle-normal obj))))
;;; Light
(define (light-pos obj)
(sphere-pos obj))
(define (light-intersection obj origVec dirVec)
(sphere-intersection obj origVec dirVec))
;;; Sphere
(define (sphere-pos obj)
(caddr obj))
(define (sphere-radius obj)
(cadddr obj))
(define (sphere-intersection obj origVec dirVec)
(let* ((eo (vec3d-sub origVec (sphere-pos obj)))
(b (vec3d-dot eo dirVec))
(c (- (vec3d-dot eo eo) (expt (sphere-radius obj) 2)))
(d (- (* b b) c)))
(if (<= d 0)
depth
(let ((r (- (- b) (sqrt d))))
(if (> r 0)
r
depth)))))
(define (sphere-normal obj point)
(vec3d-unit (vec3d-sub point (sphere-pos obj))))
;;; Plane
(define (plane-normal obj)
(cadddr obj))
(define (plane-distance obj)
(caddr obj))
(define (plane-intersection obj origVec dirVec)
(let ((d (vec3d-dot (plane-normal obj) dirVec)))
(if (not (zero? d))
(let ((dist (/ (- (+ (vec3d-dot (plane-normal obj) origVec)
(plane-distance obj)))
d)))
(if (positive? dist)
dist
depth))
depth)))
;;; Triangles
(define (triangle-v1 obj)
(caddr obj))
(define (triangle-v2 obj)
(cadddr obj))
(define (triangle-v3 obj)
(car (cddddr obj)))
(define (triangle-normal obj)
(vec3d-unit
(vec3d-cross
(vec3d-sub (triangle-v2 obj)
(triangle-v1 obj))
(vec3d-sub (triangle-v3 obj)
(triangle-v1 obj)))))
(define (triangle-intersection obj origVec dirVec)
(let* ((n (triangle-normal obj))
(v.n (vec3d-dot dirVec n)))
(if (>= v.n 0)
depth
(begin
(let* ((a (triangle-v1 obj))
(b (triangle-v2 obj))
(c (triangle-v3 obj))
(o-a.n (vec3d-dot (vec3d-sub origVec a) n))
(d (- (/ o-a.n v.n)))
(p (vec3d-add origVec (vec3d-scalar-mul dirVec d))))
(let ((signf #f))
(if (negative? (vec3d-dot (vec3d-cross (vec3d-sub b a) (vec3d-sub p a)) n))
(set! signf negative?)
(set! signf (lambda (n) (or (zero? n) (positive? n)))))
(if (and (>= d 0)
(signf (vec3d-dot (vec3d-cross (vec3d-sub c b) (vec3d-sub p b)) n))
(signf (vec3d-dot (vec3d-cross (vec3d-sub a c) (vec3d-sub p c)) n)))
d
depth))
Barycentric projection - has some bugs
#;(let ((u (/ (- (* (vec3d-y p) (vec3d-x c))
(* (vec3d-x p) (vec3d-y c)))
(- (* (vec3d-y b) (vec3d-x c))
(* (vec3d-x b) (vec3d-y c)))))
(v (/ (- (* (vec3d-y p) (vec3d-x b))
(* (vec3d-x p) (vec3d-y b)))
(- (* (vec3d-y c) (vec3d-x b))
(* (vec3d-x c) (vec3d-y b))))))
(if (and (>= u 0) (>= v 0) (<= (+ u v) 1))
d
depth)))))))
Simplistic meshes
(define (mesh-pos obj)
(caddr obj))
(define (mesh-primitives obj)
(let ((a (cadddr obj)))
(if (pair? a)
a
(force a))))
;;; Intersections and casting
(define (test-intersection obj origVec dirVec)
(obj-dispatch obj
(sphere (sphere-intersection obj origVec dirVec))
(light (sphere-intersection obj origVec dirVec))
(plane (plane-intersection obj origVec dirVec))
(triangle (triangle-intersection obj origVec dirVec))))
(define (apply-lighting hitObj point v)
(if (eq? (obj-type hitObj) 'light)
(obj-color hitObj)
(let ((acc (make-vec3d 0 0 0)))
(for-each (lambda (obj)
(when (eq? (obj-type obj) 'light)
(let* ((pointToLight (vec3d-sub (light-pos obj) point))
(l (vec3d-unit pointToLight))
(n (obj-normal hitObj point))
(n.l (saturate (vec3d-dot n l)))
(r (vec3d-sub l (vec3d-scalar-mul n (* 2 (vec3d-dot n l)))))
(r.v (saturate (vec3d-dot r v)))
(diff n.l)
(spec (expt r.v 30))
(shadow (saturate (* 4 diff))))
(if (> diff 0)
(set! acc (vec3d-add acc (vec3d-component-mul
(vec3d-scalar-mul
(vec3d-add
(vec3d-scalar-mul (obj-color hitObj)
diff)
(obj-dispatch hitObj
(plane (make-vec3d 0 0 0))
(else (vec3d-scalar-mul (make-vec3d 1 1 1)
spec))))
shadow)
(obj-color obj))))))))
scene)
(obj-dispatch hitObj
(plane acc)
(else (vec3d-add ambient acc))))))
(define (find-closest-prim orig dir prims cont)
(let ((closestObj #f)
(closestDepth depth))
(for-each (lambda (obj)
(if (eq? (obj-type obj) 'mesh)
(find-closest-prim (vec3d-add orig (vec3d-inverse (mesh-pos obj))) dir (mesh-primitives obj)
(lambda (o d)
(if (< d closestDepth)
(begin
(set! closestDepth d)
(set! closestObj o)))))
(let ((d (test-intersection obj orig dir)))
(if (< d closestDepth)
(begin
(set! closestDepth d)
(set! closestObj obj))))))
prims)
(if closestObj
(cont closestObj closestDepth)
backColor)))
(define (shoot-ray orig dir step)
(if (< step maxsteps)
(find-closest-prim
orig
dir
scene
(lambda (closestObj closestDepth)
(if closestObj
(let* ((d closestDepth)
(point (vec3d-add orig (vec3d-scalar-mul dir d)))
(n (obj-normal closestObj point))
(r (vec3d-unit (vec3d-sub dir (vec3d-scalar-mul n (* 2 (vec3d-dot dir n))))))
(view (vec3d-unit (vec3d-sub point eye))))
(vec3d-add
(apply-lighting closestObj point view)
(vec3d-scalar-mul (shoot-ray (vec3d-add point (vec3d-scalar-mul r .0001)) r (+ step 1)) (/ 1 (* (+ step 1) 2)))))
backColor)))
(make-vec3d 0 0 0)))
(define (shoot-screen-rays)
(let ((dX (/ (vec2d-x screenDimen) (vec2d-x res)))
(dY (/ (vec2d-y screenDimen) (vec2d-y res)))
(screenCorner (make-vec3d (- (/ (vec2d-x screenDimen) 2))
(- (/ (vec2d-y screenDimen) 2))
0))
(count (* (vec2d-x res) (vec2d-y res))))
(let loop ((n 0)
(acc '()))
(if (< n count)
(let* ((curPoint (make-vec3d (* (remainder n (vec2d-x res)) dX) (* (quotient n (vec2d-y res)) dY) 0))
(view (vec3d-unit
(vec3d-sub (vec3d-add screenCorner curPoint)
eye)))
(curColor (shoot-ray eye
view
0)))
(when (zero? (remainder n (* (vec2d-y res) 5)))
(print-log (real->percentage (/ n count)) "%"))
(loop (+ n 1) (cons curColor acc)))
(reverse acc)))))
(define (make-image)
(print-log "Starting...")
(with-output-to-file "image.ppm"
(lambda ()
(let ((pixels (shoot-screen-rays)))
(print-log "Writing...")
(display-args "P6\n")
(display-args (vec2d-x res) " " (vec2d-y res) "\n")
(display-args "255\n")
(for-each (lambda (c) (write-color c))
pixels)))))
(make-image)
| null | https://raw.githubusercontent.com/jlongster/schemeray/0ea0f1596cbafa05e541131fd64d482c79dd4173/ports/chicken/schemeray.scm | scheme | Scheme Raytracer v0.1
Performs sphere/plane/triangle intersection tests, loads
illumination and reflections.
The math here hasn't been optimized at all, and there's
a good deal that could be done. However, I simply wanted
next version.
This outputs to a file 'image.ppm' which is of the format
ppm's to other file formats if you need it.
10/04/2007
Roughly ported for Chicken
10/08/2007
Utility
Prints all of its args like 'print', but without the serious bug of named parameters
All references to log have been updated.
Utility stuff to help with math
(define-structure vec2d x y)
(define-structure vec3d x y z)
Config constants
Types
Light
Sphere
Plane
Triangles
(let ((u (/ (- (* (vec3d-y p) (vec3d-x c))
Intersections and casting | .obj files as a list of triangles , applies
to build a prototype . Optimization will come in the
Portable Pixmap . provides nice tools to convert
( For Chicken )
(require-extension syntax-case)
(declare (standard-bindings)
(extended-bindings)
(block)
(mostly-flonum)
(not safe))
(define-syntax when
(syntax-rules ()
((when cond do ...)
(if cond
(begin do ...)))))
(define-syntax unless
(syntax-rules ()
((when cond do ...)
(if (not cond)
(begin do ...)))))
(define current-log-port
(make-parameter (current-error-port)))
(define (display-args . rest)
(for-each (lambda (s) (display s)) rest))
JJS : Renamed to print - log to prevent collisions in Chicken
(define (print-log . rest)
(with-output-to-port (current-log-port)
(lambda ()
(apply display-args (append rest '("\n"))))))
(define (real->u8 n)
(inexact->exact
(max 0
(min 255
(if (integer? n)
n
(floor n))))))
(define (real->percentage n)
(inexact->exact (floor (* 100 n))))
: Definition for Chicken
(define write-u8 write-byte)
(define (write-color v1)
(write-u8 (real->u8 (* (vec3d-x v1) 255)))
(write-u8 (real->u8 (* (vec3d-y v1) 255)))
(write-u8 (real->u8 (* (vec3d-z v1) 255))))
JL : For Gambit
: For Chicken
(define-record vec2d x y)
(define-record vec3d x y z)
(define (vec3d-op v1 v2 op)
(make-vec3d (op (vec3d-x v1) (vec3d-x v2))
(op (vec3d-y v1) (vec3d-y v2))
(op (vec3d-z v1) (vec3d-z v2))))
(define (vec3d-add v1 v2)
(vec3d-op v1 v2 +))
(define (vec3d-sub v1 v2)
(vec3d-op v1 v2 -))
(define (vec3d-component-mul v1 v2)
(make-vec3d (* (vec3d-x v1) (vec3d-x v2))
(* (vec3d-y v1) (vec3d-y v2))
(* (vec3d-z v1) (vec3d-z v2))))
(define (vec3d-scalar-mul v1 f)
(make-vec3d (* (vec3d-x v1) f)
(* (vec3d-y v1) f)
(* (vec3d-z v1) f)))
(define (vec3d-inverse v1)
(vec3d-scalar-mul v1 -1))
(define (vec3d-length v1)
(sqrt (vec3d-dot v1 v1)))
(define (vec3d-unit v1)
(let ((l (vec3d-length v1)))
(make-vec3d (/ (vec3d-x v1) l)
(/ (vec3d-y v1) l)
(/ (vec3d-z v1) l))))
(define (vec3d-dot v1 v2)
(+ (* (vec3d-x v1) (vec3d-x v2))
(* (vec3d-y v1) (vec3d-y v2))
(* (vec3d-z v1) (vec3d-z v2))))
(define (vec3d-cross v1 v2)
(make-vec3d (- (* (vec3d-y v1) (vec3d-z v2))
(* (vec3d-z v1) (vec3d-y v2)))
(- (* (vec3d-z v1) (vec3d-x v2))
(* (vec3d-x v1) (vec3d-z v2)))
(- (* (vec3d-x v1) (vec3d-y v2))
(* (vec3d-y v1) (vec3d-x v2)))))
(define (saturate n)
(min 1.0 (max 0.0 n)))
(include "obj-file-parser.scm")
(define screenDimen (make-vec2d 8 6))
(define res (make-vec2d 600 450))
(define eye (make-vec3d 0 0 -5))
(define depth 10000)
(define backColor (make-vec3d 0 0 0))
(define ambient (make-vec3d .1 .1 .1))
(define maxsteps 3)
(define coptix (delay (load-obj "coptix_slim")))
(define box (delay (load-obj "box")))
(define (generate-spheres)
(let ((start (make-vec3d 0 0 65))
(dX (make-vec3d -1 -.25 .5))
(dY (make-vec3d 0 -1 0)))
(let loop ((num 0)
(acc '()))
(if (< num 25)
(loop (+ num 1) (cons `(sphere ,(make-vec3d .8 (+ .2 (/ num 50)) .2)
,(vec3d-add
(vec3d-add start
(vec3d-scalar-mul
(vec3d-scalar-mul dX 10)
(remainder num 5)))
(vec3d-scalar-mul
(vec3d-scalar-mul dY 10)
(quotient num 5)))
5)
acc))
acc))))
(define scene `(,@(generate-spheres)
( sphere , ( make - vec3d .4 .6 .5 ) , ( make - vec3d -15 0 90 ) 20 )
( sphere , ( make - vec3d .75 .95 .92 ) , ( make - vec3d 20 -20 65 ) 5 )
(plane ,(make-vec3d .7 .7 1.0) 10 ,(make-vec3d .25 -1 0))
(mesh #f ,(make-vec3d 23 0 50) ,coptix)
(light ,(make-vec3d .7 .9 .9) ,(make-vec3d -40 -15 60) 1)))
(define-syntax obj-dispatch
(syntax-rules (else)
((obj-dispatch obj (else body ...))
(begin body ...))
((obj-dispatch obj (type body ...) almost last ...)
(if (eq? 'type (obj-type obj))
(begin body ...)
(obj-dispatch obj almost last ...)))
((obj-dispatch obj (type body ...) last ...)
(if (eq? 'type (obj-type obj))
(begin body ...)))))
(define (obj-type obj)
(car obj))
(define (obj-color obj)
(cadr obj))
(define (obj-normal obj point)
(obj-dispatch obj
(sphere (sphere-normal obj point))
(light (sphere-normal obj point))
(plane (plane-normal obj))
(triangle (triangle-normal obj))))
(define (light-pos obj)
(sphere-pos obj))
(define (light-intersection obj origVec dirVec)
(sphere-intersection obj origVec dirVec))
(define (sphere-pos obj)
(caddr obj))
(define (sphere-radius obj)
(cadddr obj))
(define (sphere-intersection obj origVec dirVec)
(let* ((eo (vec3d-sub origVec (sphere-pos obj)))
(b (vec3d-dot eo dirVec))
(c (- (vec3d-dot eo eo) (expt (sphere-radius obj) 2)))
(d (- (* b b) c)))
(if (<= d 0)
depth
(let ((r (- (- b) (sqrt d))))
(if (> r 0)
r
depth)))))
(define (sphere-normal obj point)
(vec3d-unit (vec3d-sub point (sphere-pos obj))))
(define (plane-normal obj)
(cadddr obj))
(define (plane-distance obj)
(caddr obj))
(define (plane-intersection obj origVec dirVec)
(let ((d (vec3d-dot (plane-normal obj) dirVec)))
(if (not (zero? d))
(let ((dist (/ (- (+ (vec3d-dot (plane-normal obj) origVec)
(plane-distance obj)))
d)))
(if (positive? dist)
dist
depth))
depth)))
(define (triangle-v1 obj)
(caddr obj))
(define (triangle-v2 obj)
(cadddr obj))
(define (triangle-v3 obj)
(car (cddddr obj)))
(define (triangle-normal obj)
(vec3d-unit
(vec3d-cross
(vec3d-sub (triangle-v2 obj)
(triangle-v1 obj))
(vec3d-sub (triangle-v3 obj)
(triangle-v1 obj)))))
(define (triangle-intersection obj origVec dirVec)
(let* ((n (triangle-normal obj))
(v.n (vec3d-dot dirVec n)))
(if (>= v.n 0)
depth
(begin
(let* ((a (triangle-v1 obj))
(b (triangle-v2 obj))
(c (triangle-v3 obj))
(o-a.n (vec3d-dot (vec3d-sub origVec a) n))
(d (- (/ o-a.n v.n)))
(p (vec3d-add origVec (vec3d-scalar-mul dirVec d))))
(let ((signf #f))
(if (negative? (vec3d-dot (vec3d-cross (vec3d-sub b a) (vec3d-sub p a)) n))
(set! signf negative?)
(set! signf (lambda (n) (or (zero? n) (positive? n)))))
(if (and (>= d 0)
(signf (vec3d-dot (vec3d-cross (vec3d-sub c b) (vec3d-sub p b)) n))
(signf (vec3d-dot (vec3d-cross (vec3d-sub a c) (vec3d-sub p c)) n)))
d
depth))
Barycentric projection - has some bugs
(* (vec3d-x p) (vec3d-y c)))
(- (* (vec3d-y b) (vec3d-x c))
(* (vec3d-x b) (vec3d-y c)))))
(v (/ (- (* (vec3d-y p) (vec3d-x b))
(* (vec3d-x p) (vec3d-y b)))
(- (* (vec3d-y c) (vec3d-x b))
(* (vec3d-x c) (vec3d-y b))))))
(if (and (>= u 0) (>= v 0) (<= (+ u v) 1))
d
depth)))))))
Simplistic meshes
(define (mesh-pos obj)
(caddr obj))
(define (mesh-primitives obj)
(let ((a (cadddr obj)))
(if (pair? a)
a
(force a))))
(define (test-intersection obj origVec dirVec)
(obj-dispatch obj
(sphere (sphere-intersection obj origVec dirVec))
(light (sphere-intersection obj origVec dirVec))
(plane (plane-intersection obj origVec dirVec))
(triangle (triangle-intersection obj origVec dirVec))))
(define (apply-lighting hitObj point v)
(if (eq? (obj-type hitObj) 'light)
(obj-color hitObj)
(let ((acc (make-vec3d 0 0 0)))
(for-each (lambda (obj)
(when (eq? (obj-type obj) 'light)
(let* ((pointToLight (vec3d-sub (light-pos obj) point))
(l (vec3d-unit pointToLight))
(n (obj-normal hitObj point))
(n.l (saturate (vec3d-dot n l)))
(r (vec3d-sub l (vec3d-scalar-mul n (* 2 (vec3d-dot n l)))))
(r.v (saturate (vec3d-dot r v)))
(diff n.l)
(spec (expt r.v 30))
(shadow (saturate (* 4 diff))))
(if (> diff 0)
(set! acc (vec3d-add acc (vec3d-component-mul
(vec3d-scalar-mul
(vec3d-add
(vec3d-scalar-mul (obj-color hitObj)
diff)
(obj-dispatch hitObj
(plane (make-vec3d 0 0 0))
(else (vec3d-scalar-mul (make-vec3d 1 1 1)
spec))))
shadow)
(obj-color obj))))))))
scene)
(obj-dispatch hitObj
(plane acc)
(else (vec3d-add ambient acc))))))
(define (find-closest-prim orig dir prims cont)
(let ((closestObj #f)
(closestDepth depth))
(for-each (lambda (obj)
(if (eq? (obj-type obj) 'mesh)
(find-closest-prim (vec3d-add orig (vec3d-inverse (mesh-pos obj))) dir (mesh-primitives obj)
(lambda (o d)
(if (< d closestDepth)
(begin
(set! closestDepth d)
(set! closestObj o)))))
(let ((d (test-intersection obj orig dir)))
(if (< d closestDepth)
(begin
(set! closestDepth d)
(set! closestObj obj))))))
prims)
(if closestObj
(cont closestObj closestDepth)
backColor)))
(define (shoot-ray orig dir step)
(if (< step maxsteps)
(find-closest-prim
orig
dir
scene
(lambda (closestObj closestDepth)
(if closestObj
(let* ((d closestDepth)
(point (vec3d-add orig (vec3d-scalar-mul dir d)))
(n (obj-normal closestObj point))
(r (vec3d-unit (vec3d-sub dir (vec3d-scalar-mul n (* 2 (vec3d-dot dir n))))))
(view (vec3d-unit (vec3d-sub point eye))))
(vec3d-add
(apply-lighting closestObj point view)
(vec3d-scalar-mul (shoot-ray (vec3d-add point (vec3d-scalar-mul r .0001)) r (+ step 1)) (/ 1 (* (+ step 1) 2)))))
backColor)))
(make-vec3d 0 0 0)))
(define (shoot-screen-rays)
(let ((dX (/ (vec2d-x screenDimen) (vec2d-x res)))
(dY (/ (vec2d-y screenDimen) (vec2d-y res)))
(screenCorner (make-vec3d (- (/ (vec2d-x screenDimen) 2))
(- (/ (vec2d-y screenDimen) 2))
0))
(count (* (vec2d-x res) (vec2d-y res))))
(let loop ((n 0)
(acc '()))
(if (< n count)
(let* ((curPoint (make-vec3d (* (remainder n (vec2d-x res)) dX) (* (quotient n (vec2d-y res)) dY) 0))
(view (vec3d-unit
(vec3d-sub (vec3d-add screenCorner curPoint)
eye)))
(curColor (shoot-ray eye
view
0)))
(when (zero? (remainder n (* (vec2d-y res) 5)))
(print-log (real->percentage (/ n count)) "%"))
(loop (+ n 1) (cons curColor acc)))
(reverse acc)))))
(define (make-image)
(print-log "Starting...")
(with-output-to-file "image.ppm"
(lambda ()
(let ((pixels (shoot-screen-rays)))
(print-log "Writing...")
(display-args "P6\n")
(display-args (vec2d-x res) " " (vec2d-y res) "\n")
(display-args "255\n")
(for-each (lambda (c) (write-color c))
pixels)))))
(make-image)
|
b6b727d0e46fbe3a0d7611381245f20b9f0df54be73f292ff6dad2ed285794a0 | seckcoder/iu_c311 | grammar.rkt | #lang eopl
(provide (all-defined-out))
(define scanner-spec-a
'((white-sp (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier (letter (arbno (or letter digit))) symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define grammar-al
'((program
(expression)
a-program)
(expression
(number)
const-exp)
(expression
("-(" expression "," expression ")")
diff-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression
(identifier)
var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
(expression
("proc" "(" identifier ")" expression)
proc-exp)
(expression
("(" expression expression ")")
call-exp)
(expression
("letrec" identifier "(" identifier ")" "=" expression "in" expression)
letrec-exp)
(expression
("cons(" expression "," expression ")")
cons-exp)
(expression
("emptyList")
empty-lst-exp)
(expression
("car(" expression ")")
car-exp)
(expression
("cdr(" expression ")")
cdr-exp)
(expression
("null?(" expression ")")
is-empty-exp)
(expression
("list(" (arbno expression) ")")
list-exp)
(expression
("{" (arbno expression ";") "}")
compound-exp)
(expression
("set" identifier "=" expression)
set-exp)
(expression
("*(" expression "," expression ")")
mult-exp)
))
(define list-the-datatypes
(lambda ()
(sllgen:list-define-datatypes scanner-spec-a grammar-al)))
(sllgen:make-define-datatypes scanner-spec-a grammar-al)
(define scan&parse
(sllgen:make-string-parser scanner-spec-a grammar-al))
| null | https://raw.githubusercontent.com/seckcoder/iu_c311/a1215983b6ab08df32058ef1e089cb294419e567/racket/continuation-modular/grammar.rkt | racket | #lang eopl
(provide (all-defined-out))
(define scanner-spec-a
'((white-sp (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier (letter (arbno (or letter digit))) symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define grammar-al
'((program
(expression)
a-program)
(expression
(number)
const-exp)
(expression
("-(" expression "," expression ")")
diff-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression
(identifier)
var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
(expression
("proc" "(" identifier ")" expression)
proc-exp)
(expression
("(" expression expression ")")
call-exp)
(expression
("letrec" identifier "(" identifier ")" "=" expression "in" expression)
letrec-exp)
(expression
("cons(" expression "," expression ")")
cons-exp)
(expression
("emptyList")
empty-lst-exp)
(expression
("car(" expression ")")
car-exp)
(expression
("cdr(" expression ")")
cdr-exp)
(expression
("null?(" expression ")")
is-empty-exp)
(expression
("list(" (arbno expression) ")")
list-exp)
(expression
("{" (arbno expression ";") "}")
compound-exp)
(expression
("set" identifier "=" expression)
set-exp)
(expression
("*(" expression "," expression ")")
mult-exp)
))
(define list-the-datatypes
(lambda ()
(sllgen:list-define-datatypes scanner-spec-a grammar-al)))
(sllgen:make-define-datatypes scanner-spec-a grammar-al)
(define scan&parse
(sllgen:make-string-parser scanner-spec-a grammar-al))
| |
ee8952bfc1467789c78460f08a3a29a0dff7ae8aa6a7755a4808e81170f7305d | Perry961002/SICP | exe2.56-exponentiation.scm | (load "Chap2\\example\\exa2.3.2-Symbolic-guidance.scm")
;指数式就是第一个元素是**的biao
(define (exponentiation? x)
(and (pair? x) (eq? (car x) '**)))
底数就是指数式的第二个元素
(define (base e)
(cadr e))
指数是指数式的第三个元素
(define (exponent e)
(caddr e))
;构造指数式
(define (make-exponentiation b e)
(cond ((=number? e 0) 1)
((=number? e 1) b)
(else (list '** b e))))
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multipliter exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multipliter exp) var)
(multiplicand exp))))
((exponentiation? exp)
(make-product (exponent exp)
(make-product (make-exponentiation (base exp) (make-sum (exponent exp) -1))
(deriv (base exp) var))))
(else
(error "unknown expression type -- DERIV" exp)))) | null | https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap2/exercise/exe2.56-exponentiation.scm | scheme | 指数式就是第一个元素是**的biao
构造指数式 | (load "Chap2\\example\\exa2.3.2-Symbolic-guidance.scm")
(define (exponentiation? x)
(and (pair? x) (eq? (car x) '**)))
底数就是指数式的第二个元素
(define (base e)
(cadr e))
指数是指数式的第三个元素
(define (exponent e)
(caddr e))
(define (make-exponentiation b e)
(cond ((=number? e 0) 1)
((=number? e 1) b)
(else (list '** b e))))
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multipliter exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multipliter exp) var)
(multiplicand exp))))
((exponentiation? exp)
(make-product (exponent exp)
(make-product (make-exponentiation (base exp) (make-sum (exponent exp) -1))
(deriv (base exp) var))))
(else
(error "unknown expression type -- DERIV" exp)))) |
cc5f2dbc7f51d184cb5284e248e3b6ef1b4f72dbf68e73beea56c8836d85dd9b | ocaml-gospel/ortac | translation.mli | module W = Warnings
open Gospel
val with_checks :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
Tterm.term list ->
Translated.value ->
Translated.value
val with_pres :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
Tterm.term list ->
Translated.value ->
Translated.value
val with_models :
driver:Drv.t ->
(Symbols.lsymbol * bool) list ->
Translated.type_ ->
Translated.type_
val with_invariants :
driver:Drv.t ->
term_printer:(Gospel.Tterm.term -> string) ->
Gospel.Symbols.vsymbol option * Gospel.Tterm.term list ->
Translated.type_ ->
Translated.type_
val with_consumes :
Gospel.Tterm.term list -> Translated.value -> Translated.value
val with_modified :
Gospel.Tterm.term list -> Translated.value -> Translated.value
val with_posts :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
Tterm.term list ->
Translated.value ->
Translated.value
val with_constant_checks :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
Tterm.term list ->
Translated.constant ->
Translated.constant
val with_xposts :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
(Ttypes.xsymbol * (Tterm.pattern * Tterm.term) list) list ->
Translated.value ->
Translated.value
val function_definition :
driver:Drv.t -> Symbols.lsymbol -> string -> Tterm.term -> Translated.term
val axiom_definition :
driver:Drv.t -> register_name:string -> Tterm.term -> Translated.term
| null | https://raw.githubusercontent.com/ocaml-gospel/ortac/dacc564ffaf8cfeb6f012bacefa5319d042ba29f/src/core/translation.mli | ocaml | module W = Warnings
open Gospel
val with_checks :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
Tterm.term list ->
Translated.value ->
Translated.value
val with_pres :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
Tterm.term list ->
Translated.value ->
Translated.value
val with_models :
driver:Drv.t ->
(Symbols.lsymbol * bool) list ->
Translated.type_ ->
Translated.type_
val with_invariants :
driver:Drv.t ->
term_printer:(Gospel.Tterm.term -> string) ->
Gospel.Symbols.vsymbol option * Gospel.Tterm.term list ->
Translated.type_ ->
Translated.type_
val with_consumes :
Gospel.Tterm.term list -> Translated.value -> Translated.value
val with_modified :
Gospel.Tterm.term list -> Translated.value -> Translated.value
val with_posts :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
Tterm.term list ->
Translated.value ->
Translated.value
val with_constant_checks :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
Tterm.term list ->
Translated.constant ->
Translated.constant
val with_xposts :
driver:Drv.t ->
term_printer:(Tterm.term -> string) ->
(Ttypes.xsymbol * (Tterm.pattern * Tterm.term) list) list ->
Translated.value ->
Translated.value
val function_definition :
driver:Drv.t -> Symbols.lsymbol -> string -> Tterm.term -> Translated.term
val axiom_definition :
driver:Drv.t -> register_name:string -> Tterm.term -> Translated.term
| |
edee82ce7fd716c91d656b36108cecfc632bee821a8c346e6df5218c0c19789f | shenxs/about-scheme | 17.4.rkt | ;abstractions from templates
从模板抽象
以前一直从一般函数->抽象函数
;这一章直接从函数模板得到抽象函数
?
尽管这个话题还在研究中 , 我们现在只是了解一下基本的idea
#lang racket
(define (fun_for_l l)
(cond
[(empty? l) ...]
[else (... (first l) ... (fun_for_l (rest l)))]))
;;这是一般的列表处理函数模板,确实这种形式出现了很多次
;
;
;
;抽象之后就是以下的函数
(define (reduce l base combine)
(cond
[(empty? l) base]
[else (combine (first l) (reduce (rest l base combine)))]))
之后就可以用一行定义出sum , product(将列表里面的数字全部×qilai )
;[list of sum] -> number
(define (sum l)
(reduce l 0 +))
;[list of number ]->number
(define (product l)
(reduce l 1 *))
;(reduce 运算对象(列表) 幺元 运算符)
| null | https://raw.githubusercontent.com/shenxs/about-scheme/d458776a62cb0bbcbfbb2a044ed18b849f26fd0f/HTDP/17.4.rkt | racket | abstractions from templates
这一章直接从函数模板得到抽象函数
这是一般的列表处理函数模板,确实这种形式出现了很多次
抽象之后就是以下的函数
[list of sum] -> number
[list of number ]->number
(reduce 运算对象(列表) 幺元 运算符) | 从模板抽象
以前一直从一般函数->抽象函数
?
尽管这个话题还在研究中 , 我们现在只是了解一下基本的idea
#lang racket
(define (fun_for_l l)
(cond
[(empty? l) ...]
[else (... (first l) ... (fun_for_l (rest l)))]))
(define (reduce l base combine)
(cond
[(empty? l) base]
[else (combine (first l) (reduce (rest l base combine)))]))
之后就可以用一行定义出sum , product(将列表里面的数字全部×qilai )
(define (sum l)
(reduce l 0 +))
(define (product l)
(reduce l 1 *))
|
286b6910ab6ccb622a3cfc37a03f174b9ea6b1610f9210547698a6e3a73885af | kit-ty-kate/labrys | buildSystem.ml | Copyright ( c ) 2013 - 2017 The Labrys developers .
(* See the LICENSE file at the top-level directory. *)
exception Failure
type import_data =
{ library : bool
; hash_import : string
}
type impl_infos =
{ version : string
; hash : string
; hash_bc : string
; imports : (string * import_data) list
}
let map_msgpack_maps =
let aux = function
| (`FixRaw name, value) -> (String.of_list name, value)
| _ -> raise Failure
in
List.map aux
let parse_impl_infos file =
let content = CCIO.read_all file in
match Msgpack.Serialize.deserialize_string content with
| `FixMap l ->
begin match map_msgpack_maps l with
| [ ("version", `FixRaw version)
; ("hash", `Raw16 hash)
; ("hash-bc", `Raw16 hash_bc)
; ("imports", `Map32 imports)
] ->
let version = String.of_list version in
let hash = String.of_list hash in
let hash_bc = String.of_list hash_bc in
let imports =
let aux = function
| (`Raw16 import, `FixMap l) ->
begin match map_msgpack_maps l with
| [ ("library", `Bool library)
; ("hash", `Raw16 hash_import)
] ->
let hash_import = String.of_list hash_import in
(String.of_list import, {library; hash_import})
| _ ->
raise Failure
end
| _ ->
raise Failure
in
List.map aux imports
in
{version; hash; hash_bc; imports}
| _ ->
raise Failure
end
| _ ->
raise Failure
let check_imports_hash options =
let aux (modul, {library; hash_import}) =
let modul =
if library then
Module.library_from_module_name options modul
else
Module.from_module_name options modul
in
let hash_file = Digest.file (Module.impl_infos modul) in
if not (String.equal hash_file hash_import) then
raise Failure;
modul
in
List.map aux
let check_impl options modul =
try
let infos = Module.impl_infos modul in
let infos = Utils.CCIO.with_in infos (parse_impl_infos) in
let hash =
if Module.is_library modul then
infos.hash
else
Digest.file (Module.impl modul)
in
let hash_bc = Digest.file (Module.cimpl modul) in
if not
(String.equal infos.version Config.version
&& String.equal infos.hash hash
&& String.equal infos.hash_bc hash_bc
)
then
raise Failure;
check_imports_hash options infos.imports
with
| _ -> raise Failure
let write_impl_infos imports modul =
let version = Config.version in
let hash = Digest.file (Module.impl modul) in
let hash_bc = Digest.file (Module.cimpl modul) in
let imports =
let aux modul =
let import = Module.to_string modul in
let library = Module.is_library modul in
let hash_import = Digest.file (Module.impl_infos modul) in
let data =
`FixMap
[ (`FixRaw (String.to_list "library"), `Bool library)
; (`FixRaw (String.to_list "hash"), `Raw16 (String.to_list hash_import))
]
in
(`Raw16 (String.to_list import), data)
in
List.map aux imports
in
let content =
`FixMap
[ (`FixRaw (String.to_list "version"), `FixRaw (String.to_list version))
; (`FixRaw (String.to_list "hash"), `Raw16 (String.to_list hash))
; (`FixRaw (String.to_list "hash-bc"), `Raw16 (String.to_list hash_bc))
; (`FixRaw (String.to_list "imports"), `Map32 imports)
]
in
let content = Msgpack.Serialize.serialize_string content in
let file_name = Module.impl_infos modul in
Utils.mkdir file_name;
Utils.CCIO.with_out file_name (fun file -> output_string file content)
| null | https://raw.githubusercontent.com/kit-ty-kate/labrys/54e13e765583d76c6054fabe06dd4f18d68dc17d/src/buildSystem.ml | ocaml | See the LICENSE file at the top-level directory. | Copyright ( c ) 2013 - 2017 The Labrys developers .
exception Failure
type import_data =
{ library : bool
; hash_import : string
}
type impl_infos =
{ version : string
; hash : string
; hash_bc : string
; imports : (string * import_data) list
}
let map_msgpack_maps =
let aux = function
| (`FixRaw name, value) -> (String.of_list name, value)
| _ -> raise Failure
in
List.map aux
let parse_impl_infos file =
let content = CCIO.read_all file in
match Msgpack.Serialize.deserialize_string content with
| `FixMap l ->
begin match map_msgpack_maps l with
| [ ("version", `FixRaw version)
; ("hash", `Raw16 hash)
; ("hash-bc", `Raw16 hash_bc)
; ("imports", `Map32 imports)
] ->
let version = String.of_list version in
let hash = String.of_list hash in
let hash_bc = String.of_list hash_bc in
let imports =
let aux = function
| (`Raw16 import, `FixMap l) ->
begin match map_msgpack_maps l with
| [ ("library", `Bool library)
; ("hash", `Raw16 hash_import)
] ->
let hash_import = String.of_list hash_import in
(String.of_list import, {library; hash_import})
| _ ->
raise Failure
end
| _ ->
raise Failure
in
List.map aux imports
in
{version; hash; hash_bc; imports}
| _ ->
raise Failure
end
| _ ->
raise Failure
let check_imports_hash options =
let aux (modul, {library; hash_import}) =
let modul =
if library then
Module.library_from_module_name options modul
else
Module.from_module_name options modul
in
let hash_file = Digest.file (Module.impl_infos modul) in
if not (String.equal hash_file hash_import) then
raise Failure;
modul
in
List.map aux
let check_impl options modul =
try
let infos = Module.impl_infos modul in
let infos = Utils.CCIO.with_in infos (parse_impl_infos) in
let hash =
if Module.is_library modul then
infos.hash
else
Digest.file (Module.impl modul)
in
let hash_bc = Digest.file (Module.cimpl modul) in
if not
(String.equal infos.version Config.version
&& String.equal infos.hash hash
&& String.equal infos.hash_bc hash_bc
)
then
raise Failure;
check_imports_hash options infos.imports
with
| _ -> raise Failure
let write_impl_infos imports modul =
let version = Config.version in
let hash = Digest.file (Module.impl modul) in
let hash_bc = Digest.file (Module.cimpl modul) in
let imports =
let aux modul =
let import = Module.to_string modul in
let library = Module.is_library modul in
let hash_import = Digest.file (Module.impl_infos modul) in
let data =
`FixMap
[ (`FixRaw (String.to_list "library"), `Bool library)
; (`FixRaw (String.to_list "hash"), `Raw16 (String.to_list hash_import))
]
in
(`Raw16 (String.to_list import), data)
in
List.map aux imports
in
let content =
`FixMap
[ (`FixRaw (String.to_list "version"), `FixRaw (String.to_list version))
; (`FixRaw (String.to_list "hash"), `Raw16 (String.to_list hash))
; (`FixRaw (String.to_list "hash-bc"), `Raw16 (String.to_list hash_bc))
; (`FixRaw (String.to_list "imports"), `Map32 imports)
]
in
let content = Msgpack.Serialize.serialize_string content in
let file_name = Module.impl_infos modul in
Utils.mkdir file_name;
Utils.CCIO.with_out file_name (fun file -> output_string file content)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.