_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
|
---|---|---|---|---|---|---|---|---|
9693ae35df60b757f30ecacc7aab2a78cdbeff1bf452fb86bfc988bb4c6f77a8 | kazu-yamamoto/http3 | Internal.hs | module Network.HTTP3.Internal (
module Network.HTTP3.Error
, module Network.HTTP3.Frame
) where
import Network.HTTP3.Error
import Network.HTTP3.Frame
| null | https://raw.githubusercontent.com/kazu-yamamoto/http3/93b2b18a3b92b313129b91b6cafefd8f228215db/Network/HTTP3/Internal.hs | haskell | module Network.HTTP3.Internal (
module Network.HTTP3.Error
, module Network.HTTP3.Frame
) where
import Network.HTTP3.Error
import Network.HTTP3.Frame
|
|
89d7c3021d9dab913ba06d0f4d3168d06d17e675e619fd38478c74332f0fca99 | ocaml-ppx/ocamlformat | verbatim_comments.ml | = Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright notice , this
list of conditions and the following disclaimer .
* [ ... ]
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
[ ... ]
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* [...]
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
[...] *)
let _ =
= Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright notice , this
list of conditions and the following disclaimer .
* [ ... ]
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
[ ... ]
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* [...]
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
[...] *)
()
| null | https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/ddca4a34439926e5e36e1f0ce9180feaf69a671a/test/passing/tests/verbatim_comments.ml | ocaml | = Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright notice , this
list of conditions and the following disclaimer .
* [ ... ]
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
[ ... ]
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* [...]
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
[...] *)
let _ =
= Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright notice , this
list of conditions and the following disclaimer .
* [ ... ]
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
[ ... ]
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* [...]
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
[...] *)
()
|
|
25c0a52f9a85cc38ecb14eccb865273a46bfb3d0e9ee0a1e98acdc3466c9529f | ghc/packages-Cabal | Dependency.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
module Distribution.Types.Dependency
( Dependency(..)
, mkDependency
, depPkgName
, depVerRange
, depLibraries
, simplifyDependency
, mainLibSet
) where
import Distribution.Compat.Prelude
import Prelude ()
import Distribution.Types.VersionRange (isAnyVersionLight)
import Distribution.Version (VersionRange, anyVersion, simplifyVersionRange)
import Distribution.CabalSpecVersion
import Distribution.Compat.CharParsing (char, spaces)
import Distribution.Compat.Parsing (between, option)
import Distribution.Parsec
import Distribution.Pretty
import Distribution.Types.LibraryName
import Distribution.Types.PackageName
import Distribution.Types.UnqualComponentName
import qualified Distribution.Compat.NonEmptySet as NES
import qualified Text.PrettyPrint as PP
-- | Describes a dependency on a source package (API)
--
/Invariant:/ package name does not appear as ' ' in
-- set of library names.
--
data Dependency = Dependency
PackageName
VersionRange
(NonEmptySet LibraryName)
-- ^ The set of libraries required from the package.
-- Only the selected libraries will be built.
-- It does not affect the cabal-install solver yet.
deriving (Generic, Read, Show, Eq, Typeable, Data)
depPkgName :: Dependency -> PackageName
depPkgName (Dependency pn _ _) = pn
depVerRange :: Dependency -> VersionRange
depVerRange (Dependency _ vr _) = vr
depLibraries :: Dependency -> NonEmptySet LibraryName
depLibraries (Dependency _ _ cs) = cs
-- | Smart constructor of 'Dependency'.
--
If ' PackageName ' is appears as ' ' in a set of sublibraries ,
-- it is automatically converted to 'LMainLibName'.
--
-- @since 3.4.0.0
--
mkDependency :: PackageName -> VersionRange -> NonEmptySet LibraryName -> Dependency
mkDependency pn vr lb = Dependency pn vr (NES.map conv lb)
where
pn' = packageNameToUnqualComponentName pn
conv l@LMainLibName = l
conv l@(LSubLibName ln) | ln == pn' = LMainLibName
| otherwise = l
instance Binary Dependency
instance Structured Dependency
instance NFData Dependency where rnf = genericRnf
-- |
--
-- >>> prettyShow $ Dependency "pkg" anyVersion mainLibSet
-- "pkg"
--
> > > prettyShow $ Dependency " pkg " anyVersion $ NES.insert ( " sublib " ) mainLibSet
-- "pkg:{pkg, sublib}"
--
> > > prettyShow $ Dependency " pkg " anyVersion $ NES.singleton ( " sublib " )
-- "pkg:sublib"
--
> > > prettyShow $ Dependency " pkg " anyVersion $ NES.insert ( " sublib - b " ) $ NES.singleton ( " sublib - a " )
" pkg:{sublib - a , sublib - b } "
--
instance Pretty Dependency where
pretty (Dependency name ver sublibs) = withSubLibs (pretty name) <+> pver
where
TODO : change to isAnyVersion after # 6736
pver | isAnyVersionLight ver = PP.empty
| otherwise = pretty ver
withSubLibs doc = case NES.toList sublibs of
[LMainLibName] -> doc
[LSubLibName uq] -> doc <<>> PP.colon <<>> pretty uq
_ -> doc <<>> PP.colon <<>> PP.braces prettySublibs
prettySublibs = PP.hsep $ PP.punctuate PP.comma $ prettySublib <$> NES.toList sublibs
prettySublib LMainLibName = PP.text $ unPackageName name
prettySublib (LSubLibName un) = PP.text $ unUnqualComponentName un
-- |
--
> > > simpleParsec " : sub " : : Maybe Dependency
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub " ) :| [ ] ) ) )
--
> > > simpleParsec " mylib:{sub1,sub2 } " : : Maybe Dependency
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) )
--
> > > simpleParsec " : { sub1 , sub2 } " : : Maybe Dependency
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) )
--
> > > simpleParsec " : { sub1 , sub2 } ^>= 42 " : : Maybe Dependency
Just ( Dependency ( PackageName " " ) ( MajorBoundVersion ( mkVersion [ 42 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) )
--
> > > simpleParsec " : { } ^>= 42 " : : Maybe Dependency
-- Nothing
--
> > > traverse _ print ( map simpleParsec [ " : " , " mylib:{mylib } " , " mylib:{mylib , sublib } " ] : : [ Maybe Dependency ] )
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ] ) ) )
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ] ) ) )
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ( UnqualComponentName " sublib " ) ] ) ) )
--
-- Spaces around colon are not allowed:
--
> > > map [ " : sub " , " : sub " , " : { sub1,sub2 } " , " : { sub1,sub2 } " ] : : [ Maybe Dependency ]
-- [Nothing,Nothing,Nothing,Nothing]
--
Sublibrary syntax is accepted since - version : 3.0@
--
> > > map ( ` simpleParsec ' ` " : sub " ) [ CabalSpecV2_4 , CabalSpecV3_0 ] : : [ Maybe Dependency ]
[ Nothing , Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub " ) :| [ ] ) ) ) ]
--
instance Parsec Dependency where
parsec = do
name <- parsec
libs <- option mainLibSet $ do
_ <- char ':'
versionGuardMultilibs
parsecWarning PWTExperimental "colon specifier is experimental feature (issue #5660)"
NES.singleton <$> parseLib <|> parseMultipleLibs
spaces --
ver <- parsec <|> pure anyVersion
return $ mkDependency name ver libs
where
parseLib = LSubLibName <$> parsec
parseMultipleLibs = between
(char '{' *> spaces)
(spaces *> char '}')
(NES.fromNonEmpty <$> parsecCommaNonEmpty parseLib)
versionGuardMultilibs :: CabalParsing m => m ()
versionGuardMultilibs = do
csv <- askCabalSpecVersion
when (csv < CabalSpecV3_0) $ fail $ unwords
[ "Sublibrary dependency syntax used."
, "To use this syntax the package needs to specify at least 'cabal-version: 3.0'."
, "Alternatively, if you are depending on an internal library, you can write"
, "directly the library name as it were a package."
]
-- | Library set with main library.
--
-- @since 3.4.0.0
mainLibSet :: NonEmptySet LibraryName
mainLibSet = NES.singleton LMainLibName
| Simplify the ' VersionRange ' expression in a ' Dependency ' .
-- See 'simplifyVersionRange'.
--
simplifyDependency :: Dependency -> Dependency
simplifyDependency (Dependency name range comps) =
Dependency name (simplifyVersionRange range) comps
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/Cabal/Distribution/Types/Dependency.hs | haskell | # LANGUAGE DeriveDataTypeable #
| Describes a dependency on a source package (API)
set of library names.
^ The set of libraries required from the package.
Only the selected libraries will be built.
It does not affect the cabal-install solver yet.
| Smart constructor of 'Dependency'.
it is automatically converted to 'LMainLibName'.
@since 3.4.0.0
|
>>> prettyShow $ Dependency "pkg" anyVersion mainLibSet
"pkg"
"pkg:{pkg, sublib}"
"pkg:sublib"
|
Nothing
Spaces around colon are not allowed:
[Nothing,Nothing,Nothing,Nothing]
| Library set with main library.
@since 3.4.0.0
See 'simplifyVersionRange'.
| # LANGUAGE DeriveGeneric #
module Distribution.Types.Dependency
( Dependency(..)
, mkDependency
, depPkgName
, depVerRange
, depLibraries
, simplifyDependency
, mainLibSet
) where
import Distribution.Compat.Prelude
import Prelude ()
import Distribution.Types.VersionRange (isAnyVersionLight)
import Distribution.Version (VersionRange, anyVersion, simplifyVersionRange)
import Distribution.CabalSpecVersion
import Distribution.Compat.CharParsing (char, spaces)
import Distribution.Compat.Parsing (between, option)
import Distribution.Parsec
import Distribution.Pretty
import Distribution.Types.LibraryName
import Distribution.Types.PackageName
import Distribution.Types.UnqualComponentName
import qualified Distribution.Compat.NonEmptySet as NES
import qualified Text.PrettyPrint as PP
/Invariant:/ package name does not appear as ' ' in
data Dependency = Dependency
PackageName
VersionRange
(NonEmptySet LibraryName)
deriving (Generic, Read, Show, Eq, Typeable, Data)
depPkgName :: Dependency -> PackageName
depPkgName (Dependency pn _ _) = pn
depVerRange :: Dependency -> VersionRange
depVerRange (Dependency _ vr _) = vr
depLibraries :: Dependency -> NonEmptySet LibraryName
depLibraries (Dependency _ _ cs) = cs
If ' PackageName ' is appears as ' ' in a set of sublibraries ,
mkDependency :: PackageName -> VersionRange -> NonEmptySet LibraryName -> Dependency
mkDependency pn vr lb = Dependency pn vr (NES.map conv lb)
where
pn' = packageNameToUnqualComponentName pn
conv l@LMainLibName = l
conv l@(LSubLibName ln) | ln == pn' = LMainLibName
| otherwise = l
instance Binary Dependency
instance Structured Dependency
instance NFData Dependency where rnf = genericRnf
> > > prettyShow $ Dependency " pkg " anyVersion $ NES.insert ( " sublib " ) mainLibSet
> > > prettyShow $ Dependency " pkg " anyVersion $ NES.singleton ( " sublib " )
> > > prettyShow $ Dependency " pkg " anyVersion $ NES.insert ( " sublib - b " ) $ NES.singleton ( " sublib - a " )
" pkg:{sublib - a , sublib - b } "
instance Pretty Dependency where
pretty (Dependency name ver sublibs) = withSubLibs (pretty name) <+> pver
where
TODO : change to isAnyVersion after # 6736
pver | isAnyVersionLight ver = PP.empty
| otherwise = pretty ver
withSubLibs doc = case NES.toList sublibs of
[LMainLibName] -> doc
[LSubLibName uq] -> doc <<>> PP.colon <<>> pretty uq
_ -> doc <<>> PP.colon <<>> PP.braces prettySublibs
prettySublibs = PP.hsep $ PP.punctuate PP.comma $ prettySublib <$> NES.toList sublibs
prettySublib LMainLibName = PP.text $ unPackageName name
prettySublib (LSubLibName un) = PP.text $ unUnqualComponentName un
> > > simpleParsec " : sub " : : Maybe Dependency
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub " ) :| [ ] ) ) )
> > > simpleParsec " mylib:{sub1,sub2 } " : : Maybe Dependency
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) )
> > > simpleParsec " : { sub1 , sub2 } " : : Maybe Dependency
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) )
> > > simpleParsec " : { sub1 , sub2 } ^>= 42 " : : Maybe Dependency
Just ( Dependency ( PackageName " " ) ( MajorBoundVersion ( mkVersion [ 42 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub1 " ) :| [ ( UnqualComponentName " sub2 " ) ] ) ) )
> > > simpleParsec " : { } ^>= 42 " : : Maybe Dependency
> > > traverse _ print ( map simpleParsec [ " : " , " mylib:{mylib } " , " mylib:{mylib , sublib } " ] : : [ Maybe Dependency ] )
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ] ) ) )
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ] ) ) )
Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( LMainLibName :| [ ( UnqualComponentName " sublib " ) ] ) ) )
> > > map [ " : sub " , " : sub " , " : { sub1,sub2 } " , " : { sub1,sub2 } " ] : : [ Maybe Dependency ]
Sublibrary syntax is accepted since - version : 3.0@
> > > map ( ` simpleParsec ' ` " : sub " ) [ CabalSpecV2_4 , CabalSpecV3_0 ] : : [ Maybe Dependency ]
[ Nothing , Just ( Dependency ( PackageName " " ) ( OrLaterVersion ( mkVersion [ 0 ] ) ) ( fromNonEmpty ( ( UnqualComponentName " sub " ) :| [ ] ) ) ) ]
instance Parsec Dependency where
parsec = do
name <- parsec
libs <- option mainLibSet $ do
_ <- char ':'
versionGuardMultilibs
parsecWarning PWTExperimental "colon specifier is experimental feature (issue #5660)"
NES.singleton <$> parseLib <|> parseMultipleLibs
ver <- parsec <|> pure anyVersion
return $ mkDependency name ver libs
where
parseLib = LSubLibName <$> parsec
parseMultipleLibs = between
(char '{' *> spaces)
(spaces *> char '}')
(NES.fromNonEmpty <$> parsecCommaNonEmpty parseLib)
versionGuardMultilibs :: CabalParsing m => m ()
versionGuardMultilibs = do
csv <- askCabalSpecVersion
when (csv < CabalSpecV3_0) $ fail $ unwords
[ "Sublibrary dependency syntax used."
, "To use this syntax the package needs to specify at least 'cabal-version: 3.0'."
, "Alternatively, if you are depending on an internal library, you can write"
, "directly the library name as it were a package."
]
mainLibSet :: NonEmptySet LibraryName
mainLibSet = NES.singleton LMainLibName
| Simplify the ' VersionRange ' expression in a ' Dependency ' .
simplifyDependency :: Dependency -> Dependency
simplifyDependency (Dependency name range comps) =
Dependency name (simplifyVersionRange range) comps
|
6bcf14f03e840ba8010d0cda4415259e071eff0b0b4dde2170847bb86e0ecd86 | polymeris/cljs-aws | cloudsearch.cljs | (ns cljs-aws.cloudsearch
(:require [cljs-aws.base.requests])
(:require-macros [cljs-aws.base.service :refer [defservice]]))
(defservice "CloudSearch" "cloudsearch-2013-01-01.min.json")
| null | https://raw.githubusercontent.com/polymeris/cljs-aws/3326e7c4db4dfc36dcb80770610c14c8a7fd0d66/src/cljs_aws/cloudsearch.cljs | clojure | (ns cljs-aws.cloudsearch
(:require [cljs-aws.base.requests])
(:require-macros [cljs-aws.base.service :refer [defservice]]))
(defservice "CloudSearch" "cloudsearch-2013-01-01.min.json")
|
|
3b6c9c17b3a21f3ec6e387f14f27aca4e631306a6367fd9abb8ca27b49d0d4c4 | stchang/lazyprofile-tool | csv-parser-full-profiled.rkt | # lang racket
#lang s-exp "../../lazy-profile.rkt"
;(require "parser-with-errors.rkt")
;(provide (all-defined-out))
;(require "string-helpers.rkt")
(define (str-empty? str) (string=? str ""))
(define (str-fst str) (string-ref str 0))
(define (str-rst str) (substring str 1))
;(require (only-in racket [string mk-string]))
(define (mk-string x) (string x))
;(provide (all-defined-out))
Parsec with errors messages
A [ Parser X ] is a function State - > [ Consumed X ]
A State is a ( State String Pos )
- parsers consume a State
(struct State (string pos) #:transparent)
A Message is a ( String [ List String ] )
(struct Msg (pos string strings) #:transparent)
A [ Consumed X ] is one of :
;; - (Consumed [Reply X])
;; - (Empty [Reply X])
(struct Consumed (Reply) #:transparent) ;; should be lazy? (see >>= def)
(struct Empty (Reply) #:transparent)
A [ Reply X ] is one of :
;; - (Ok X State Message)
;; - (Error Message)
(struct Ok (parsed rest msg) #:transparent)
(struct Error (msg) #:transparent)
;; creates a parser that consumes no input and returns x
(define (return x)
(match-lambda
[(and state (State _ pos))
(Empty (Ok x state (Msg pos "" null)))]))
creates a parser that consumes 1 char if it satisfies predicate p ?
(define (satisfy p?)
(match-lambda
[(State input pos)
(if (str-empty? input)
(Empty (Error (Msg pos "end of input" null)))
(let ([c (str-fst input)]
[cs (str-rst input)])
(if (p? c)
(let* ([new-pos (add1 pos)]
[new-state (State cs new-pos)])
(Consumed (Ok c new-state (Msg new-pos "" null))))
(Empty (Error (Msg pos (mk-string c) null #;(list "input satisfying given predicate")))))))]))
(define (noneOf str)
(define (char=any c s)
(if (str-empty? s)
#f
(or (char=? c (str-fst s))
(char=any c (str-rst s)))))
(define (str->strs)
(format-exp (map (λ (x) (string-append "\"" (mk-string x) "\"")) (string->list str))))
(λ (state)
(match ((satisfy (λ (c) (not (char=any c str)))) state)
[(Consumed (Error (Msg pos inp exp)))
(Consumed (Error (Msg pos inp (cons (string-append "none of " (str->strs)) exp))))]
[(Empty (Error (Msg pos inp exp)))
(Empty (Error (Msg pos inp (cons (string-append "none of " (str->strs))
exp))))]
[ok ok])))
creates a parser that combines two parsers p and f
- if p succeeds but does not consume input , then f determines result
- if p succeeds and consumes input , return Consumed with thunk that delays
;; parsing from f
(define (>>= p f)
(λ (input)
(match (p input)
[(Empty reply)
(match reply
[(Ok x rest msg1)
(match ((f x) rest)
[(Empty (Error msg2)) (mergeError msg1 msg2)]
[(Empty (Ok x inp msg2)) (mergeOk x inp msg1 msg2)]
[consumed consumed])]
[err (Empty err)])]
[(Consumed reply1)
(Consumed ; arg to Consumed constructor should be delayed
; (lazy
( force )
[(Ok x rest msg1)
(match ((f x) rest)
[(Consumed reply2) reply2]
[(Empty (Error msg2)) (Error (merge msg1 msg2))]
[(Empty ok) ok]
[ ( Empty ) ] ) ]
[error error]))])))
(define (>> p q) (>>= p (λ _ q)))
;; <|> choice combinator
(define (<or>2 p q)
(λ (state)
(match (p state)
[(Empty (Error msg1))
(match (q state)
[(Empty (Error msg2)) (mergeError msg1 msg2)]
[(Empty (Ok x inp msg2)) (mergeOk x inp msg1 msg2)]
[ ( Consumed ( Ok x inp msg2 ) ) ( mergeConsumed x inp msg1 msg2 ) ]
[consumed consumed])]
[(Empty (Ok x inp msg1))
(match (q state)
[(Empty (Error msg2)) (mergeOk x inp msg1 msg2)]
[(Empty (Ok _ _ msg2)) (mergeOk x inp msg1 msg2)]
[ ( Consumed ( Ok x inp msg2 ) ) ( mergeConsumed x inp msg1 msg2 ) ]
[consumed consumed])]
#;[(Consumed (Ok x inp msg1))
(match (q inp)
[(Empty (Error msg2)) (mergeError msg1 msg2)]
[consumed consumed])]
[consumed consumed])))
(define (mergeConsumed x inp msg1 msg2) (Consumed (Ok x inp (merge msg1 msg2))))
(define (mergeOk x inp msg1 msg2) (Empty (Ok x inp (merge msg1 msg2))))
(define (mergeError msg1 msg2) (Empty (Error (merge msg1 msg2))))
(define/match (merge msg1 msg2)
[((Msg pos inp exp1) (Msg _ _ exp2))
(Msg pos inp (append exp1 exp2))])
(define (foldl f acc lst)
(if (null? lst)
acc
(foldl f (f (car lst) acc) (cdr lst))))
assumes ( length args ) > = 2
(define (<or> . args)
(foldl (λ (p acc) (<or>2 acc p)) (car args) (cdr args)))
;; lookahead
(define (try p)
(λ (state)
(match (p state)
[(Consumed (Error msg)) (Empty (Error msg))]
[other other])))
;; parse with p 0 or more times
(define (many p)
(<or> (>>= p
(λ (x) (>>= (many p) (λ (xs) (return (cons x xs))))))
(return null)))
parse with p 1 or more times
(define (many1 p)
(>>= p
(λ (x) (>>= (<or> (many1 p) (return null))
(λ (xs) (return (cons x xs)))))))
(define (sepBy1 p sep)
(>>= p (λ (x) (>>= (many (>>= sep (λ _ p))) (λ (xs) (return (cons x xs)))))))
(define (sepBy p sep) (<or> (sepBy1 p sep) (return null)))
(define (endBy p end)
;(<or>
(many (>>= p (λ (x) (>>= end (λ _ (return x)))))))
;(return null)))
(define (<?> p exp)
(λ (state)
(match (p state)
[(Empty (Error msg)) (Empty (Error (expect msg exp)))]
[(Empty (Ok x st msg)) (Empty (Ok x st (expect msg exp)))]
[other other])))
(define (expect msg exp)
(match msg
[(Msg pos inp _) (Msg pos inp (list exp))]))
;; creates a parser that parses char c
(define (char c) (<?> (satisfy (curry char=? c)) (string-append "\"" (mk-string c) "\"")))
(define letter (<?> (satisfy char-alphabetic?) "letter"))
(define digit (<?> (satisfy char-numeric?) "digit"))
(define (parse-string str)
(if (str-empty? str)
(return null)
(>>= (char (str-fst str)) (λ _ (parse-string (str-rst str))))))
;; parser that only succeeds on empty input
(define eof
(<?>
(λ (state)
(match state
[(State inp pos)
(if (str-empty? inp)
(Empty (Ok null state (Msg pos "" null)))
(Empty (Error (Msg pos "non-empty input" null))))]))
"end-of-file"))
(define eol (<?> (<or> (try (parse-string "\n\r"))
(try (parse-string "\r\n"))
(try (parse-string "\n"))
(try (parse-string "\r")))
"end-of-line"))
(define identifier (<?> (many1 (<or> letter digit (char #\_))) "identifier"))
(define (format-exp exp) (string-join exp ", " #:before-last " or "))
(define (parse p inp)
(define res (p (State inp 0)))
res
( match ( p ( State inp 0 ) )
[(Empty (Error (Msg pos msg exp)))
(error 'parse-error
"at pos ~a\nunexpected ~a: expected ~a"
pos msg (format-exp exp))]
[(Consumed (Error (Msg pos msg exp)))
(error 'parse-error
"at pos ~a\nunexpected ~a: expected ~a"
pos msg (format-exp exp))]
[x x]))
(define-syntax (mk-parser stx)
(syntax-case stx (<-)
[(_ p) #'p]
[(_ (x <- p) e ...)
#'(>>= p (λ (x) (mk-parser e ...)))]
[(_ q e ...) #'(>>= q (λ (x) (mk-parser e ...)))]))
;;;;;;; csv-parser-sepBy-with-errors.rkt + support for quoted cells
(define quotedChar
(<or> (noneOf "\"")
(try (>> (parse-string "\"\"") (return #\")))))
(define quotedCell
(mk-parser
(char #\")
(content <- (many quotedChar))
(<?> (char #\") "quote at end of cell")
(return content))
#;(>>= (char #\")
(λ _ (>>= (many quotedChar)
(λ (content) (>>= (<?> (char #\") "quote at end of cell")
(λ _ (return content))))))))
;; cellContent in csv-parser.rkt
( define cell ( many ( noneOf " , ) ) )
(define cell (<or> quotedCell (many (noneOf ",\n\r"))))
;; a line must end in \n
(define line (sepBy cell (char #\,)))
;; result is list of list of chars
(define csv (endBy line eol))
(define (csvFile filename)
(parse csv (with-input-from-file filename port->string)))
(csvFile "csv-example") | null | https://raw.githubusercontent.com/stchang/lazyprofile-tool/f347cbe6e91f671320d025d9217dfe1795b8d0f0/examples-popl2014/parsec/csv-parser-full-profiled.rkt | racket | (require "parser-with-errors.rkt")
(provide (all-defined-out))
(require "string-helpers.rkt")
(require (only-in racket [string mk-string]))
(provide (all-defined-out))
- (Consumed [Reply X])
- (Empty [Reply X])
should be lazy? (see >>= def)
- (Ok X State Message)
- (Error Message)
creates a parser that consumes no input and returns x
(list "input satisfying given predicate")))))))]))
parsing from f
arg to Consumed constructor should be delayed
(lazy
<|> choice combinator
[(Consumed (Ok x inp msg1))
lookahead
parse with p 0 or more times
(<or>
(return null)))
creates a parser that parses char c
parser that only succeeds on empty input
csv-parser-sepBy-with-errors.rkt + support for quoted cells
(>>= (char #\")
cellContent in csv-parser.rkt
a line must end in \n
result is list of list of chars | # lang racket
#lang s-exp "../../lazy-profile.rkt"
(define (str-empty? str) (string=? str ""))
(define (str-fst str) (string-ref str 0))
(define (str-rst str) (substring str 1))
(define (mk-string x) (string x))
Parsec with errors messages
A [ Parser X ] is a function State - > [ Consumed X ]
A State is a ( State String Pos )
- parsers consume a State
(struct State (string pos) #:transparent)
A Message is a ( String [ List String ] )
(struct Msg (pos string strings) #:transparent)
A [ Consumed X ] is one of :
(struct Empty (Reply) #:transparent)
A [ Reply X ] is one of :
(struct Ok (parsed rest msg) #:transparent)
(struct Error (msg) #:transparent)
(define (return x)
(match-lambda
[(and state (State _ pos))
(Empty (Ok x state (Msg pos "" null)))]))
creates a parser that consumes 1 char if it satisfies predicate p ?
(define (satisfy p?)
(match-lambda
[(State input pos)
(if (str-empty? input)
(Empty (Error (Msg pos "end of input" null)))
(let ([c (str-fst input)]
[cs (str-rst input)])
(if (p? c)
(let* ([new-pos (add1 pos)]
[new-state (State cs new-pos)])
(Consumed (Ok c new-state (Msg new-pos "" null))))
(define (noneOf str)
(define (char=any c s)
(if (str-empty? s)
#f
(or (char=? c (str-fst s))
(char=any c (str-rst s)))))
(define (str->strs)
(format-exp (map (λ (x) (string-append "\"" (mk-string x) "\"")) (string->list str))))
(λ (state)
(match ((satisfy (λ (c) (not (char=any c str)))) state)
[(Consumed (Error (Msg pos inp exp)))
(Consumed (Error (Msg pos inp (cons (string-append "none of " (str->strs)) exp))))]
[(Empty (Error (Msg pos inp exp)))
(Empty (Error (Msg pos inp (cons (string-append "none of " (str->strs))
exp))))]
[ok ok])))
creates a parser that combines two parsers p and f
- if p succeeds but does not consume input , then f determines result
- if p succeeds and consumes input , return Consumed with thunk that delays
(define (>>= p f)
(λ (input)
(match (p input)
[(Empty reply)
(match reply
[(Ok x rest msg1)
(match ((f x) rest)
[(Empty (Error msg2)) (mergeError msg1 msg2)]
[(Empty (Ok x inp msg2)) (mergeOk x inp msg1 msg2)]
[consumed consumed])]
[err (Empty err)])]
[(Consumed reply1)
( force )
[(Ok x rest msg1)
(match ((f x) rest)
[(Consumed reply2) reply2]
[(Empty (Error msg2)) (Error (merge msg1 msg2))]
[(Empty ok) ok]
[ ( Empty ) ] ) ]
[error error]))])))
(define (>> p q) (>>= p (λ _ q)))
(define (<or>2 p q)
(λ (state)
(match (p state)
[(Empty (Error msg1))
(match (q state)
[(Empty (Error msg2)) (mergeError msg1 msg2)]
[(Empty (Ok x inp msg2)) (mergeOk x inp msg1 msg2)]
[ ( Consumed ( Ok x inp msg2 ) ) ( mergeConsumed x inp msg1 msg2 ) ]
[consumed consumed])]
[(Empty (Ok x inp msg1))
(match (q state)
[(Empty (Error msg2)) (mergeOk x inp msg1 msg2)]
[(Empty (Ok _ _ msg2)) (mergeOk x inp msg1 msg2)]
[ ( Consumed ( Ok x inp msg2 ) ) ( mergeConsumed x inp msg1 msg2 ) ]
[consumed consumed])]
(match (q inp)
[(Empty (Error msg2)) (mergeError msg1 msg2)]
[consumed consumed])]
[consumed consumed])))
(define (mergeConsumed x inp msg1 msg2) (Consumed (Ok x inp (merge msg1 msg2))))
(define (mergeOk x inp msg1 msg2) (Empty (Ok x inp (merge msg1 msg2))))
(define (mergeError msg1 msg2) (Empty (Error (merge msg1 msg2))))
(define/match (merge msg1 msg2)
[((Msg pos inp exp1) (Msg _ _ exp2))
(Msg pos inp (append exp1 exp2))])
(define (foldl f acc lst)
(if (null? lst)
acc
(foldl f (f (car lst) acc) (cdr lst))))
assumes ( length args ) > = 2
(define (<or> . args)
(foldl (λ (p acc) (<or>2 acc p)) (car args) (cdr args)))
(define (try p)
(λ (state)
(match (p state)
[(Consumed (Error msg)) (Empty (Error msg))]
[other other])))
(define (many p)
(<or> (>>= p
(λ (x) (>>= (many p) (λ (xs) (return (cons x xs))))))
(return null)))
parse with p 1 or more times
(define (many1 p)
(>>= p
(λ (x) (>>= (<or> (many1 p) (return null))
(λ (xs) (return (cons x xs)))))))
(define (sepBy1 p sep)
(>>= p (λ (x) (>>= (many (>>= sep (λ _ p))) (λ (xs) (return (cons x xs)))))))
(define (sepBy p sep) (<or> (sepBy1 p sep) (return null)))
(define (endBy p end)
(many (>>= p (λ (x) (>>= end (λ _ (return x)))))))
(define (<?> p exp)
(λ (state)
(match (p state)
[(Empty (Error msg)) (Empty (Error (expect msg exp)))]
[(Empty (Ok x st msg)) (Empty (Ok x st (expect msg exp)))]
[other other])))
(define (expect msg exp)
(match msg
[(Msg pos inp _) (Msg pos inp (list exp))]))
(define (char c) (<?> (satisfy (curry char=? c)) (string-append "\"" (mk-string c) "\"")))
(define letter (<?> (satisfy char-alphabetic?) "letter"))
(define digit (<?> (satisfy char-numeric?) "digit"))
(define (parse-string str)
(if (str-empty? str)
(return null)
(>>= (char (str-fst str)) (λ _ (parse-string (str-rst str))))))
(define eof
(<?>
(λ (state)
(match state
[(State inp pos)
(if (str-empty? inp)
(Empty (Ok null state (Msg pos "" null)))
(Empty (Error (Msg pos "non-empty input" null))))]))
"end-of-file"))
(define eol (<?> (<or> (try (parse-string "\n\r"))
(try (parse-string "\r\n"))
(try (parse-string "\n"))
(try (parse-string "\r")))
"end-of-line"))
(define identifier (<?> (many1 (<or> letter digit (char #\_))) "identifier"))
(define (format-exp exp) (string-join exp ", " #:before-last " or "))
(define (parse p inp)
(define res (p (State inp 0)))
res
( match ( p ( State inp 0 ) )
[(Empty (Error (Msg pos msg exp)))
(error 'parse-error
"at pos ~a\nunexpected ~a: expected ~a"
pos msg (format-exp exp))]
[(Consumed (Error (Msg pos msg exp)))
(error 'parse-error
"at pos ~a\nunexpected ~a: expected ~a"
pos msg (format-exp exp))]
[x x]))
(define-syntax (mk-parser stx)
(syntax-case stx (<-)
[(_ p) #'p]
[(_ (x <- p) e ...)
#'(>>= p (λ (x) (mk-parser e ...)))]
[(_ q e ...) #'(>>= q (λ (x) (mk-parser e ...)))]))
(define quotedChar
(<or> (noneOf "\"")
(try (>> (parse-string "\"\"") (return #\")))))
(define quotedCell
(mk-parser
(char #\")
(content <- (many quotedChar))
(<?> (char #\") "quote at end of cell")
(return content))
(λ _ (>>= (many quotedChar)
(λ (content) (>>= (<?> (char #\") "quote at end of cell")
(λ _ (return content))))))))
( define cell ( many ( noneOf " , ) ) )
(define cell (<or> quotedCell (many (noneOf ",\n\r"))))
(define line (sepBy cell (char #\,)))
(define csv (endBy line eol))
(define (csvFile filename)
(parse csv (with-input-from-file filename port->string)))
(csvFile "csv-example") |
be6cef10499a28d90583490bcbbeb6a5a5b4b68d20efa8a891bcc55383c0fbad | Tyruiop/syncretism | options.clj | (ns syncretism.crawler.options
(:require
[taoensso.timbre :as timbre :refer [info warn error]]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.data.json :as json]
[clojure.set :as set]
[clj-http.client :as http]
[syncretism.crawler.db :as odb]
[syncretism.crawler.shared :refer [config state symbols update-tickers-dict]]
[syncretism.crawler.endpoints :refer [all-endpoints available-endpoints
register-failure sort-endpoints]]
[syncretism.time :refer [cur-ny-time market-time]]
[syncretism.greeks :as gks])
(:gen-class))
(def iter (atom (long 1)))
(defn get-ticker-data
"Given an endpoint and possibly a proxy, extract a given ticker's option
data on a given date (can be nil)."
[{:keys [endpoint proxy]} ticker date]
(println ticker date)
(let [addr (if date
(str endpoint ticker "?date=" date)
(str endpoint ticker))
base-params {:accept :json :socket-timeout 10000 :connection-timeout 10000
:retry-handler (fn [_ex try-count _http-context] (if (> try-count 4) false true))}
params (if proxy
(merge
base-params
{:proxy-host (first proxy) :proxy-port (second proxy)})
base-params)]
(-> (http/get addr params)
:body
(json/read-str :key-fn keyword)
(get-in [:optionChain :result])
first
(assoc :status :success))))
(defn gz-write-line
"Append data to gziped target"
[target content]
(with-open [w (-> target
(clojure.java.io/output-stream :append true)
java.util.zip.GZIPOutputStream.
clojure.java.io/writer)]
(binding [*out* w]
(println content))))
CRAWLER
;; -------
;;
;; REQUEST QUEUE
;; -------------
;; (count @symbols)
NYSE + NASDAQ have about 7400 listed symbols with our current filters .
Queue reached ~ 50 000 entries , and found 650 000 different options valid at a given time .
;;
We can make 48000×2 requests to Yahoo Finance , so 96000 requests .
We start with a simple queue that will query Yahoo every 1s .
;; (alternating query endpoint)
;; Once a day, clean the queue and the symbols list (mainly, remove all options that
;; have expired)
;;
;; Query a (symbol, date) pair, add any never seen before expiration date to the queue,
;; and append a new call for the on just seen.
;;
;; STORING DATA
;; ------------
One file per symbol per day .
One line per option , line is the merge of
;; * `quote` → info related to the underlying stock
;; * `opt` → info related to the option
;; * opt-type, cur-time → extra fields to complete all info
Filename should be TYPE - TICKER - STRIKEPRICE - DATE , e.g. C - AMZN-100 - 1600000000
Note , all times should be NY time .
;;
;; Eventually we will want to add more fields (e.g. sentiment analysis) to each record.
;; List[[ticker date nb-views]]
(def queue (atom []))
(defn clean-queue
"Remove all expired options from the queue, not to crawl them anymore"
[old deleted new]
(let [cur-time (cur-ny-time)
limit-expiration (+ (:instant-seconds cur-time) (:offset-seconds cur-time))
new-entries (into [] (map #(do [% nil 0]) new))]
(->> old
(filter (fn [[ticker date _]]
(and (nil? (deleted ticker))
(or (nil? date)
(> date limit-expiration)))))
(into new-entries))))
(defn clean-queue-inside-loop
[]
(info "Updating queue")
(let [{:keys [deleted]} (update-tickers-dict)
all-symbs (into #{} (keys @symbols))
queue-symbs (into #{} (map first @queue))
new (set/difference all-symbs queue-symbs)]
(swap! queue clean-queue deleted new)
(info (str "New symbols found " new))
(info (str "Symbols removed " deleted))
(info (str "Updated queue size: " (count @queue)))
;; Know which dates we are looking at already
(doseq [[symb _] @queue]
(swap! symbols #(assoc-in % [symb :exp-dates] #{})))
(doseq [[symb date] @queue]
(swap! symbols #(update-in % [symb :exp-dates] conj date)))
(info (str "Cleaning done"))))
(defn clean-queue-loop
"Once a day, clean the queue, queue is short enough that it doesn't really matter when.
t is in seconds"
[t]
(case (:options-status @state)
:running
(do
(clean-queue-inside-loop)
(Thread/sleep (* t 1000))
(recur t))
:paused
(do
(Thread/sleep (* t 1000))
(recur t))
:terminate
:terminated))
;; Map[[type symbol date strike], Map[kw, dataval]]
;; Not used for now, let's just dump directly to file.
(def options-data (atom {}))
(defn add-options [old symb quote cur-time t opts]
(reduce
(fn [acc {:keys [strike expiration] :as opt}]
(update
acc [t symb expiration strike]
(fn [old-data]
(if old-data
(conj old-data (merge opt quote {:req-time cur-time}))
[(merge opt quote {:req-time cur-time})]))))
old
opts))
;; Agent to handle futures trying to write to different files
(def agent-options (agent nil))
(add-watch
agent-options :append
(fn [_key _ref _old {:keys [target data]}]
(gz-write-line target data)))
;; Agent to handle futures trying to write to mariadb
(def agent-live-options (agent []))
;; Keep a list of all currently tracked options by the crawler,
;; reminder, this is not all options, only the ones seen since the crawler started.
(def options-set (atom #{}))
(defn add-tracked-options
[old symb t opts]
(reduce
(fn [acc {:keys [strike expiration] :as opt}]
(conj acc [t symb expiration strike]))
old
opts))
(defn append-options
"Appends to `SYMBOL.txt.gz` AND to db all required data"
[symb quote cur-time t opts]
(let [{:keys [year month-of-year day-of-month]} (cur-ny-time)
cur-date (str year (format "%02d" month-of-year) (format "%02d" day-of-month))
path (str (:save-path config) "/" cur-date "/" symb ".txt.gz")
data
(map
(fn [opt]
(let [greeks (try
(gks/calculate-greeks
(assoc
opt
:opt-type t
:annual-dividend-rate (:trailingAnnualDividendRate quote)
:annual-dividend-yield (:tailingAnnualDividendYield quote)
:stock-price (:regularMarketPrice quote)))
(catch Exception e (do (println e) {})))
breakeven (/ (Math/abs (- (:regularMarketPrice quote)
((if (= t "C") + -)
(:strike opt)
(or (:ask opt) (:lastPrice opt)))))
(:regularMarketPrice quote))]
{:req-time cur-time
:opt (merge
(assoc opt :opt-type t :quote-type (:quoteType quote) :breakeven breakeven)
greeks)
:quote
(dissoc
quote
;; Remove redundant / useless data to save some space...
:language :exchangeTimezoneName :region :currency :longName :displayName
:shortName :market :exchange :messageBoardId)}))
opts)]
(io/make-parents path)
(when (and quote (not-empty quote))
(try
(odb/insert-or-update-live-quote symb (json/write-str quote))
(catch Exception e (error (str "SQL FAILURE quote for " symb)))))
(when (not-empty data)
(send agent-live-options (fn [old] (into old data)))
(send agent-options (fn [old] {:target path :data (str/join "\n" data)})))))
(defn process-queue
"Take a symbol, a date, a query entrypoint number, and process & adapt the queue
Concretely, append all the data to the correct keys in `options` and add the missing
expiration dates to the queue."
[debug endpoint [symb date nb-views]]
(when debug
(info (str "Querying " symb " at date " (if date date "unset"))))
(let [{:keys [instant-seconds offset-seconds]} (cur-ny-time)
cur-time (+ instant-seconds offset-seconds)
{:keys [expirationDates quote options status] :as data}
(try
(get-ticker-data endpoint symb date)
(catch Exception e
(do
(when debug
(error endpoint))
(register-failure endpoint)
nil)))
{:keys [calls puts]} (first options)
new-exp-dates (set/difference
(into #{} expirationDates)
(-> @symbols (get symb) :exp-dates))]
;; (swap! options-data add-options symb quote cur-time "C" calls)
;; (swap! options-data add-options symb quote cur-time "P" puts)
(swap! options-set add-tracked-options symb "C" calls)
(swap! options-set add-tracked-options symb "P" puts)
(append-options symb quote cur-time "C" calls)
(append-options symb quote cur-time "P" puts)
(swap! symbols #(update-in % [symb :exp-dates] set/union new-exp-dates))
(doseq [exp-date new-exp-dates]
(swap! queue conj [symb exp-date 0]))
(if (= status :success)
(swap! queue conj [symb date (inc nb-views)])
(swap! queue conj [symb date nb-views]))))
(defn scheduler
"Basic scheduler that handles reorganisation of the queue & of the proxies,
and saving the data"
[config]
;; Re-order queue
(info (str "Running scheduler (iteration: " @iter ")"))
(swap! queue #(into [] (sort-by last %)))
;; Re-order proxies
(sort-endpoints)
(spit (str (:save-path config) "/status.edn") (pr-str @all-endpoints))
(spit (str (:save-path config) "/queue.edn") (pr-str @queue))
(info (str "Seen options: " (count @options-set) " | queue size: " (count @queue)))
(let [data (take (:batch-size config) @agent-live-options)
c-data (count data)]
(try
(info (str "SQL Write in progress, " c-data " rows."))
(odb/insert-or-update-live data)
(catch Exception e (error (str "SQL FAILURE " e))))
(send agent-live-options (fn [old] (into [] (drop c-data old))))))
(defn init-queue
[]
(let [fname (str (:save-path config) "/queue.edn")]
(if (.exists (io/file fname))
(reset! queue (-> fname slurp read-string distinct))
(clean-queue-inside-loop))))
(defn crawler
[]
;; Trigger clean-queue-loop, if queue was empty, update is twice in a row, I can
;; live with that.
(println "Starting crawler")
(future (clean-queue-loop (:t-clean-queue config)))
(let [nb-endpoints (:nb-endpoints config)
old-time (atom 0)]
(loop []
(case (:options-status @state)
:running
(let [cur-time (System/currentTimeMillis)
is-market (market-time cur-time)
cur-op (first @queue)
endpoint (nth @available-endpoints (mod @iter nb-endpoints))]
(if (or (not= "CLOSED" is-market) (:force-crawl config))
(do
(swap! queue #(->> % rest (into [])))
(future (process-queue (:debug config) endpoint cur-op))
(when (> (/ (- cur-time @old-time) 1000) (:t-reorder config))
(reset! old-time cur-time)
(scheduler config))
(swap! iter inc))
(do
(when (= (mod @iter (* nb-endpoints 500)) 0)
(info "Currently outside of [PRE|POST] market hours."))))
(Thread/sleep (/ 2000 nb-endpoints))
(recur))
:paused
(do
(Thread/sleep 1000)
(recur))
:terminate
(do
(info "Terminating options crawler.")
:done)
))
(warn "Crawler coming to a halt.")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Functions that will be useful when we try to make the queue smart.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(comment
(defn append-to-queue
"Takes a recently processed entry, and appends the next query time if it's
not after expiration and not again outside of market hours (not need to request twice...)."
[queue {:keys [ticker date next-time]}]
(let [n-next-time (-> queue last :next-time inc get-time (max (+ 3600 next-time)))]
(if (> n-next-time date)
queue
(conj queue {:ticker ticker :date date :next-time next-time})))))
| null | https://raw.githubusercontent.com/Tyruiop/syncretism/f387ab88abf8a9c1aea48e3a2f616de879e75883/syncretism-crawler/src/syncretism/crawler/options.clj | clojure | -------
REQUEST QUEUE
-------------
(count @symbols)
(alternating query endpoint)
Once a day, clean the queue and the symbols list (mainly, remove all options that
have expired)
Query a (symbol, date) pair, add any never seen before expiration date to the queue,
and append a new call for the on just seen.
STORING DATA
------------
* `quote` → info related to the underlying stock
* `opt` → info related to the option
* opt-type, cur-time → extra fields to complete all info
Eventually we will want to add more fields (e.g. sentiment analysis) to each record.
List[[ticker date nb-views]]
Know which dates we are looking at already
Map[[type symbol date strike], Map[kw, dataval]]
Not used for now, let's just dump directly to file.
Agent to handle futures trying to write to different files
Agent to handle futures trying to write to mariadb
Keep a list of all currently tracked options by the crawler,
reminder, this is not all options, only the ones seen since the crawler started.
Remove redundant / useless data to save some space...
(swap! options-data add-options symb quote cur-time "C" calls)
(swap! options-data add-options symb quote cur-time "P" puts)
Re-order queue
Re-order proxies
Trigger clean-queue-loop, if queue was empty, update is twice in a row, I can
live with that.
Functions that will be useful when we try to make the queue smart.
| (ns syncretism.crawler.options
(:require
[taoensso.timbre :as timbre :refer [info warn error]]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.data.json :as json]
[clojure.set :as set]
[clj-http.client :as http]
[syncretism.crawler.db :as odb]
[syncretism.crawler.shared :refer [config state symbols update-tickers-dict]]
[syncretism.crawler.endpoints :refer [all-endpoints available-endpoints
register-failure sort-endpoints]]
[syncretism.time :refer [cur-ny-time market-time]]
[syncretism.greeks :as gks])
(:gen-class))
(def iter (atom (long 1)))
(defn get-ticker-data
"Given an endpoint and possibly a proxy, extract a given ticker's option
data on a given date (can be nil)."
[{:keys [endpoint proxy]} ticker date]
(println ticker date)
(let [addr (if date
(str endpoint ticker "?date=" date)
(str endpoint ticker))
base-params {:accept :json :socket-timeout 10000 :connection-timeout 10000
:retry-handler (fn [_ex try-count _http-context] (if (> try-count 4) false true))}
params (if proxy
(merge
base-params
{:proxy-host (first proxy) :proxy-port (second proxy)})
base-params)]
(-> (http/get addr params)
:body
(json/read-str :key-fn keyword)
(get-in [:optionChain :result])
first
(assoc :status :success))))
(defn gz-write-line
"Append data to gziped target"
[target content]
(with-open [w (-> target
(clojure.java.io/output-stream :append true)
java.util.zip.GZIPOutputStream.
clojure.java.io/writer)]
(binding [*out* w]
(println content))))
CRAWLER
NYSE + NASDAQ have about 7400 listed symbols with our current filters .
Queue reached ~ 50 000 entries , and found 650 000 different options valid at a given time .
We can make 48000×2 requests to Yahoo Finance , so 96000 requests .
We start with a simple queue that will query Yahoo every 1s .
One file per symbol per day .
One line per option , line is the merge of
Filename should be TYPE - TICKER - STRIKEPRICE - DATE , e.g. C - AMZN-100 - 1600000000
Note , all times should be NY time .
(def queue (atom []))
(defn clean-queue
"Remove all expired options from the queue, not to crawl them anymore"
[old deleted new]
(let [cur-time (cur-ny-time)
limit-expiration (+ (:instant-seconds cur-time) (:offset-seconds cur-time))
new-entries (into [] (map #(do [% nil 0]) new))]
(->> old
(filter (fn [[ticker date _]]
(and (nil? (deleted ticker))
(or (nil? date)
(> date limit-expiration)))))
(into new-entries))))
(defn clean-queue-inside-loop
[]
(info "Updating queue")
(let [{:keys [deleted]} (update-tickers-dict)
all-symbs (into #{} (keys @symbols))
queue-symbs (into #{} (map first @queue))
new (set/difference all-symbs queue-symbs)]
(swap! queue clean-queue deleted new)
(info (str "New symbols found " new))
(info (str "Symbols removed " deleted))
(info (str "Updated queue size: " (count @queue)))
(doseq [[symb _] @queue]
(swap! symbols #(assoc-in % [symb :exp-dates] #{})))
(doseq [[symb date] @queue]
(swap! symbols #(update-in % [symb :exp-dates] conj date)))
(info (str "Cleaning done"))))
(defn clean-queue-loop
"Once a day, clean the queue, queue is short enough that it doesn't really matter when.
t is in seconds"
[t]
(case (:options-status @state)
:running
(do
(clean-queue-inside-loop)
(Thread/sleep (* t 1000))
(recur t))
:paused
(do
(Thread/sleep (* t 1000))
(recur t))
:terminate
:terminated))
(def options-data (atom {}))
(defn add-options [old symb quote cur-time t opts]
(reduce
(fn [acc {:keys [strike expiration] :as opt}]
(update
acc [t symb expiration strike]
(fn [old-data]
(if old-data
(conj old-data (merge opt quote {:req-time cur-time}))
[(merge opt quote {:req-time cur-time})]))))
old
opts))
(def agent-options (agent nil))
(add-watch
agent-options :append
(fn [_key _ref _old {:keys [target data]}]
(gz-write-line target data)))
(def agent-live-options (agent []))
(def options-set (atom #{}))
(defn add-tracked-options
[old symb t opts]
(reduce
(fn [acc {:keys [strike expiration] :as opt}]
(conj acc [t symb expiration strike]))
old
opts))
(defn append-options
"Appends to `SYMBOL.txt.gz` AND to db all required data"
[symb quote cur-time t opts]
(let [{:keys [year month-of-year day-of-month]} (cur-ny-time)
cur-date (str year (format "%02d" month-of-year) (format "%02d" day-of-month))
path (str (:save-path config) "/" cur-date "/" symb ".txt.gz")
data
(map
(fn [opt]
(let [greeks (try
(gks/calculate-greeks
(assoc
opt
:opt-type t
:annual-dividend-rate (:trailingAnnualDividendRate quote)
:annual-dividend-yield (:tailingAnnualDividendYield quote)
:stock-price (:regularMarketPrice quote)))
(catch Exception e (do (println e) {})))
breakeven (/ (Math/abs (- (:regularMarketPrice quote)
((if (= t "C") + -)
(:strike opt)
(or (:ask opt) (:lastPrice opt)))))
(:regularMarketPrice quote))]
{:req-time cur-time
:opt (merge
(assoc opt :opt-type t :quote-type (:quoteType quote) :breakeven breakeven)
greeks)
:quote
(dissoc
quote
:language :exchangeTimezoneName :region :currency :longName :displayName
:shortName :market :exchange :messageBoardId)}))
opts)]
(io/make-parents path)
(when (and quote (not-empty quote))
(try
(odb/insert-or-update-live-quote symb (json/write-str quote))
(catch Exception e (error (str "SQL FAILURE quote for " symb)))))
(when (not-empty data)
(send agent-live-options (fn [old] (into old data)))
(send agent-options (fn [old] {:target path :data (str/join "\n" data)})))))
(defn process-queue
"Take a symbol, a date, a query entrypoint number, and process & adapt the queue
Concretely, append all the data to the correct keys in `options` and add the missing
expiration dates to the queue."
[debug endpoint [symb date nb-views]]
(when debug
(info (str "Querying " symb " at date " (if date date "unset"))))
(let [{:keys [instant-seconds offset-seconds]} (cur-ny-time)
cur-time (+ instant-seconds offset-seconds)
{:keys [expirationDates quote options status] :as data}
(try
(get-ticker-data endpoint symb date)
(catch Exception e
(do
(when debug
(error endpoint))
(register-failure endpoint)
nil)))
{:keys [calls puts]} (first options)
new-exp-dates (set/difference
(into #{} expirationDates)
(-> @symbols (get symb) :exp-dates))]
(swap! options-set add-tracked-options symb "C" calls)
(swap! options-set add-tracked-options symb "P" puts)
(append-options symb quote cur-time "C" calls)
(append-options symb quote cur-time "P" puts)
(swap! symbols #(update-in % [symb :exp-dates] set/union new-exp-dates))
(doseq [exp-date new-exp-dates]
(swap! queue conj [symb exp-date 0]))
(if (= status :success)
(swap! queue conj [symb date (inc nb-views)])
(swap! queue conj [symb date nb-views]))))
(defn scheduler
"Basic scheduler that handles reorganisation of the queue & of the proxies,
and saving the data"
[config]
(info (str "Running scheduler (iteration: " @iter ")"))
(swap! queue #(into [] (sort-by last %)))
(sort-endpoints)
(spit (str (:save-path config) "/status.edn") (pr-str @all-endpoints))
(spit (str (:save-path config) "/queue.edn") (pr-str @queue))
(info (str "Seen options: " (count @options-set) " | queue size: " (count @queue)))
(let [data (take (:batch-size config) @agent-live-options)
c-data (count data)]
(try
(info (str "SQL Write in progress, " c-data " rows."))
(odb/insert-or-update-live data)
(catch Exception e (error (str "SQL FAILURE " e))))
(send agent-live-options (fn [old] (into [] (drop c-data old))))))
(defn init-queue
[]
(let [fname (str (:save-path config) "/queue.edn")]
(if (.exists (io/file fname))
(reset! queue (-> fname slurp read-string distinct))
(clean-queue-inside-loop))))
(defn crawler
[]
(println "Starting crawler")
(future (clean-queue-loop (:t-clean-queue config)))
(let [nb-endpoints (:nb-endpoints config)
old-time (atom 0)]
(loop []
(case (:options-status @state)
:running
(let [cur-time (System/currentTimeMillis)
is-market (market-time cur-time)
cur-op (first @queue)
endpoint (nth @available-endpoints (mod @iter nb-endpoints))]
(if (or (not= "CLOSED" is-market) (:force-crawl config))
(do
(swap! queue #(->> % rest (into [])))
(future (process-queue (:debug config) endpoint cur-op))
(when (> (/ (- cur-time @old-time) 1000) (:t-reorder config))
(reset! old-time cur-time)
(scheduler config))
(swap! iter inc))
(do
(when (= (mod @iter (* nb-endpoints 500)) 0)
(info "Currently outside of [PRE|POST] market hours."))))
(Thread/sleep (/ 2000 nb-endpoints))
(recur))
:paused
(do
(Thread/sleep 1000)
(recur))
:terminate
(do
(info "Terminating options crawler.")
:done)
))
(warn "Crawler coming to a halt.")))
(comment
(defn append-to-queue
"Takes a recently processed entry, and appends the next query time if it's
not after expiration and not again outside of market hours (not need to request twice...)."
[queue {:keys [ticker date next-time]}]
(let [n-next-time (-> queue last :next-time inc get-time (max (+ 3600 next-time)))]
(if (> n-next-time date)
queue
(conj queue {:ticker ticker :date date :next-time next-time})))))
|
d70cc51a9aeaa56840eb643b7bc783a8203ed9d9fbfaa5c17d69c2919be5f5e4 | phoe/riichi-evaluator | payment-trainer.lisp | ;;;; src/payment-trainer.lisp
;;;;
Copyright 2012 - 2019 Kimmo " keko " and " phoe " Herda .
;;;;
;;;; 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.
;;; Simple payment trainer
(defparameter *ten-scoring-values*
(nconc (mapcar (a:curry #'list 1) (a:iota 9 :start 30 :step 10))
(mapcar (a:curry #'list 2) (a:iota 10 :start 20 :step 10))
(mapcar (a:curry #'list 3) (a:iota 5 :start 20 :step 10))
(mapcar (a:curry #'list 4) (a:iota 2 :start 20 :step 10))))
(defun ten (han fu &key oya-p ron-p)
(let* ((base-ten (* fu (expt 2 (+ 2 han))))
(ten (cond ((and (not ron-p) (not oya-p)) (* 1 base-ten))
((and (not ron-p) oya-p) (* 2 base-ten))
((and ron-p (not oya-p)) (* 4 base-ten))
((and ron-p oya-p) (* 6 base-ten)))))
(* 100 (ceiling ten 100))))
(defun compute-ten-list (han fu)
(list (ten han fu)
(ten han fu :oya-p t)
(ten han fu :ron-p t)
(ten han fu :oya-p t :ron-p t)))
(defun test-check-answer (actual expected)
(cond ((equal actual expected)
(format *query-io* (a:whichever "Good!" "Nice!" "Awesome!"))
t)
(t
(format *query-io* "Wrong! ~{~D~^ ~}" expected))))
(defun test-han-fu->ten ()
(destructuring-bind (han fu) (a:random-elt *ten-scoring-values*)
(format *query-io* "~&~D han ~D fu is: " han fu)
(let ((actual (loop repeat 4 collect (read *query-io*)))
(expected (compute-ten-list han fu)))
(test-check-answer actual expected))))
(defun test-ten->han-fu ()
(let* ((datum (a:random-elt *ten-scoring-values*))
(expected (apply #'compute-ten-list datum)))
(format *query-io* "~&~{~D~^ ~} ten is: " expected)
(let ((actual (apply #'compute-ten-list
(loop repeat 2 collect (read *query-io*)))))
(test-check-answer actual expected))))
(defun train-ten (&optional (max 10))
(loop with correct = 0
for all from 0 below max
when (test-han-fu->ten)
;; (a:whichever (test-han-fu->ten) (test-ten->han-fu))
do (incf correct)
finally (format *query-io* "~&Correct answers: ~D out of ~D."
correct all))) | null | https://raw.githubusercontent.com/phoe/riichi-evaluator/52503213129e82c6e7c9f06a5ccd4a4fc4f6b186/src/payment-trainer.lisp | lisp | src/payment-trainer.lisp
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
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.
Simple payment trainer
(a:whichever (test-han-fu->ten) (test-ten->han-fu)) | Copyright 2012 - 2019 Kimmo " keko " and " phoe " Herda .
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(defparameter *ten-scoring-values*
(nconc (mapcar (a:curry #'list 1) (a:iota 9 :start 30 :step 10))
(mapcar (a:curry #'list 2) (a:iota 10 :start 20 :step 10))
(mapcar (a:curry #'list 3) (a:iota 5 :start 20 :step 10))
(mapcar (a:curry #'list 4) (a:iota 2 :start 20 :step 10))))
(defun ten (han fu &key oya-p ron-p)
(let* ((base-ten (* fu (expt 2 (+ 2 han))))
(ten (cond ((and (not ron-p) (not oya-p)) (* 1 base-ten))
((and (not ron-p) oya-p) (* 2 base-ten))
((and ron-p (not oya-p)) (* 4 base-ten))
((and ron-p oya-p) (* 6 base-ten)))))
(* 100 (ceiling ten 100))))
(defun compute-ten-list (han fu)
(list (ten han fu)
(ten han fu :oya-p t)
(ten han fu :ron-p t)
(ten han fu :oya-p t :ron-p t)))
(defun test-check-answer (actual expected)
(cond ((equal actual expected)
(format *query-io* (a:whichever "Good!" "Nice!" "Awesome!"))
t)
(t
(format *query-io* "Wrong! ~{~D~^ ~}" expected))))
(defun test-han-fu->ten ()
(destructuring-bind (han fu) (a:random-elt *ten-scoring-values*)
(format *query-io* "~&~D han ~D fu is: " han fu)
(let ((actual (loop repeat 4 collect (read *query-io*)))
(expected (compute-ten-list han fu)))
(test-check-answer actual expected))))
(defun test-ten->han-fu ()
(let* ((datum (a:random-elt *ten-scoring-values*))
(expected (apply #'compute-ten-list datum)))
(format *query-io* "~&~{~D~^ ~} ten is: " expected)
(let ((actual (apply #'compute-ten-list
(loop repeat 2 collect (read *query-io*)))))
(test-check-answer actual expected))))
(defun train-ten (&optional (max 10))
(loop with correct = 0
for all from 0 below max
when (test-han-fu->ten)
do (incf correct)
finally (format *query-io* "~&Correct answers: ~D out of ~D."
correct all))) |
31396287c7d03b53b82b7aa8bc2979e0d4a7543436fe434ea25fe152827b0d2e | mchakravarty/HaskellSpriteKit | Geometry.hs | # LANGUAGE TemplateHaskell , QuasiQuotes , DeriveDataTypeable , RecordWildCards , ForeignFunctionInterface #
-- |
Module : Graphics . . Geometry
Copyright : [ 2014 ]
-- License : All rights reserved
--
Maintainer : < >
-- Stability : experimental
--
-- Geometry types and operations
module Graphics.SpriteKit.Geometry (
-- ** Basic temporal definition
TimeInterval,
-- ** Basic geometry definitions
GFloat, Point(..), Size(..), Rect(..), Vector(..),
pointZero, sizeZero, rectZero, vectorZero,
-- * Marshalling functions (internal)
pointToCGPoint, cgPointToPoint,
sizeToCGSize, cgSizeToSize,
rectToCGRect, cgRectToRect,
vectorToCGVector, cgVectorToVector,
geometry_initialise
) where
-- standard libraries
import Data.Typeable
import Foreign
-- language-c-inline
import Language.C.Quote.ObjC
import Language.C.Inline.ObjC
objc_import ["<Cocoa/Cocoa.h>", "<SpriteKit/SpriteKit.h>", "GHC/HsFFI.h"]
-- Temporal definitions
-- --------------------
type TimeInterval = Double
-- Basic geometry definitions
-- --------------------------
|Graphics float ( which is a ' Float ' or ' Double ' depending on whether we are on a 32 or 64 bit architecture )
--
type GFloat = Double -- ^FIXME: need to be set in dependence on the definition of 'CGFloat' resp 'CGFLOAT_IS_DOUBLE'
|Point in a two - dimensional coordinate system .
--
data Point = Point {pointX :: !GFloat, pointY :: !GFloat}
deriving (Eq, Ord, Show, Read, Typeable)
-- |Point at (0, 0).
--
pointZero :: Point
pointZero = Point 0 0
|Size of a two - dimensional geometry entity .
--
data Size = Size {sizeWidth :: !GFloat, sizeHeight :: !GFloat}
deriving (Eq, Ord, Show, Read, Typeable)
sizeZero :: Size
sizeZero = Size 0 0
-- |Location and size of a rectangle.
--
data Rect = Rect {rectOrigin :: !Point, rectSize :: !Size}
deriving (Eq, Ord, Show, Read, Typeable)
rectZero :: Rect
rectZero = Rect pointZero sizeZero
-- |Two-dimensional vector.
--
data Vector = Vector {vectorDx :: !GFloat, vectorDy :: !GFloat}
deriving (Eq, Ord, Show, Read, Typeable)
vectorZero :: Vector
vectorZero = Vector 0 0
-- Marshalling support
-- -------------------
newtype CGPoint = CGPoint (ForeignPtr CGPoint)
needed for now until migrating to new TH
objc_typecheck
pointToCGPoint :: Point -> IO CGPoint
pointToCGPoint (Point {..})
-- FIXME: language-c-inline needs to look through type synonyms
= $ ( objc [ ' pointX :> '' , ' pointY :> '' GFloat ] $ Struct '' CGPoint < :
= $(objc ['pointX :> ''Double, 'pointY :> ''Double] $ Struct ''CGPoint <:
[cexp| ({
typename CGPoint *pnt = (typename CGPoint *) malloc(sizeof(CGPoint));
*pnt = CGPointMake(pointX, pointY);
pnt;
}) |] )
cgPointToPoint :: CGPoint -> IO Point
cgPointToPoint (CGPoint pointPtr)
= withForeignPtr pointPtr $ \pointPtr -> do
{ x <- peekElemOff (castPtr pointPtr :: Ptr GFloat) 0
; y <- peekElemOff (castPtr pointPtr :: Ptr GFloat) 1
; return $ Point x y
}
objc_struct_marshaller 'pointToCGPoint 'cgPointToPoint
newtype CGSize = CGSize (ForeignPtr CGSize)
needed for now until migrating to new TH
objc_typecheck
sizeToCGSize :: Size -> IO CGSize
sizeToCGSize (Size {..})
-- FIXME: language-c-inline needs to look through type synonyms
= $ ( objc [ ' sizeWidth :> '' , ' sizeHeight :> '' GFloat ] $ Struct '' CGSize < :
= $(objc ['sizeWidth :> ''Double, 'sizeHeight :> ''Double] $ Struct ''CGSize <:
[cexp| ({
typename CGSize *sz = (typename CGSize *) malloc(sizeof(CGSize));
*sz = CGSizeMake(sizeWidth, sizeHeight);
sz;
}) |] )
cgSizeToSize :: CGSize -> IO Size
cgSizeToSize (CGSize sizePtr)
= withForeignPtr sizePtr $ \sizePtr -> do
{ width <- peekElemOff (castPtr sizePtr :: Ptr GFloat) 0
; height <- peekElemOff (castPtr sizePtr :: Ptr GFloat) 1
; return $ Size width height
}
objc_struct_marshaller 'sizeToCGSize 'cgSizeToSize
newtype CGRect = CGRect (ForeignPtr CGRect)
needed for now until migrating to new TH
objc_typecheck
rectToCGRect :: Rect -> IO CGRect
rectToCGRect (Rect {..})
= $(objc ['rectOrigin :> ''Point, 'rectSize :> ''Size] $ Struct ''CGRect <:
[cexp| ({
typename CGRect *rect = (typename CGRect *) malloc(sizeof(CGRect));
rect->origin = *rectOrigin;
rect->size = *rectSize;
rect;
}) |] )
cgRectToRect :: CGRect -> IO Rect
cgRectToRect (CGRect rectPtr)
= withForeignPtr rectPtr $ \rectPtr -> do
{ x <- peekElemOff (castPtr rectPtr :: Ptr GFloat) 0
; y <- peekElemOff (castPtr rectPtr :: Ptr GFloat) 1
; width <- peekElemOff (castPtr rectPtr :: Ptr GFloat) 2
; height <- peekElemOff (castPtr rectPtr :: Ptr GFloat) 3
; return $ Rect (Point x y) (Size width height)
}
newtype CGVector = CGVector (ForeignPtr CGVector)
needed for now until migrating to new TH
objc_typecheck
vectorToCGVector :: Vector -> IO CGVector
vectorToCGVector (Vector {..})
-- FIXME: language-c-inline needs to look through type synonyms
= $ ( objc [ ' vectorDx :> '' , ' vectorDy :> '' GFloat ] $ Struct '' CGVector < :
= $(objc ['vectorDx :> ''Double, 'vectorDy :> ''Double] $ Struct ''CGVector <:
[cexp| ({
typename CGVector *vec = (typename CGVector *) malloc(sizeof(CGVector));
*vec = CGVectorMake(vectorDx, vectorDy);
vec;
}) |] )
cgVectorToVector :: CGVector -> IO Vector
cgVectorToVector (CGVector vectorPtr)
= withForeignPtr vectorPtr $ \vectorPtr -> do
{ vectorDx <- peekElemOff (castPtr vectorPtr :: Ptr GFloat) 0
; vectorDy <- peekElemOff (castPtr vectorPtr :: Ptr GFloat) 1
; return $ Vector vectorDx vectorDy
}
objc_emit
geometry_initialise = objc_initialise
| null | https://raw.githubusercontent.com/mchakravarty/HaskellSpriteKit/f4ed000f0c0e0055d0f6d2d87a1e3d6f38996bed/HaskellSpriteKit/spritekit/Graphics/SpriteKit/Geometry.hs | haskell | |
License : All rights reserved
Stability : experimental
Geometry types and operations
** Basic temporal definition
** Basic geometry definitions
* Marshalling functions (internal)
standard libraries
language-c-inline
Temporal definitions
--------------------
Basic geometry definitions
--------------------------
^FIXME: need to be set in dependence on the definition of 'CGFloat' resp 'CGFLOAT_IS_DOUBLE'
|Point at (0, 0).
|Location and size of a rectangle.
|Two-dimensional vector.
Marshalling support
-------------------
FIXME: language-c-inline needs to look through type synonyms
FIXME: language-c-inline needs to look through type synonyms
FIXME: language-c-inline needs to look through type synonyms | # LANGUAGE TemplateHaskell , QuasiQuotes , DeriveDataTypeable , RecordWildCards , ForeignFunctionInterface #
Module : Graphics . . Geometry
Copyright : [ 2014 ]
Maintainer : < >
module Graphics.SpriteKit.Geometry (
TimeInterval,
GFloat, Point(..), Size(..), Rect(..), Vector(..),
pointZero, sizeZero, rectZero, vectorZero,
pointToCGPoint, cgPointToPoint,
sizeToCGSize, cgSizeToSize,
rectToCGRect, cgRectToRect,
vectorToCGVector, cgVectorToVector,
geometry_initialise
) where
import Data.Typeable
import Foreign
import Language.C.Quote.ObjC
import Language.C.Inline.ObjC
objc_import ["<Cocoa/Cocoa.h>", "<SpriteKit/SpriteKit.h>", "GHC/HsFFI.h"]
type TimeInterval = Double
|Graphics float ( which is a ' Float ' or ' Double ' depending on whether we are on a 32 or 64 bit architecture )
|Point in a two - dimensional coordinate system .
data Point = Point {pointX :: !GFloat, pointY :: !GFloat}
deriving (Eq, Ord, Show, Read, Typeable)
pointZero :: Point
pointZero = Point 0 0
|Size of a two - dimensional geometry entity .
data Size = Size {sizeWidth :: !GFloat, sizeHeight :: !GFloat}
deriving (Eq, Ord, Show, Read, Typeable)
sizeZero :: Size
sizeZero = Size 0 0
data Rect = Rect {rectOrigin :: !Point, rectSize :: !Size}
deriving (Eq, Ord, Show, Read, Typeable)
rectZero :: Rect
rectZero = Rect pointZero sizeZero
data Vector = Vector {vectorDx :: !GFloat, vectorDy :: !GFloat}
deriving (Eq, Ord, Show, Read, Typeable)
vectorZero :: Vector
vectorZero = Vector 0 0
newtype CGPoint = CGPoint (ForeignPtr CGPoint)
needed for now until migrating to new TH
objc_typecheck
pointToCGPoint :: Point -> IO CGPoint
pointToCGPoint (Point {..})
= $ ( objc [ ' pointX :> '' , ' pointY :> '' GFloat ] $ Struct '' CGPoint < :
= $(objc ['pointX :> ''Double, 'pointY :> ''Double] $ Struct ''CGPoint <:
[cexp| ({
typename CGPoint *pnt = (typename CGPoint *) malloc(sizeof(CGPoint));
*pnt = CGPointMake(pointX, pointY);
pnt;
}) |] )
cgPointToPoint :: CGPoint -> IO Point
cgPointToPoint (CGPoint pointPtr)
= withForeignPtr pointPtr $ \pointPtr -> do
{ x <- peekElemOff (castPtr pointPtr :: Ptr GFloat) 0
; y <- peekElemOff (castPtr pointPtr :: Ptr GFloat) 1
; return $ Point x y
}
objc_struct_marshaller 'pointToCGPoint 'cgPointToPoint
newtype CGSize = CGSize (ForeignPtr CGSize)
needed for now until migrating to new TH
objc_typecheck
sizeToCGSize :: Size -> IO CGSize
sizeToCGSize (Size {..})
= $ ( objc [ ' sizeWidth :> '' , ' sizeHeight :> '' GFloat ] $ Struct '' CGSize < :
= $(objc ['sizeWidth :> ''Double, 'sizeHeight :> ''Double] $ Struct ''CGSize <:
[cexp| ({
typename CGSize *sz = (typename CGSize *) malloc(sizeof(CGSize));
*sz = CGSizeMake(sizeWidth, sizeHeight);
sz;
}) |] )
cgSizeToSize :: CGSize -> IO Size
cgSizeToSize (CGSize sizePtr)
= withForeignPtr sizePtr $ \sizePtr -> do
{ width <- peekElemOff (castPtr sizePtr :: Ptr GFloat) 0
; height <- peekElemOff (castPtr sizePtr :: Ptr GFloat) 1
; return $ Size width height
}
objc_struct_marshaller 'sizeToCGSize 'cgSizeToSize
newtype CGRect = CGRect (ForeignPtr CGRect)
needed for now until migrating to new TH
objc_typecheck
rectToCGRect :: Rect -> IO CGRect
rectToCGRect (Rect {..})
= $(objc ['rectOrigin :> ''Point, 'rectSize :> ''Size] $ Struct ''CGRect <:
[cexp| ({
typename CGRect *rect = (typename CGRect *) malloc(sizeof(CGRect));
rect->origin = *rectOrigin;
rect->size = *rectSize;
rect;
}) |] )
cgRectToRect :: CGRect -> IO Rect
cgRectToRect (CGRect rectPtr)
= withForeignPtr rectPtr $ \rectPtr -> do
{ x <- peekElemOff (castPtr rectPtr :: Ptr GFloat) 0
; y <- peekElemOff (castPtr rectPtr :: Ptr GFloat) 1
; width <- peekElemOff (castPtr rectPtr :: Ptr GFloat) 2
; height <- peekElemOff (castPtr rectPtr :: Ptr GFloat) 3
; return $ Rect (Point x y) (Size width height)
}
newtype CGVector = CGVector (ForeignPtr CGVector)
needed for now until migrating to new TH
objc_typecheck
vectorToCGVector :: Vector -> IO CGVector
vectorToCGVector (Vector {..})
= $ ( objc [ ' vectorDx :> '' , ' vectorDy :> '' GFloat ] $ Struct '' CGVector < :
= $(objc ['vectorDx :> ''Double, 'vectorDy :> ''Double] $ Struct ''CGVector <:
[cexp| ({
typename CGVector *vec = (typename CGVector *) malloc(sizeof(CGVector));
*vec = CGVectorMake(vectorDx, vectorDy);
vec;
}) |] )
cgVectorToVector :: CGVector -> IO Vector
cgVectorToVector (CGVector vectorPtr)
= withForeignPtr vectorPtr $ \vectorPtr -> do
{ vectorDx <- peekElemOff (castPtr vectorPtr :: Ptr GFloat) 0
; vectorDy <- peekElemOff (castPtr vectorPtr :: Ptr GFloat) 1
; return $ Vector vectorDx vectorDy
}
objc_emit
geometry_initialise = objc_initialise
|
1242b7e542b56f904a50537bbc2ffb48e0bb4dd7738122848d5de12847389c60 | formal-land/coq-of-ocaml | coqOfOCaml.ml | module Output = struct
type t = {
error_message : string;
generated_file : (string * string) option;
has_errors : bool;
source_file_name : string;
success_message : string;
}
let write (json_mode : bool) (output : t) : unit =
if json_mode then
let error_file_name = output.source_file_name ^ ".errors" in
Util.File.write error_file_name output.error_message
else if output.has_errors then print_endline output.error_message;
print_endline output.success_message;
match output.generated_file with
| None -> ()
| Some (generated_file_name, generated_file_content) ->
Util.File.write generated_file_name generated_file_content
end
let exp (context : MonadEval.Context.t) (typedtree : Mtyper.typedtree)
(typedtree_errors : exn list) (source_file_name : string)
(source_file_content : string) (json_mode : bool) :
Ast.t * MonadEval.Import.t list * string * bool =
let { MonadEval.Result.errors; imports; value; _ } =
MonadEval.eval (Ast.of_typedtree typedtree typedtree_errors) context
in
let error_message =
Error.display_errors json_mode source_file_name source_file_content errors
in
let has_errors = match errors with [] -> false | _ :: _ -> true in
(value, imports, error_message, has_errors)
* Display on stdout the conversion in Coq of an OCaml structure .
let of_ocaml (context : MonadEval.Context.t) (typedtree : Mtyper.typedtree)
(typedtree_errors : exn list) (source_file_name : string)
(source_file_content : string) (output_file_name : string option)
(json_mode : bool) : Output.t =
let ast, imports, error_message, has_errors =
exp context typedtree typedtree_errors source_file_name source_file_content
json_mode
in
let document = Ast.to_coq imports ast in
let generated_file_name =
match output_file_name with
| None ->
let without_extension = Filename.remove_extension source_file_name in
let extension = Filename.extension source_file_name in
let new_extension =
match extension with
| ".ml" -> ".v"
| ".mli" -> "_mli.v"
| _ ->
failwith
("Unexpected extension " ^ extension ^ " for the file "
^ source_file_name)
in
Filename.concat
(Filename.dirname without_extension)
(String.capitalize_ascii (Filename.basename without_extension))
^ new_extension
| Some output_file_name -> output_file_name
in
let generated_file_content = SmartPrint.to_string 80 2 document in
let success_message =
if has_errors then
Error.colorize "31" "❌" ^ " "
^ Printf.sprintf "File '%s' generated with some errors"
generated_file_name
else
Error.colorize "32" "✔️"
^ " "
^ Printf.sprintf "File '%s' successfully generated" generated_file_name
in
{
error_message;
generated_file = Some (generated_file_name, generated_file_content);
has_errors;
source_file_name;
success_message;
}
let exit (context : MonadEval.Context.t) (output : Output.t) : unit =
let is_blacklist =
Configuration.is_filename_in_error_blacklist context.configuration
in
if output.has_errors && not is_blacklist then exit 1 else exit 0
(** The main function. *)
let main () =
Printexc.record_backtrace true;
let file_name = ref None in
let json_mode = ref false in
let configuration_file_name = ref None in
let output_file_name = ref None in
let options =
[
( "-config",
Arg.String (fun value -> configuration_file_name := Some value),
"file the configuration file of coq-of-ocaml" );
( "-output",
Arg.String (fun value -> output_file_name := Some value),
"file the name of the .v file to output" );
( "-json-mode",
Arg.Set json_mode,
" produce the list of error messages in a JSON file" );
]
in
let usage_msg = "Usage:\n coq-of-ocaml [options] file.ml(i)\nOptions are:" in
Arg.parse options (fun arg -> file_name := Some arg) usage_msg;
match !file_name with
| None -> Arg.usage options usage_msg
| Some file_name ->
let base_name = Filename.basename file_name in
let directory_name = Filename.dirname file_name in
let configuration =
Configuration.of_optional_file_name file_name !configuration_file_name
in
let merlin_config =
Mconfig.get_external_config file_name Mconfig.initial
in
let merlin_config =
{
merlin_config with
query =
{
merlin_config.query with
directory = directory_name;
filename = base_name;
};
}
in
let file_channel = open_in file_name in
let file_size = in_channel_length file_channel in
let file_content = really_input_string file_channel file_size in
close_in file_channel;
let file_source = Msource.make file_content in
let pipeline = Mpipeline.make merlin_config file_source in
Mpipeline.with_pipeline pipeline (fun _ ->
let comments = Mpipeline.reader_comments pipeline in
let typing = Mpipeline.typer_result pipeline in
let typedtree = Mtyper.get_typedtree typing in
let typedtree_errors = Mtyper.get_errors typing in
let initial_loc = Ast.get_initial_loc typedtree in
let initial_env = Mtyper.get_env typing in
let context =
MonadEval.Context.init comments configuration initial_env
initial_loc
in
let output =
of_ocaml context typedtree typedtree_errors file_name file_content
!output_file_name !json_mode
in
Output.write !json_mode output;
exit context output)
;;
main ()
| null | https://raw.githubusercontent.com/formal-land/coq-of-ocaml/19fe7cf51722da9453cb7ce43724e774e7c9d040/src/coqOfOCaml.ml | ocaml | * The main function. | module Output = struct
type t = {
error_message : string;
generated_file : (string * string) option;
has_errors : bool;
source_file_name : string;
success_message : string;
}
let write (json_mode : bool) (output : t) : unit =
if json_mode then
let error_file_name = output.source_file_name ^ ".errors" in
Util.File.write error_file_name output.error_message
else if output.has_errors then print_endline output.error_message;
print_endline output.success_message;
match output.generated_file with
| None -> ()
| Some (generated_file_name, generated_file_content) ->
Util.File.write generated_file_name generated_file_content
end
let exp (context : MonadEval.Context.t) (typedtree : Mtyper.typedtree)
(typedtree_errors : exn list) (source_file_name : string)
(source_file_content : string) (json_mode : bool) :
Ast.t * MonadEval.Import.t list * string * bool =
let { MonadEval.Result.errors; imports; value; _ } =
MonadEval.eval (Ast.of_typedtree typedtree typedtree_errors) context
in
let error_message =
Error.display_errors json_mode source_file_name source_file_content errors
in
let has_errors = match errors with [] -> false | _ :: _ -> true in
(value, imports, error_message, has_errors)
* Display on stdout the conversion in Coq of an OCaml structure .
let of_ocaml (context : MonadEval.Context.t) (typedtree : Mtyper.typedtree)
(typedtree_errors : exn list) (source_file_name : string)
(source_file_content : string) (output_file_name : string option)
(json_mode : bool) : Output.t =
let ast, imports, error_message, has_errors =
exp context typedtree typedtree_errors source_file_name source_file_content
json_mode
in
let document = Ast.to_coq imports ast in
let generated_file_name =
match output_file_name with
| None ->
let without_extension = Filename.remove_extension source_file_name in
let extension = Filename.extension source_file_name in
let new_extension =
match extension with
| ".ml" -> ".v"
| ".mli" -> "_mli.v"
| _ ->
failwith
("Unexpected extension " ^ extension ^ " for the file "
^ source_file_name)
in
Filename.concat
(Filename.dirname without_extension)
(String.capitalize_ascii (Filename.basename without_extension))
^ new_extension
| Some output_file_name -> output_file_name
in
let generated_file_content = SmartPrint.to_string 80 2 document in
let success_message =
if has_errors then
Error.colorize "31" "❌" ^ " "
^ Printf.sprintf "File '%s' generated with some errors"
generated_file_name
else
Error.colorize "32" "✔️"
^ " "
^ Printf.sprintf "File '%s' successfully generated" generated_file_name
in
{
error_message;
generated_file = Some (generated_file_name, generated_file_content);
has_errors;
source_file_name;
success_message;
}
let exit (context : MonadEval.Context.t) (output : Output.t) : unit =
let is_blacklist =
Configuration.is_filename_in_error_blacklist context.configuration
in
if output.has_errors && not is_blacklist then exit 1 else exit 0
let main () =
Printexc.record_backtrace true;
let file_name = ref None in
let json_mode = ref false in
let configuration_file_name = ref None in
let output_file_name = ref None in
let options =
[
( "-config",
Arg.String (fun value -> configuration_file_name := Some value),
"file the configuration file of coq-of-ocaml" );
( "-output",
Arg.String (fun value -> output_file_name := Some value),
"file the name of the .v file to output" );
( "-json-mode",
Arg.Set json_mode,
" produce the list of error messages in a JSON file" );
]
in
let usage_msg = "Usage:\n coq-of-ocaml [options] file.ml(i)\nOptions are:" in
Arg.parse options (fun arg -> file_name := Some arg) usage_msg;
match !file_name with
| None -> Arg.usage options usage_msg
| Some file_name ->
let base_name = Filename.basename file_name in
let directory_name = Filename.dirname file_name in
let configuration =
Configuration.of_optional_file_name file_name !configuration_file_name
in
let merlin_config =
Mconfig.get_external_config file_name Mconfig.initial
in
let merlin_config =
{
merlin_config with
query =
{
merlin_config.query with
directory = directory_name;
filename = base_name;
};
}
in
let file_channel = open_in file_name in
let file_size = in_channel_length file_channel in
let file_content = really_input_string file_channel file_size in
close_in file_channel;
let file_source = Msource.make file_content in
let pipeline = Mpipeline.make merlin_config file_source in
Mpipeline.with_pipeline pipeline (fun _ ->
let comments = Mpipeline.reader_comments pipeline in
let typing = Mpipeline.typer_result pipeline in
let typedtree = Mtyper.get_typedtree typing in
let typedtree_errors = Mtyper.get_errors typing in
let initial_loc = Ast.get_initial_loc typedtree in
let initial_env = Mtyper.get_env typing in
let context =
MonadEval.Context.init comments configuration initial_env
initial_loc
in
let output =
of_ocaml context typedtree typedtree_errors file_name file_content
!output_file_name !json_mode
in
Output.write !json_mode output;
exit context output)
;;
main ()
|
5418169a4198f21bca2de0fe95f2e0f4dcb4fea0a98e6b2440628e2eb8aecf8c | ocaml-multicore/tezos | block.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
open Protocol
open Alpha_context
type t = {
hash : Block_hash.t;
header : Block_header.t;
operations : Operation.packed list;
context : Tezos_protocol_environment.Context.t; (** Resulting context *)
}
type block = t
val rpc_ctxt : t Environment.RPC_context.simple
* Policies to select the next baker :
- [ By_round r ] selects the baker at round [ r ]
- [ By_account pkh ] selects the first slot for baker [ pkh ]
- [ Excluding pkhs ] selects the first baker that does n't belong to ]
- [By_round r] selects the baker at round [r]
- [By_account pkh] selects the first slot for baker [pkh]
- [Excluding pkhs] selects the first baker that doesn't belong to [pkhs]
*)
type baker_policy =
| By_round of int
| By_account of public_key_hash
| Excluding of public_key_hash list
(**
The default baking functions below is to use (blocks) [Application] mode.
Setting [baking_mode] allows to switch to [Full_construction] mode.
*)
type baking_mode = Application | Baking
* Returns ( account , round , timestamp ) of the next baker given
a policy , defaults to By_round 0 .
a policy, defaults to By_round 0. *)
val get_next_baker :
?policy:baker_policy ->
t ->
(public_key_hash * int * Time.Protocol.t) tzresult Lwt.t
val get_round : block -> Round.t tzresult
module Forge : sig
val contents :
?proof_of_work_nonce:Bytes.t ->
?seed_nonce_hash:Nonce_hash.t ->
?liquidity_baking_escape_vote:bool ->
payload_hash:Block_payload_hash.t ->
payload_round:Round.t ->
unit ->
Block_header.contents
type header
val classify_operations : packed_operation list -> packed_operation list list
(** Forges a correct header following the policy.
The header can then be modified and applied with [apply]. *)
val forge_header :
?locked_round:Alpha_context.Round.t option ->
?payload_round:Round.t option ->
?policy:baker_policy ->
?timestamp:Timestamp.time ->
?operations:Operation.packed list ->
?liquidity_baking_escape_vote:bool ->
t ->
header tzresult Lwt.t
(** Sets uniquely seed_nonce_hash of a header *)
val set_seed_nonce_hash : Nonce_hash.t option -> header -> header
(** Sets the baker that will sign the header to an arbitrary pkh *)
val set_baker : public_key_hash -> header -> header
(** Signs the header with the key of the baker configured in the header.
The header can no longer be modified, only applied. *)
val sign_header : header -> Block_header.block_header tzresult Lwt.t
end
val check_constants_consistency : Constants.parametric -> unit tzresult Lwt.t
(** [genesis <opts> accounts] : generates an initial block with the
given constants [<opts>] and initializes [accounts] with their
associated amounts.
*)
val genesis :
?commitments:Commitment.t list ->
?consensus_threshold:int ->
?min_proposal_quorum:int32 ->
?bootstrap_contracts:Parameters.bootstrap_contract list ->
?level:int32 ->
?cost_per_byte:Tez.t ->
?liquidity_baking_subsidy:Tez.t ->
?endorsing_reward_per_slot:Tez.t ->
?baking_reward_bonus_per_slot:Tez.t ->
?baking_reward_fixed_portion:Tez.t ->
?origination_size:int ->
?blocks_per_cycle:int32 ->
?blocks_per_voting_period:int32 ->
?tx_rollup_enable:bool ->
?sc_rollup_enable:bool ->
(Account.t * Tez.tez) list ->
block tzresult Lwt.t
val genesis_with_parameters : Parameters.t -> block tzresult Lwt.t
(** [alpha_context <opts> accounts] : instantiates an alpha_context with the
given constants [<opts>] and initializes [accounts] with their
associated amounts.
*)
val alpha_context :
?commitments:Commitment.t list ->
?min_proposal_quorum:int32 ->
(Account.t * Tez.tez) list ->
Alpha_context.t tzresult Lwt.t
(**
[get_application_vstate pred operations] constructs a protocol validation
environment for operations in application mode on top of the given block
with the given operations. It's a shortcut for [begin_application]
*)
val get_application_vstate :
t -> Protocol.operation list -> validation_state tzresult Lwt.t
(**
[get_construction_vstate ?policy ?timestamp ?protocol_data pred]
constructs a protocol validation environment for operations in
construction mode on top of the given block. The mode is
full(baking)/partial(mempool) if [protocol_data] given/absent. It's a
shortcut for [begin_construction]
*)
val get_construction_vstate :
?policy:baker_policy ->
?timestamp:Timestamp.time ->
?protocol_data:block_header_data option ->
block ->
validation_state tzresult Lwt.t
(** applies a signed header and its operations to a block and
obtains a new block *)
val apply :
Block_header.block_header ->
?operations:Operation.packed list ->
t ->
t tzresult Lwt.t
(**
[bake b] returns a block [b'] which has as predecessor block [b].
Optional parameter [policy] allows to pick the next baker in several ways.
This function bundles together [forge_header], [sign_header] and [apply].
These functions should be used instead of bake to craft unusual blocks for
testing together with setters for properties of the headers.
For examples see seed.ml or double_baking.ml
*)
val bake :
?baking_mode:baking_mode ->
?payload_round:Round.t option ->
?locked_round:Alpha_context.Round.t option ->
?policy:baker_policy ->
?timestamp:Timestamp.time ->
?operation:Operation.packed ->
?operations:Operation.packed list ->
?liquidity_baking_escape_vote:bool ->
t ->
t tzresult Lwt.t
(** Bakes [n] blocks. *)
val bake_n :
?baking_mode:baking_mode ->
?policy:baker_policy ->
?liquidity_baking_escape_vote:bool ->
int ->
t ->
block tzresult Lwt.t
(** Version of bake_n that returns a list of all balance updates included
in the metadata of baked blocks. **)
val bake_n_with_all_balance_updates :
?baking_mode:baking_mode ->
?policy:baker_policy ->
?liquidity_baking_escape_vote:bool ->
int ->
t ->
(block * Alpha_context.Receipt.balance_updates) tzresult Lwt.t
(** Version of bake_n that returns a list of all origination results
in the metadata of baked blocks. **)
val bake_n_with_origination_results :
?baking_mode:baking_mode ->
?policy:baker_policy ->
int ->
t ->
(block
* Alpha_context.Kind.origination
Apply_results.successful_manager_operation_result
list)
tzresult
Lwt.t
* Version of bake_n that returns the liquidity baking escape EMA after [ n ] blocks . *
val bake_n_with_liquidity_baking_escape_ema :
?baking_mode:baking_mode ->
?policy:baker_policy ->
?liquidity_baking_escape_vote:bool ->
int ->
t ->
(block * Alpha_context.Liquidity_baking.escape_ema) tzresult Lwt.t
val current_cycle : t -> Cycle.t tzresult Lwt.t
(** Given a block [b] at level [l] bakes enough blocks to complete a cycle,
that is [blocks_per_cycle - (l % blocks_per_cycle)]. *)
val bake_until_cycle_end : ?policy:baker_policy -> t -> t tzresult Lwt.t
(** Bakes enough blocks to end [n] cycles. *)
val bake_until_n_cycle_end :
?policy:baker_policy -> int -> t -> t tzresult Lwt.t
(** Bakes enough blocks to reach the cycle. *)
val bake_until_cycle : ?policy:baker_policy -> Cycle.t -> t -> t tzresult Lwt.t
(** Common util function to create parameters for [initial_context] function *)
val prepare_initial_context_params :
?consensus_threshold:int ->
?min_proposal_quorum:int32 ->
?level:int32 ->
?cost_per_byte:Tez.t ->
?liquidity_baking_subsidy:Tez.t ->
?endorsing_reward_per_slot:Tez.t ->
?baking_reward_bonus_per_slot:Tez.t ->
?baking_reward_fixed_portion:Tez.t ->
?origination_size:int ->
?blocks_per_cycle:int32 ->
?blocks_per_voting_period:int32 ->
?tx_rollup_enable:bool ->
?sc_rollup_enable:bool ->
(Account.t * Tez.t) list ->
( Constants.parametric * Block_header.shell_header * Block_hash.t,
tztrace )
result
Lwt.t
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/test/helpers/block.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Resulting context
*
The default baking functions below is to use (blocks) [Application] mode.
Setting [baking_mode] allows to switch to [Full_construction] mode.
* Forges a correct header following the policy.
The header can then be modified and applied with [apply].
* Sets uniquely seed_nonce_hash of a header
* Sets the baker that will sign the header to an arbitrary pkh
* Signs the header with the key of the baker configured in the header.
The header can no longer be modified, only applied.
* [genesis <opts> accounts] : generates an initial block with the
given constants [<opts>] and initializes [accounts] with their
associated amounts.
* [alpha_context <opts> accounts] : instantiates an alpha_context with the
given constants [<opts>] and initializes [accounts] with their
associated amounts.
*
[get_application_vstate pred operations] constructs a protocol validation
environment for operations in application mode on top of the given block
with the given operations. It's a shortcut for [begin_application]
*
[get_construction_vstate ?policy ?timestamp ?protocol_data pred]
constructs a protocol validation environment for operations in
construction mode on top of the given block. The mode is
full(baking)/partial(mempool) if [protocol_data] given/absent. It's a
shortcut for [begin_construction]
* applies a signed header and its operations to a block and
obtains a new block
*
[bake b] returns a block [b'] which has as predecessor block [b].
Optional parameter [policy] allows to pick the next baker in several ways.
This function bundles together [forge_header], [sign_header] and [apply].
These functions should be used instead of bake to craft unusual blocks for
testing together with setters for properties of the headers.
For examples see seed.ml or double_baking.ml
* Bakes [n] blocks.
* Version of bake_n that returns a list of all balance updates included
in the metadata of baked blocks. *
* Version of bake_n that returns a list of all origination results
in the metadata of baked blocks. *
* Given a block [b] at level [l] bakes enough blocks to complete a cycle,
that is [blocks_per_cycle - (l % blocks_per_cycle)].
* Bakes enough blocks to end [n] cycles.
* Bakes enough blocks to reach the cycle.
* Common util function to create parameters for [initial_context] function | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
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
open Protocol
open Alpha_context
type t = {
hash : Block_hash.t;
header : Block_header.t;
operations : Operation.packed list;
}
type block = t
val rpc_ctxt : t Environment.RPC_context.simple
* Policies to select the next baker :
- [ By_round r ] selects the baker at round [ r ]
- [ By_account pkh ] selects the first slot for baker [ pkh ]
- [ Excluding pkhs ] selects the first baker that does n't belong to ]
- [By_round r] selects the baker at round [r]
- [By_account pkh] selects the first slot for baker [pkh]
- [Excluding pkhs] selects the first baker that doesn't belong to [pkhs]
*)
type baker_policy =
| By_round of int
| By_account of public_key_hash
| Excluding of public_key_hash list
type baking_mode = Application | Baking
* Returns ( account , round , timestamp ) of the next baker given
a policy , defaults to By_round 0 .
a policy, defaults to By_round 0. *)
val get_next_baker :
?policy:baker_policy ->
t ->
(public_key_hash * int * Time.Protocol.t) tzresult Lwt.t
val get_round : block -> Round.t tzresult
module Forge : sig
val contents :
?proof_of_work_nonce:Bytes.t ->
?seed_nonce_hash:Nonce_hash.t ->
?liquidity_baking_escape_vote:bool ->
payload_hash:Block_payload_hash.t ->
payload_round:Round.t ->
unit ->
Block_header.contents
type header
val classify_operations : packed_operation list -> packed_operation list list
val forge_header :
?locked_round:Alpha_context.Round.t option ->
?payload_round:Round.t option ->
?policy:baker_policy ->
?timestamp:Timestamp.time ->
?operations:Operation.packed list ->
?liquidity_baking_escape_vote:bool ->
t ->
header tzresult Lwt.t
val set_seed_nonce_hash : Nonce_hash.t option -> header -> header
val set_baker : public_key_hash -> header -> header
val sign_header : header -> Block_header.block_header tzresult Lwt.t
end
val check_constants_consistency : Constants.parametric -> unit tzresult Lwt.t
val genesis :
?commitments:Commitment.t list ->
?consensus_threshold:int ->
?min_proposal_quorum:int32 ->
?bootstrap_contracts:Parameters.bootstrap_contract list ->
?level:int32 ->
?cost_per_byte:Tez.t ->
?liquidity_baking_subsidy:Tez.t ->
?endorsing_reward_per_slot:Tez.t ->
?baking_reward_bonus_per_slot:Tez.t ->
?baking_reward_fixed_portion:Tez.t ->
?origination_size:int ->
?blocks_per_cycle:int32 ->
?blocks_per_voting_period:int32 ->
?tx_rollup_enable:bool ->
?sc_rollup_enable:bool ->
(Account.t * Tez.tez) list ->
block tzresult Lwt.t
val genesis_with_parameters : Parameters.t -> block tzresult Lwt.t
val alpha_context :
?commitments:Commitment.t list ->
?min_proposal_quorum:int32 ->
(Account.t * Tez.tez) list ->
Alpha_context.t tzresult Lwt.t
val get_application_vstate :
t -> Protocol.operation list -> validation_state tzresult Lwt.t
val get_construction_vstate :
?policy:baker_policy ->
?timestamp:Timestamp.time ->
?protocol_data:block_header_data option ->
block ->
validation_state tzresult Lwt.t
val apply :
Block_header.block_header ->
?operations:Operation.packed list ->
t ->
t tzresult Lwt.t
val bake :
?baking_mode:baking_mode ->
?payload_round:Round.t option ->
?locked_round:Alpha_context.Round.t option ->
?policy:baker_policy ->
?timestamp:Timestamp.time ->
?operation:Operation.packed ->
?operations:Operation.packed list ->
?liquidity_baking_escape_vote:bool ->
t ->
t tzresult Lwt.t
val bake_n :
?baking_mode:baking_mode ->
?policy:baker_policy ->
?liquidity_baking_escape_vote:bool ->
int ->
t ->
block tzresult Lwt.t
val bake_n_with_all_balance_updates :
?baking_mode:baking_mode ->
?policy:baker_policy ->
?liquidity_baking_escape_vote:bool ->
int ->
t ->
(block * Alpha_context.Receipt.balance_updates) tzresult Lwt.t
val bake_n_with_origination_results :
?baking_mode:baking_mode ->
?policy:baker_policy ->
int ->
t ->
(block
* Alpha_context.Kind.origination
Apply_results.successful_manager_operation_result
list)
tzresult
Lwt.t
* Version of bake_n that returns the liquidity baking escape EMA after [ n ] blocks . *
val bake_n_with_liquidity_baking_escape_ema :
?baking_mode:baking_mode ->
?policy:baker_policy ->
?liquidity_baking_escape_vote:bool ->
int ->
t ->
(block * Alpha_context.Liquidity_baking.escape_ema) tzresult Lwt.t
val current_cycle : t -> Cycle.t tzresult Lwt.t
val bake_until_cycle_end : ?policy:baker_policy -> t -> t tzresult Lwt.t
val bake_until_n_cycle_end :
?policy:baker_policy -> int -> t -> t tzresult Lwt.t
val bake_until_cycle : ?policy:baker_policy -> Cycle.t -> t -> t tzresult Lwt.t
val prepare_initial_context_params :
?consensus_threshold:int ->
?min_proposal_quorum:int32 ->
?level:int32 ->
?cost_per_byte:Tez.t ->
?liquidity_baking_subsidy:Tez.t ->
?endorsing_reward_per_slot:Tez.t ->
?baking_reward_bonus_per_slot:Tez.t ->
?baking_reward_fixed_portion:Tez.t ->
?origination_size:int ->
?blocks_per_cycle:int32 ->
?blocks_per_voting_period:int32 ->
?tx_rollup_enable:bool ->
?sc_rollup_enable:bool ->
(Account.t * Tez.t) list ->
( Constants.parametric * Block_header.shell_header * Block_hash.t,
tztrace )
result
Lwt.t
|
98a00ba6a023beaff7dabadf8395c14f206e0d65bb216d7f360d57613f7f19ad | kpreid/e-on-cl | smethod.lisp | Copyright 2005 - 2007 , under the terms of the MIT X license
found at ................
(cl:in-package :e.elib)
(defvar *exercise-reffiness* nil
"Set this true to test for code which is inappropriately sensitive to the presence of forwarding refs, by placing them around each argument to methods written in Lisp.")
(defun reffify-args (args)
"See *EXERCISE-REFFINESS*."
(mapcar (lambda (x) (make-instance 'resolved-ref :target x)) args))
(defun partition (test sequence &rest options)
"Return, as two values, the elements of SEQUENCE satisfying the test and those not satisfying the test. Accepts all the options REMOVE-IF[-NOT] does."
;;
(let (not)
(values
(apply #'remove-if-not
#'(lambda (element)
(not
(unless (funcall test element)
(push element not))))
sequence
options)
(nreverse not))))
(defun mangled-verb-p (thing)
(and (typep thing 'keyword)
(find #\/ (symbol-name thing))))
(defun smethod-mverb (smethod prefix-arity
&aux (verb-or-mverb (first smethod)))
(etypecase verb-or-mverb
((and symbol (or (not keyword) (satisfies mangled-verb-p)))
verb-or-mverb)
(keyword
(let ((verb-string (symbol-name verb-or-mverb)))
(mangle-verb
verb-string
(multiple-value-bind (min max)
(progn
(assert (cddr smethod) () "Inferring arity for function smethod not supported: ~S" smethod)
(lambda-list-arguments-range (second smethod)))
(assert (>= min prefix-arity) () "Method ~S has ~S parameters, which is not enough to accept ~S prefix argument~:P." verb-string min prefix-arity)
(assert (= min max) () "Variable arguments not yet supported for smethod-case-entry arity inference")
(- min prefix-arity)))))))
(defun smethod-case-entry (smethod args-sym prefix-args &key type-name
&aux (mverb (smethod-mverb smethod (length prefix-args))))
"Return a CASE clause whose key is a mangled-verb, suitable for implementing method dispatch for E objects.
if not , the second element must be a lambda list , which is used to determine the number of arguments .
If there is exactly one further element, then it is an expression (typically #'...) which the returned clause will use in `(apply ,expr ,args-sym).
If there are two or more further elements, then they are a lambda list and implicit-progn forms which will be evaluated.
prefix-args is a list of forms which will be prepended to the arguments of the method body."
(assert (not (eq (first smethod) 'otherwise)))
`((,mverb)
,(smethod-body (rest smethod) args-sym prefix-args :type-name type-name :verb-name mverb)))
(defun smethod-function-case-entry (smethod prefix-arity &key type-name
&aux (mverb (smethod-mverb smethod prefix-arity)))
(assert (not (eq (first smethod) 'otherwise)))
`((,mverb)
,(smethod-function-form (rest smethod) :type-name type-name :verb-name mverb)))
(defun functional-smethod-body-p (body)
(= 1 (length body)))
(defun delete-documentation (decls-and-forms)
"Remove from DECLS-AND-FORMS a value that would be interpreted as a documentation string according to CLHS section 3.4.11, thus allowing it to be used as a body in forms like DESTRUCTURING-BIND."
(loop with head = '()
for (thing . rest) on decls-and-forms
when (and (stringp thing) rest)
do (return (nreconc head rest))
do (push thing head)
finally (return decls-and-forms)))
(defun convert-coercing-lambda-list (coercing-ll body)
(let* ((ordinary-ll '())
(lets '()))
(loop with aux = nil
for x in coercing-ll do
(cond
(aux
(push x lets))
((and (typep x '(cons t (cons t null))))
(let ((uncoerced (gensym (format nil "UNCOERCED-~A" x))))
(push uncoerced ordinary-ll)
(push `(,(first x) (e-coerce ,uncoerced ,(second x))) lets)))
((member x '(&aux))
(setf aux t))
((member x '(&rest))
(push x ordinary-ll))
((member x lambda-list-keywords)
(error "lambda-list-keyword ~S in ~S unsupported by ~S" x coercing-ll 'convert-coercing-lambda-list))
(t
;; so declarations and scoping work right
(let ((g (gensym (format nil "ENTRY-~A" x))))
(push g ordinary-ll)
(push `(,x ,g) lets)))))
(nreverse-here ordinary-ll)
(nreverse-here lets)
(let ((decls '())
(doc nil))
(loop while (typep body '(or (cons string cons)
(cons (cons (eql declare)) t))) do
;; (declare ...) or non-final string
(if (typep (first body) 'string)
(push (pop body) doc)
(push (pop body) decls)))
`(,ordinary-ll ,@doc (let* ,lets ,@(nreverse decls) ,@body)))))
(defun smethod-body (body args-sym prefix-args &key type-name verb-name)
#-e.method-lambdas
(declare (ignore type-name))
(let ((args-form
(if (keywordp verb-name)
`(if *exercise-reffiness*
(reffify-args ,args-sym)
,args-sym)
args-sym)))
#+e.method-lambdas
`(apply ,(smethod-function-form body :type-name type-name :verb-name verb-name)
,@prefix-args ,args-form)
#-e.method-lambdas
(if (functional-smethod-body-p body)
`(apply ,(first body) ,@prefix-args ,args-form)
(destructuring-bind (post-ll &rest post-body)
(convert-coercing-lambda-list (first body) (rest body))
`(destructuring-bind ,post-ll
(list* ,@prefix-args ,args-form)
,@(delete-documentation post-body))))))
(defun smethod-function-form (body &key type-name verb-name)
"XXX transfer the relevant portions of smethod-case-entry's documentation here"
(if (functional-smethod-body-p body)
(first body)
(let* ((name (format nil "~A#~A" type-name verb-name))
(name-sym
; These are feature conditionals to remind me that they must be set at compile time anyway.
#-e.intern-vtable-methods
(make-symbol name)
#+e.intern-vtable-methods
(loop
for i from 1
for free = name then (format nil "~A-dup-~A" name i)
while (find-symbol name :e.elib.vtable-methods)
finally (intern free :e.elib.vtable-methods))))
`(named-lambda ,name-sym ,@(convert-coercing-lambda-list (first body) (rest body))))))
(defun conventional-constant-symbol-p (specimen)
(and (symbolp specimen)
(let ((name (symbol-name specimen)))
(and (> (length name) 2)
(eql #\+ (elt name 0))
(eql #\+ (elt name (1- (length name))))))
(boundp specimen)))
(deftype global-constant ()
'(or (cons (eql quote) (cons t null)) ; quote form
keyword
(satisfies conventional-constant-symbol-p) ; +foo+
(not (or symbol cons)))) ; per CLHS 3.1.2.1.3
(defun coercing-lambda-list-item-to-param-desc (item)
(etypecase item
((cons t (cons global-constant null))
(destructuring-bind (name type-form) item
(make-instance 'eval-param-desc
:opt-name (guess-lowercase-string (symbol-name name))
:form type-form)))
((cons t (cons t null))
(make-instance 'param-desc
:opt-name (guess-lowercase-string (symbol-name (first item)))))
(symbol
(make-instance 'param-desc
:opt-name (guess-lowercase-string (symbol-name item))))))
(defun coercing-lambda-list-to-param-desc-vector (list arity prefix-arity
&aux (end (or (position '&aux list) (length list))))
(unless (= end (+ arity prefix-arity))
(error "arity ~A + prefix-arity ~A doesn't match lambda list ~S" arity prefix-arity list))
(coerce (loop
for i below arity
for sym in (nthcdr prefix-arity list)
do
(when (member sym lambda-list-keywords)
(error "constructing param-desc vector from lambda list ~S with keyword ~s not possible" list sym))
collect
(coercing-lambda-list-item-to-param-desc sym)) 'vector))
(defun smethod-message-desc-pair (smethod &rest keys &key (prefix-arity 0) &allow-other-keys
&aux (mverb (smethod-mverb smethod prefix-arity)))
(vector (symbol-name mverb)
(apply #'smethod-message-desc smethod keys)))
(defun smethod-message-desc (smethod &key (prefix-arity 0)
&aux (mverb (smethod-mverb smethod prefix-arity))
(impl-desc (rest smethod)))
(assert (mangled-verb-p mverb))
(multiple-value-bind (verb arity) (unmangle-verb mverb)
(make-instance 'message-desc
:verb verb
:doc-comment (find-if #'stringp impl-desc) ; XXX too lenient
:params (if (rest impl-desc) ; therefore inline
(coercing-lambda-list-to-param-desc-vector (first impl-desc) arity prefix-arity)
(make-array arity :initial-element
(make-instance 'param-desc))))))
(defun smethod-maybe-describe-fresh (function smethod &rest options)
"messy."
;; XXX should be more like mverb-is-magic-p
(if (typep (first smethod) '(and symbol (not keyword)))
nil
(list (apply function smethod options))))
| null | https://raw.githubusercontent.com/kpreid/e-on-cl/f93d188051c66db0ad4ff150bd73b838f7bc25ed/lisp/smethod.lisp | lisp |
so declarations and scoping work right
(declare ...) or non-final string
These are feature conditionals to remind me that they must be set at compile time anyway.
quote form
+foo+
per CLHS 3.1.2.1.3
XXX too lenient
therefore inline
XXX should be more like mverb-is-magic-p | Copyright 2005 - 2007 , under the terms of the MIT X license
found at ................
(cl:in-package :e.elib)
(defvar *exercise-reffiness* nil
"Set this true to test for code which is inappropriately sensitive to the presence of forwarding refs, by placing them around each argument to methods written in Lisp.")
(defun reffify-args (args)
"See *EXERCISE-REFFINESS*."
(mapcar (lambda (x) (make-instance 'resolved-ref :target x)) args))
(defun partition (test sequence &rest options)
"Return, as two values, the elements of SEQUENCE satisfying the test and those not satisfying the test. Accepts all the options REMOVE-IF[-NOT] does."
(let (not)
(values
(apply #'remove-if-not
#'(lambda (element)
(not
(unless (funcall test element)
(push element not))))
sequence
options)
(nreverse not))))
(defun mangled-verb-p (thing)
(and (typep thing 'keyword)
(find #\/ (symbol-name thing))))
(defun smethod-mverb (smethod prefix-arity
&aux (verb-or-mverb (first smethod)))
(etypecase verb-or-mverb
((and symbol (or (not keyword) (satisfies mangled-verb-p)))
verb-or-mverb)
(keyword
(let ((verb-string (symbol-name verb-or-mverb)))
(mangle-verb
verb-string
(multiple-value-bind (min max)
(progn
(assert (cddr smethod) () "Inferring arity for function smethod not supported: ~S" smethod)
(lambda-list-arguments-range (second smethod)))
(assert (>= min prefix-arity) () "Method ~S has ~S parameters, which is not enough to accept ~S prefix argument~:P." verb-string min prefix-arity)
(assert (= min max) () "Variable arguments not yet supported for smethod-case-entry arity inference")
(- min prefix-arity)))))))
(defun smethod-case-entry (smethod args-sym prefix-args &key type-name
&aux (mverb (smethod-mverb smethod (length prefix-args))))
"Return a CASE clause whose key is a mangled-verb, suitable for implementing method dispatch for E objects.
if not , the second element must be a lambda list , which is used to determine the number of arguments .
If there is exactly one further element, then it is an expression (typically #'...) which the returned clause will use in `(apply ,expr ,args-sym).
If there are two or more further elements, then they are a lambda list and implicit-progn forms which will be evaluated.
prefix-args is a list of forms which will be prepended to the arguments of the method body."
(assert (not (eq (first smethod) 'otherwise)))
`((,mverb)
,(smethod-body (rest smethod) args-sym prefix-args :type-name type-name :verb-name mverb)))
(defun smethod-function-case-entry (smethod prefix-arity &key type-name
&aux (mverb (smethod-mverb smethod prefix-arity)))
(assert (not (eq (first smethod) 'otherwise)))
`((,mverb)
,(smethod-function-form (rest smethod) :type-name type-name :verb-name mverb)))
(defun functional-smethod-body-p (body)
(= 1 (length body)))
(defun delete-documentation (decls-and-forms)
"Remove from DECLS-AND-FORMS a value that would be interpreted as a documentation string according to CLHS section 3.4.11, thus allowing it to be used as a body in forms like DESTRUCTURING-BIND."
(loop with head = '()
for (thing . rest) on decls-and-forms
when (and (stringp thing) rest)
do (return (nreconc head rest))
do (push thing head)
finally (return decls-and-forms)))
(defun convert-coercing-lambda-list (coercing-ll body)
(let* ((ordinary-ll '())
(lets '()))
(loop with aux = nil
for x in coercing-ll do
(cond
(aux
(push x lets))
((and (typep x '(cons t (cons t null))))
(let ((uncoerced (gensym (format nil "UNCOERCED-~A" x))))
(push uncoerced ordinary-ll)
(push `(,(first x) (e-coerce ,uncoerced ,(second x))) lets)))
((member x '(&aux))
(setf aux t))
((member x '(&rest))
(push x ordinary-ll))
((member x lambda-list-keywords)
(error "lambda-list-keyword ~S in ~S unsupported by ~S" x coercing-ll 'convert-coercing-lambda-list))
(t
(let ((g (gensym (format nil "ENTRY-~A" x))))
(push g ordinary-ll)
(push `(,x ,g) lets)))))
(nreverse-here ordinary-ll)
(nreverse-here lets)
(let ((decls '())
(doc nil))
(loop while (typep body '(or (cons string cons)
(cons (cons (eql declare)) t))) do
(if (typep (first body) 'string)
(push (pop body) doc)
(push (pop body) decls)))
`(,ordinary-ll ,@doc (let* ,lets ,@(nreverse decls) ,@body)))))
(defun smethod-body (body args-sym prefix-args &key type-name verb-name)
#-e.method-lambdas
(declare (ignore type-name))
(let ((args-form
(if (keywordp verb-name)
`(if *exercise-reffiness*
(reffify-args ,args-sym)
,args-sym)
args-sym)))
#+e.method-lambdas
`(apply ,(smethod-function-form body :type-name type-name :verb-name verb-name)
,@prefix-args ,args-form)
#-e.method-lambdas
(if (functional-smethod-body-p body)
`(apply ,(first body) ,@prefix-args ,args-form)
(destructuring-bind (post-ll &rest post-body)
(convert-coercing-lambda-list (first body) (rest body))
`(destructuring-bind ,post-ll
(list* ,@prefix-args ,args-form)
,@(delete-documentation post-body))))))
(defun smethod-function-form (body &key type-name verb-name)
"XXX transfer the relevant portions of smethod-case-entry's documentation here"
(if (functional-smethod-body-p body)
(first body)
(let* ((name (format nil "~A#~A" type-name verb-name))
(name-sym
#-e.intern-vtable-methods
(make-symbol name)
#+e.intern-vtable-methods
(loop
for i from 1
for free = name then (format nil "~A-dup-~A" name i)
while (find-symbol name :e.elib.vtable-methods)
finally (intern free :e.elib.vtable-methods))))
`(named-lambda ,name-sym ,@(convert-coercing-lambda-list (first body) (rest body))))))
(defun conventional-constant-symbol-p (specimen)
(and (symbolp specimen)
(let ((name (symbol-name specimen)))
(and (> (length name) 2)
(eql #\+ (elt name 0))
(eql #\+ (elt name (1- (length name))))))
(boundp specimen)))
(deftype global-constant ()
keyword
(defun coercing-lambda-list-item-to-param-desc (item)
(etypecase item
((cons t (cons global-constant null))
(destructuring-bind (name type-form) item
(make-instance 'eval-param-desc
:opt-name (guess-lowercase-string (symbol-name name))
:form type-form)))
((cons t (cons t null))
(make-instance 'param-desc
:opt-name (guess-lowercase-string (symbol-name (first item)))))
(symbol
(make-instance 'param-desc
:opt-name (guess-lowercase-string (symbol-name item))))))
(defun coercing-lambda-list-to-param-desc-vector (list arity prefix-arity
&aux (end (or (position '&aux list) (length list))))
(unless (= end (+ arity prefix-arity))
(error "arity ~A + prefix-arity ~A doesn't match lambda list ~S" arity prefix-arity list))
(coerce (loop
for i below arity
for sym in (nthcdr prefix-arity list)
do
(when (member sym lambda-list-keywords)
(error "constructing param-desc vector from lambda list ~S with keyword ~s not possible" list sym))
collect
(coercing-lambda-list-item-to-param-desc sym)) 'vector))
(defun smethod-message-desc-pair (smethod &rest keys &key (prefix-arity 0) &allow-other-keys
&aux (mverb (smethod-mverb smethod prefix-arity)))
(vector (symbol-name mverb)
(apply #'smethod-message-desc smethod keys)))
(defun smethod-message-desc (smethod &key (prefix-arity 0)
&aux (mverb (smethod-mverb smethod prefix-arity))
(impl-desc (rest smethod)))
(assert (mangled-verb-p mverb))
(multiple-value-bind (verb arity) (unmangle-verb mverb)
(make-instance 'message-desc
:verb verb
(coercing-lambda-list-to-param-desc-vector (first impl-desc) arity prefix-arity)
(make-array arity :initial-element
(make-instance 'param-desc))))))
(defun smethod-maybe-describe-fresh (function smethod &rest options)
"messy."
(if (typep (first smethod) '(and symbol (not keyword)))
nil
(list (apply function smethod options))))
|
f37266338c44145725abb9f3527353a7168f53e39b82c61b654e69272f126692 | zed-throben/erlangeos | sample_rpcobj.erl | - module('sample_rpcobj').
- compile(export_all).
start() ->
RPC1 = eos:new(eos@rpc,[],[{node , '192.168.0.2@main' },{module , main }]),
eos:invoke(RPC1,hello,["world"]),
RPC2 = eos:new(eos@rpc,[],[{node , '192.168.0.3@main' },{module , main }]),
eos:invoke(RPC2,hello,["world"]).
| null | https://raw.githubusercontent.com/zed-throben/erlangeos/44e50e442f5d396c69ae90db530b0b60b01d692a/sample/sample_rpcobj.erl | erlang | - module('sample_rpcobj').
- compile(export_all).
start() ->
RPC1 = eos:new(eos@rpc,[],[{node , '192.168.0.2@main' },{module , main }]),
eos:invoke(RPC1,hello,["world"]),
RPC2 = eos:new(eos@rpc,[],[{node , '192.168.0.3@main' },{module , main }]),
eos:invoke(RPC2,hello,["world"]).
|
|
dea8778ce24a2fce67a722423fc0722738ebd9d5f5cedbb7d1bccce73889a5ca | ChrisPenner/proton | Coalgebraic.hs | module Examples.Coalgebraic where
> > > [ Just 1 , Just 2 , Just 3 ] & _ Just > - sum
Just 6
> > > [ Just 1 , Nothing , Just 3 ] & _ Just > - sum
-- Nothing
> > > [ Right 1 , Left " whoops " , Right 2 ] & _ Right > - sum
-- Left "whoops"
| null | https://raw.githubusercontent.com/ChrisPenner/proton/4ce22d473ce5bece8322c841bd2cf7f18673d57d/src/Examples/Coalgebraic.hs | haskell | Nothing
Left "whoops" | module Examples.Coalgebraic where
> > > [ Just 1 , Just 2 , Just 3 ] & _ Just > - sum
Just 6
> > > [ Just 1 , Nothing , Just 3 ] & _ Just > - sum
> > > [ Right 1 , Left " whoops " , Right 2 ] & _ Right > - sum
|
a92192b31cd879a0bd08d0a9f5e7f10fb4e776fad7c70461f882e819ddf13c31 | NorfairKing/the-notes | Macro.hs | module Macro.Topology.Macro where
import Types
import Macro.Math
import Macro.Text
import Macro.Tuple
import Functions.Distances.Macro (dist_, metr_)
Topology set
topset :: Note
topset = "X"
Topology Topology ( Topology on topset )
toptop :: Note
toptop = comm0 "tau"
-- Topological space
topsp :: Note
topsp = pars $ cs [topset, toptop]
Topology Pseudometric
toppm :: Note
toppm = dist_
Topology Pseudometric Space
toppms :: Note
toppms = toppms_ topset toppm
toppms_ :: Note -> Note -> Note
toppms_ = tuple
Topology Metric
topm :: Note
topm = metr_
Topology Metric Space
topms :: Note
topms = topms_ topset topm
topms_ :: Note -> Note -> Note
topms_ = tuple
| null | https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Macro/Topology/Macro.hs | haskell | Topological space | module Macro.Topology.Macro where
import Types
import Macro.Math
import Macro.Text
import Macro.Tuple
import Functions.Distances.Macro (dist_, metr_)
Topology set
topset :: Note
topset = "X"
Topology Topology ( Topology on topset )
toptop :: Note
toptop = comm0 "tau"
topsp :: Note
topsp = pars $ cs [topset, toptop]
Topology Pseudometric
toppm :: Note
toppm = dist_
Topology Pseudometric Space
toppms :: Note
toppms = toppms_ topset toppm
toppms_ :: Note -> Note -> Note
toppms_ = tuple
Topology Metric
topm :: Note
topm = metr_
Topology Metric Space
topms :: Note
topms = topms_ topset topm
topms_ :: Note -> Note -> Note
topms_ = tuple
|
ab02fbdf249d3bc4b385bbdbe042573a821b1d1cc22e888a15214f32312aa89d | NorfairKing/cursor | NonEmpty.hs | # LANGUAGE TypeFamilies #
module Cursor.Simple.List.NonEmpty
( NonEmptyCursor,
NEC.nonEmptyCursorPrev,
NEC.nonEmptyCursorCurrent,
NEC.nonEmptyCursorNext,
makeNonEmptyCursor,
makeNonEmptyCursorWithSelection,
NEC.singletonNonEmptyCursor,
rebuildNonEmptyCursor,
mapNonEmptyCursor,
NEC.nonEmptyCursorElemL,
nonEmptyCursorSelectPrev,
nonEmptyCursorSelectNext,
nonEmptyCursorSelectFirst,
nonEmptyCursorSelectLast,
NEC.nonEmptyCursorSelection,
nonEmptyCursorSelectIndex,
NEC.nonEmptyCursorInsert,
NEC.nonEmptyCursorAppend,
nonEmptyCursorInsertAndSelect,
nonEmptyCursorAppendAndSelect,
NEC.nonEmptyCursorInsertAtStart,
NEC.nonEmptyCursorAppendAtEnd,
nonEmptyCursorInsertAtStartAndSelect,
nonEmptyCursorAppendAtEndAndSelect,
nonEmptyCursorRemoveElemAndSelectPrev,
nonEmptyCursorDeleteElemAndSelectNext,
nonEmptyCursorRemoveElem,
nonEmptyCursorDeleteElem,
nonEmptyCursorSearch,
nonEmptyCursorSelectOrAdd,
)
where
import qualified Cursor.List.NonEmpty as NEC
import Cursor.Types
import Data.List.NonEmpty (NonEmpty (..))
-- | A 'nonempty list' cursor
type NonEmptyCursor a = NEC.NonEmptyCursor a a
makeNonEmptyCursor :: NonEmpty a -> NonEmptyCursor a
makeNonEmptyCursor = NEC.makeNonEmptyCursor id
makeNonEmptyCursorWithSelection :: Int -> NonEmpty a -> Maybe (NonEmptyCursor a)
makeNonEmptyCursorWithSelection = NEC.makeNonEmptyCursorWithSelection id
rebuildNonEmptyCursor :: NonEmptyCursor a -> NonEmpty a
rebuildNonEmptyCursor = NEC.rebuildNonEmptyCursor id
mapNonEmptyCursor :: (a -> b) -> NonEmptyCursor a -> NonEmptyCursor b
mapNonEmptyCursor f = NEC.mapNonEmptyCursor f f
nonEmptyCursorSelectPrev :: NonEmptyCursor a -> Maybe (NonEmptyCursor a)
nonEmptyCursorSelectPrev = NEC.nonEmptyCursorSelectPrev id id
nonEmptyCursorSelectNext :: NonEmptyCursor a -> Maybe (NonEmptyCursor a)
nonEmptyCursorSelectNext = NEC.nonEmptyCursorSelectNext id id
nonEmptyCursorSelectFirst :: NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorSelectFirst = NEC.nonEmptyCursorSelectFirst id id
nonEmptyCursorSelectLast :: NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorSelectLast = NEC.nonEmptyCursorSelectLast id id
nonEmptyCursorSelectIndex :: Int -> NonEmptyCursor a -> Maybe (NonEmptyCursor a)
nonEmptyCursorSelectIndex = NEC.nonEmptyCursorSelectIndex id id
nonEmptyCursorInsertAndSelect :: a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorInsertAndSelect = NEC.nonEmptyCursorInsertAndSelect id
nonEmptyCursorAppendAndSelect :: a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorAppendAndSelect = NEC.nonEmptyCursorAppendAndSelect id
nonEmptyCursorInsertAtStartAndSelect :: a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorInsertAtStartAndSelect = NEC.nonEmptyCursorInsertAtStartAndSelect id id
nonEmptyCursorAppendAtEndAndSelect :: a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorAppendAtEndAndSelect = NEC.nonEmptyCursorAppendAtEndAndSelect id id
nonEmptyCursorRemoveElemAndSelectPrev ::
NonEmptyCursor a -> Maybe (DeleteOrUpdate (NonEmptyCursor a))
nonEmptyCursorRemoveElemAndSelectPrev = NEC.nonEmptyCursorRemoveElemAndSelectPrev id
nonEmptyCursorDeleteElemAndSelectNext ::
NonEmptyCursor a -> Maybe (DeleteOrUpdate (NonEmptyCursor a))
nonEmptyCursorDeleteElemAndSelectNext = NEC.nonEmptyCursorDeleteElemAndSelectNext id
nonEmptyCursorRemoveElem :: NonEmptyCursor a -> DeleteOrUpdate (NonEmptyCursor a)
nonEmptyCursorRemoveElem = NEC.nonEmptyCursorRemoveElem id
nonEmptyCursorDeleteElem :: NonEmptyCursor a -> DeleteOrUpdate (NonEmptyCursor a)
nonEmptyCursorDeleteElem = NEC.nonEmptyCursorDeleteElem id
nonEmptyCursorSearch :: (a -> Bool) -> NonEmptyCursor a -> Maybe (NonEmptyCursor a)
nonEmptyCursorSearch = NEC.nonEmptyCursorSearch id id
nonEmptyCursorSelectOrAdd :: (a -> Bool) -> a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorSelectOrAdd = NEC.nonEmptyCursorSelectOrAdd id id
| null | https://raw.githubusercontent.com/NorfairKing/cursor/71ec3154809e229efbf35d500ac6d1a42ae5fdc0/cursor/src/Cursor/Simple/List/NonEmpty.hs | haskell | | A 'nonempty list' cursor | # LANGUAGE TypeFamilies #
module Cursor.Simple.List.NonEmpty
( NonEmptyCursor,
NEC.nonEmptyCursorPrev,
NEC.nonEmptyCursorCurrent,
NEC.nonEmptyCursorNext,
makeNonEmptyCursor,
makeNonEmptyCursorWithSelection,
NEC.singletonNonEmptyCursor,
rebuildNonEmptyCursor,
mapNonEmptyCursor,
NEC.nonEmptyCursorElemL,
nonEmptyCursorSelectPrev,
nonEmptyCursorSelectNext,
nonEmptyCursorSelectFirst,
nonEmptyCursorSelectLast,
NEC.nonEmptyCursorSelection,
nonEmptyCursorSelectIndex,
NEC.nonEmptyCursorInsert,
NEC.nonEmptyCursorAppend,
nonEmptyCursorInsertAndSelect,
nonEmptyCursorAppendAndSelect,
NEC.nonEmptyCursorInsertAtStart,
NEC.nonEmptyCursorAppendAtEnd,
nonEmptyCursorInsertAtStartAndSelect,
nonEmptyCursorAppendAtEndAndSelect,
nonEmptyCursorRemoveElemAndSelectPrev,
nonEmptyCursorDeleteElemAndSelectNext,
nonEmptyCursorRemoveElem,
nonEmptyCursorDeleteElem,
nonEmptyCursorSearch,
nonEmptyCursorSelectOrAdd,
)
where
import qualified Cursor.List.NonEmpty as NEC
import Cursor.Types
import Data.List.NonEmpty (NonEmpty (..))
type NonEmptyCursor a = NEC.NonEmptyCursor a a
makeNonEmptyCursor :: NonEmpty a -> NonEmptyCursor a
makeNonEmptyCursor = NEC.makeNonEmptyCursor id
makeNonEmptyCursorWithSelection :: Int -> NonEmpty a -> Maybe (NonEmptyCursor a)
makeNonEmptyCursorWithSelection = NEC.makeNonEmptyCursorWithSelection id
rebuildNonEmptyCursor :: NonEmptyCursor a -> NonEmpty a
rebuildNonEmptyCursor = NEC.rebuildNonEmptyCursor id
mapNonEmptyCursor :: (a -> b) -> NonEmptyCursor a -> NonEmptyCursor b
mapNonEmptyCursor f = NEC.mapNonEmptyCursor f f
nonEmptyCursorSelectPrev :: NonEmptyCursor a -> Maybe (NonEmptyCursor a)
nonEmptyCursorSelectPrev = NEC.nonEmptyCursorSelectPrev id id
nonEmptyCursorSelectNext :: NonEmptyCursor a -> Maybe (NonEmptyCursor a)
nonEmptyCursorSelectNext = NEC.nonEmptyCursorSelectNext id id
nonEmptyCursorSelectFirst :: NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorSelectFirst = NEC.nonEmptyCursorSelectFirst id id
nonEmptyCursorSelectLast :: NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorSelectLast = NEC.nonEmptyCursorSelectLast id id
nonEmptyCursorSelectIndex :: Int -> NonEmptyCursor a -> Maybe (NonEmptyCursor a)
nonEmptyCursorSelectIndex = NEC.nonEmptyCursorSelectIndex id id
nonEmptyCursorInsertAndSelect :: a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorInsertAndSelect = NEC.nonEmptyCursorInsertAndSelect id
nonEmptyCursorAppendAndSelect :: a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorAppendAndSelect = NEC.nonEmptyCursorAppendAndSelect id
nonEmptyCursorInsertAtStartAndSelect :: a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorInsertAtStartAndSelect = NEC.nonEmptyCursorInsertAtStartAndSelect id id
nonEmptyCursorAppendAtEndAndSelect :: a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorAppendAtEndAndSelect = NEC.nonEmptyCursorAppendAtEndAndSelect id id
nonEmptyCursorRemoveElemAndSelectPrev ::
NonEmptyCursor a -> Maybe (DeleteOrUpdate (NonEmptyCursor a))
nonEmptyCursorRemoveElemAndSelectPrev = NEC.nonEmptyCursorRemoveElemAndSelectPrev id
nonEmptyCursorDeleteElemAndSelectNext ::
NonEmptyCursor a -> Maybe (DeleteOrUpdate (NonEmptyCursor a))
nonEmptyCursorDeleteElemAndSelectNext = NEC.nonEmptyCursorDeleteElemAndSelectNext id
nonEmptyCursorRemoveElem :: NonEmptyCursor a -> DeleteOrUpdate (NonEmptyCursor a)
nonEmptyCursorRemoveElem = NEC.nonEmptyCursorRemoveElem id
nonEmptyCursorDeleteElem :: NonEmptyCursor a -> DeleteOrUpdate (NonEmptyCursor a)
nonEmptyCursorDeleteElem = NEC.nonEmptyCursorDeleteElem id
nonEmptyCursorSearch :: (a -> Bool) -> NonEmptyCursor a -> Maybe (NonEmptyCursor a)
nonEmptyCursorSearch = NEC.nonEmptyCursorSearch id id
nonEmptyCursorSelectOrAdd :: (a -> Bool) -> a -> NonEmptyCursor a -> NonEmptyCursor a
nonEmptyCursorSelectOrAdd = NEC.nonEmptyCursorSelectOrAdd id id
|
1a7ba3ba8200cbfc3ea5259eca21ee861d0d2c2552e05d24e127a4e36ee83d51 | dcos/dcos-net | dcos_overlay_app.erl | %%%-------------------------------------------------------------------
%% @doc navstar public API
%% @end
%%%-------------------------------------------------------------------
-module(dcos_overlay_app).
-behaviour(application).
%% Application callbacks
-export([start/2,
stop/1]).
%%====================================================================
%% API
%%====================================================================
start(_StartType, _StartArgs) ->
dcos_net_app:load_config_files(dcos_overlay),
dcos_overlay_sup:start_link(
[application:get_env(dcos_overlay, enable_overlay, true)]).
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/dcos/dcos-net/7bd01ac237ff4b9a12a020ed443e71c45f7063f4/apps/dcos_overlay/src/dcos_overlay_app.erl | erlang | -------------------------------------------------------------------
@doc navstar public API
@end
-------------------------------------------------------------------
Application callbacks
====================================================================
API
==================================================================== |
-module(dcos_overlay_app).
-behaviour(application).
-export([start/2,
stop/1]).
start(_StartType, _StartArgs) ->
dcos_net_app:load_config_files(dcos_overlay),
dcos_overlay_sup:start_link(
[application:get_env(dcos_overlay, enable_overlay, true)]).
stop(_State) ->
ok.
|
2477530f2045729bc4f0f3d35f4c4a64e51f228257d138b473381a8940092e67 | inaka/apns4erl | apns_connection.erl | @doc This gen_statem handles the APNs Connection .
%%%
Copyright 2017 Erlang Solutions Ltd.
%%%
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.
%%% @end
< >
%%%
-module(apns_connection).
-author("Felipe Ripoll <>").
-behaviour(gen_statem).
%% API
-export([ start_link/2
, default_connection/2
, name/1
, host/1
, port/1
, certdata/1
, certfile/1
, keydata/1
, keyfile/1
, type/1
, gun_pid/1
, close_connection/1
, push_notification/4
, push_notification/5
, wait_apns_connection_up/1
]).
%% gen_statem callbacks
-export([ init/1
, callback_mode/0
, open_connection/3
, open_origin/3
, open_proxy/3
, open_common/3
, await_up/3
, proxy_connect_to_origin/3
, await_tunnel_up/3
, connected/3
, down/3
, code_change/4
]).
-export_type([ name/0
, host/0
, port/0
, path/0
, connection/0
, notification/0
, type/0
]).
-type name() :: atom().
-type host() :: string() | inet:ip_address().
-type path() :: string().
-type notification() :: binary().
-type type() :: certdata | cert | token.
-type keydata() :: {'RSAPrivateKey' | 'DSAPrivateKey' | 'ECPrivateKey' |
'PrivateKeyInfo'
, binary()}.
-type proxy_info() :: #{ type := connect
, host := host()
, port := inet:port_number()
, username => iodata()
, password => iodata()
}.
-type connection() :: #{ name := name()
, apple_host := host()
, apple_port := inet:port_number()
, certdata => binary()
, certfile => path()
, keydata => keydata()
, keyfile => path()
, timeout => integer()
, type := type()
, proxy_info => proxy_info()
}.
-type state() :: #{ connection := connection()
, gun_pid => pid()
, gun_monitor => reference()
, gun_connect_ref => reference()
, client := pid()
, backoff := non_neg_integer()
, backoff_ceiling := non_neg_integer()
}.
%%%===================================================================
%%% API
%%%===================================================================
%% @doc starts the gen_statem
-spec start_link(connection(), pid()) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}.
start_link(#{name := undefined} = Connection, Client) ->
gen_statem:start_link(?MODULE, {Connection, Client}, []);
start_link(Connection, Client) ->
Name = name(Connection),
gen_statem:start_link({local, Name}, ?MODULE, {Connection, Client}, []).
%% @doc Builds a connection() map from the environment variables.
-spec default_connection(type(), name()) -> connection().
default_connection(certdata, ConnectionName) ->
{ok, Host} = application:get_env(apns, apple_host),
{ok, Port} = application:get_env(apns, apple_port),
{ok, Cert} = application:get_env(apns, certdata),
{ok, Key} = application:get_env(apns, keydata),
{ok, Timeout} = application:get_env(apns, timeout),
#{ name => ConnectionName
, apple_host => Host
, apple_port => Port
, certdata => Cert
, keydata => Key
, timeout => Timeout
, type => certdata
};
default_connection(cert, ConnectionName) ->
{ok, Host} = application:get_env(apns, apple_host),
{ok, Port} = application:get_env(apns, apple_port),
{ok, Certfile} = application:get_env(apns, certfile),
{ok, Keyfile} = application:get_env(apns, keyfile),
{ok, Timeout} = application:get_env(apns, timeout),
#{ name => ConnectionName
, apple_host => Host
, apple_port => Port
, certfile => Certfile
, keyfile => Keyfile
, timeout => Timeout
, type => cert
};
default_connection(token, ConnectionName) ->
{ok, Host} = application:get_env(apns, apple_host),
{ok, Port} = application:get_env(apns, apple_port),
{ok, Timeout} = application:get_env(apns, timeout),
#{ name => ConnectionName
, apple_host => Host
, apple_port => Port
, timeout => Timeout
, type => token
}.
%% @doc Close the connection with APNs gracefully
-spec close_connection(name() | pid()) -> ok.
close_connection(ConnectionId) ->
gen_statem:cast(ConnectionId, stop).
%% @doc Returns the gun's connection PID. This function is only used in tests.
-spec gun_pid(name() | pid()) -> pid().
gun_pid(ConnectionId) ->
gen_statem:call(ConnectionId, gun_pid).
%% @doc Pushes notification to certificate APNs connection.
-spec push_notification( name() | pid()
, apns:device_id()
, notification()
, apns:headers()) -> apns:response() | {error, not_connection_owner}.
push_notification(ConnectionId, DeviceId, Notification, Headers) ->
gen_statem:call(ConnectionId, {push_notification, DeviceId, Notification, Headers}).
%% @doc Pushes notification to certificate APNs connection.
-spec push_notification( name() | pid()
, apns:token()
, apns:device_id()
, notification()
, apns:headers()) -> apns:response() | {error, not_connection_owner}.
push_notification(ConnectionId, Token, DeviceId, Notification, Headers) ->
gen_statem:call(ConnectionId, {push_notification, Token, DeviceId, Notification, Headers}).
@doc Waits until the APNS connection is up .
%%
%% Note that this function does not need to be called before
%% sending push notifications, since they will be queued up
%% and sent when the connection is established.
-spec wait_apns_connection_up(pid()) -> ok.
wait_apns_connection_up(Server) ->
gen_statem:call(Server, wait_apns_connection_up, infinity).
%%%===================================================================
%%% gen_statem callbacks
%%%===================================================================
-spec callback_mode() -> state_functions.
callback_mode() -> state_functions.
-spec init({connection(), pid()})
-> { ok
, open_connection
, State :: state()
, {next_event, internal, init}
}.
init({Connection, Client}) ->
StateData = #{ connection => Connection
, client => Client
, backoff => 1
, backoff_ceiling => application:get_env(apns, backoff_ceiling, 10)
},
{ok, open_connection, StateData,
{next_event, internal, init}}.
-spec open_connection(_, _, _) -> _.
open_connection(internal, _, #{connection := Connection} = StateData) ->
NextState = case proxy(Connection) of
#{type := connect} -> open_proxy;
undefined -> open_origin
end,
{next_state, NextState, StateData,
{next_event, internal, init}}.
-spec open_origin(_, _, _) -> _.
open_origin(internal, _, #{connection := Connection} = StateData) ->
Host = host(Connection),
Port = port(Connection),
TransportOpts = transport_opts(Connection),
{next_state, open_common, StateData,
{next_event, internal, { Host
, Port
, #{ protocols => [http2]
, transport_opts => TransportOpts
, retry => 0
}}}}.
-spec open_proxy(_, _, _) -> _.
open_proxy(internal, _, StateData) ->
#{connection := Connection} = StateData,
#{type := connect, host := ProxyHost, port := ProxyPort} = proxy(Connection),
{next_state, open_common, StateData,
{next_event, internal, { ProxyHost
, ProxyPort
, #{ protocols => [http]
, transport => tcp
, retry => 0
}}}}.
This function exists only to make happy .
%% I do not think it makes things any easier to read.
-spec open_common(_, _, _) -> _.
open_common(internal, {Host, Port, Opts}, StateData) ->
{ok, GunPid} = gun:open(Host, Port, Opts),
GunMon = monitor(process, GunPid),
{next_state, await_up,
StateData#{gun_pid => GunPid, gun_monitor => GunMon},
{state_timeout, 15000, open_timeout}}.
-spec await_up(_, _, _) -> _.
await_up(info, {gun_up, GunPid, Protocol}, #{gun_pid := GunPid} = StateData) ->
#{connection := Connection} = StateData,
NextState = case proxy(Connection) of
#{type := connect} when Protocol =:= http -> proxy_connect_to_origin;
undefined when Protocol =:= http2 -> connected
end,
{next_state, NextState, StateData,
{next_event, internal, on_connect}};
await_up(EventType, EventContent, StateData) ->
handle_common(EventType, EventContent, ?FUNCTION_NAME, StateData, postpone).
-spec proxy_connect_to_origin(_, _, _) -> _.
proxy_connect_to_origin(internal, on_connect, StateData) ->
#{connection := Connection, gun_pid := GunPid} = StateData,
Host = host(Connection),
Port = port(Connection),
TransportOpts = transport_opts(Connection),
Destination0 = #{ host => Host
, port => Port
, protocol => http2
, transport => tls
, tls_opts => TransportOpts
},
Destination = case proxy(Connection) of
#{ username := Username, password := Password } ->
Destination0#{ username => Username, password => Password };
_ ->
Destination0
end,
ConnectRef = gun:connect(GunPid, Destination),
{next_state, await_tunnel_up, StateData#{gun_connect_ref => ConnectRef},
{state_timeout, 30000, proxy_connect_timeout}}.
-spec await_tunnel_up(_, _, _) -> _.
await_tunnel_up( info
, {gun_response, GunPid, ConnectRef, fin, 200, _}
, #{gun_pid := GunPid, gun_connect_ref := ConnectRef} = StateData) ->
{next_state, connected, StateData,
{next_event, internal, on_connect}};
await_tunnel_up(EventType, EventContent, StateData) ->
handle_common(EventType, EventContent, ?FUNCTION_NAME, StateData, postpone).
-spec connected(_, _, _) -> _.
connected(internal, on_connect, #{client := Client}) ->
Client ! {connection_up, self()},
keep_state_and_data;
connected( {call, {Client, _} = From}
, {push_notification, DeviceId, Notification, Headers}
, #{client := Client} = StateData) ->
#{connection := Connection, gun_pid := GunPid} = StateData,
#{timeout := Timeout} = Connection,
Response = push(GunPid, DeviceId, Headers, Notification, Timeout),
{keep_state_and_data, {reply, From, Response}};
connected( {call, {Client, _} = From}
, {push_notification, Token, DeviceId, Notification, Headers0}
, #{client := Client} = StateData) ->
#{connection := Connection, gun_pid := GunConn} = StateData,
#{timeout := Timeout} = Connection,
Headers = add_authorization_header(Headers0, Token),
Response = push(GunConn, DeviceId, Headers, Notification, Timeout),
{keep_state_and_data, {reply, From, Response}};
connected({call, From}, Event, _) when element(1, Event) =:= push_notification ->
{keep_state_and_data, {reply, From, {error, not_connection_owner}}};
connected({call, From}, wait_apns_connection_up, _) ->
{keep_state_and_data, {reply, From, ok}};
connected({call, From}, Event, _) when Event =/= gun_pid ->
{keep_state_and_data, {reply, From, {error, bad_call}}};
connected(EventType, EventContent, StateData) ->
handle_common(EventType, EventContent, ?FUNCTION_NAME, StateData, drop).
-spec down(_, _, _) -> _.
down(internal
, _
, #{ gun_pid := GunPid
, gun_monitor := GunMon
, client := Client
, backoff := Backoff
, backoff_ceiling := Ceiling
}) ->
true = demonitor(GunMon, [flush]),
gun:close(GunPid),
Client ! {reconnecting, self()},
Sleep = backoff(Backoff, Ceiling) * 1000,
{keep_state_and_data, {state_timeout, Sleep, backoff}};
down(state_timeout, backoff, StateData) ->
{next_state, open_connection, StateData,
{next_event, internal, init}};
down(EventType, EventContent, StateData) ->
handle_common(EventType, EventContent, ?FUNCTION_NAME, StateData, postpone).
-spec handle_common(_, _, _, _, _) -> _.
handle_common({call, From}, gun_pid, _, #{gun_pid := GunPid}, _) ->
{keep_state_and_data, {reply, From, GunPid}};
handle_common(cast, stop, _, _, _) ->
{stop, normal};
handle_common( info
, {'DOWN', GunMon, process, GunPid, Reason}
, StateName
, #{gun_pid := GunPid, gun_monitor := GunMon} = StateData
, _) ->
{next_state, down, StateData,
{next_event, internal, {down, StateName, Reason}}};
handle_common( state_timeout
, EventContent
, StateName
, #{gun_pid := GunPid} = StateData
, _) ->
gun:close(GunPid),
{next_state, down, StateData,
{next_event, internal, {state_timeout, StateName, EventContent}}};
handle_common(_, _, _, _, postpone) ->
{keep_state_and_data, postpone};
handle_common(_, _, _, _, drop) ->
keep_state_and_data.
-spec code_change(OldVsn :: term() | {down, term()}
, StateName
, StateData
, Extra :: term()
) -> {ok, StateName, StateData}.
code_change(_OldVsn, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
%%%===================================================================
%%% Connection getters/setters Functions
%%%===================================================================
-spec name(connection()) -> name().
name(#{name := ConnectionName}) ->
ConnectionName.
-spec host(connection()) -> host().
host(#{apple_host := Host}) ->
Host.
-spec port(connection()) -> inet:port_number().
port(#{apple_port := Port}) ->
Port.
-spec certdata(connection()) -> binary().
certdata(#{certdata := Cert}) ->
Cert.
-spec certfile(connection()) -> path().
certfile(#{certfile := Certfile}) ->
Certfile.
-spec keydata(connection()) -> keydata().
keydata(#{keydata := Key}) ->
Key.
-spec keyfile(connection()) -> path().
keyfile(#{keyfile := Keyfile}) ->
Keyfile.
-spec type(connection()) -> type().
type(#{type := Type}) ->
Type.
-spec proxy(connection()) -> proxy_info() | undefined.
proxy(#{proxy_info := Proxy}) ->
Proxy;
proxy(_) ->
undefined.
transport_opts(Connection) ->
case type(Connection) of
certdata ->
Cert = certdata(Connection),
Key = keydata(Connection),
[{cert, Cert}, {key, Key}];
cert ->
Certfile = certfile(Connection),
Keyfile = keyfile(Connection),
[{certfile, Certfile}, {keyfile, Keyfile}];
token ->
[]
end.
%%%===================================================================
%%% Internal Functions
%%%===================================================================
-spec get_headers(apns:headers()) -> list().
get_headers(Headers) ->
List = [ {<<"apns-id">>, apns_id}
, {<<"apns-expiration">>, apns_expiration}
, {<<"apns-priority">>, apns_priority}
, {<<"apns-topic">>, apns_topic}
, {<<"apns-collapse-id">>, apns_collapse_id}
, {<<"apns-push-type">>, apns_push_type}
, {<<"authorization">>, apns_auth_token}
],
F = fun({ActualHeader, Key}) ->
case (catch maps:get(Key, Headers)) of
{'EXIT', {{badkey, Key}, _}} -> [];
Value -> [{ActualHeader, Value}]
end
end,
lists:flatmap(F, List).
-spec get_device_path(apns:device_id()) -> binary().
get_device_path(DeviceId) ->
<<"/3/device/", DeviceId/binary>>.
-spec add_authorization_header(apns:headers(), apnd:token()) -> apns:headers().
add_authorization_header(Headers, Token) ->
Headers#{apns_auth_token => <<"bearer ", Token/binary>>}.
-spec push(pid(), apns:device_id(), apns:headers(), notification(), integer()) ->
apns:stream_id().
push(GunConn, DeviceId, HeadersMap, Notification, Timeout) ->
Headers = get_headers(HeadersMap),
Path = get_device_path(DeviceId),
StreamRef = gun:post(GunConn, Path, Headers, Notification),
case gun:await(GunConn, StreamRef, Timeout) of
{response, fin, Status, ResponseHeaders} ->
{Status, ResponseHeaders, no_body};
{response, nofin, Status, ResponseHeaders} ->
{ok, Body} = gun:await_body(GunConn, StreamRef, Timeout),
DecodedBody = jsx:decode(Body, [{return_maps, false}]),
{Status, ResponseHeaders, DecodedBody};
{error, timeout} -> timeout
end.
-spec backoff(non_neg_integer(), non_neg_integer()) -> non_neg_integer().
backoff(N, Ceiling) ->
case (math:pow(2, N) - 1) of
R when R > Ceiling ->
Ceiling;
NextN ->
NString = float_to_list(NextN, [{decimals, 0}]),
list_to_integer(NString)
end.
| null | https://raw.githubusercontent.com/inaka/apns4erl/bf2d11530ebffcc8906e417c8d4c765619db81b0/src/apns_connection.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@end
API
gen_statem callbacks
===================================================================
API
===================================================================
@doc starts the gen_statem
@doc Builds a connection() map from the environment variables.
@doc Close the connection with APNs gracefully
@doc Returns the gun's connection PID. This function is only used in tests.
@doc Pushes notification to certificate APNs connection.
@doc Pushes notification to certificate APNs connection.
Note that this function does not need to be called before
sending push notifications, since they will be queued up
and sent when the connection is established.
===================================================================
gen_statem callbacks
===================================================================
I do not think it makes things any easier to read.
===================================================================
Connection getters/setters Functions
===================================================================
===================================================================
Internal Functions
=================================================================== | @doc This gen_statem handles the APNs Connection .
Copyright 2017 Erlang Solutions Ltd.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
< >
-module(apns_connection).
-author("Felipe Ripoll <>").
-behaviour(gen_statem).
-export([ start_link/2
, default_connection/2
, name/1
, host/1
, port/1
, certdata/1
, certfile/1
, keydata/1
, keyfile/1
, type/1
, gun_pid/1
, close_connection/1
, push_notification/4
, push_notification/5
, wait_apns_connection_up/1
]).
-export([ init/1
, callback_mode/0
, open_connection/3
, open_origin/3
, open_proxy/3
, open_common/3
, await_up/3
, proxy_connect_to_origin/3
, await_tunnel_up/3
, connected/3
, down/3
, code_change/4
]).
-export_type([ name/0
, host/0
, port/0
, path/0
, connection/0
, notification/0
, type/0
]).
-type name() :: atom().
-type host() :: string() | inet:ip_address().
-type path() :: string().
-type notification() :: binary().
-type type() :: certdata | cert | token.
-type keydata() :: {'RSAPrivateKey' | 'DSAPrivateKey' | 'ECPrivateKey' |
'PrivateKeyInfo'
, binary()}.
-type proxy_info() :: #{ type := connect
, host := host()
, port := inet:port_number()
, username => iodata()
, password => iodata()
}.
-type connection() :: #{ name := name()
, apple_host := host()
, apple_port := inet:port_number()
, certdata => binary()
, certfile => path()
, keydata => keydata()
, keyfile => path()
, timeout => integer()
, type := type()
, proxy_info => proxy_info()
}.
-type state() :: #{ connection := connection()
, gun_pid => pid()
, gun_monitor => reference()
, gun_connect_ref => reference()
, client := pid()
, backoff := non_neg_integer()
, backoff_ceiling := non_neg_integer()
}.
-spec start_link(connection(), pid()) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}.
start_link(#{name := undefined} = Connection, Client) ->
gen_statem:start_link(?MODULE, {Connection, Client}, []);
start_link(Connection, Client) ->
Name = name(Connection),
gen_statem:start_link({local, Name}, ?MODULE, {Connection, Client}, []).
-spec default_connection(type(), name()) -> connection().
default_connection(certdata, ConnectionName) ->
{ok, Host} = application:get_env(apns, apple_host),
{ok, Port} = application:get_env(apns, apple_port),
{ok, Cert} = application:get_env(apns, certdata),
{ok, Key} = application:get_env(apns, keydata),
{ok, Timeout} = application:get_env(apns, timeout),
#{ name => ConnectionName
, apple_host => Host
, apple_port => Port
, certdata => Cert
, keydata => Key
, timeout => Timeout
, type => certdata
};
default_connection(cert, ConnectionName) ->
{ok, Host} = application:get_env(apns, apple_host),
{ok, Port} = application:get_env(apns, apple_port),
{ok, Certfile} = application:get_env(apns, certfile),
{ok, Keyfile} = application:get_env(apns, keyfile),
{ok, Timeout} = application:get_env(apns, timeout),
#{ name => ConnectionName
, apple_host => Host
, apple_port => Port
, certfile => Certfile
, keyfile => Keyfile
, timeout => Timeout
, type => cert
};
default_connection(token, ConnectionName) ->
{ok, Host} = application:get_env(apns, apple_host),
{ok, Port} = application:get_env(apns, apple_port),
{ok, Timeout} = application:get_env(apns, timeout),
#{ name => ConnectionName
, apple_host => Host
, apple_port => Port
, timeout => Timeout
, type => token
}.
-spec close_connection(name() | pid()) -> ok.
close_connection(ConnectionId) ->
gen_statem:cast(ConnectionId, stop).
-spec gun_pid(name() | pid()) -> pid().
gun_pid(ConnectionId) ->
gen_statem:call(ConnectionId, gun_pid).
-spec push_notification( name() | pid()
, apns:device_id()
, notification()
, apns:headers()) -> apns:response() | {error, not_connection_owner}.
push_notification(ConnectionId, DeviceId, Notification, Headers) ->
gen_statem:call(ConnectionId, {push_notification, DeviceId, Notification, Headers}).
-spec push_notification( name() | pid()
, apns:token()
, apns:device_id()
, notification()
, apns:headers()) -> apns:response() | {error, not_connection_owner}.
push_notification(ConnectionId, Token, DeviceId, Notification, Headers) ->
gen_statem:call(ConnectionId, {push_notification, Token, DeviceId, Notification, Headers}).
@doc Waits until the APNS connection is up .
-spec wait_apns_connection_up(pid()) -> ok.
wait_apns_connection_up(Server) ->
gen_statem:call(Server, wait_apns_connection_up, infinity).
-spec callback_mode() -> state_functions.
callback_mode() -> state_functions.
-spec init({connection(), pid()})
-> { ok
, open_connection
, State :: state()
, {next_event, internal, init}
}.
init({Connection, Client}) ->
StateData = #{ connection => Connection
, client => Client
, backoff => 1
, backoff_ceiling => application:get_env(apns, backoff_ceiling, 10)
},
{ok, open_connection, StateData,
{next_event, internal, init}}.
-spec open_connection(_, _, _) -> _.
open_connection(internal, _, #{connection := Connection} = StateData) ->
NextState = case proxy(Connection) of
#{type := connect} -> open_proxy;
undefined -> open_origin
end,
{next_state, NextState, StateData,
{next_event, internal, init}}.
-spec open_origin(_, _, _) -> _.
open_origin(internal, _, #{connection := Connection} = StateData) ->
Host = host(Connection),
Port = port(Connection),
TransportOpts = transport_opts(Connection),
{next_state, open_common, StateData,
{next_event, internal, { Host
, Port
, #{ protocols => [http2]
, transport_opts => TransportOpts
, retry => 0
}}}}.
-spec open_proxy(_, _, _) -> _.
open_proxy(internal, _, StateData) ->
#{connection := Connection} = StateData,
#{type := connect, host := ProxyHost, port := ProxyPort} = proxy(Connection),
{next_state, open_common, StateData,
{next_event, internal, { ProxyHost
, ProxyPort
, #{ protocols => [http]
, transport => tcp
, retry => 0
}}}}.
This function exists only to make happy .
-spec open_common(_, _, _) -> _.
open_common(internal, {Host, Port, Opts}, StateData) ->
{ok, GunPid} = gun:open(Host, Port, Opts),
GunMon = monitor(process, GunPid),
{next_state, await_up,
StateData#{gun_pid => GunPid, gun_monitor => GunMon},
{state_timeout, 15000, open_timeout}}.
-spec await_up(_, _, _) -> _.
await_up(info, {gun_up, GunPid, Protocol}, #{gun_pid := GunPid} = StateData) ->
#{connection := Connection} = StateData,
NextState = case proxy(Connection) of
#{type := connect} when Protocol =:= http -> proxy_connect_to_origin;
undefined when Protocol =:= http2 -> connected
end,
{next_state, NextState, StateData,
{next_event, internal, on_connect}};
await_up(EventType, EventContent, StateData) ->
handle_common(EventType, EventContent, ?FUNCTION_NAME, StateData, postpone).
-spec proxy_connect_to_origin(_, _, _) -> _.
proxy_connect_to_origin(internal, on_connect, StateData) ->
#{connection := Connection, gun_pid := GunPid} = StateData,
Host = host(Connection),
Port = port(Connection),
TransportOpts = transport_opts(Connection),
Destination0 = #{ host => Host
, port => Port
, protocol => http2
, transport => tls
, tls_opts => TransportOpts
},
Destination = case proxy(Connection) of
#{ username := Username, password := Password } ->
Destination0#{ username => Username, password => Password };
_ ->
Destination0
end,
ConnectRef = gun:connect(GunPid, Destination),
{next_state, await_tunnel_up, StateData#{gun_connect_ref => ConnectRef},
{state_timeout, 30000, proxy_connect_timeout}}.
-spec await_tunnel_up(_, _, _) -> _.
await_tunnel_up( info
, {gun_response, GunPid, ConnectRef, fin, 200, _}
, #{gun_pid := GunPid, gun_connect_ref := ConnectRef} = StateData) ->
{next_state, connected, StateData,
{next_event, internal, on_connect}};
await_tunnel_up(EventType, EventContent, StateData) ->
handle_common(EventType, EventContent, ?FUNCTION_NAME, StateData, postpone).
-spec connected(_, _, _) -> _.
connected(internal, on_connect, #{client := Client}) ->
Client ! {connection_up, self()},
keep_state_and_data;
connected( {call, {Client, _} = From}
, {push_notification, DeviceId, Notification, Headers}
, #{client := Client} = StateData) ->
#{connection := Connection, gun_pid := GunPid} = StateData,
#{timeout := Timeout} = Connection,
Response = push(GunPid, DeviceId, Headers, Notification, Timeout),
{keep_state_and_data, {reply, From, Response}};
connected( {call, {Client, _} = From}
, {push_notification, Token, DeviceId, Notification, Headers0}
, #{client := Client} = StateData) ->
#{connection := Connection, gun_pid := GunConn} = StateData,
#{timeout := Timeout} = Connection,
Headers = add_authorization_header(Headers0, Token),
Response = push(GunConn, DeviceId, Headers, Notification, Timeout),
{keep_state_and_data, {reply, From, Response}};
connected({call, From}, Event, _) when element(1, Event) =:= push_notification ->
{keep_state_and_data, {reply, From, {error, not_connection_owner}}};
connected({call, From}, wait_apns_connection_up, _) ->
{keep_state_and_data, {reply, From, ok}};
connected({call, From}, Event, _) when Event =/= gun_pid ->
{keep_state_and_data, {reply, From, {error, bad_call}}};
connected(EventType, EventContent, StateData) ->
handle_common(EventType, EventContent, ?FUNCTION_NAME, StateData, drop).
-spec down(_, _, _) -> _.
down(internal
, _
, #{ gun_pid := GunPid
, gun_monitor := GunMon
, client := Client
, backoff := Backoff
, backoff_ceiling := Ceiling
}) ->
true = demonitor(GunMon, [flush]),
gun:close(GunPid),
Client ! {reconnecting, self()},
Sleep = backoff(Backoff, Ceiling) * 1000,
{keep_state_and_data, {state_timeout, Sleep, backoff}};
down(state_timeout, backoff, StateData) ->
{next_state, open_connection, StateData,
{next_event, internal, init}};
down(EventType, EventContent, StateData) ->
handle_common(EventType, EventContent, ?FUNCTION_NAME, StateData, postpone).
-spec handle_common(_, _, _, _, _) -> _.
handle_common({call, From}, gun_pid, _, #{gun_pid := GunPid}, _) ->
{keep_state_and_data, {reply, From, GunPid}};
handle_common(cast, stop, _, _, _) ->
{stop, normal};
handle_common( info
, {'DOWN', GunMon, process, GunPid, Reason}
, StateName
, #{gun_pid := GunPid, gun_monitor := GunMon} = StateData
, _) ->
{next_state, down, StateData,
{next_event, internal, {down, StateName, Reason}}};
handle_common( state_timeout
, EventContent
, StateName
, #{gun_pid := GunPid} = StateData
, _) ->
gun:close(GunPid),
{next_state, down, StateData,
{next_event, internal, {state_timeout, StateName, EventContent}}};
handle_common(_, _, _, _, postpone) ->
{keep_state_and_data, postpone};
handle_common(_, _, _, _, drop) ->
keep_state_and_data.
-spec code_change(OldVsn :: term() | {down, term()}
, StateName
, StateData
, Extra :: term()
) -> {ok, StateName, StateData}.
code_change(_OldVsn, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
-spec name(connection()) -> name().
name(#{name := ConnectionName}) ->
ConnectionName.
-spec host(connection()) -> host().
host(#{apple_host := Host}) ->
Host.
-spec port(connection()) -> inet:port_number().
port(#{apple_port := Port}) ->
Port.
-spec certdata(connection()) -> binary().
certdata(#{certdata := Cert}) ->
Cert.
-spec certfile(connection()) -> path().
certfile(#{certfile := Certfile}) ->
Certfile.
-spec keydata(connection()) -> keydata().
keydata(#{keydata := Key}) ->
Key.
-spec keyfile(connection()) -> path().
keyfile(#{keyfile := Keyfile}) ->
Keyfile.
-spec type(connection()) -> type().
type(#{type := Type}) ->
Type.
-spec proxy(connection()) -> proxy_info() | undefined.
proxy(#{proxy_info := Proxy}) ->
Proxy;
proxy(_) ->
undefined.
transport_opts(Connection) ->
case type(Connection) of
certdata ->
Cert = certdata(Connection),
Key = keydata(Connection),
[{cert, Cert}, {key, Key}];
cert ->
Certfile = certfile(Connection),
Keyfile = keyfile(Connection),
[{certfile, Certfile}, {keyfile, Keyfile}];
token ->
[]
end.
-spec get_headers(apns:headers()) -> list().
get_headers(Headers) ->
List = [ {<<"apns-id">>, apns_id}
, {<<"apns-expiration">>, apns_expiration}
, {<<"apns-priority">>, apns_priority}
, {<<"apns-topic">>, apns_topic}
, {<<"apns-collapse-id">>, apns_collapse_id}
, {<<"apns-push-type">>, apns_push_type}
, {<<"authorization">>, apns_auth_token}
],
F = fun({ActualHeader, Key}) ->
case (catch maps:get(Key, Headers)) of
{'EXIT', {{badkey, Key}, _}} -> [];
Value -> [{ActualHeader, Value}]
end
end,
lists:flatmap(F, List).
-spec get_device_path(apns:device_id()) -> binary().
get_device_path(DeviceId) ->
<<"/3/device/", DeviceId/binary>>.
-spec add_authorization_header(apns:headers(), apnd:token()) -> apns:headers().
add_authorization_header(Headers, Token) ->
Headers#{apns_auth_token => <<"bearer ", Token/binary>>}.
-spec push(pid(), apns:device_id(), apns:headers(), notification(), integer()) ->
apns:stream_id().
push(GunConn, DeviceId, HeadersMap, Notification, Timeout) ->
Headers = get_headers(HeadersMap),
Path = get_device_path(DeviceId),
StreamRef = gun:post(GunConn, Path, Headers, Notification),
case gun:await(GunConn, StreamRef, Timeout) of
{response, fin, Status, ResponseHeaders} ->
{Status, ResponseHeaders, no_body};
{response, nofin, Status, ResponseHeaders} ->
{ok, Body} = gun:await_body(GunConn, StreamRef, Timeout),
DecodedBody = jsx:decode(Body, [{return_maps, false}]),
{Status, ResponseHeaders, DecodedBody};
{error, timeout} -> timeout
end.
-spec backoff(non_neg_integer(), non_neg_integer()) -> non_neg_integer().
backoff(N, Ceiling) ->
case (math:pow(2, N) - 1) of
R when R > Ceiling ->
Ceiling;
NextN ->
NString = float_to_list(NextN, [{decimals, 0}]),
list_to_integer(NString)
end.
|
7d9dc3da37562cee4878524aaa072c3b6367f45ea32e4a0f4350f1240ec7873f | wdebeaum/step | tend.lisp | ;;;;
;;;; W::tend
;;;;
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::tend
(SENSES
((LF-PARENT ONT::be-inclined)
(example "It tends to increase.")
(TEMPL NEUTRAL-FORMAL-CP-SUBJCONTROL-TEMPL (xp (% W::cp (W::ctype W::s-to))))
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/tend.lisp | lisp |
W::tend
|
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::tend
(SENSES
((LF-PARENT ONT::be-inclined)
(example "It tends to increase.")
(TEMPL NEUTRAL-FORMAL-CP-SUBJCONTROL-TEMPL (xp (% W::cp (W::ctype W::s-to))))
)
)
)
))
|
24999557b711aeffb882ea8f38cb650f141b995e6b1800edec05d48cfb9c1f12 | arttuka/reagent-material-ui | account_circle.cljs | (ns reagent-mui.icons.account-circle
"Imports @mui/icons-material/AccountCircle as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def account-circle (create-svg-icon (e "path" #js {"d" "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 4c1.93 0 3.5 1.57 3.5 3.5S13.93 13 12 13s-3.5-1.57-3.5-3.5S10.07 6 12 6zm0 14c-2.03 0-4.43-.82-6.14-2.88C7.55 15.8 9.68 15 12 15s4.45.8 6.14 2.12C16.43 19.18 14.03 20 12 20z"})
"AccountCircle"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/account_circle.cljs | clojure | (ns reagent-mui.icons.account-circle
"Imports @mui/icons-material/AccountCircle as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def account-circle (create-svg-icon (e "path" #js {"d" "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 4c1.93 0 3.5 1.57 3.5 3.5S13.93 13 12 13s-3.5-1.57-3.5-3.5S10.07 6 12 6zm0 14c-2.03 0-4.43-.82-6.14-2.88C7.55 15.8 9.68 15 12 15s4.45.8 6.14 2.12C16.43 19.18 14.03 20 12 20z"})
"AccountCircle"))
|
|
78a2c216be5f1569fbb25cb81c5be4ee7356a463bdc1d38871e02c2116314753 | robert-strandh/SICL | sublis-defun.lisp | (cl:in-package #:sicl-cons)
(defun |sublis key=identity test=eq| (alist tree)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (eq tree (car element))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=identity test=eql| (alist tree)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (eql tree (car element))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=other test=eq| (alist tree key)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (eq (funcall key tree) (car element))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=other test=eql| (alist tree key)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (eql (funcall key tree) (car element))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=identity test=other| (alist tree test)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (funcall test (car element) tree)
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=other-test-other| (alist tree test key)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (funcall test (car element) (funcall key tree))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=identity test-not=other| (alist tree test)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (not (funcall test (car element) tree))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=other test-not=other| (alist tree test key)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (not (funcall test (car element) (funcall key tree)))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun sublis (alist tree
&key key (test nil test-given) (test-not nil test-not-given))
(when (and test-given test-not-given)
(error 'both-test-and-test-not-given))
(if key
(if test-given
(if (or (eq test #'eq) (eq test 'eq))
(|sublis key=other test=eq| alist tree key)
(if (or (eq test #'eql) (eq test 'eql))
(|sublis key=other test=eql| alist tree key)
(|sublis key=other-test-other| alist tree test key)))
(if test-not-given
(|sublis key=other test-not=other| alist tree test-not key)
(|sublis key=other test=eql| alist tree key)))
(if test-given
(if (or (eq test #'eq) (eq test 'eq))
(|sublis key=identity test=eq| alist tree)
(if (or (eq test #'eql) (eq test 'eql))
(|sublis key=identity test=eql| alist tree)
(|sublis key=identity test=other| alist tree test)))
(if test-not-given
(|sublis key=identity test-not=other| alist tree test-not)
(|sublis key=identity test=eql| alist tree)))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/32d995c4f8e7d228e9c0cda6f670b2fa53ad0287/Code/Cons/sublis-defun.lisp | lisp | (cl:in-package #:sicl-cons)
(defun |sublis key=identity test=eq| (alist tree)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (eq tree (car element))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=identity test=eql| (alist tree)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (eql tree (car element))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=other test=eq| (alist tree key)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (eq (funcall key tree) (car element))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=other test=eql| (alist tree key)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (eql (funcall key tree) (car element))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=identity test=other| (alist tree test)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (funcall test (car element) tree)
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=other-test-other| (alist tree test key)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (funcall test (car element) (funcall key tree))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=identity test-not=other| (alist tree test)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (not (funcall test (car element) tree))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun |sublis key=other test-not=other| (alist tree test key)
(let ((substitution-p nil))
(labels ((traverse (tree)
(let ((entry (with-alist-elements (element alist sublis)
(when (not (funcall test (car element) (funcall key tree)))
(return element)))))
(cond ((not (null entry))
(setf substitution-p t)
(cdr entry))
((atom tree) tree)
(t (cons (traverse (car tree))
(traverse (cdr tree))))))))
(let ((new-tree (traverse tree)))
(if substitution-p new-tree tree)))))
(defun sublis (alist tree
&key key (test nil test-given) (test-not nil test-not-given))
(when (and test-given test-not-given)
(error 'both-test-and-test-not-given))
(if key
(if test-given
(if (or (eq test #'eq) (eq test 'eq))
(|sublis key=other test=eq| alist tree key)
(if (or (eq test #'eql) (eq test 'eql))
(|sublis key=other test=eql| alist tree key)
(|sublis key=other-test-other| alist tree test key)))
(if test-not-given
(|sublis key=other test-not=other| alist tree test-not key)
(|sublis key=other test=eql| alist tree key)))
(if test-given
(if (or (eq test #'eq) (eq test 'eq))
(|sublis key=identity test=eq| alist tree)
(if (or (eq test #'eql) (eq test 'eql))
(|sublis key=identity test=eql| alist tree)
(|sublis key=identity test=other| alist tree test)))
(if test-not-given
(|sublis key=identity test-not=other| alist tree test-not)
(|sublis key=identity test=eql| alist tree)))))
|
|
b07137e2967efa2acdef17b689eb7ca93e81ddc002bc537d7560ee6caa35a866 | sbcl/sbcl | arith-slow.pure.lisp | These two tests are by themselves because they consume more run time
;;; than all other tests in arith.pure combined.
(defmacro test-guts ()
#+sb-thread '(let ((t1 (sb-thread:make-thread #'doit :arguments '(-8 0)))
(t2 (sb-thread:make-thread #'doit :arguments '(1 8))))
(sb-thread:join-thread t1)
(sb-thread:join-thread t2))
#-sb-thread '(doit -8 8))
(with-test (:name (logand :complicated-identity)
:skipped-on :mips) ; too slow
(flet ((doit (k-lo k-hi)
(loop for k from k-lo upto k-hi do
(loop for min from -16 upto 16 do
(loop for max from min upto 16 do
(let ((f (checked-compile `(lambda (x)
(declare (type (integer ,min ,max) x))
(logand x ,k)))))
(loop for x from min upto max do
(assert (eql (logand x k) (funcall f x))))))))))
(test-guts)))
(with-test (:name (logior :complicated-identity)
:skipped-on :mips) ; too slow
(flet ((doit (k-lo k-hi)
(loop for k from k-lo upto k-hi do
(loop for min from -16 upto 16 do
(loop for max from min upto 16 do
(let ((f (checked-compile `(lambda (x)
(declare (type (integer ,min ,max) x))
(logior x ,k)))))
(loop for x from min upto max do
(assert (eql (logior x k) (funcall f x))))))))))
(test-guts)))
(defun type-derivation (op u-l u-h s-l s-h)
(let ((interval (sb-c::numeric-type->interval
(sb-kernel:specifier-type (cadr (caddr (sb-kernel:%simple-fun-type
(compile nil `(lambda (u s)
(,op (truly-the (integer ,u-l ,u-h) u)
(truly-the (integer ,s-l ,s-h) s)))))))))))
(values (loop for u from u-l to u-h
minimize (loop for s from s-l to s-h
minimize (funcall op u s)))
(loop for u from u-l to u-h
maximize (loop for s from s-l to s-h
maximize (funcall op u s)))
(sb-c::interval-low interval)
(sb-c::interval-high interval))))
(with-test (:name :logical-type-derivation)
(loop
for low1 from -4 to 5
do
(loop
for high1 from low1 to 5
do
(loop
for low2 from -4 to 5
do
(loop
for high2 from low2 to 5
do
(loop for op in '(logand logior logxor)
do
(multiple-value-bind (low high r-low r-high)
(type-derivation op low1 high1 low2 high2)
(assert (>= low r-low))
(assert (<= high r-high)))))))))
| null | https://raw.githubusercontent.com/sbcl/sbcl/fa10fc0554789ba1c18467790e665db74c6035b5/tests/arith-slow.pure.lisp | lisp | than all other tests in arith.pure combined.
too slow
too slow | These two tests are by themselves because they consume more run time
(defmacro test-guts ()
#+sb-thread '(let ((t1 (sb-thread:make-thread #'doit :arguments '(-8 0)))
(t2 (sb-thread:make-thread #'doit :arguments '(1 8))))
(sb-thread:join-thread t1)
(sb-thread:join-thread t2))
#-sb-thread '(doit -8 8))
(with-test (:name (logand :complicated-identity)
(flet ((doit (k-lo k-hi)
(loop for k from k-lo upto k-hi do
(loop for min from -16 upto 16 do
(loop for max from min upto 16 do
(let ((f (checked-compile `(lambda (x)
(declare (type (integer ,min ,max) x))
(logand x ,k)))))
(loop for x from min upto max do
(assert (eql (logand x k) (funcall f x))))))))))
(test-guts)))
(with-test (:name (logior :complicated-identity)
(flet ((doit (k-lo k-hi)
(loop for k from k-lo upto k-hi do
(loop for min from -16 upto 16 do
(loop for max from min upto 16 do
(let ((f (checked-compile `(lambda (x)
(declare (type (integer ,min ,max) x))
(logior x ,k)))))
(loop for x from min upto max do
(assert (eql (logior x k) (funcall f x))))))))))
(test-guts)))
(defun type-derivation (op u-l u-h s-l s-h)
(let ((interval (sb-c::numeric-type->interval
(sb-kernel:specifier-type (cadr (caddr (sb-kernel:%simple-fun-type
(compile nil `(lambda (u s)
(,op (truly-the (integer ,u-l ,u-h) u)
(truly-the (integer ,s-l ,s-h) s)))))))))))
(values (loop for u from u-l to u-h
minimize (loop for s from s-l to s-h
minimize (funcall op u s)))
(loop for u from u-l to u-h
maximize (loop for s from s-l to s-h
maximize (funcall op u s)))
(sb-c::interval-low interval)
(sb-c::interval-high interval))))
(with-test (:name :logical-type-derivation)
(loop
for low1 from -4 to 5
do
(loop
for high1 from low1 to 5
do
(loop
for low2 from -4 to 5
do
(loop
for high2 from low2 to 5
do
(loop for op in '(logand logior logxor)
do
(multiple-value-bind (low high r-low r-high)
(type-derivation op low1 high1 low2 high2)
(assert (>= low r-low))
(assert (<= high r-high)))))))))
|
a11bb71721cae718afb3f11c4188184c1713041eb805fd7d147fa3a0d648d193 | rfkm/zou | schema.clj | (ns zou.web.asset.schema
(:require [schema.core :as s]))
(def AssetSpec {(s/optional-key :id) s/Keyword
:name s/Str
:type (s/enum :javascript :stylesheet)
:src (s/either java.net.URL java.io.File s/Str)})
(defn validate-asset-specs [assets]
(s/validate [AssetSpec] assets))
| null | https://raw.githubusercontent.com/rfkm/zou/228feefae3e008f56806589cb8019511981f7b01/web/src/zou/web/asset/schema.clj | clojure | (ns zou.web.asset.schema
(:require [schema.core :as s]))
(def AssetSpec {(s/optional-key :id) s/Keyword
:name s/Str
:type (s/enum :javascript :stylesheet)
:src (s/either java.net.URL java.io.File s/Str)})
(defn validate-asset-specs [assets]
(s/validate [AssetSpec] assets))
|
|
23b36b69153a801ee37b723fc83403710f6eaf9c7e4d37df925eaa80d6ae27c9 | gelisam/klister | Test.hs | # LANGUAGE BlockArguments #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
module Main where
import Control.Lens hiding (List)
import Control.Monad
import qualified Data.Map as Map
import Control.Monad.IO.Class (liftIO)
import Data.Maybe (maybeToList)
import Data.Text (Text)
import Data.Set (Set)
import System.IO (stdout)
import qualified Data.Text as T
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.Hedgehog (testProperty)
import Hedgehog hiding (eval, Var)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import qualified Hedgehog.Internal.Gen as Gen (generalize)
import qualified Hedgehog.Internal.Property as Prop (forAllT)
import Alpha
import Core
import Core.Builder
import Evaluator (EvalResult(..))
import Expander
import Expander.Monad
import Module
import ModuleName
import Parser
import PartialCore
import Phase (prior, runtime, Phased(..), Phase)
import Pretty
import Scope
import qualified ScopeSet
import ScopeSet (ScopeSet)
import ShortShow
import SplitCore
import Syntax.SrcLoc
import Syntax
import Unique
import Value
import World
import Golden
main :: IO ()
main = do
defaultMain =<< (tests <$> mkGoldenTests)
tests :: TestTree ->TestTree
tests goldenTests = testGroup "All tests"
[ testGroup "Expander tests" [ operationTests, miniTests, moduleTests ]
, testGroup "Hedgehog tests" [ testProperty
"runPartialCore . nonPartial = id"
(withTests 10 propRunPartialCoreNonPartial)
, testProperty
"unsplit . split = pure"
(withTests 10 propSplitUnsplit)
]
, goldenTests
]
operationTests :: TestTree
operationTests =
testGroup "Core operations"
[ testCase "Shifting core expressions" $
let sc = Scope 42 "Test suite"
scs = ScopeSet.insertAtPhase runtime sc ScopeSet.empty
stx = Syntax (Stx scs fakeLoc (Id "hey"))
expr = Core (CoreApp (Core (CoreInteger 2))
(Core (CoreSyntax stx)))
in case shift 1 expr of
Core (CoreApp (Core (CoreInteger 2))
(Core (CoreSyntax stx'))) ->
case stx' of
Syntax (Stx scs' _ (Id "hey")) ->
if scs' == ScopeSet.insertAtPhase (prior runtime) sc ScopeSet.empty
then pure ()
else assertFailure $ "Shifting gave wrong scopes" ++ show scs'
Syntax _ -> assertFailure "Wrong shape in shifted syntax"
_ -> assertFailure "Shifting didn't preserve structure!"
]
miniTests :: TestTree
miniTests =
testGroup "Mini-tests" [ expectedSuccess, expectedFailure]
where
expectedSuccess =
testGroup "Expected to succeed"
[ testCase name (testExpander input output)
| (name, input, output) <-
[ ( "[lambda [x] x]"
, "[lambda [x] x]"
, lam $ \x -> x
)
, ( "[lambda [x] [lambda [x] x]]"
, "[lambda [x] [lambda [x] x]]"
, lam $ \_ -> lam $ \y -> y
)
, ( "42"
, "42"
, int 42
)
, ( "[lambda [f] [lambda [x] [f x]]]"
, "[lambda [f] [lambda [x] [f x]]]"
, lam $ \f -> lam $ \x -> f `app` x
)
, ( "Trivial user macro"
, "[let-syntax \n\
\ [m [lambda [_] \n\
\ [pure [quote [lambda [x] x]]]]] \n\
\ m]"
, lam $ \x -> x
)
, ( "Let macro"
, "[let-syntax \n\
\ [let1 [lambda [stx] \n\
\ (syntax-case stx \n\
\ [[list [_ binder body]] \n\
\ (syntax-case binder \n\
\ [[list [x e]] \n\
\ {- [[lambda [x] body] e] -} \n\
\ [pure [list-syntax \n\
\ [[list-syntax \n\
\ [[ident-syntax 'lambda stx] \n\
\ [list-syntax [x] stx] \n\
\ body] \n\
\ stx] \n\
\ e] \n\
\ stx]]])])]] \n\
\ [let1 [x [lambda [x] x]] \n\
\ x]]"
, (lam $ \x -> x) `app` (lam $ \x -> x)
)
]
]
expectedFailure =
testGroup "Expected to fail"
[ testCase name (testExpansionFails input predicate)
| (name, input, predicate) <-
[ ( "unbound variable and nothing else"
, "x"
, \case
Unknown (Stx _ _ "x") -> True
_ -> False
)
, ( "unbound variable inside let-syntax"
, "[let-syntax \
\ [m [lambda [_] \
\ [pure [quote [lambda [x] x]]]]] \
\ anyRandomWord]"
, \case
Unknown (Stx _ _ "anyRandomWord") -> True
_ -> False
)
, ( "refer to a local variable from a future phase"
, "[lambda [x] [let-syntax [m [lambda [_] x]] x]]"
, \case
Unknown (Stx _ _ "x") -> True
_ -> False
)
, ( "a macro calls itself"
, "[let-syntax [m [lambda [x] [m x]]] m]"
, \case
Unknown (Stx _ loc "m") ->
-- Make sure it's the use site in the macro body that
-- throws the error
view (srcLocStart . srcPosCol) loc == 29
_ -> False
)
]
]
moduleTests :: TestTree
moduleTests = testGroup "Module tests" [ shouldWork, shouldn'tWork ]
where
shouldWork =
testGroup "Expected to succeed"
[ testCase fn (testFile fn p)
| (fn, p) <-
[ ( "examples/small.kl"
, \m _ -> isEmpty (view moduleBody m)
)
, ( "examples/two-defs.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
filter (\case {(Define {}) -> True; _ -> False}) &
\case
[Define {}, Define {}] -> pure ()
_ -> assertFailure "Expected two definitions"
)
, ( "examples/id-compare.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
filter (\case {(Example _ _ _) -> True; _ -> False}) &
\case
[Example _ _ e1, Example _ _ e2] -> do
assertAlphaEq "first example" e1 (Core (corePrimitiveCtor "true" []))
assertAlphaEq "second example" e2 (Core (corePrimitiveCtor "false" []))
_ -> assertFailure "Expected two examples"
)
, ( "examples/lang.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
[Define _fn fv _t fbody, Example _ _ e] -> do
fspec <- lam \_x -> lam \ y -> lam \_z -> y
assertAlphaEq "definition of f" fbody fspec
case e of
Core (CoreApp (Core (CoreApp (Core (CoreApp (Core (CoreVar fv')) _)) _)) _) ->
assertAlphaEq "function position in example" fv' fv
_ -> assertFailure "example has wrong shape"
_ -> assertFailure "Expected two examples"
)
, ( "examples/import.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
filter (\case {(Example _ _ _) -> True; _ -> False}) &
\case
[Example _ _ e1, Example _ _ e2] -> do
case e1 of
(Core (CoreApp (Core (CoreApp (Core (CoreVar _)) _)) _)) ->
pure ()
_ -> assertFailure "example 1 has wrong shape"
case e2 of
Core (CoreApp (Core (CoreApp (Core (CoreApp fun _)) _)) _) -> do
fspec <- lam \_x -> lam \ y -> lam \_z -> y
assertAlphaEq "function in second example" fun fspec
_ -> assertFailure "example 2 has wrong shape"
_ -> assertFailure "Expected two examples"
)
, ( "examples/phase1.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
[Import _,
Meta [ view completeDecl -> Define _ _ _ _
, view completeDecl -> Define _ _ _ _
],
DefineMacros [(_, _, _)],
Example _ _ ex] ->
assertAlphaEq "Example is integer" ex (Core (CoreInteger 1))
_ -> assertFailure "Expected an import, two meta-defs, a macro def, and an example"
)
, ( "examples/imports-shifted-macro.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
[Import _, Import _, DefineMacros [(_, _, _)], Example _ _ ex] ->
assertAlphaEq "Example is (false)" ex (Core (corePrimitiveCtor "false" []))
_ -> assertFailure "Expected import, import, macro, example"
)
, ( "examples/macro-body-shift.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
[Import _, Define _ _ _ e, DefineMacros [(_, _, _)]] -> do
spec <- lam \_x -> lam \y -> lam \_z -> y
assertAlphaEq "Definition is λx y z . y" e spec
_ -> assertFailure "Expected an import, a definition, and a macro"
)
, ( "examples/test-quasiquote.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
(Import _ : Import _ : Define _ _ _ thingDef : examples) -> do
case thingDef of
Core (CoreSyntax (Syntax (Stx _ _ (Id "nothing")))) ->
case examples of
[e1, e2, e3, e4, e5, e6, e7, e8, Example _ _ _] -> do
testQuasiquoteExamples [e1, e2, e3, e4, e5, e6, e7, e8]
other -> assertFailure ("Expected 8 tested examples, 1 untested: " ++ show other)
other -> assertFailure ("Unexpected thing def " ++ show other)
_ -> assertFailure "Expected two imports, a definition, and examples"
)
, ( "examples/quasiquote-syntax-test.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
(Import _ : _ : _ : Define _ _ _ thingDef : examples) -> do
case thingDef of
Core (CoreSyntax (Syntax (Stx _ _ (Id "nothing")))) ->
case examples of
[e1, e2, e3, e4, e5, e6, e7, e8] -> do
testQuasiquoteExamples [e1, e2, e3, e4, e5, e6, e7, e8]
other -> assertFailure ("Expected 8 examples and 2 exports: " ++ show other)
other -> assertFailure ("Unexpected thing def " ++ show other)
_ -> assertFailure "Expected an import, two macros, a definition, and examples"
)
, ( "examples/hygiene.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
(Import _ : Import _ : Import _ : Import _ : Define _ fun1 _ firstFun : DefineMacros [_] :
Define _ fun2 _ secondFun : Example _ _ e1 : Example _ _ e2 : DefineMacros [_] :
Example _ _ e3 : _) -> do
spec1 <- lam \x -> lam \_y -> x
spec2 <- lam \_x -> lam \y -> y
assertAlphaEq "First fun drops second argument" firstFun spec1
assertAlphaEq "Second fun drops first argument" secondFun spec2
case e1 of
Core (CoreApp (Core (CoreApp f _)) _) ->
assertAlphaEq "Ex 1 picks fun 2" (Core (CoreVar fun2)) f
other -> assertFailure $ "Ex 1 should be an application, but it's " ++ shortShow other
case e2 of
Core (CoreApp (Core (CoreApp f _)) _) ->
assertAlphaEq "Ex 2 picks fun 1" (Core (CoreVar fun1)) f
other -> assertFailure $ "Ex 2 should be an application, but it's " ++ shortShow other
spec3 <- lam (const (pure (Core (CoreVar fun2))))
case e3 of
Core (CoreApp (Core (CoreApp (Core (CoreApp f _)) _)) _) ->
assertAlphaEq "Ex 3 picks fun 2" f spec3
other -> assertFailure $ "Ex 3 should be an application, but it's " ++ shortShow other
_ -> assertFailure "Expected two imports, a def, a macro, a def, two examples, a macro, and an example"
)
, ( "examples/defun-test.kl"
, \_m exampleVals ->
case exampleVals of
[ValueSyntax (Syntax (Stx _ _ (Id "a"))), ValueSyntax (Syntax (Stx _ _ (Id "g")))] ->
pure ()
[_, _] -> assertFailure $ "Wrong example values: " ++ show exampleVals
_ -> assertFailure "Wrong number of examples in file"
)
, ( "examples/fun-exports.kl"
, \_m exampleVals ->
case exampleVals of
[ValueInteger a, ValueInteger b, ValueInteger c, ValueInteger d] -> do
a @?= 1
b @?= 2
c @?= 3
d @?= 4
_ ->
assertFailure "Expected four signals in example"
)
, ( "examples/fun-exports-test.kl"
, \_m exampleVals ->
case exampleVals of
[ValueInteger a, ValueInteger b, ValueInteger c] -> do
a @?= 1
b @?= 2
c @?= 3
_ ->
assertFailure "Expected three integers in example"
)
, ( "examples/syntax-loc.kl"
, \_m exampleVals ->
case exampleVals of
[ValueSyntax (Syntax (Stx _ loc1 (Id "here"))), ValueSyntax (Syntax (Stx _ loc2 (Id "here")))] -> do
let SrcLoc _ (SrcPos l1 c1) (SrcPos l2 c2) = loc1
SrcLoc _ (SrcPos l1' c1') (SrcPos l2' c2') = loc2
l1 @?= 3
c1 @?= 15
l2 @?= 3
c2 @?= 19
l1' @?= 5
c1' @?= 16
l2' @?= 5
c2' @?= 21
_ ->
assertFailure "Expected two identifiers in example"
)
, ( "examples/bound-identifier.kl"
, \_m exampleVals ->
case exampleVals of
[ValueSyntax (Syntax (Stx _ _ (Id a))), ValueSyntax (Syntax (Stx _ _ (Id b)))] -> do
assertAlphaEq "First example is true" a "t"
assertAlphaEq "Second example is false" b "f"
_ ->
assertFailure "Expected two symbols in example"
)
]
]
shouldn'tWork =
testGroup "Expected to fail"
[ testCase fn (testFileError fn p)
| (fn, p) <-
[ ( "examples/non-examples/import-phase.kl"
, \case
Unknown (Stx _ _ "define") -> True
_ -> False
)
, ( "examples/non-examples/missing-import.kl"
, \case
NotExported (Stx _ _ "magic") p -> p == runtime
_ -> False
)
, ( "examples/non-examples/type-errors.kl"
, \case
TypeCheckError (TypeMismatch (Just _) _ _ _) -> True
_ -> False
)
]
]
isEmpty [] = return ()
isEmpty _ = assertFailure "Expected empty, got non-empty"
testQuasiquoteExamples :: (Show t, Show sch, Show decl) => [Decl t sch decl Core] -> IO ()
testQuasiquoteExamples examples =
case examples of
[ Example _ _ e1, Example _ _ e2, Example _ _ e3, Example _ _ e4,
Example _ _ e5, Example _ _ e6, Example _ _ e7, Example _ _ e8 ] -> do
case e1 of
Core (CoreVar _) -> pure ()
other -> assertFailure ("Expected a var ref, got " ++ show other)
case e2 of
Core (CoreSyntax (Syntax (Stx _ _ (Id "thing")))) -> pure ()
other -> assertFailure ("Expected thing, got " ++ show other)
assertAlphaEq "Third and first example are the same" e3 e1
case e4 of
Core (CoreList (ScopedList [Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))] _)) -> pure ()
other -> assertFailure ("Expected (thing), got " ++ shortShow other)
case e5 of
Core (CoreList (ScopedList [expr] _)) ->
assertAlphaEq "the expression is e1" expr e1
other -> assertFailure ("Expected [nothing], got " ++ shortShow other)
case e6 of
Core (CoreList (ScopedList [ Core (CoreSyntax (Syntax (Stx _ _ (Id "list-syntax"))))
, Core (CoreList
(ScopedList [ expr
, Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))
]
_))
, _
]
_)) -> assertAlphaEq "the expression is e1" expr e1
other -> assertFailure ("Expected [list-syntax [nothing thing] thing], got " ++ shortShow other)
case e7 of
Core (CoreList (ScopedList [ Core (CoreSyntax (Syntax (Stx _ _ (Id "list-syntax"))))
, Core (CoreList
(ScopedList [ expr
, Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))
, Core (CoreEmpty _)
]
_))
, _
]
_)) -> assertAlphaEq "the expression is e1" expr e1
other -> assertFailure ("Expected [list-syntax [nothing thing ()] thing], got " ++ shortShow other)
-- assertFailure
case e8 of
Core (CoreList (ScopedList
[ Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))
, expr
, Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))
]
_)) -> assertAlphaEq "the expression is e1" expr e1
other -> assertFailure ("Expected [thing nothing thing], got " ++ shortShow other)
other -> assertFailure ("Expected 8 examples: " ++ show other)
testExpander :: Text -> IO Core -> Assertion
testExpander input spec = do
output <- spec
case readExpr "<test suite>" input of
Left err -> assertFailure . T.unpack $ err
Right expr -> do
ctx <- mkInitContext (KernelName kernelName)
c <- execExpand ctx $ completely $ do
initializeKernel stdout
initializeLanguage (Stx ScopeSet.empty testLoc (KernelName kernelName))
inEarlierPhase $
initializeLanguage (Stx ScopeSet.empty testLoc (KernelName kernelName))
addRootScope expr >>= addModuleScope >>= expandExpr
case c of
Left err -> assertFailure . T.unpack . pretty $ err
Right expanded ->
case runPartialCore $ unsplit expanded of
Nothing -> assertFailure "Incomplete expansion"
Just done -> assertAlphaEq (T.unpack input) output done
where testLoc = SrcLoc "test contents" (SrcPos 0 0) (SrcPos 0 0)
testExpansionFails :: Text -> (ExpansionErr -> Bool) -> Assertion
testExpansionFails input okp =
case readExpr "<test suite>" input of
Left err -> assertFailure . T.unpack $ err
Right expr -> do
ctx <- mkInitContext (KernelName kernelName)
c <- execExpand ctx $ completely $ do
initializeKernel stdout
initializeLanguage (Stx ScopeSet.empty testLoc (KernelName kernelName))
inEarlierPhase $
initializeLanguage (Stx ScopeSet.empty testLoc (KernelName kernelName))
expandExpr =<< addModuleScope =<< addRootScope expr
case c of
Left err
| okp err -> return ()
| otherwise ->
assertFailure $ "An error was expected but not this one: " ++ show err
Right expanded ->
case runPartialCore $ unsplit expanded of
Nothing -> assertFailure "Incomplete expansion"
Just _ -> assertFailure "Error expected, but expansion succeeded"
where testLoc = SrcLoc "test contents" (SrcPos 0 0) (SrcPos 0 0)
testFile :: FilePath -> (Module [] CompleteDecl -> [Value] -> Assertion) -> Assertion
testFile f p = do
mn <- moduleNameFromPath f
ctx <- mkInitContext mn
void $ execExpand ctx (initializeKernel stdout)
(execExpand ctx $ do
visit mn >> view expanderWorld <$> getState) >>=
\case
Left err -> assertFailure (T.unpack (pretty err))
Right w ->
view (worldModules . at mn) w &
\case
Nothing ->
assertFailure "No module found"
Just (KernelModule _) ->
assertFailure "Expected user module, got kernel"
Just (Expanded m _) ->
case Map.lookup mn (view worldEvaluated w) of
Nothing -> assertFailure "Module values not in its own expansion"
Just evalResults ->
p m [val | ExampleResult _ _ _ _ val <- evalResults]
testFileError :: FilePath -> (ExpansionErr -> Bool) -> Assertion
testFileError f p = do
mn <- moduleNameFromPath f
ctx <- mkInitContext mn
void $ execExpand ctx (initializeKernel stdout)
(execExpand ctx $ do
visit mn >> view expanderWorld <$> getState) >>=
\case
Left err | p err -> return ()
| otherwise ->
assertFailure $ "Expected a different error than " ++
T.unpack (pretty err)
Right _ -> assertFailure "Unexpected success expanding file"
assertAlphaEq :: (AlphaEq a, ShortShow a) => String -> a -> a -> Assertion
assertAlphaEq preface expected actual =
unless (alphaEq actual expected) (assertFailure msg)
where msg = (if null preface then "" else preface ++ "\n") ++
"expected: " ++ shortShow expected ++ "\n but got: " ++ shortShow actual
--------------------------------------------------------------------------------
Hedgehog
-- TODO(lb): Should we be accessing size parameters from the Gen monad to decide
-- these ranges?
range16 :: Range.Range Int
range16 = Range.linear 0 32
range32 :: Range.Range Int
range32 = Range.linear 0 32
range256 :: Range.Range Int
range256 = Range.linear 0 256
range1024 :: Range.Range Int
range1024 = Range.linear 0 1024
genPhase :: MonadGen m => m Phase
genPhase =
let more 0 phase = phase
more n phase = more (n - 1) (prior phase)
in more <$> Gen.int range256 <*> pure runtime
genScope :: MonadGen m => m Scope
genScope = Scope <$> Gen.int range1024 <*> Gen.text range16 Gen.lower
genSetScope :: MonadGen m => m (Set Scope)
genSetScope = Gen.set range32 genScope
genScopeSet :: MonadGen m => m ScopeSet
genScopeSet =
let more :: MonadGen m => Int -> ScopeSet -> m ScopeSet
more 0 ss = pure ss
more n ss = do
b <- Gen.choice [pure True, pure False]
more (n - 1) =<<
if b
then ScopeSet.insertAtPhase <$> genPhase <*> genScope <*> pure ss
else ScopeSet.insertUniversally <$> genScope <*> pure ss
in flip more ScopeSet.empty =<< Gen.int range256
genSrcPos :: MonadGen m => m SrcPos
genSrcPos = SrcPos <$> Gen.int range256 <*> Gen.int range256
genSrcLoc :: MonadGen m => m SrcLoc
genSrcLoc = SrcLoc <$> Gen.string range256 Gen.ascii <*> genSrcPos <*> genSrcPos
genStx :: MonadGen m => m a -> m (Stx a)
genStx subgen =
Stx
<$> genScopeSet
<*> genSrcLoc
<*> subgen
genIdent :: MonadGen m => m Ident
genIdent = genStx (Gen.text range256 Gen.ascii)
genVar :: GenT IO Var
genVar = liftIO $ Var <$> newUnique
genSyntaxError :: MonadGen m => m a -> m (SyntaxError a)
genSyntaxError subgen =
SyntaxError
<$> Gen.list range256 subgen
<*> subgen
genLam ::
(CoreF TypePattern ConstructorPattern Bool -> GenT IO a) ->
GenT IO (CoreF TypePattern ConstructorPattern a)
genLam subgen = do
ident <- Gen.generalize genIdent
var <- genVar
CoreLam ident var <$> subgen (CoreLam ident var True)
| Generate an instance of ' '
--
-- Subgenerators have access to both a list of identifiers and the knowledge of
which subtree of ' ' they 're being asked to generate .
genCoreF ::
forall a.
(Maybe (GenT IO Var) -> CoreF TypePattern ConstructorPattern Bool ->
GenT IO a) {- ^ Generic sub-generator -} ->
Maybe (GenT IO Var) {- ^ Variable generator -} ->
GenT IO (CoreF TypePattern ConstructorPattern a)
genCoreF subgen varGen =
let sameVars = subgen varGen
-- A unary constructor with no binding
unary ::
(forall b. b -> CoreF TypePattern ConstructorPattern b) ->
GenT IO (CoreF TypePattern ConstructorPattern a)
unary constructor = constructor <$> sameVars (constructor True)
-- A binary constructor with no binding
binary ::
(forall b. b -> b -> CoreF TypePattern ConstructorPattern b) ->
GenT IO (CoreF TypePattern ConstructorPattern a)
binary constructor =
constructor
<$> sameVars (constructor True False)
<*> sameVars (constructor False True)
nonRecursive =
[ (\b -> corePrimitiveCtor (if b then "true" else "false") []) <$> Gen.bool
, CoreInteger . fromIntegral <$> Gen.int range1024
] ++ map (fmap CoreVar) (maybeToList varGen)
recursive =
[ genLam sameVars
, binary CoreApp
, unary CorePureMacro
, binary CoreBindMacro
, CoreSyntaxError <$> genSyntaxError (sameVars (CoreSyntaxError (SyntaxError [] True)))
-- , CoreIdentEq _ <$> sameVars <*> sameVars
, CoreSyntax Syntax
, CoreCase sameVars [ ( Pattern , core ) ]
, core [ ( ConstructorPattern , core ) ]
, CoreIdent ( ScopedIdent core )
, CoreEmpty ( ScopedEmpty core )
, ( ScopedCons core )
, CoreVec ( ScopedVec core )
]
in Gen.recursive Gen.choice nonRecursive recursive
| Generate possibly - ill - scoped ' Core '
genAnyCore :: GenT IO Core
genAnyCore = Core <$> genCoreF (\_varGen _pos -> genAnyCore) (Just genVar)
| Generate well - scoped but possibly - ill - formed ' Core '
--
e.g. @f a@ where is not a lambda
genWellScopedCore :: GenT IO Core
genWellScopedCore =
sub : : Maybe ( GenT IO Var ) - > CoreF Bool - > GenT IO Core
sub vars pos = top $
case pos of
CoreLam _ var _ -> Just $ Gen.choice (pure var : maybeToList vars)
_ -> vars
top vars = Core <$> genCoreF sub vars
in top Nothing
propRunPartialCoreNonPartial :: Property
propRunPartialCoreNonPartial = property $ do
core <- Prop.forAllT $ genAnyCore
Just core === runPartialCore (nonPartial core)
propSplitUnsplit :: Property
propSplitUnsplit = property $ do
core <- Prop.forAllT $ genAnyCore
let part = nonPartial core
splitted <- liftIO $ split part
part === unsplit splitted
-- | Test that everything generated by 'genWellFormedCore' can be evaluated
--
-- TODO(lb) this needs to wait for a well-typed 'Core' generator
-- propEvalWellFormed :: Property
-- propEvalWellFormed =
-- property $ do
-- core <- Prop.forAllT $ genWellScopedCore
-- out <- liftIO $ runExceptT $ runReaderT (runEval (eval core)) Env.empty
-- True ===
-- case out of
-- Left _err -> False
-- Right _val -> True
| null | https://raw.githubusercontent.com/gelisam/klister/795393ce4f8c17489b8ca4f855b462db409c5514/tests/Test.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
[[lambda [x] body] e]
Make sure it's the use site in the macro body that
throws the error
assertFailure
------------------------------------------------------------------------------
TODO(lb): Should we be accessing size parameters from the Gen monad to decide
these ranges?
Subgenerators have access to both a list of identifiers and the knowledge of
^ Generic sub-generator
^ Variable generator
A unary constructor with no binding
A binary constructor with no binding
, CoreIdentEq _ <$> sameVars <*> sameVars
| Test that everything generated by 'genWellFormedCore' can be evaluated
TODO(lb) this needs to wait for a well-typed 'Core' generator
propEvalWellFormed :: Property
propEvalWellFormed =
property $ do
core <- Prop.forAllT $ genWellScopedCore
out <- liftIO $ runExceptT $ runReaderT (runEval (eval core)) Env.empty
True ===
case out of
Left _err -> False
Right _val -> True | # LANGUAGE BlockArguments #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
module Main where
import Control.Lens hiding (List)
import Control.Monad
import qualified Data.Map as Map
import Control.Monad.IO.Class (liftIO)
import Data.Maybe (maybeToList)
import Data.Text (Text)
import Data.Set (Set)
import System.IO (stdout)
import qualified Data.Text as T
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.Hedgehog (testProperty)
import Hedgehog hiding (eval, Var)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import qualified Hedgehog.Internal.Gen as Gen (generalize)
import qualified Hedgehog.Internal.Property as Prop (forAllT)
import Alpha
import Core
import Core.Builder
import Evaluator (EvalResult(..))
import Expander
import Expander.Monad
import Module
import ModuleName
import Parser
import PartialCore
import Phase (prior, runtime, Phased(..), Phase)
import Pretty
import Scope
import qualified ScopeSet
import ScopeSet (ScopeSet)
import ShortShow
import SplitCore
import Syntax.SrcLoc
import Syntax
import Unique
import Value
import World
import Golden
main :: IO ()
main = do
defaultMain =<< (tests <$> mkGoldenTests)
tests :: TestTree ->TestTree
tests goldenTests = testGroup "All tests"
[ testGroup "Expander tests" [ operationTests, miniTests, moduleTests ]
, testGroup "Hedgehog tests" [ testProperty
"runPartialCore . nonPartial = id"
(withTests 10 propRunPartialCoreNonPartial)
, testProperty
"unsplit . split = pure"
(withTests 10 propSplitUnsplit)
]
, goldenTests
]
operationTests :: TestTree
operationTests =
testGroup "Core operations"
[ testCase "Shifting core expressions" $
let sc = Scope 42 "Test suite"
scs = ScopeSet.insertAtPhase runtime sc ScopeSet.empty
stx = Syntax (Stx scs fakeLoc (Id "hey"))
expr = Core (CoreApp (Core (CoreInteger 2))
(Core (CoreSyntax stx)))
in case shift 1 expr of
Core (CoreApp (Core (CoreInteger 2))
(Core (CoreSyntax stx'))) ->
case stx' of
Syntax (Stx scs' _ (Id "hey")) ->
if scs' == ScopeSet.insertAtPhase (prior runtime) sc ScopeSet.empty
then pure ()
else assertFailure $ "Shifting gave wrong scopes" ++ show scs'
Syntax _ -> assertFailure "Wrong shape in shifted syntax"
_ -> assertFailure "Shifting didn't preserve structure!"
]
miniTests :: TestTree
miniTests =
testGroup "Mini-tests" [ expectedSuccess, expectedFailure]
where
expectedSuccess =
testGroup "Expected to succeed"
[ testCase name (testExpander input output)
| (name, input, output) <-
[ ( "[lambda [x] x]"
, "[lambda [x] x]"
, lam $ \x -> x
)
, ( "[lambda [x] [lambda [x] x]]"
, "[lambda [x] [lambda [x] x]]"
, lam $ \_ -> lam $ \y -> y
)
, ( "42"
, "42"
, int 42
)
, ( "[lambda [f] [lambda [x] [f x]]]"
, "[lambda [f] [lambda [x] [f x]]]"
, lam $ \f -> lam $ \x -> f `app` x
)
, ( "Trivial user macro"
, "[let-syntax \n\
\ [m [lambda [_] \n\
\ [pure [quote [lambda [x] x]]]]] \n\
\ m]"
, lam $ \x -> x
)
, ( "Let macro"
, "[let-syntax \n\
\ [let1 [lambda [stx] \n\
\ (syntax-case stx \n\
\ [[list [_ binder body]] \n\
\ (syntax-case binder \n\
\ [[list [x e]] \n\
\ [pure [list-syntax \n\
\ [[list-syntax \n\
\ [[ident-syntax 'lambda stx] \n\
\ [list-syntax [x] stx] \n\
\ body] \n\
\ stx] \n\
\ e] \n\
\ stx]]])])]] \n\
\ [let1 [x [lambda [x] x]] \n\
\ x]]"
, (lam $ \x -> x) `app` (lam $ \x -> x)
)
]
]
expectedFailure =
testGroup "Expected to fail"
[ testCase name (testExpansionFails input predicate)
| (name, input, predicate) <-
[ ( "unbound variable and nothing else"
, "x"
, \case
Unknown (Stx _ _ "x") -> True
_ -> False
)
, ( "unbound variable inside let-syntax"
, "[let-syntax \
\ [m [lambda [_] \
\ [pure [quote [lambda [x] x]]]]] \
\ anyRandomWord]"
, \case
Unknown (Stx _ _ "anyRandomWord") -> True
_ -> False
)
, ( "refer to a local variable from a future phase"
, "[lambda [x] [let-syntax [m [lambda [_] x]] x]]"
, \case
Unknown (Stx _ _ "x") -> True
_ -> False
)
, ( "a macro calls itself"
, "[let-syntax [m [lambda [x] [m x]]] m]"
, \case
Unknown (Stx _ loc "m") ->
view (srcLocStart . srcPosCol) loc == 29
_ -> False
)
]
]
moduleTests :: TestTree
moduleTests = testGroup "Module tests" [ shouldWork, shouldn'tWork ]
where
shouldWork =
testGroup "Expected to succeed"
[ testCase fn (testFile fn p)
| (fn, p) <-
[ ( "examples/small.kl"
, \m _ -> isEmpty (view moduleBody m)
)
, ( "examples/two-defs.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
filter (\case {(Define {}) -> True; _ -> False}) &
\case
[Define {}, Define {}] -> pure ()
_ -> assertFailure "Expected two definitions"
)
, ( "examples/id-compare.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
filter (\case {(Example _ _ _) -> True; _ -> False}) &
\case
[Example _ _ e1, Example _ _ e2] -> do
assertAlphaEq "first example" e1 (Core (corePrimitiveCtor "true" []))
assertAlphaEq "second example" e2 (Core (corePrimitiveCtor "false" []))
_ -> assertFailure "Expected two examples"
)
, ( "examples/lang.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
[Define _fn fv _t fbody, Example _ _ e] -> do
fspec <- lam \_x -> lam \ y -> lam \_z -> y
assertAlphaEq "definition of f" fbody fspec
case e of
Core (CoreApp (Core (CoreApp (Core (CoreApp (Core (CoreVar fv')) _)) _)) _) ->
assertAlphaEq "function position in example" fv' fv
_ -> assertFailure "example has wrong shape"
_ -> assertFailure "Expected two examples"
)
, ( "examples/import.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
filter (\case {(Example _ _ _) -> True; _ -> False}) &
\case
[Example _ _ e1, Example _ _ e2] -> do
case e1 of
(Core (CoreApp (Core (CoreApp (Core (CoreVar _)) _)) _)) ->
pure ()
_ -> assertFailure "example 1 has wrong shape"
case e2 of
Core (CoreApp (Core (CoreApp (Core (CoreApp fun _)) _)) _) -> do
fspec <- lam \_x -> lam \ y -> lam \_z -> y
assertAlphaEq "function in second example" fun fspec
_ -> assertFailure "example 2 has wrong shape"
_ -> assertFailure "Expected two examples"
)
, ( "examples/phase1.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
[Import _,
Meta [ view completeDecl -> Define _ _ _ _
, view completeDecl -> Define _ _ _ _
],
DefineMacros [(_, _, _)],
Example _ _ ex] ->
assertAlphaEq "Example is integer" ex (Core (CoreInteger 1))
_ -> assertFailure "Expected an import, two meta-defs, a macro def, and an example"
)
, ( "examples/imports-shifted-macro.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
[Import _, Import _, DefineMacros [(_, _, _)], Example _ _ ex] ->
assertAlphaEq "Example is (false)" ex (Core (corePrimitiveCtor "false" []))
_ -> assertFailure "Expected import, import, macro, example"
)
, ( "examples/macro-body-shift.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
[Import _, Define _ _ _ e, DefineMacros [(_, _, _)]] -> do
spec <- lam \_x -> lam \y -> lam \_z -> y
assertAlphaEq "Definition is λx y z . y" e spec
_ -> assertFailure "Expected an import, a definition, and a macro"
)
, ( "examples/test-quasiquote.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
(Import _ : Import _ : Define _ _ _ thingDef : examples) -> do
case thingDef of
Core (CoreSyntax (Syntax (Stx _ _ (Id "nothing")))) ->
case examples of
[e1, e2, e3, e4, e5, e6, e7, e8, Example _ _ _] -> do
testQuasiquoteExamples [e1, e2, e3, e4, e5, e6, e7, e8]
other -> assertFailure ("Expected 8 tested examples, 1 untested: " ++ show other)
other -> assertFailure ("Unexpected thing def " ++ show other)
_ -> assertFailure "Expected two imports, a definition, and examples"
)
, ( "examples/quasiquote-syntax-test.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
(Import _ : _ : _ : Define _ _ _ thingDef : examples) -> do
case thingDef of
Core (CoreSyntax (Syntax (Stx _ _ (Id "nothing")))) ->
case examples of
[e1, e2, e3, e4, e5, e6, e7, e8] -> do
testQuasiquoteExamples [e1, e2, e3, e4, e5, e6, e7, e8]
other -> assertFailure ("Expected 8 examples and 2 exports: " ++ show other)
other -> assertFailure ("Unexpected thing def " ++ show other)
_ -> assertFailure "Expected an import, two macros, a definition, and examples"
)
, ( "examples/hygiene.kl"
, \m _ ->
view moduleBody m & map (view completeDecl) &
\case
(Import _ : Import _ : Import _ : Import _ : Define _ fun1 _ firstFun : DefineMacros [_] :
Define _ fun2 _ secondFun : Example _ _ e1 : Example _ _ e2 : DefineMacros [_] :
Example _ _ e3 : _) -> do
spec1 <- lam \x -> lam \_y -> x
spec2 <- lam \_x -> lam \y -> y
assertAlphaEq "First fun drops second argument" firstFun spec1
assertAlphaEq "Second fun drops first argument" secondFun spec2
case e1 of
Core (CoreApp (Core (CoreApp f _)) _) ->
assertAlphaEq "Ex 1 picks fun 2" (Core (CoreVar fun2)) f
other -> assertFailure $ "Ex 1 should be an application, but it's " ++ shortShow other
case e2 of
Core (CoreApp (Core (CoreApp f _)) _) ->
assertAlphaEq "Ex 2 picks fun 1" (Core (CoreVar fun1)) f
other -> assertFailure $ "Ex 2 should be an application, but it's " ++ shortShow other
spec3 <- lam (const (pure (Core (CoreVar fun2))))
case e3 of
Core (CoreApp (Core (CoreApp (Core (CoreApp f _)) _)) _) ->
assertAlphaEq "Ex 3 picks fun 2" f spec3
other -> assertFailure $ "Ex 3 should be an application, but it's " ++ shortShow other
_ -> assertFailure "Expected two imports, a def, a macro, a def, two examples, a macro, and an example"
)
, ( "examples/defun-test.kl"
, \_m exampleVals ->
case exampleVals of
[ValueSyntax (Syntax (Stx _ _ (Id "a"))), ValueSyntax (Syntax (Stx _ _ (Id "g")))] ->
pure ()
[_, _] -> assertFailure $ "Wrong example values: " ++ show exampleVals
_ -> assertFailure "Wrong number of examples in file"
)
, ( "examples/fun-exports.kl"
, \_m exampleVals ->
case exampleVals of
[ValueInteger a, ValueInteger b, ValueInteger c, ValueInteger d] -> do
a @?= 1
b @?= 2
c @?= 3
d @?= 4
_ ->
assertFailure "Expected four signals in example"
)
, ( "examples/fun-exports-test.kl"
, \_m exampleVals ->
case exampleVals of
[ValueInteger a, ValueInteger b, ValueInteger c] -> do
a @?= 1
b @?= 2
c @?= 3
_ ->
assertFailure "Expected three integers in example"
)
, ( "examples/syntax-loc.kl"
, \_m exampleVals ->
case exampleVals of
[ValueSyntax (Syntax (Stx _ loc1 (Id "here"))), ValueSyntax (Syntax (Stx _ loc2 (Id "here")))] -> do
let SrcLoc _ (SrcPos l1 c1) (SrcPos l2 c2) = loc1
SrcLoc _ (SrcPos l1' c1') (SrcPos l2' c2') = loc2
l1 @?= 3
c1 @?= 15
l2 @?= 3
c2 @?= 19
l1' @?= 5
c1' @?= 16
l2' @?= 5
c2' @?= 21
_ ->
assertFailure "Expected two identifiers in example"
)
, ( "examples/bound-identifier.kl"
, \_m exampleVals ->
case exampleVals of
[ValueSyntax (Syntax (Stx _ _ (Id a))), ValueSyntax (Syntax (Stx _ _ (Id b)))] -> do
assertAlphaEq "First example is true" a "t"
assertAlphaEq "Second example is false" b "f"
_ ->
assertFailure "Expected two symbols in example"
)
]
]
shouldn'tWork =
testGroup "Expected to fail"
[ testCase fn (testFileError fn p)
| (fn, p) <-
[ ( "examples/non-examples/import-phase.kl"
, \case
Unknown (Stx _ _ "define") -> True
_ -> False
)
, ( "examples/non-examples/missing-import.kl"
, \case
NotExported (Stx _ _ "magic") p -> p == runtime
_ -> False
)
, ( "examples/non-examples/type-errors.kl"
, \case
TypeCheckError (TypeMismatch (Just _) _ _ _) -> True
_ -> False
)
]
]
isEmpty [] = return ()
isEmpty _ = assertFailure "Expected empty, got non-empty"
testQuasiquoteExamples :: (Show t, Show sch, Show decl) => [Decl t sch decl Core] -> IO ()
testQuasiquoteExamples examples =
case examples of
[ Example _ _ e1, Example _ _ e2, Example _ _ e3, Example _ _ e4,
Example _ _ e5, Example _ _ e6, Example _ _ e7, Example _ _ e8 ] -> do
case e1 of
Core (CoreVar _) -> pure ()
other -> assertFailure ("Expected a var ref, got " ++ show other)
case e2 of
Core (CoreSyntax (Syntax (Stx _ _ (Id "thing")))) -> pure ()
other -> assertFailure ("Expected thing, got " ++ show other)
assertAlphaEq "Third and first example are the same" e3 e1
case e4 of
Core (CoreList (ScopedList [Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))] _)) -> pure ()
other -> assertFailure ("Expected (thing), got " ++ shortShow other)
case e5 of
Core (CoreList (ScopedList [expr] _)) ->
assertAlphaEq "the expression is e1" expr e1
other -> assertFailure ("Expected [nothing], got " ++ shortShow other)
case e6 of
Core (CoreList (ScopedList [ Core (CoreSyntax (Syntax (Stx _ _ (Id "list-syntax"))))
, Core (CoreList
(ScopedList [ expr
, Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))
]
_))
, _
]
_)) -> assertAlphaEq "the expression is e1" expr e1
other -> assertFailure ("Expected [list-syntax [nothing thing] thing], got " ++ shortShow other)
case e7 of
Core (CoreList (ScopedList [ Core (CoreSyntax (Syntax (Stx _ _ (Id "list-syntax"))))
, Core (CoreList
(ScopedList [ expr
, Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))
, Core (CoreEmpty _)
]
_))
, _
]
_)) -> assertAlphaEq "the expression is e1" expr e1
other -> assertFailure ("Expected [list-syntax [nothing thing ()] thing], got " ++ shortShow other)
case e8 of
Core (CoreList (ScopedList
[ Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))
, expr
, Core (CoreSyntax (Syntax (Stx _ _ (Id "thing"))))
]
_)) -> assertAlphaEq "the expression is e1" expr e1
other -> assertFailure ("Expected [thing nothing thing], got " ++ shortShow other)
other -> assertFailure ("Expected 8 examples: " ++ show other)
testExpander :: Text -> IO Core -> Assertion
testExpander input spec = do
output <- spec
case readExpr "<test suite>" input of
Left err -> assertFailure . T.unpack $ err
Right expr -> do
ctx <- mkInitContext (KernelName kernelName)
c <- execExpand ctx $ completely $ do
initializeKernel stdout
initializeLanguage (Stx ScopeSet.empty testLoc (KernelName kernelName))
inEarlierPhase $
initializeLanguage (Stx ScopeSet.empty testLoc (KernelName kernelName))
addRootScope expr >>= addModuleScope >>= expandExpr
case c of
Left err -> assertFailure . T.unpack . pretty $ err
Right expanded ->
case runPartialCore $ unsplit expanded of
Nothing -> assertFailure "Incomplete expansion"
Just done -> assertAlphaEq (T.unpack input) output done
where testLoc = SrcLoc "test contents" (SrcPos 0 0) (SrcPos 0 0)
testExpansionFails :: Text -> (ExpansionErr -> Bool) -> Assertion
testExpansionFails input okp =
case readExpr "<test suite>" input of
Left err -> assertFailure . T.unpack $ err
Right expr -> do
ctx <- mkInitContext (KernelName kernelName)
c <- execExpand ctx $ completely $ do
initializeKernel stdout
initializeLanguage (Stx ScopeSet.empty testLoc (KernelName kernelName))
inEarlierPhase $
initializeLanguage (Stx ScopeSet.empty testLoc (KernelName kernelName))
expandExpr =<< addModuleScope =<< addRootScope expr
case c of
Left err
| okp err -> return ()
| otherwise ->
assertFailure $ "An error was expected but not this one: " ++ show err
Right expanded ->
case runPartialCore $ unsplit expanded of
Nothing -> assertFailure "Incomplete expansion"
Just _ -> assertFailure "Error expected, but expansion succeeded"
where testLoc = SrcLoc "test contents" (SrcPos 0 0) (SrcPos 0 0)
testFile :: FilePath -> (Module [] CompleteDecl -> [Value] -> Assertion) -> Assertion
testFile f p = do
mn <- moduleNameFromPath f
ctx <- mkInitContext mn
void $ execExpand ctx (initializeKernel stdout)
(execExpand ctx $ do
visit mn >> view expanderWorld <$> getState) >>=
\case
Left err -> assertFailure (T.unpack (pretty err))
Right w ->
view (worldModules . at mn) w &
\case
Nothing ->
assertFailure "No module found"
Just (KernelModule _) ->
assertFailure "Expected user module, got kernel"
Just (Expanded m _) ->
case Map.lookup mn (view worldEvaluated w) of
Nothing -> assertFailure "Module values not in its own expansion"
Just evalResults ->
p m [val | ExampleResult _ _ _ _ val <- evalResults]
testFileError :: FilePath -> (ExpansionErr -> Bool) -> Assertion
testFileError f p = do
mn <- moduleNameFromPath f
ctx <- mkInitContext mn
void $ execExpand ctx (initializeKernel stdout)
(execExpand ctx $ do
visit mn >> view expanderWorld <$> getState) >>=
\case
Left err | p err -> return ()
| otherwise ->
assertFailure $ "Expected a different error than " ++
T.unpack (pretty err)
Right _ -> assertFailure "Unexpected success expanding file"
assertAlphaEq :: (AlphaEq a, ShortShow a) => String -> a -> a -> Assertion
assertAlphaEq preface expected actual =
unless (alphaEq actual expected) (assertFailure msg)
where msg = (if null preface then "" else preface ++ "\n") ++
"expected: " ++ shortShow expected ++ "\n but got: " ++ shortShow actual
Hedgehog
range16 :: Range.Range Int
range16 = Range.linear 0 32
range32 :: Range.Range Int
range32 = Range.linear 0 32
range256 :: Range.Range Int
range256 = Range.linear 0 256
range1024 :: Range.Range Int
range1024 = Range.linear 0 1024
genPhase :: MonadGen m => m Phase
genPhase =
let more 0 phase = phase
more n phase = more (n - 1) (prior phase)
in more <$> Gen.int range256 <*> pure runtime
genScope :: MonadGen m => m Scope
genScope = Scope <$> Gen.int range1024 <*> Gen.text range16 Gen.lower
genSetScope :: MonadGen m => m (Set Scope)
genSetScope = Gen.set range32 genScope
genScopeSet :: MonadGen m => m ScopeSet
genScopeSet =
let more :: MonadGen m => Int -> ScopeSet -> m ScopeSet
more 0 ss = pure ss
more n ss = do
b <- Gen.choice [pure True, pure False]
more (n - 1) =<<
if b
then ScopeSet.insertAtPhase <$> genPhase <*> genScope <*> pure ss
else ScopeSet.insertUniversally <$> genScope <*> pure ss
in flip more ScopeSet.empty =<< Gen.int range256
genSrcPos :: MonadGen m => m SrcPos
genSrcPos = SrcPos <$> Gen.int range256 <*> Gen.int range256
genSrcLoc :: MonadGen m => m SrcLoc
genSrcLoc = SrcLoc <$> Gen.string range256 Gen.ascii <*> genSrcPos <*> genSrcPos
genStx :: MonadGen m => m a -> m (Stx a)
genStx subgen =
Stx
<$> genScopeSet
<*> genSrcLoc
<*> subgen
genIdent :: MonadGen m => m Ident
genIdent = genStx (Gen.text range256 Gen.ascii)
genVar :: GenT IO Var
genVar = liftIO $ Var <$> newUnique
genSyntaxError :: MonadGen m => m a -> m (SyntaxError a)
genSyntaxError subgen =
SyntaxError
<$> Gen.list range256 subgen
<*> subgen
genLam ::
(CoreF TypePattern ConstructorPattern Bool -> GenT IO a) ->
GenT IO (CoreF TypePattern ConstructorPattern a)
genLam subgen = do
ident <- Gen.generalize genIdent
var <- genVar
CoreLam ident var <$> subgen (CoreLam ident var True)
| Generate an instance of ' '
which subtree of ' ' they 're being asked to generate .
genCoreF ::
forall a.
(Maybe (GenT IO Var) -> CoreF TypePattern ConstructorPattern Bool ->
GenT IO (CoreF TypePattern ConstructorPattern a)
genCoreF subgen varGen =
let sameVars = subgen varGen
unary ::
(forall b. b -> CoreF TypePattern ConstructorPattern b) ->
GenT IO (CoreF TypePattern ConstructorPattern a)
unary constructor = constructor <$> sameVars (constructor True)
binary ::
(forall b. b -> b -> CoreF TypePattern ConstructorPattern b) ->
GenT IO (CoreF TypePattern ConstructorPattern a)
binary constructor =
constructor
<$> sameVars (constructor True False)
<*> sameVars (constructor False True)
nonRecursive =
[ (\b -> corePrimitiveCtor (if b then "true" else "false") []) <$> Gen.bool
, CoreInteger . fromIntegral <$> Gen.int range1024
] ++ map (fmap CoreVar) (maybeToList varGen)
recursive =
[ genLam sameVars
, binary CoreApp
, unary CorePureMacro
, binary CoreBindMacro
, CoreSyntaxError <$> genSyntaxError (sameVars (CoreSyntaxError (SyntaxError [] True)))
, CoreSyntax Syntax
, CoreCase sameVars [ ( Pattern , core ) ]
, core [ ( ConstructorPattern , core ) ]
, CoreIdent ( ScopedIdent core )
, CoreEmpty ( ScopedEmpty core )
, ( ScopedCons core )
, CoreVec ( ScopedVec core )
]
in Gen.recursive Gen.choice nonRecursive recursive
| Generate possibly - ill - scoped ' Core '
genAnyCore :: GenT IO Core
genAnyCore = Core <$> genCoreF (\_varGen _pos -> genAnyCore) (Just genVar)
| Generate well - scoped but possibly - ill - formed ' Core '
e.g. @f a@ where is not a lambda
genWellScopedCore :: GenT IO Core
genWellScopedCore =
sub : : Maybe ( GenT IO Var ) - > CoreF Bool - > GenT IO Core
sub vars pos = top $
case pos of
CoreLam _ var _ -> Just $ Gen.choice (pure var : maybeToList vars)
_ -> vars
top vars = Core <$> genCoreF sub vars
in top Nothing
propRunPartialCoreNonPartial :: Property
propRunPartialCoreNonPartial = property $ do
core <- Prop.forAllT $ genAnyCore
Just core === runPartialCore (nonPartial core)
propSplitUnsplit :: Property
propSplitUnsplit = property $ do
core <- Prop.forAllT $ genAnyCore
let part = nonPartial core
splitted <- liftIO $ split part
part === unsplit splitted
|
99d169924eb9067b0e7d76ffb1d5155287224a2cebb9eb7a2a981b40ae90b833 | janestreet/bonsai | update_options.ml | open! Core
open! Import
open Gen_js_api
type t = Ojs.t
let t_to_js x = x
let t_of_js x = x
let create ?options ?data () =
(* This is intentionally different than an object with a property "options". *)
let options =
let default = Ojs.empty_obj () in
Option.value_map options ~default ~f:Options.t_to_js
in
Option.iter data ~f:(fun data -> Ojs.set_prop_ascii options "file" (Data.t_to_js data));
options
;;
| null | https://raw.githubusercontent.com/janestreet/bonsai/c202b961f41e20e0b735c4e33c2bbac57a590941/bindings/dygraph/src/update_options.ml | ocaml | This is intentionally different than an object with a property "options". | open! Core
open! Import
open Gen_js_api
type t = Ojs.t
let t_to_js x = x
let t_of_js x = x
let create ?options ?data () =
let options =
let default = Ojs.empty_obj () in
Option.value_map options ~default ~f:Options.t_to_js
in
Option.iter data ~f:(fun data -> Ojs.set_prop_ascii options "file" (Data.t_to_js data));
options
;;
|
250ae8b190facb3f3dffa136dffdc08be1d901abb5d2d97edbacb0cf066a4297 | yallop/causal-commutative-arrows-revisited | Sample.hs | {-# LANGUAGE Arrows #-}
module Sample where
import Control.Arrow
import Control.CCA.Types
import Control.CCA.Instances
import SigFun
import Prelude hiding (init, exp)
sr = 44100 :: Int
dt = 1 / (fromIntegral sr)
exp :: ArrowInit a => a () Double
exp = proc () -> do
rec let e = 1 + i
i <- integral -< e
returnA -< e
-- SPECIALIZE INLINE would make SF version even slower!
-- {-# SPECIALIZE INLINE exp :: SF () Double #-}
# SPECIALIZE INLINE exp : : CCNF_D ( ) Double #
# SPECIALIZE INLINE exp : : CCNF_ST s ( ) Double #
integral :: ArrowInit a => a Double Double
integral = proc x -> do
rec let i' = i + x * dt
i <- init 0 -< i'
returnA -< i
-- alternatively, we could define intergral directly as loopD,
-- which helps CCNF_ST signficantly by skip the direct use of
loop combinator , because loop uses mfix with a significant
-- overhead.
-- integral = loopD 0 (\ (x, i) -> (i, i + dt * x))
sine :: ArrowInit a => Double -> a () Double
sine freq = proc _ -> do
rec x <- init i -< r
y <- init 0 -< x
let r = c * x - y
returnA -< r
where
omh = 2 * pi / (fromIntegral sr) * freq
# NOINLINE omh #
i = sin omh
# NOINLINE i #
c = 2 * cos omh
# NOINLINE c #
-- SPECIALIZE INLINE would make SF version even slower!
-- {-# SPECIALIZE INLINE sine :: Double -> SF () Double #-}
{-# SPECIALIZE INLINE sine :: Double -> CCNF_D () Double #-}
{-# SPECIALIZE INLINE sine :: Double -> CCNF_ST s () Double #-}
oscSine :: ArrowInit a => Double -> a Double Double
oscSine f0 = proc cv -> do
let f = f0 * (2 ** cv)
phi <- integral -< 2 * pi * f
returnA -< sin phi
testOsc :: ArrowInit a => (Double -> a Double Double) -> a () Double
testOsc f = arr (\_ -> 1) >>> f 440
oscSineA :: ArrowInit a => a () Double
oscSineA = testOsc oscSine
-- SPECIALIZE INLINE would make SF version even slower!
-- {-# SPECIALIZE INLINE oscSineA :: SF () Double #-}
# SPECIALIZE INLINE oscSineA : : CCNF_D ( ) Double #
# SPECIALIZE INLINE oscSineA : : CCNF_ST s ( ) Double #
sciFi :: ArrowInit a => a () Double
sciFi = proc () -> do
und <- oscSine 3.0 -< 0
swp <- integral -< -0.25
audio <- oscSine 440 -< und * 0.2 + swp + 1
returnA -< audio
-- SPECIALIZE INLINE would make SF version even slower!
-- {-# SPECIALIZE INLINE sciFi :: SF () Double #-}
{-# SPECIALIZE INLINE sciFi :: CCNF_D () Double #-}
{-# SPECIALIZE INLINE sciFi :: CCNF_ST s () Double #-}
robot :: ArrowInit a => a (Double, Double) Double
robot = proc inp -> do
let vr = snd inp
vl = fst inp
vz = vr + vl
t <- integral -< vr - vl
let t' = t / 10
x <- integral -< vz * cos t'
y <- integral -< vz * sin t'
returnA -< x / 2 + y / 2
testRobot :: ArrowInit a => a (Double, Double) Double -> a () Double
testRobot bot = proc () -> do
u <- sine 2 -< ()
robot -< (u, 1 - u)
robotA :: ArrowInit a => a () Double
robotA = testRobot robot
-- SPECIALIZE INLINE would make SF version even slower!
-- {-# SPECIALIZE INLINE robotA :: SF () Double #-}
{-# SPECIALIZE INLINE robotA :: CCNF_D () Double #-}
{-# SPECIALIZE INLINE robotA :: CCNF_ST s () Double #-}
fibA :: ArrowInit arr => arr () Integer
fibA = proc _ -> do
rec let r = d2 + d1
d1 <- init 0 -< d2
d2 <- init 1 -< r
returnA -< r
-- SPECIALIZE INLINE would make SF version even slower!
-- {-# SPECIALIZE INLINE fibA :: SF () Integer #-}
{-# SPECIALIZE INLINE fibA :: CCNF_D () Integer #-}
{-# SPECIALIZE INLINE fibA :: CCNF_ST s () Integer #-}
| null | https://raw.githubusercontent.com/yallop/causal-commutative-arrows-revisited/95aaadd8c79f39972a1c83ad7f9961cc3bf7974f/test/Sample.hs | haskell | # LANGUAGE Arrows #
SPECIALIZE INLINE would make SF version even slower!
{-# SPECIALIZE INLINE exp :: SF () Double #-}
alternatively, we could define intergral directly as loopD,
which helps CCNF_ST signficantly by skip the direct use of
overhead.
integral = loopD 0 (\ (x, i) -> (i, i + dt * x))
SPECIALIZE INLINE would make SF version even slower!
{-# SPECIALIZE INLINE sine :: Double -> SF () Double #-}
# SPECIALIZE INLINE sine :: Double -> CCNF_D () Double #
# SPECIALIZE INLINE sine :: Double -> CCNF_ST s () Double #
SPECIALIZE INLINE would make SF version even slower!
{-# SPECIALIZE INLINE oscSineA :: SF () Double #-}
SPECIALIZE INLINE would make SF version even slower!
{-# SPECIALIZE INLINE sciFi :: SF () Double #-}
# SPECIALIZE INLINE sciFi :: CCNF_D () Double #
# SPECIALIZE INLINE sciFi :: CCNF_ST s () Double #
SPECIALIZE INLINE would make SF version even slower!
{-# SPECIALIZE INLINE robotA :: SF () Double #-}
# SPECIALIZE INLINE robotA :: CCNF_D () Double #
# SPECIALIZE INLINE robotA :: CCNF_ST s () Double #
SPECIALIZE INLINE would make SF version even slower!
{-# SPECIALIZE INLINE fibA :: SF () Integer #-}
# SPECIALIZE INLINE fibA :: CCNF_D () Integer #
# SPECIALIZE INLINE fibA :: CCNF_ST s () Integer # | module Sample where
import Control.Arrow
import Control.CCA.Types
import Control.CCA.Instances
import SigFun
import Prelude hiding (init, exp)
sr = 44100 :: Int
dt = 1 / (fromIntegral sr)
exp :: ArrowInit a => a () Double
exp = proc () -> do
rec let e = 1 + i
i <- integral -< e
returnA -< e
# SPECIALIZE INLINE exp : : CCNF_D ( ) Double #
# SPECIALIZE INLINE exp : : CCNF_ST s ( ) Double #
integral :: ArrowInit a => a Double Double
integral = proc x -> do
rec let i' = i + x * dt
i <- init 0 -< i'
returnA -< i
loop combinator , because loop uses mfix with a significant
sine :: ArrowInit a => Double -> a () Double
sine freq = proc _ -> do
rec x <- init i -< r
y <- init 0 -< x
let r = c * x - y
returnA -< r
where
omh = 2 * pi / (fromIntegral sr) * freq
# NOINLINE omh #
i = sin omh
# NOINLINE i #
c = 2 * cos omh
# NOINLINE c #
oscSine :: ArrowInit a => Double -> a Double Double
oscSine f0 = proc cv -> do
let f = f0 * (2 ** cv)
phi <- integral -< 2 * pi * f
returnA -< sin phi
testOsc :: ArrowInit a => (Double -> a Double Double) -> a () Double
testOsc f = arr (\_ -> 1) >>> f 440
oscSineA :: ArrowInit a => a () Double
oscSineA = testOsc oscSine
# SPECIALIZE INLINE oscSineA : : CCNF_D ( ) Double #
# SPECIALIZE INLINE oscSineA : : CCNF_ST s ( ) Double #
sciFi :: ArrowInit a => a () Double
sciFi = proc () -> do
und <- oscSine 3.0 -< 0
swp <- integral -< -0.25
audio <- oscSine 440 -< und * 0.2 + swp + 1
returnA -< audio
robot :: ArrowInit a => a (Double, Double) Double
robot = proc inp -> do
let vr = snd inp
vl = fst inp
vz = vr + vl
t <- integral -< vr - vl
let t' = t / 10
x <- integral -< vz * cos t'
y <- integral -< vz * sin t'
returnA -< x / 2 + y / 2
testRobot :: ArrowInit a => a (Double, Double) Double -> a () Double
testRobot bot = proc () -> do
u <- sine 2 -< ()
robot -< (u, 1 - u)
robotA :: ArrowInit a => a () Double
robotA = testRobot robot
fibA :: ArrowInit arr => arr () Integer
fibA = proc _ -> do
rec let r = d2 + d1
d1 <- init 0 -< d2
d2 <- init 1 -< r
returnA -< r
|
e55d19809944e11af75445cd7c975afc64e09428781fd54882d0d4437a06c51f | Paczesiowa/virthualenv | Actions.hs | module Actions ( cabalUpdate
, installCabalConfig
, installCabalWrapper
, installActivateScript
, copyBaseSystem
, initGhcDb
, installGhc
, createDirStructure
) where
import System.Directory (setCurrentDirectory, getCurrentDirectory, createDirectory, removeDirectoryRecursive)
import System.FilePath ((</>))
import Distribution.Version (Version (..))
import Distribution.Package (PackageName(..))
import Safe (lastMay)
import Data.List (intercalate)
import MyMonad
import Types
import Paths
import PackageManagement
import Process
import Util.Template (substs)
import Util.IO (makeExecutable, createTemporaryDirectory)
import Skeletons
update cabal package info inside Virtual Haskell Environmentn
cabalUpdate :: MyMonad ()
cabalUpdate = do
env <- getVirtualEnvironment
cabalConfig <- cabalConfigLocation
info "Updating cabal package database inside Virtual Haskell Environment."
_ <- indentMessages $ runProcess (Just env) "cabal" ["--config-file=" ++ cabalConfig, "update"] Nothing
return ()
-- install cabal wrapper (in bin/ directory) inside virtual environment dir structure
installCabalWrapper :: MyMonad ()
installCabalWrapper = do
cabalConfig <- cabalConfigLocation
dirStructure <- vheDirStructure
let cabalWrapper = virthualEnvBinDir dirStructure </> "cabal"
info $ concat [ "Installing cabal wrapper using "
, cabalConfig
, " at "
, cabalWrapper
]
let cabalWrapperContents = substs [("<CABAL_CONFIG>", cabalConfig)] cabalWrapperSkel
indentMessages $ do
trace "cabal wrapper contents:"
indentMessages $ mapM_ trace $ lines cabalWrapperContents
liftIO $ writeFile cabalWrapper cabalWrapperContents
liftIO $ makeExecutable cabalWrapper
installActivateScriptSupportFiles :: MyMonad ()
installActivateScriptSupportFiles = do
debug "installing supporting files"
dirStructure <- vheDirStructure
ghc <- asks ghcSource
indentMessages $ do
let pathVarPrependixLocation = virthualEnvDir dirStructure </> "path_var_prependix"
pathVarElems =
case ghc of
System -> [virthualEnvBinDir dirStructure, cabalBinDir dirStructure]
Tarball _ -> [ virthualEnvBinDir dirStructure
, cabalBinDir dirStructure
, ghcBinDir dirStructure
]
pathVarPrependix = intercalate ":" pathVarElems
debug $ "installing path_var_prependix file to " ++ pathVarPrependixLocation
indentMessages $ trace $ "path_var_prependix contents: " ++ pathVarPrependix
liftIO $ writeFile pathVarPrependixLocation pathVarPrependix
ghcPkgDbPath <- indentMessages ghcPkgDbPathLocation
let ghcPackagePathVarLocation = virthualEnvDir dirStructure </> "ghc_package_path_var"
ghcPackagePathVar = ghcPkgDbPath
debug $ "installing ghc_package_path_var file to " ++ ghcPackagePathVarLocation
indentMessages $ trace $ "path_var_prependix contents: " ++ ghcPackagePathVar
liftIO $ writeFile ghcPackagePathVarLocation ghcPackagePathVar
-- install activate script (in bin/ directory) inside virtual environment dir structure
installActivateScript :: MyMonad ()
installActivateScript = do
info "Installing activate script"
virthualEnvName <- asks vheName
dirStructure <- vheDirStructure
ghcPkgDbPath <- indentMessages ghcPkgDbPathLocation
let activateScript = virthualEnvBinDir dirStructure </> "activate"
indentMessages $ debug $ "using location: " ++ activateScript
let activateScriptContents = substs [ ("<VIRTHUALENV_NAME>", virthualEnvName)
, ("<VIRTHUALENV_DIR>", virthualEnvDir dirStructure)
, ("<VIRTHUALENV>", virthualEnv dirStructure)
, ("<GHC_PACKAGE_PATH>", ghcPkgDbPath)
, ("<VIRTHUALENV_BIN_DIR>", virthualEnvBinDir dirStructure)
, ("<CABAL_BIN_DIR>", cabalBinDir dirStructure)
, ("<GHC_BIN_DIR>", ghcBinDir dirStructure)
] activateSkel
indentMessages $ do
trace "activate script contents:"
indentMessages $ mapM_ trace $ lines activateScriptContents
liftIO $ writeFile activateScript activateScriptContents
indentMessages installActivateScriptSupportFiles
-- install cabal's config file (in cabal/ directory) inside virtual environment dir structure
installCabalConfig :: MyMonad ()
installCabalConfig = do
cabalConfig <- cabalConfigLocation
dirStructure <- vheDirStructure
info $ "Installing cabal config at " ++ cabalConfig
let cabalConfigContents = substs [ ("<GHC_PACKAGE_PATH>", ghcPackagePath dirStructure)
, ("<CABAL_DIR>", cabalDir dirStructure)
] cabalConfigSkel
indentMessages $ do
trace "cabal config contents:"
indentMessages $ mapM_ trace $ lines cabalConfigContents
liftIO $ writeFile cabalConfig cabalConfigContents
createDirStructure :: MyMonad ()
createDirStructure = do
dirStructure <- vheDirStructure
info "Creating Virtual Haskell directory structure"
indentMessages $ do
debug $ "virthualenv directory: " ++ virthualEnvDir dirStructure
liftIO $ createDirectory $ virthualEnvDir dirStructure
debug $ "cabal directory: " ++ cabalDir dirStructure
liftIO $ createDirectory $ cabalDir dirStructure
debug $ "virthualenv bin directory: " ++ virthualEnvBinDir dirStructure
liftIO $ createDirectory $ virthualEnvBinDir dirStructure
initialize private GHC package database inside virtual environment
initGhcDb :: MyMonad ()
initGhcDb = do
dirStructure <- vheDirStructure
info $ "Initializing GHC Package database at " ++ ghcPackagePath dirStructure
out <- indentMessages $ outsideGhcPkg ["--version"]
case lastMay $ words out of
Nothing -> throwError $ MyException $ "Couldn't extract ghc-pkg version number from: " ++ out
Just versionString -> do
indentMessages $ trace $ "Found version string: " ++ versionString
version <- parseVersion versionString
let ghc_6_12_1_version = Version [6,12,1] []
if version < ghc_6_12_1_version then do
indentMessages $ debug "Detected GHC older than 6.12, initializing GHC_PACKAGE_PATH to file with '[]'"
liftIO $ writeFile (ghcPackagePath dirStructure) "[]"
else do
_ <- indentMessages $ outsideGhcPkg ["init", ghcPackagePath dirStructure]
return ()
-- copy optional packages and don't fail completely if this copying fails
some packages mail fail to copy and it 's not fatal ( e.g. older GHCs do n't have )
transplantOptionalPackage :: String -> MyMonad ()
transplantOptionalPackage name = transplantPackage (PackageName name) `catchError` handler
where handler e = do
warning $ "Failed to copy optional package " ++ name ++ " from system's GHC: "
indentMessages $ warning $ getExceptionMessage e
-- copy base system
-- base - needed for ghci and everything else
Cabal - needed to install non - trivial cabal packages with cabal - install
-- haskell98 - some packages need it but they don't specify it (seems it's an implicit dependancy)
-- haskell2010 - maybe it's similar to haskell98?
ghc and ghc - binary - two packages that are provided with GHC and can not be installed any other way
-- also include dependant packages of all the above
when using GHC from tarball , just reuse its package database
can not do the same when using system 's GHC , because there might be additional packages installed
-- then it wouldn't be possible to work on them insie virtual environment
copyBaseSystem :: MyMonad ()
copyBaseSystem = do
info "Copying necessary packages from original GHC package database"
indentMessages $ do
ghc <- asks ghcSource
case ghc of
System -> do
transplantPackage $ PackageName "base"
transplantPackage $ PackageName "Cabal"
mapM_ transplantOptionalPackage ["haskell98", "haskell2010", "ghc", "ghc-binary"]
Tarball _ ->
debug "Using external GHC - nothing to copy, Virtual environment will reuse GHC package database"
installGhc :: MyMonad ()
installGhc = do
info "Installing GHC"
ghc <- asks ghcSource
case ghc of
System -> indentMessages $ debug "Using system version of GHC - nothing to install."
Tarball tarballPath -> indentMessages $ installExternalGhc tarballPath
installExternalGhc :: FilePath -> MyMonad ()
installExternalGhc tarballPath = do
info $ "Installing GHC from " ++ tarballPath
indentMessages $ do
dirStructure <- vheDirStructure
tmpGhcDir <- liftIO $ createTemporaryDirectory (virthualEnv dirStructure) "ghc"
debug $ "Unpacking GHC tarball to " ++ tmpGhcDir
_ <- indentMessages $ runProcess Nothing "tar" ["xf", tarballPath, "-C", tmpGhcDir, "--strip-components", "1"] Nothing
let configureScript = tmpGhcDir </> "configure"
debug $ "Configuring GHC with prefix " ++ ghcDir dirStructure
cwd <- liftIO getCurrentDirectory
liftIO $ setCurrentDirectory tmpGhcDir
make <- asks makeCmd
let configureAndInstall = do
_ <- indentMessages $ runProcess Nothing configureScript ["--prefix=" ++ ghcDir dirStructure] Nothing
debug $ "Installing GHC with " ++ make ++ " install"
_ <- indentMessages $ runProcess Nothing make ["install"] Nothing
return ()
configureAndInstall `finally` liftIO (setCurrentDirectory cwd)
liftIO $ removeDirectoryRecursive tmpGhcDir
return ()
| null | https://raw.githubusercontent.com/Paczesiowa/virthualenv/aab89dad9de7dac5268472eaa50c11eb40b02380/src/Actions.hs | haskell | install cabal wrapper (in bin/ directory) inside virtual environment dir structure
install activate script (in bin/ directory) inside virtual environment dir structure
install cabal's config file (in cabal/ directory) inside virtual environment dir structure
copy optional packages and don't fail completely if this copying fails
copy base system
base - needed for ghci and everything else
haskell98 - some packages need it but they don't specify it (seems it's an implicit dependancy)
haskell2010 - maybe it's similar to haskell98?
also include dependant packages of all the above
then it wouldn't be possible to work on them insie virtual environment | module Actions ( cabalUpdate
, installCabalConfig
, installCabalWrapper
, installActivateScript
, copyBaseSystem
, initGhcDb
, installGhc
, createDirStructure
) where
import System.Directory (setCurrentDirectory, getCurrentDirectory, createDirectory, removeDirectoryRecursive)
import System.FilePath ((</>))
import Distribution.Version (Version (..))
import Distribution.Package (PackageName(..))
import Safe (lastMay)
import Data.List (intercalate)
import MyMonad
import Types
import Paths
import PackageManagement
import Process
import Util.Template (substs)
import Util.IO (makeExecutable, createTemporaryDirectory)
import Skeletons
update cabal package info inside Virtual Haskell Environmentn
cabalUpdate :: MyMonad ()
cabalUpdate = do
env <- getVirtualEnvironment
cabalConfig <- cabalConfigLocation
info "Updating cabal package database inside Virtual Haskell Environment."
_ <- indentMessages $ runProcess (Just env) "cabal" ["--config-file=" ++ cabalConfig, "update"] Nothing
return ()
installCabalWrapper :: MyMonad ()
installCabalWrapper = do
cabalConfig <- cabalConfigLocation
dirStructure <- vheDirStructure
let cabalWrapper = virthualEnvBinDir dirStructure </> "cabal"
info $ concat [ "Installing cabal wrapper using "
, cabalConfig
, " at "
, cabalWrapper
]
let cabalWrapperContents = substs [("<CABAL_CONFIG>", cabalConfig)] cabalWrapperSkel
indentMessages $ do
trace "cabal wrapper contents:"
indentMessages $ mapM_ trace $ lines cabalWrapperContents
liftIO $ writeFile cabalWrapper cabalWrapperContents
liftIO $ makeExecutable cabalWrapper
installActivateScriptSupportFiles :: MyMonad ()
installActivateScriptSupportFiles = do
debug "installing supporting files"
dirStructure <- vheDirStructure
ghc <- asks ghcSource
indentMessages $ do
let pathVarPrependixLocation = virthualEnvDir dirStructure </> "path_var_prependix"
pathVarElems =
case ghc of
System -> [virthualEnvBinDir dirStructure, cabalBinDir dirStructure]
Tarball _ -> [ virthualEnvBinDir dirStructure
, cabalBinDir dirStructure
, ghcBinDir dirStructure
]
pathVarPrependix = intercalate ":" pathVarElems
debug $ "installing path_var_prependix file to " ++ pathVarPrependixLocation
indentMessages $ trace $ "path_var_prependix contents: " ++ pathVarPrependix
liftIO $ writeFile pathVarPrependixLocation pathVarPrependix
ghcPkgDbPath <- indentMessages ghcPkgDbPathLocation
let ghcPackagePathVarLocation = virthualEnvDir dirStructure </> "ghc_package_path_var"
ghcPackagePathVar = ghcPkgDbPath
debug $ "installing ghc_package_path_var file to " ++ ghcPackagePathVarLocation
indentMessages $ trace $ "path_var_prependix contents: " ++ ghcPackagePathVar
liftIO $ writeFile ghcPackagePathVarLocation ghcPackagePathVar
installActivateScript :: MyMonad ()
installActivateScript = do
info "Installing activate script"
virthualEnvName <- asks vheName
dirStructure <- vheDirStructure
ghcPkgDbPath <- indentMessages ghcPkgDbPathLocation
let activateScript = virthualEnvBinDir dirStructure </> "activate"
indentMessages $ debug $ "using location: " ++ activateScript
let activateScriptContents = substs [ ("<VIRTHUALENV_NAME>", virthualEnvName)
, ("<VIRTHUALENV_DIR>", virthualEnvDir dirStructure)
, ("<VIRTHUALENV>", virthualEnv dirStructure)
, ("<GHC_PACKAGE_PATH>", ghcPkgDbPath)
, ("<VIRTHUALENV_BIN_DIR>", virthualEnvBinDir dirStructure)
, ("<CABAL_BIN_DIR>", cabalBinDir dirStructure)
, ("<GHC_BIN_DIR>", ghcBinDir dirStructure)
] activateSkel
indentMessages $ do
trace "activate script contents:"
indentMessages $ mapM_ trace $ lines activateScriptContents
liftIO $ writeFile activateScript activateScriptContents
indentMessages installActivateScriptSupportFiles
installCabalConfig :: MyMonad ()
installCabalConfig = do
cabalConfig <- cabalConfigLocation
dirStructure <- vheDirStructure
info $ "Installing cabal config at " ++ cabalConfig
let cabalConfigContents = substs [ ("<GHC_PACKAGE_PATH>", ghcPackagePath dirStructure)
, ("<CABAL_DIR>", cabalDir dirStructure)
] cabalConfigSkel
indentMessages $ do
trace "cabal config contents:"
indentMessages $ mapM_ trace $ lines cabalConfigContents
liftIO $ writeFile cabalConfig cabalConfigContents
createDirStructure :: MyMonad ()
createDirStructure = do
dirStructure <- vheDirStructure
info "Creating Virtual Haskell directory structure"
indentMessages $ do
debug $ "virthualenv directory: " ++ virthualEnvDir dirStructure
liftIO $ createDirectory $ virthualEnvDir dirStructure
debug $ "cabal directory: " ++ cabalDir dirStructure
liftIO $ createDirectory $ cabalDir dirStructure
debug $ "virthualenv bin directory: " ++ virthualEnvBinDir dirStructure
liftIO $ createDirectory $ virthualEnvBinDir dirStructure
initialize private GHC package database inside virtual environment
initGhcDb :: MyMonad ()
initGhcDb = do
dirStructure <- vheDirStructure
info $ "Initializing GHC Package database at " ++ ghcPackagePath dirStructure
out <- indentMessages $ outsideGhcPkg ["--version"]
case lastMay $ words out of
Nothing -> throwError $ MyException $ "Couldn't extract ghc-pkg version number from: " ++ out
Just versionString -> do
indentMessages $ trace $ "Found version string: " ++ versionString
version <- parseVersion versionString
let ghc_6_12_1_version = Version [6,12,1] []
if version < ghc_6_12_1_version then do
indentMessages $ debug "Detected GHC older than 6.12, initializing GHC_PACKAGE_PATH to file with '[]'"
liftIO $ writeFile (ghcPackagePath dirStructure) "[]"
else do
_ <- indentMessages $ outsideGhcPkg ["init", ghcPackagePath dirStructure]
return ()
some packages mail fail to copy and it 's not fatal ( e.g. older GHCs do n't have )
transplantOptionalPackage :: String -> MyMonad ()
transplantOptionalPackage name = transplantPackage (PackageName name) `catchError` handler
where handler e = do
warning $ "Failed to copy optional package " ++ name ++ " from system's GHC: "
indentMessages $ warning $ getExceptionMessage e
Cabal - needed to install non - trivial cabal packages with cabal - install
ghc and ghc - binary - two packages that are provided with GHC and can not be installed any other way
when using GHC from tarball , just reuse its package database
can not do the same when using system 's GHC , because there might be additional packages installed
copyBaseSystem :: MyMonad ()
copyBaseSystem = do
info "Copying necessary packages from original GHC package database"
indentMessages $ do
ghc <- asks ghcSource
case ghc of
System -> do
transplantPackage $ PackageName "base"
transplantPackage $ PackageName "Cabal"
mapM_ transplantOptionalPackage ["haskell98", "haskell2010", "ghc", "ghc-binary"]
Tarball _ ->
debug "Using external GHC - nothing to copy, Virtual environment will reuse GHC package database"
installGhc :: MyMonad ()
installGhc = do
info "Installing GHC"
ghc <- asks ghcSource
case ghc of
System -> indentMessages $ debug "Using system version of GHC - nothing to install."
Tarball tarballPath -> indentMessages $ installExternalGhc tarballPath
installExternalGhc :: FilePath -> MyMonad ()
installExternalGhc tarballPath = do
info $ "Installing GHC from " ++ tarballPath
indentMessages $ do
dirStructure <- vheDirStructure
tmpGhcDir <- liftIO $ createTemporaryDirectory (virthualEnv dirStructure) "ghc"
debug $ "Unpacking GHC tarball to " ++ tmpGhcDir
_ <- indentMessages $ runProcess Nothing "tar" ["xf", tarballPath, "-C", tmpGhcDir, "--strip-components", "1"] Nothing
let configureScript = tmpGhcDir </> "configure"
debug $ "Configuring GHC with prefix " ++ ghcDir dirStructure
cwd <- liftIO getCurrentDirectory
liftIO $ setCurrentDirectory tmpGhcDir
make <- asks makeCmd
let configureAndInstall = do
_ <- indentMessages $ runProcess Nothing configureScript ["--prefix=" ++ ghcDir dirStructure] Nothing
debug $ "Installing GHC with " ++ make ++ " install"
_ <- indentMessages $ runProcess Nothing make ["install"] Nothing
return ()
configureAndInstall `finally` liftIO (setCurrentDirectory cwd)
liftIO $ removeDirectoryRecursive tmpGhcDir
return ()
|
0fc566332759edae97fb82826d92a54e69f92acf6cdbf972a7cb3d7c3a283df3 | clojure-interop/java-jdk | MultiColorChooserUI.clj | (ns javax.swing.plaf.multi.MultiColorChooserUI
"A multiplexing UI used to combine ColorChooserUIs.
This file was automatically generated by AutoMulti."
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.plaf.multi MultiColorChooserUI]))
(defn ->multi-color-chooser-ui
"Constructor."
(^MultiColorChooserUI []
(new MultiColorChooserUI )))
(defn *create-ui
"Returns a multiplexing UI instance if any of the auxiliary
LookAndFeels supports this UI. Otherwise, just returns the
UI object obtained from the default LookAndFeel.
a - `javax.swing.JComponent`
returns: `javax.swing.plaf.ComponentUI`"
(^javax.swing.plaf.ComponentUI [^javax.swing.JComponent a]
(MultiColorChooserUI/createUI a)))
(defn install-ui
"Invokes the installUI method on each UI handled by this object.
a - the component where this UI delegate is being installed - `javax.swing.JComponent`"
([^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.installUI a))))
(defn get-minimum-size
"Invokes the getMinimumSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.getMinimumSize a))))
(defn get-maximum-size
"Invokes the getMaximumSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.getMaximumSize a))))
(defn get-accessible-child
"Invokes the getAccessibleChild method on each UI handled by this object.
a - `javax.swing.JComponent`
b - `int`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `javax.accessibility.Accessible`"
(^javax.accessibility.Accessible [^MultiColorChooserUI this ^javax.swing.JComponent a ^Integer b]
(-> this (.getAccessibleChild a b))))
(defn get-u-is
"Returns the list of UIs associated with this multiplexing UI. This
allows processing of the UIs by an application aware of multiplexing
UIs on components.
returns: `javax.swing.plaf.ComponentUI[]`"
([^MultiColorChooserUI this]
(-> this (.getUIs))))
(defn uninstall-ui
"Invokes the uninstallUI method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.uninstallUI a))))
(defn contains
"Invokes the contains method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
b - the x coordinate of the point - `int`
c - the y coordinate of the point - `int`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `boolean`"
(^Boolean [^MultiColorChooserUI this ^javax.swing.JComponent a ^Integer b ^Integer c]
(-> this (.contains a b c))))
(defn update
"Invokes the update method on each UI handled by this object.
a - the Graphics context in which to paint - `java.awt.Graphics`
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiColorChooserUI this ^java.awt.Graphics a ^javax.swing.JComponent b]
(-> this (.update a b))))
(defn get-accessible-children-count
"Invokes the getAccessibleChildrenCount method on each UI handled by this object.
a - `javax.swing.JComponent`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `int`"
(^Integer [^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.getAccessibleChildrenCount a))))
(defn paint
"Invokes the paint method on each UI handled by this object.
a - the Graphics context in which to paint - `java.awt.Graphics`
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiColorChooserUI this ^java.awt.Graphics a ^javax.swing.JComponent b]
(-> this (.paint a b))))
(defn get-preferred-size
"Invokes the getPreferredSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.getPreferredSize a))))
| null | https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/plaf/multi/MultiColorChooserUI.clj | clojure | (ns javax.swing.plaf.multi.MultiColorChooserUI
"A multiplexing UI used to combine ColorChooserUIs.
This file was automatically generated by AutoMulti."
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.plaf.multi MultiColorChooserUI]))
(defn ->multi-color-chooser-ui
"Constructor."
(^MultiColorChooserUI []
(new MultiColorChooserUI )))
(defn *create-ui
"Returns a multiplexing UI instance if any of the auxiliary
LookAndFeels supports this UI. Otherwise, just returns the
UI object obtained from the default LookAndFeel.
a - `javax.swing.JComponent`
returns: `javax.swing.plaf.ComponentUI`"
(^javax.swing.plaf.ComponentUI [^javax.swing.JComponent a]
(MultiColorChooserUI/createUI a)))
(defn install-ui
"Invokes the installUI method on each UI handled by this object.
a - the component where this UI delegate is being installed - `javax.swing.JComponent`"
([^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.installUI a))))
(defn get-minimum-size
"Invokes the getMinimumSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.getMinimumSize a))))
(defn get-maximum-size
"Invokes the getMaximumSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.getMaximumSize a))))
(defn get-accessible-child
"Invokes the getAccessibleChild method on each UI handled by this object.
a - `javax.swing.JComponent`
b - `int`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `javax.accessibility.Accessible`"
(^javax.accessibility.Accessible [^MultiColorChooserUI this ^javax.swing.JComponent a ^Integer b]
(-> this (.getAccessibleChild a b))))
(defn get-u-is
"Returns the list of UIs associated with this multiplexing UI. This
allows processing of the UIs by an application aware of multiplexing
UIs on components.
returns: `javax.swing.plaf.ComponentUI[]`"
([^MultiColorChooserUI this]
(-> this (.getUIs))))
(defn uninstall-ui
"Invokes the uninstallUI method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.uninstallUI a))))
(defn contains
"Invokes the contains method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
b - the x coordinate of the point - `int`
c - the y coordinate of the point - `int`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `boolean`"
(^Boolean [^MultiColorChooserUI this ^javax.swing.JComponent a ^Integer b ^Integer c]
(-> this (.contains a b c))))
(defn update
"Invokes the update method on each UI handled by this object.
a - the Graphics context in which to paint - `java.awt.Graphics`
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiColorChooserUI this ^java.awt.Graphics a ^javax.swing.JComponent b]
(-> this (.update a b))))
(defn get-accessible-children-count
"Invokes the getAccessibleChildrenCount method on each UI handled by this object.
a - `javax.swing.JComponent`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `int`"
(^Integer [^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.getAccessibleChildrenCount a))))
(defn paint
"Invokes the paint method on each UI handled by this object.
a - the Graphics context in which to paint - `java.awt.Graphics`
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiColorChooserUI this ^java.awt.Graphics a ^javax.swing.JComponent b]
(-> this (.paint a b))))
(defn get-preferred-size
"Invokes the getPreferredSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiColorChooserUI this ^javax.swing.JComponent a]
(-> this (.getPreferredSize a))))
|
|
a2c7cf6550983ba3e2c0042ea807d5852311f3b4a28dfbd39f9b6de047ee78e4 | ha-mo-we/Racer | lracer-utf8-test.lisp | ;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: cl-user -*-
(in-package cl-user)
#-(or :sbcl :allegro :clisp)
(error "UTF8 demo requires ACL or SBCL.")
(close-server-connection)
(setf *external-format* :utf-8)
;;; make sure RacerPro is running in UTF8 mode: RacerPro -- -ef @UTF8
(enable-lracer-read-macros)
;;;
Server Side Loading
;;;
(full-reset)
(racer-read-file
(demo-file "family-j-utf8.racer"))
(pprint (taxonomy))
(pprint (describe-individual 'みよ))
(pprint (retrieve (?x ?y) (and (?x 母)
(?x ?y 子孫を持つ))))
;;;
;;; Client Side Loading
;;;
(full-reset)
(load (demo-file "family-j-utf8.racer")
#+:allegro :external-format
#+:allegro *external-format*)
(pprint (taxonomy))
(pprint (describe-individual 'みよ))
(pprint (retrieve (?x ?y) (and (?x 母)
(?x ?y 子孫を持つ))))
| null | https://raw.githubusercontent.com/ha-mo-we/Racer/d690841d10015c7a75b1ded393fcf0a33092c4de/clients/lracer/lracer-utf8-test.lisp | lisp | -*- Mode: Lisp; Syntax: Common-Lisp; Package: cl-user -*-
make sure RacerPro is running in UTF8 mode: RacerPro -- -ef @UTF8
Client Side Loading
|
(in-package cl-user)
#-(or :sbcl :allegro :clisp)
(error "UTF8 demo requires ACL or SBCL.")
(close-server-connection)
(setf *external-format* :utf-8)
(enable-lracer-read-macros)
Server Side Loading
(full-reset)
(racer-read-file
(demo-file "family-j-utf8.racer"))
(pprint (taxonomy))
(pprint (describe-individual 'みよ))
(pprint (retrieve (?x ?y) (and (?x 母)
(?x ?y 子孫を持つ))))
(full-reset)
(load (demo-file "family-j-utf8.racer")
#+:allegro :external-format
#+:allegro *external-format*)
(pprint (taxonomy))
(pprint (describe-individual 'みよ))
(pprint (retrieve (?x ?y) (and (?x 母)
(?x ?y 子孫を持つ))))
|
d83f42a2c1e7a3dc117e8bd0c4f42b58a2a8893fa13db60bae04822deeafb7b8 | CRogers/obc | switch.mli |
* switch.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright ( c ) 2006
* All rights reserved
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
* 2 . Redistributions in binary form must reproduce the above copyright notice ,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution .
* 3 . The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
* IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED .
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL ,
* SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ;
* OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
* IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
* OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
* $ I d : switch.mli 1434 2009 - 07 - 28 20:03:09Z mike $
* switch.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright (c) 2006 J. M. Spivey
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $Id: switch.mli 1434 2009-07-28 20:03:09Z mike $
*)
open Symtab
open Eval
(* |switch| -- generate switching code for CASE statement *)
val switch : (integer * integer * codelab) list -> codelab -> unit
| null | https://raw.githubusercontent.com/CRogers/obc/49064db244e0c9d2ec2a83420c8d0ee917b54196/compiler/switch.mli | ocaml | |switch| -- generate switching code for CASE statement |
* switch.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright ( c ) 2006
* All rights reserved
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
* 2 . Redistributions in binary form must reproduce the above copyright notice ,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution .
* 3 . The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
* IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED .
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL ,
* SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ;
* OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
* IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR
* OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
* $ I d : switch.mli 1434 2009 - 07 - 28 20:03:09Z mike $
* switch.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright (c) 2006 J. M. Spivey
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $Id: switch.mli 1434 2009-07-28 20:03:09Z mike $
*)
open Symtab
open Eval
val switch : (integer * integer * codelab) list -> codelab -> unit
|
b4c249d1d7d985db6634528e4ed0fcdd926633bc548fd7aff0c4544d6643e091 | simonmar/monad-par | nbody.hs |
- Modified from code released with :
- Intel Concurrent Collections for ( c ) 2010 , Intel Corporation .
- Modified from code released with:
- Intel Concurrent Collections for Haskell
- Copyright (c) 2010, Intel Corporation.
-}
# LANGUAGE ExistentialQuantification
, ScopedTypeVariables
, BangPatterns
, NamedFieldPuns
, RecordWildCards
, FlexibleInstances
, DeriveDataTypeable
, MagicHash
, UnboxedTuples
, CPP #
, ScopedTypeVariables
, BangPatterns
, NamedFieldPuns
, RecordWildCards
, FlexibleInstances
, DeriveDataTypeable
, MagicHash
, UnboxedTuples
, CPP #-}
This is INCOMPATIBLE with CncPure ..
Author :
Ported to Monad - par by .
This program uses CnC to calculate the accelerations of the bodies in a 3D system .
import Control.Monad
import Data.Int
import qualified Data.List as List
import qualified Data.Array as A
import GHC.Exts
import System.Environment
#ifdef PARSCHED
import PARSCHED
#else
import Control.Monad.Par
#endif
type Float3D = (Float, Float, Float)
type UFloat3D = (# Float#, Float#, Float# #)
-- This step generates the bodies in the system.
genVector tag = (tag' * 1.0, tag' * 0.2, tag' * 30.0)
where tag' = fromIntegral tag
We are keeping the idiomatic version around as well for comparison :
-- #define IDIOMATIC_VER
-- Only doing the O(N^2) part in parallel:
-- This step computes the accelerations of the bodies.
compute : : A.Array Int Float3D - > A.Array Int ( IVar Float3D ) - > Int - > Par ( )
compute vecList accels tag =
do
let myvector = vecList A.! (tag-1)
put (accels A.! tag) (accel myvector vecList)
where
g = 9.8
multTriple :: Float -> Float3D -> Float3D
multTriple c ( x,y,z ) = ( c*x,c*y,c*z )
pairWiseAccel :: Float3D -> Float3D -> Float3D
pairWiseAccel (x,y,z) (x',y',z') = let dx = x'-x
dy = y'-y
dz = z'-z
eps = 0.005
-- Performance degredation here:
distanceSq = dx*dx + dy*dy + dz*dz + eps
factor = 1/sqrt(distanceSq * distanceSq * distanceSq)
in multTriple factor ( dx , dy , dz )
in multTriple factor (dx,dy,dz)
#ifdef IDIOMATIC_VER
sumTriples = foldr (\(x,y,z) (x',y',z') -> (x+x',y+y',z+z')) (0,0,0)
accel vector vecList = multTriple g $ sumTriples $ List.map (pairWiseAccel vector) vecList
#else
-- Making this much less idiomatic to avoid allocation:
(strt,end) = A.bounds vecList
accel :: Float3D -> (A.Array Int Float3D) -> Float3D
accel vector vecList =
-- Manually inlining to see if the tuples unbox:
let (# sx,sy,sz #) = loop strt 0 0 0
loop !i !ax !ay !az
| i == end = (# ax,ay,az #)
| otherwise =
let ( x,y,z ) = vector
( x',y',z' ) = vecList A.! i
(# dx,dy,dz #) = (# x'-x, y'-y, z'-z #)
eps = 0.005
distanceSq = dx*dx + dy*dy + dz*dz + eps
factor = 1/sqrt(distanceSq * distanceSq * distanceSq)
(# px,py,pz #) = (# factor * dx, factor * dy, factor *dz #)
in loop (i+1) (ax+px) (ay+py) (az+pz)
in ( g*sx, g*sy, g*sz )
#endif
run :: Int -> [Float3D]
run n = runPar $
do
vars <- sequence$ take n $ repeat new
-- accels <- A.array (0,n-1) [ (i,) | i <- [0..n-1]]
Is there a better way to make an array of pvars ?
let accels = A.array (1,n) (zip [1..n] vars)
#ifdef IDIOMATIC_VER
let initVecs = List.map genVector [1..n]
#else
let initVecs = A.array (0,n-1) [ (i, genVector i) | i <- [0..n-1] ]
#endif
forM_ [1..n] $ \ t -> fork (compute initVecs accels t)
sequence (List.map (\i -> get (accels A.! i)) [1..n])
main =
do args <- getArgs
let accList = case args of
[] -> run (3::Int)
[s] -> run (read s)
putStrLn $ show (foldl (\sum (x,y,z) -> if x>0 then sum+1 else sum) 0 accList)
| null | https://raw.githubusercontent.com/simonmar/monad-par/1266b0ac1b4040963ab356cf032c6aae6b8a7add/examples/src/nbody/nbody.hs | haskell | This step generates the bodies in the system.
#define IDIOMATIC_VER
Only doing the O(N^2) part in parallel:
This step computes the accelerations of the bodies.
Performance degredation here:
Making this much less idiomatic to avoid allocation:
Manually inlining to see if the tuples unbox:
accels <- A.array (0,n-1) [ (i,) | i <- [0..n-1]] |
- Modified from code released with :
- Intel Concurrent Collections for ( c ) 2010 , Intel Corporation .
- Modified from code released with:
- Intel Concurrent Collections for Haskell
- Copyright (c) 2010, Intel Corporation.
-}
# LANGUAGE ExistentialQuantification
, ScopedTypeVariables
, BangPatterns
, NamedFieldPuns
, RecordWildCards
, FlexibleInstances
, DeriveDataTypeable
, MagicHash
, UnboxedTuples
, CPP #
, ScopedTypeVariables
, BangPatterns
, NamedFieldPuns
, RecordWildCards
, FlexibleInstances
, DeriveDataTypeable
, MagicHash
, UnboxedTuples
, CPP #-}
This is INCOMPATIBLE with CncPure ..
Author :
Ported to Monad - par by .
This program uses CnC to calculate the accelerations of the bodies in a 3D system .
import Control.Monad
import Data.Int
import qualified Data.List as List
import qualified Data.Array as A
import GHC.Exts
import System.Environment
#ifdef PARSCHED
import PARSCHED
#else
import Control.Monad.Par
#endif
type Float3D = (Float, Float, Float)
type UFloat3D = (# Float#, Float#, Float# #)
genVector tag = (tag' * 1.0, tag' * 0.2, tag' * 30.0)
where tag' = fromIntegral tag
We are keeping the idiomatic version around as well for comparison :
compute : : A.Array Int Float3D - > A.Array Int ( IVar Float3D ) - > Int - > Par ( )
compute vecList accels tag =
do
let myvector = vecList A.! (tag-1)
put (accels A.! tag) (accel myvector vecList)
where
g = 9.8
multTriple :: Float -> Float3D -> Float3D
multTriple c ( x,y,z ) = ( c*x,c*y,c*z )
pairWiseAccel :: Float3D -> Float3D -> Float3D
pairWiseAccel (x,y,z) (x',y',z') = let dx = x'-x
dy = y'-y
dz = z'-z
eps = 0.005
distanceSq = dx*dx + dy*dy + dz*dz + eps
factor = 1/sqrt(distanceSq * distanceSq * distanceSq)
in multTriple factor ( dx , dy , dz )
in multTriple factor (dx,dy,dz)
#ifdef IDIOMATIC_VER
sumTriples = foldr (\(x,y,z) (x',y',z') -> (x+x',y+y',z+z')) (0,0,0)
accel vector vecList = multTriple g $ sumTriples $ List.map (pairWiseAccel vector) vecList
#else
(strt,end) = A.bounds vecList
accel :: Float3D -> (A.Array Int Float3D) -> Float3D
accel vector vecList =
let (# sx,sy,sz #) = loop strt 0 0 0
loop !i !ax !ay !az
| i == end = (# ax,ay,az #)
| otherwise =
let ( x,y,z ) = vector
( x',y',z' ) = vecList A.! i
(# dx,dy,dz #) = (# x'-x, y'-y, z'-z #)
eps = 0.005
distanceSq = dx*dx + dy*dy + dz*dz + eps
factor = 1/sqrt(distanceSq * distanceSq * distanceSq)
(# px,py,pz #) = (# factor * dx, factor * dy, factor *dz #)
in loop (i+1) (ax+px) (ay+py) (az+pz)
in ( g*sx, g*sy, g*sz )
#endif
run :: Int -> [Float3D]
run n = runPar $
do
vars <- sequence$ take n $ repeat new
Is there a better way to make an array of pvars ?
let accels = A.array (1,n) (zip [1..n] vars)
#ifdef IDIOMATIC_VER
let initVecs = List.map genVector [1..n]
#else
let initVecs = A.array (0,n-1) [ (i, genVector i) | i <- [0..n-1] ]
#endif
forM_ [1..n] $ \ t -> fork (compute initVecs accels t)
sequence (List.map (\i -> get (accels A.! i)) [1..n])
main =
do args <- getArgs
let accList = case args of
[] -> run (3::Int)
[s] -> run (read s)
putStrLn $ show (foldl (\sum (x,y,z) -> if x>0 then sum+1 else sum) 0 accList)
|
5eedf713d5366d7f7f526fecbae90ad3dc96d3d55bccc1fbea641274d4b6621a | maximedenes/native-coq | recdef.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 *)
(************************************************************************)
(*i camlp4deps: "parsing/grammar.cma" i*)
open Tacexpr
open Term
open Namegen
open Environ
open Declarations
open Entries
open Pp
open Names
open Libnames
open Nameops
open Errors
open Util
open Closure
open RedFlags
open Tacticals
open Typing
open Tacmach
open Tactics
open Nametab
open Decls
open Declare
open Decl_kinds
open Tacred
open Proof_type
open Vernacinterp
open Pfedit
open Topconstr
open Glob_term
open Pretyping
open Safe_typing
open Constrintern
open Hiddentac
open Equality
open Auto
open Eauto
open Genarg
open Indfun_common
(* Ugly things which should not be here *)
let coq_base_constant s =
Coqlib.gen_constant_in_modules "RecursiveDefinition"
(Coqlib.init_modules @ [["Coq";"Arith";"Le"];["Coq";"Arith";"Lt"]]) s;;
let coq_constant s =
Coqlib.gen_constant_in_modules "RecursiveDefinition"
(Coqlib.init_modules @ Coqlib.arith_modules) s;;
let find_reference sl s =
(locate (make_qualid(Names.make_dirpath
(List.map id_of_string (List.rev sl)))
(id_of_string s)));;
let (declare_fun : identifier -> logical_kind -> constr -> global_reference) =
fun f_id kind value ->
let ce = {const_entry_body = value;
const_entry_secctx = None;
const_entry_type = None;
const_entry_opaque = false;
const_entry_inline_code = false} in
ConstRef(declare_constant f_id (DefinitionEntry ce, kind));;
let defined () = Lemmas.save_named false
let def_of_const t =
match (kind_of_term t) with
Const sp ->
(try (match body_of_constant (Global.lookup_constant sp) with
| Some c -> Declarations.force c
| _ -> assert false)
with _ ->
anomaly ("Cannot find definition of constant "^
(string_of_id (id_of_label (con_label sp))))
)
|_ -> assert false
let type_of_const t =
match (kind_of_term t) with
Const sp -> Typeops.type_of_constant (Global.env()) sp
|_ -> assert false
let constant sl s =
constr_of_global
(locate (make_qualid(Names.make_dirpath
(List.map id_of_string (List.rev sl)))
(id_of_string s)));;
let const_of_ref = function
ConstRef kn -> kn
| _ -> anomaly "ConstRef expected"
let nf_zeta env =
Reductionops.clos_norm_flags (Closure.RedFlags.mkflags [Closure.RedFlags.fZETA])
env
Evd.empty
let nf_betaiotazeta = (* Reductionops.local_strong Reductionops.whd_betaiotazeta *)
let clos_norm_flags flgs env sigma t =
Closure.norm_val (Closure.create_clos_infos flgs env) (Closure.inject (Reductionops.nf_evar sigma t)) in
clos_norm_flags Closure.betaiotazeta Environ.empty_env Evd.empty
Generic values
let pf_get_new_ids idl g =
let ids = pf_ids_of_hyps g in
List.fold_right
(fun id acc -> next_global_ident_away id (acc@ids)::acc)
idl
[]
let compute_renamed_type gls c =
rename_bound_vars_as_displayed (*no avoid*) [] (*no rels*) []
(pf_type_of gls c)
let h'_id = id_of_string "h'"
let heq_id = id_of_string "Heq"
let teq_id = id_of_string "teq"
let ano_id = id_of_string "anonymous"
let x_id = id_of_string "x"
let k_id = id_of_string "k"
let v_id = id_of_string "v"
let def_id = id_of_string "def"
let p_id = id_of_string "p"
let rec_res_id = id_of_string "rec_res";;
let lt = function () -> (coq_base_constant "lt")
let le = function () -> (coq_base_constant "le")
let ex = function () -> (coq_base_constant "ex")
let nat = function () -> (coq_base_constant "nat")
let coq_sig = function () -> (coq_base_constant "sig")
let iter_ref () =
try find_reference ["Recdef"] "iter"
with Not_found -> error "module Recdef not loaded"
let iter = function () -> (constr_of_global (delayed_force iter_ref))
let eq = function () -> (coq_base_constant "eq")
let le_lt_SS = function () -> (constant ["Recdef"] "le_lt_SS")
let le_lt_n_Sm = function () -> (coq_base_constant "le_lt_n_Sm")
let le_trans = function () -> (coq_base_constant "le_trans")
let le_lt_trans = function () -> (coq_base_constant "le_lt_trans")
let lt_S_n = function () -> (coq_base_constant "lt_S_n")
let le_n = function () -> (coq_base_constant "le_n")
let coq_sig_ref = function () -> (find_reference ["Coq";"Init";"Specif"] "sig")
let coq_O = function () -> (coq_base_constant "O")
let coq_S = function () -> (coq_base_constant "S")
let gt_antirefl = function () -> (coq_constant "gt_irrefl")
let lt_n_O = function () -> (coq_base_constant "lt_n_O")
let lt_n_Sn = function () -> (coq_base_constant "lt_n_Sn")
let f_equal = function () -> (coq_constant "f_equal")
let well_founded_induction = function () -> (coq_constant "well_founded_induction")
let max_ref = function () -> (find_reference ["Recdef"] "max")
let max_constr = function () -> (constr_of_global (delayed_force max_ref))
let coq_conj = function () -> find_reference ["Coq";"Init";"Logic"] "conj"
let f_S t = mkApp(delayed_force coq_S, [|t|]);;
let make_refl_eq constructor type_of_t t =
mkApp(constructor,[|type_of_t;t|])
let rec n_x_id ids n =
if n = 0 then []
else let x = next_ident_away_in_goal x_id ids in
x::n_x_id (x::ids) (n-1);;
let simpl_iter clause =
reduce
(Lazy
{rBeta=true;rIota=true;rZeta= true; rDelta=false;
rConst = [ EvalConstRef (const_of_ref (delayed_force iter_ref))]})
clause
(* Others ugly things ... *)
let (value_f:constr list -> global_reference -> constr) =
fun al fterm ->
let d0 = dummy_loc in
let rev_x_id_l =
(
List.fold_left
(fun x_id_l _ ->
let x_id = next_ident_away_in_goal x_id x_id_l in
x_id::x_id_l
)
[]
al
)
in
let context = List.map
(fun (x, c) -> Name x, None, c) (List.combine rev_x_id_l (List.rev al))
in
let env = Environ.push_rel_context context (Global.env ()) in
let glob_body =
GCases
(d0,RegularStyle,None,
[GApp(d0, GRef(d0,fterm), List.rev_map (fun x_id -> GVar(d0, x_id)) rev_x_id_l),
(Anonymous,None)],
[d0, [v_id], [PatCstr(d0,(destIndRef
(delayed_force coq_sig_ref),1),
[PatVar(d0, Name v_id);
PatVar(d0, Anonymous)],
Anonymous)],
GVar(d0,v_id)])
in
let body = understand Evd.empty env glob_body in
it_mkLambda_or_LetIn body context
let (declare_f : identifier -> logical_kind -> constr list -> global_reference -> global_reference) =
fun f_id kind input_type fterm_ref ->
declare_fun f_id kind (value_f input_type fterm_ref);;
(* Debuging mechanism *)
let debug_queue = Stack.create ()
let rec print_debug_queue b e =
if not (Stack.is_empty debug_queue)
then
begin
let lmsg,goal = Stack.pop debug_queue in
if b then
Pp.msgnl (lmsg ++ (str " raised exception " ++ Errors.print e) ++ str " on goal " ++ goal)
else
begin
Pp.msgnl (str " from " ++ lmsg ++ str " on goal " ++ goal);
end;
print_debug_queue false e;
end
let observe strm =
if do_observe ()
then Pp.msgnl strm
else ()
let do_observe_tac s tac g =
let goal = Printer.pr_goal g in
let lmsg = (str "recdef : ") ++ s in
observe (s++fnl());
Stack.push (lmsg,goal) debug_queue;
try
let v = tac g in
ignore(Stack.pop debug_queue);
v
with e ->
if not (Stack.is_empty debug_queue)
then
begin
let e : exn = Cerrors.process_vernac_interp_error e in
print_debug_queue true e
end
;
raise e
let observe_tac s tac g =
if do_observe ()
then do_observe_tac s tac g
else tac g
(* Conclusion tactics *)
(* The boolean value is_mes expresses that the termination is expressed
using a measure function instead of a well-founded relation. *)
let tclUSER tac is_mes l g =
let clear_tac =
match l with
| None -> h_clear false []
| Some l -> tclMAP (fun id -> tclTRY (h_clear false [id])) (List.rev l)
in
tclTHENSEQ
[
clear_tac;
if is_mes
then tclTHENLIST
[
unfold_in_concl [(Termops.all_occurrences, evaluable_of_global_reference
(delayed_force Indfun_common.ltof_ref))];
tac
]
else tac
]
g
let tclUSER_if_not_mes concl_tac is_mes names_to_suppress =
if is_mes
then tclCOMPLETE (h_simplest_apply (delayed_force well_founded_ltof))
else tclUSER concl_tac is_mes names_to_suppress
(* Travelling term.
Both definitions of [f_terminate] and [f_equation] use the same generic
travelling mechanism.
*)
(* [check_not_nested forbidden e] checks that [e] does not contains any variable
of [forbidden]
*)
let check_not_nested forbidden e =
let rec check_not_nested e =
match kind_of_term e with
| Rel _ -> ()
| Var x -> if List.mem x (forbidden) then error ("check_not_nested : failure "^string_of_id x)
| Meta _ | Evar _ | Sort _ -> ()
| Cast(e,_,t) -> check_not_nested e;check_not_nested t
| Prod(_,t,b) -> check_not_nested t;check_not_nested b
| Lambda(_,t,b) -> check_not_nested t;check_not_nested b
| LetIn(_,v,t,b) -> check_not_nested t;check_not_nested b;check_not_nested v
| App(f,l) -> check_not_nested f;Array.iter check_not_nested l
| Const _ -> ()
| Ind _ -> ()
| Construct _ -> ()
| Case(_,t,e,a) ->
check_not_nested t;check_not_nested e;Array.iter check_not_nested a
| Fix _ -> error "check_not_nested : Fix"
| CoFix _ -> error "check_not_nested : Fix"
in
try
check_not_nested e
with UserError(_,p) ->
errorlabstrm "_" (str "on expr : " ++ Printer.pr_lconstr e ++ str " " ++ p)
(* ['a info] contains the local information for travelling *)
type 'a infos =
{ nb_arg : int; (* function number of arguments *)
concl_tac : tactic; (* final tactic to finish proofs *)
rec_arg_id : identifier; (*name of the declared recursive argument *)
is_mes : bool; (* type of recursion *)
ih : identifier; (* induction hypothesis name *)
f_id : identifier; (* function name *)
f_constr : constr; (* function term *)
f_terminate : constr; (* termination proof term *)
func : global_reference; (* functionnal reference *)
info : 'a;
is_main_branch : bool; (* on the main branch or on a matched expression *)
final first order term or not
values_and_bounds : (identifier*identifier) list;
eqs : identifier list;
forbidden_ids : identifier list;
acc_inv : constr lazy_t;
acc_id : identifier;
args_assoc : ((constr list)*constr) list;
}
type ('a,'b) journey_info_tac =
'a -> (* the arguments of the constructor *)
'b infos -> (* infos of the caller *)
('b infos -> tactic) -> (* the continuation tactic of the caller *)
'b infos -> (* argument of the tactic *)
tactic
(* journey_info : specifies the actions to do on the different term constructors during the travelling of the term
*)
type journey_info =
{ letiN : ((name*constr*types*constr),constr) journey_info_tac;
lambdA : ((name*types*constr),constr) journey_info_tac;
casE : ((constr infos -> tactic) -> constr infos -> tactic) ->
((case_info * constr * constr * constr array),constr) journey_info_tac;
otherS : (unit,constr) journey_info_tac;
apP : (constr*(constr list),constr) journey_info_tac;
app_reC : (constr*(constr list),constr) journey_info_tac;
message : string
}
let rec add_vars forbidden e =
match kind_of_term e with
| Var x -> x::forbidden
| _ -> fold_constr add_vars forbidden e
let treat_case forbid_new_ids to_intros finalize_tac nb_lam e infos : tactic =
fun g ->
let rev_context,b = decompose_lam_n nb_lam e in
let ids = List.fold_left (fun acc (na,_) ->
let pre_id =
match na with
| Name x -> x
| Anonymous -> ano_id
in
pre_id::acc
) [] rev_context in
let rev_ids = pf_get_new_ids (List.rev ids) g in
let new_b = substl (List.map mkVar rev_ids) b in
tclTHENSEQ
[
h_intros (List.rev rev_ids);
intro_using teq_id;
onLastHypId (fun heq ->
tclTHENSEQ[
thin to_intros;
h_intros to_intros;
(fun g' ->
let ty_teq = pf_type_of g' (mkVar heq) in
let teq_lhs,teq_rhs =
let _,args = try destApp ty_teq with _ -> Pp.msgnl (Printer.pr_goal g' ++ fnl () ++ pr_id heq ++ str ":" ++ Printer.pr_lconstr ty_teq); assert false in
args.(1),args.(2)
in
let new_b' = Termops.replace_term teq_lhs teq_rhs new_b in
let new_infos = {
infos with
info = new_b';
eqs = heq::infos.eqs;
forbidden_ids =
if forbid_new_ids
then add_vars infos.forbidden_ids new_b'
else infos.forbidden_ids
} in
finalize_tac new_infos g'
)
]
)
] g
let rec travel_aux jinfo continuation_tac (expr_info:constr infos) =
match kind_of_term expr_info.info with
| CoFix _ | Fix _ -> error "Function cannot treat local fixpoint or cofixpoint"
| LetIn(na,b,t,e) ->
begin
let new_continuation_tac =
jinfo.letiN (na,b,t,e) expr_info continuation_tac
in
travel jinfo new_continuation_tac
{expr_info with info = b; is_final=false}
end
| Rel _ -> anomaly "Free var in goal conclusion !"
| Prod _ ->
begin
try
check_not_nested (expr_info.f_id::expr_info.forbidden_ids) expr_info.info;
jinfo.otherS () expr_info continuation_tac expr_info
with _ ->
errorlabstrm "Recdef.travel" (str "the term " ++ Printer.pr_lconstr expr_info.info ++ str " can not contain a recursive call to " ++ pr_id expr_info.f_id)
end
| Lambda(n,t,b) ->
begin
try
check_not_nested (expr_info.f_id::expr_info.forbidden_ids) expr_info.info;
jinfo.otherS () expr_info continuation_tac expr_info
with _ ->
errorlabstrm "Recdef.travel" (str "the term " ++ Printer.pr_lconstr expr_info.info ++ str " can not contain a recursive call to " ++ pr_id expr_info.f_id)
end
| Case(ci,t,a,l) ->
begin
let continuation_tac_a =
jinfo.casE
(travel jinfo) (ci,t,a,l)
expr_info continuation_tac in
travel
jinfo continuation_tac_a
{expr_info with info = a; is_main_branch = false;
is_final = false}
end
| App _ ->
let f,args = decompose_app expr_info.info in
if eq_constr f (expr_info.f_constr)
then jinfo.app_reC (f,args) expr_info continuation_tac expr_info
else
begin
match kind_of_term f with
| App _ -> assert false (* f is coming from a decompose_app *)
| Const _ | Construct _ | Rel _ | Evar _ | Meta _ | Ind _
| Sort _ | Prod _ | Var _ ->
let new_infos = {expr_info with info=(f,args)} in
let new_continuation_tac =
jinfo.apP (f,args) expr_info continuation_tac in
travel_args jinfo
expr_info.is_main_branch new_continuation_tac new_infos
| _ -> assert false
end
| Cast(t,_,_) -> travel jinfo continuation_tac {expr_info with info=t}
| Const _ | Var _ | Meta _ | Evar _ | Sort _ | Construct _ | Ind _ ->
let new_continuation_tac =
jinfo.otherS () expr_info continuation_tac in
new_continuation_tac expr_info
and travel_args jinfo is_final continuation_tac infos =
let (f_args',args) = infos.info in
match args with
| [] ->
continuation_tac {infos with info = f_args'; is_final = is_final}
| arg::args' ->
let new_continuation_tac new_infos =
let new_arg = new_infos.info in
travel_args jinfo is_final
continuation_tac
{new_infos with info = (mkApp(f_args',[|new_arg|]),args')}
in
travel jinfo new_continuation_tac
{infos with info=arg;is_final=false}
and travel jinfo continuation_tac expr_info =
observe_tac
(str jinfo.message ++ Printer.pr_lconstr expr_info.info)
(travel_aux jinfo continuation_tac expr_info)
(* Termination proof *)
let rec prove_lt hyple g =
begin
try
let (_,args) = decompose_app (pf_concl g) in
let x = try destVar (List.hd args) with _ -> assert false in
let z = try destVar (List.hd (List.tl args)) with _ -> assert false in
let h =
List.find (fun id ->
let _,args' = decompose_app (pf_type_of g (mkVar id)) in
try x = destVar (List.hd args')
with _ -> false
) hyple
in
let y =
List.hd (List.tl (snd (decompose_app (pf_type_of g (mkVar h))))) in
tclTHENLIST[
apply (mkApp(le_lt_trans (),[|mkVar x;y;mkVar z;mkVar h|]));
observe_tac (str "prove_lt") (prove_lt hyple)
]
with Not_found ->
(
(
tclTHENLIST[
apply (delayed_force lt_S_n);
(observe_tac (str "assumption: " ++ Printer.pr_goal g) (h_assumption))
])
)
end
g
let rec destruct_bounds_aux infos (bound,hyple,rechyps) lbounds g =
match lbounds with
| [] ->
let ids = pf_ids_of_hyps g in
let s_max = mkApp(delayed_force coq_S, [|bound|]) in
let k = next_ident_away_in_goal k_id ids in
let ids = k::ids in
let h' = next_ident_away_in_goal (h'_id) ids in
let ids = h'::ids in
let def = next_ident_away_in_goal def_id ids in
tclTHENLIST[
split (ImplicitBindings [s_max]);
intro_then
(fun id ->
observe_tac (str "destruct_bounds_aux")
(tclTHENS (simplest_case (mkVar id))
[
tclTHENLIST[intro_using h_id;
simplest_elim(mkApp(delayed_force lt_n_O,[|s_max|]));
default_full_auto];
tclTHENLIST[
observe_tac (str "clearing k ") (clear [id]);
h_intros [k;h';def];
observe_tac (str "simple_iter") (simpl_iter onConcl);
observe_tac (str "unfold functional")
(unfold_in_concl[((true,[1]),
evaluable_of_global_reference infos.func)]);
observe_tac (str "test" ) (
tclTHENLIST[
list_rewrite true
(List.fold_right
(fun e acc -> (mkVar e,true)::acc)
infos.eqs
(List.map (fun e -> (e,true)) rechyps)
);
(* list_rewrite true *)
( List.map ( fun e - > ( mkVar e , true ) ) infos.eqs )
(* ; *)
(observe_tac (str "finishing")
(tclORELSE
h_reflexivity
(observe_tac (str "calling prove_lt") (prove_lt hyple))))])
]
]
))
] g
| (_,v_bound)::l ->
tclTHENLIST[
simplest_elim (mkVar v_bound);
h_clear false [v_bound];
tclDO 2 intro;
onNthHypId 1
(fun p_hyp ->
(onNthHypId 2
(fun p ->
tclTHENLIST[
simplest_elim
(mkApp(delayed_force max_constr, [| bound; mkVar p|]));
tclDO 3 intro;
onNLastHypsId 3 (fun lids ->
match lids with
[hle2;hle1;pmax] ->
destruct_bounds_aux infos
((mkVar pmax),
hle1::hle2::hyple,(mkVar p_hyp)::rechyps)
l
| _ -> assert false) ;
]
)
)
)
] g
let destruct_bounds infos =
destruct_bounds_aux infos (delayed_force coq_O,[],[]) infos.values_and_bounds
let terminate_app f_and_args expr_info continuation_tac infos =
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST[
continuation_tac infos;
observe_tac (str "first split")
(split (ImplicitBindings [infos.info]));
observe_tac (str "destruct_bounds (1)") (destruct_bounds infos)
]
else continuation_tac infos
let terminate_others _ expr_info continuation_tac infos =
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST[
continuation_tac infos;
observe_tac (str "first split")
(split (ImplicitBindings [infos.info]));
observe_tac (str "destruct_bounds") (destruct_bounds infos)
]
else continuation_tac infos
let terminate_letin (na,b,t,e) expr_info continuation_tac info =
let new_e = subst1 info.info e in
let new_forbidden =
let forbid =
try
check_not_nested (expr_info.f_id::expr_info.forbidden_ids) b;
true
with _ -> false
in
if forbid
then
match na with
| Anonymous -> info.forbidden_ids
| Name id -> id::info.forbidden_ids
else info.forbidden_ids
in
continuation_tac {info with info = new_e; forbidden_ids = new_forbidden}
This is like the previous one except that it also rewrite on all
hypotheses except the ones given in the first argument . All the
modified hypotheses are generalized in the process and should be
introduced back later ; the result is the pair of the tactic and the
list of hypotheses that have been generalized and cleared .
hypotheses except the ones given in the first argument. All the
modified hypotheses are generalized in the process and should be
introduced back later; the result is the pair of the tactic and the
list of hypotheses that have been generalized and cleared. *)
let mkDestructEq :
identifier list -> constr -> goal sigma -> tactic * identifier list =
fun not_on_hyp expr g ->
let hyps = pf_hyps g in
let to_revert =
Util.map_succeed
(fun (id,_,t) ->
if List.mem id not_on_hyp || not (Termops.occur_term expr t)
then failwith "is_expr_context";
id) hyps in
let to_revert_constr = List.rev_map mkVar to_revert in
let type_of_expr = pf_type_of g expr in
let new_hyps = mkApp(Lazy.force refl_equal, [|type_of_expr; expr|])::
to_revert_constr in
tclTHENLIST
[h_generalize new_hyps;
(fun g2 ->
change_in_concl None
(pattern_occs [((false,[1]), expr)] (pf_env g2) Evd.empty (pf_concl g2)) g2);
simplest_case expr], to_revert
let terminate_case next_step (ci,a,t,l) expr_info continuation_tac infos g =
let b =
try
check_not_nested (expr_info.f_id::expr_info.forbidden_ids) a;
false
with _ ->
true
in
let a' = infos.info in
let new_info =
{infos with
info = mkCase(ci,t,a',l);
is_main_branch = expr_info.is_main_branch;
is_final = expr_info.is_final} in
let destruct_tac,rev_to_thin_intro =
mkDestructEq [expr_info.rec_arg_id] a' g in
let to_thin_intro = List.rev rev_to_thin_intro in
observe_tac (str "treating case " ++ int (Array.length l) ++ spc () ++ Printer.pr_lconstr a')
(try
(tclTHENS
destruct_tac
(list_map_i (fun i e -> observe_tac (str "do treat case") (treat_case b to_thin_intro (next_step continuation_tac) ci.ci_cstr_ndecls.(i) e new_info)) 0 (Array.to_list l)
))
with
| UserError("Refiner.thensn_tac3",_)
| UserError("Refiner.tclFAIL_s",_) ->
(observe_tac (str "is computable " ++ Printer.pr_lconstr new_info.info) (next_step continuation_tac {new_info with info = nf_betaiotazeta new_info.info} )
))
g
let terminate_app_rec (f,args) expr_info continuation_tac _ =
List.iter (check_not_nested (expr_info.f_id::expr_info.forbidden_ids))
args;
begin
try
let v = List.assoc args expr_info.args_assoc in
let new_infos = {expr_info with info = v} in
tclTHENLIST[
continuation_tac new_infos;
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST[
observe_tac (str "first split")
(split (ImplicitBindings [new_infos.info]));
observe_tac (str "destruct_bounds (3)")
(destruct_bounds new_infos)
]
else
tclIDTAC
]
with Not_found ->
observe_tac (str "terminate_app_rec not found") (tclTHENS
(simplest_elim (mkApp(mkVar expr_info.ih,Array.of_list args)))
[
tclTHENLIST[
intro_using rec_res_id;
intro;
onNthHypId 1
(fun v_bound ->
(onNthHypId 2
(fun v ->
let new_infos = { expr_info with
info = (mkVar v);
values_and_bounds =
(v,v_bound)::expr_info.values_and_bounds;
args_assoc=(args,mkVar v)::expr_info.args_assoc
} in
tclTHENLIST[
continuation_tac new_infos;
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST[
observe_tac (str "first split")
(split (ImplicitBindings [new_infos.info]));
observe_tac (str "destruct_bounds (2)")
(destruct_bounds new_infos)
]
else
tclIDTAC
]
)
)
)
];
observe_tac (str "proving decreasing") (
tclTHENS (* proof of args < formal args *)
(apply (Lazy.force expr_info.acc_inv))
[
observe_tac (str "h_assumption") h_assumption;
tclTHENLIST
[
tclTRY(list_rewrite true
(List.map
(fun e -> mkVar e,true)
expr_info.eqs
)
);
tclUSER expr_info.concl_tac true
(Some (
expr_info.ih::expr_info.acc_id::
(fun (x,y) -> y)
(List.split expr_info.values_and_bounds)
)
);
]
])
])
end
let terminate_info =
{ message = "prove_terminate with term ";
letiN = terminate_letin;
lambdA = (fun _ _ _ _ -> assert false);
casE = terminate_case;
otherS = terminate_others;
apP = terminate_app;
app_reC = terminate_app_rec;
}
let prove_terminate = travel terminate_info
(* Equation proof *)
let equation_case next_step (ci,a,t,l) expr_info continuation_tac infos =
terminate_case next_step (ci,a,t,l) expr_info continuation_tac infos
let rec prove_le g =
let x,z =
let _,args = decompose_app (pf_concl g) in
(List.hd args,List.hd (List.tl args))
in
tclFIRST[
h_assumption;
apply (delayed_force le_n);
begin
try
let matching_fun =
pf_is_matching g
(Pattern.PApp(Pattern.PRef (reference_of_constr (le ())),[|Pattern.PVar (destVar x);Pattern.PMeta None|])) in
let (h,t) = List.find (fun (_,t) -> matching_fun t) (pf_hyps_types g)
in
let y =
let _,args = decompose_app t in
List.hd (List.tl args)
in
tclTHENLIST[
apply(mkApp(le_trans (),[|x;y;z;mkVar h|]));
observe_tac (str "prove_le (rec)") (prove_le)
]
with Not_found -> tclFAIL 0 (mt())
end;
]
g
let rec make_rewrite_list expr_info max = function
| [] -> tclIDTAC
| (_,p,hp)::l ->
observe_tac (str "make_rewrite_list") (tclTHENS
(observe_tac (str "rewrite heq on " ++ pr_id p ) (
(fun g ->
let t_eq = compute_renamed_type g (mkVar hp) in
let k,def =
let k_na,_,t = destProd t_eq in
let _,_,t = destProd t in
let def_na,_,_ = destProd t in
Nameops.out_name k_na,Nameops.out_name def_na
in
general_rewrite_bindings false Termops.all_occurrences
true (* dep proofs also: *) true
(mkVar hp,
ExplicitBindings[dummy_loc,NamedHyp def,
expr_info.f_constr;dummy_loc,NamedHyp k,
(f_S max)]) false g) )
)
[make_rewrite_list expr_info max l;
tclTHENLIST[ (* x < S max proof *)
apply (delayed_force le_lt_n_Sm);
observe_tac (str "prove_le(2)") prove_le
]
] )
let make_rewrite expr_info l hp max =
tclTHENFIRST
(observe_tac (str "make_rewrite") (make_rewrite_list expr_info max l))
(observe_tac (str "make_rewrite") (tclTHENS
(fun g ->
let t_eq = compute_renamed_type g (mkVar hp) in
let k,def =
let k_na,_,t = destProd t_eq in
let _,_,t = destProd t in
let def_na,_,_ = destProd t in
Nameops.out_name k_na,Nameops.out_name def_na
in
observe_tac (str "general_rewrite_bindings") (general_rewrite_bindings false Termops.all_occurrences
true (* dep proofs also: *) true
(mkVar hp,
ExplicitBindings[dummy_loc,NamedHyp def,
expr_info.f_constr;dummy_loc,NamedHyp k,
(f_S (f_S max))]) false) g)
[observe_tac(str "make_rewrite finalize") (
(* tclORELSE( h_reflexivity) *)
(tclTHENLIST[
simpl_iter onConcl;
observe_tac (str "unfold functional")
(unfold_in_concl[((true,[1]),
evaluable_of_global_reference expr_info.func)]);
(list_rewrite true
(List.map (fun e -> mkVar e,true) expr_info.eqs));
(observe_tac (str "h_reflexivity") h_reflexivity)]))
;
tclTHENLIST[ (* x < S (S max) proof *)
apply (delayed_force le_lt_SS);
observe_tac (str "prove_le (3)") prove_le
]
])
)
let rec compute_max rew_tac max l =
match l with
| [] -> rew_tac max
| (_,p,_)::l ->
tclTHENLIST[
simplest_elim
(mkApp(delayed_force max_constr, [| max; mkVar p|]));
tclDO 3 intro;
onNLastHypsId 3 (fun lids ->
match lids with
| [hle2;hle1;pmax] -> compute_max rew_tac (mkVar pmax) l
| _ -> assert false
)]
let rec destruct_hex expr_info acc l =
match l with
| [] ->
begin
match List.rev acc with
| [] -> tclIDTAC
| (_,p,hp)::tl ->
observe_tac (str "compute max ") (compute_max (make_rewrite expr_info tl hp) (mkVar p) tl)
end
| (v,hex)::l ->
tclTHENLIST[
simplest_case (mkVar hex);
clear [hex];
tclDO 2 intro;
onNthHypId 1 (fun hp ->
onNthHypId 2 (fun p ->
observe_tac
(str "destruct_hex after " ++ pr_id hp ++ spc () ++ pr_id p)
(destruct_hex expr_info ((v,p,hp)::acc) l)
)
)
]
let rec intros_values_eq expr_info acc =
tclORELSE(
tclTHENLIST[
tclDO 2 intro;
onNthHypId 1 (fun hex ->
(onNthHypId 2 (fun v -> intros_values_eq expr_info ((v,hex)::acc)))
)
])
(tclCOMPLETE (
destruct_hex expr_info [] acc
))
let equation_others _ expr_info continuation_tac infos =
if expr_info.is_final && expr_info.is_main_branch
then
tclTHEN
(continuation_tac infos)
(intros_values_eq expr_info [])
else continuation_tac infos
let equation_letin (na,b,t,e) expr_info continuation_tac info =
let new_e = subst1 info.info e in
continuation_tac {info with info = new_e;}
let equation_app f_and_args expr_info continuation_tac infos =
if expr_info.is_final && expr_info.is_main_branch
then intros_values_eq expr_info []
else continuation_tac infos
let equation_app_rec (f,args) expr_info continuation_tac info =
begin
try
let v = List.assoc args expr_info.args_assoc in
let new_infos = {expr_info with info = v} in
observe_tac (str "app_rec found") (continuation_tac new_infos)
with Not_found ->
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST
[ simplest_case (mkApp (expr_info.f_terminate,Array.of_list args));
continuation_tac {expr_info with args_assoc = (args,delayed_force coq_O)::expr_info.args_assoc};
observe_tac (str "app_rec intros_values_eq") (intros_values_eq expr_info [])
]
else
tclTHENLIST[
simplest_case (mkApp (expr_info.f_terminate,Array.of_list args));
observe_tac (str "app_rec not_found") (continuation_tac {expr_info with args_assoc = (args,delayed_force coq_O)::expr_info.args_assoc})
]
end
let equation_info =
{message = "prove_equation with term ";
letiN = (fun _ -> assert false);
lambdA = (fun _ _ _ _ -> assert false);
casE = equation_case;
otherS = equation_others;
apP = equation_app;
app_reC = equation_app_rec
}
let prove_eq = travel equation_info
(* wrappers *)
(* [compute_terminate_type] computes the type of the Definition f_terminate from the type of f_F
*)
let compute_terminate_type nb_args func =
let _,a_arrow_b,_ = destLambda(def_of_const (constr_of_global func)) in
let rev_args,b = decompose_prod_n nb_args a_arrow_b in
let left =
mkApp(delayed_force iter,
Array.of_list
(lift 5 a_arrow_b:: mkRel 3::
constr_of_global func::mkRel 1::
List.rev (list_map_i (fun i _ -> mkRel (6+i)) 0 rev_args)
)
)
in
let right = mkRel 5 in
let equality = mkApp(delayed_force eq, [|lift 5 b; left; right|]) in
let result = (mkProd ((Name def_id) , lift 4 a_arrow_b, equality)) in
let cond = mkApp(delayed_force lt, [|(mkRel 2); (mkRel 1)|]) in
let nb_iter =
mkApp(delayed_force ex,
[|delayed_force nat;
(mkLambda
(Name
p_id,
delayed_force nat,
(mkProd (Name k_id, delayed_force nat,
mkArrow cond result))))|])in
let value = mkApp(delayed_force coq_sig,
[|b;
(mkLambda (Name v_id, b, nb_iter))|]) in
compose_prod rev_args value
let termination_proof_header is_mes input_type ids args_id relation
rec_arg_num rec_arg_id tac wf_tac : tactic =
begin
fun g ->
let nargs = List.length args_id in
let pre_rec_args =
List.rev_map
mkVar (fst (list_chop (rec_arg_num - 1) args_id))
in
let relation = substl pre_rec_args relation in
let input_type = substl pre_rec_args input_type in
let wf_thm = next_ident_away_in_goal (id_of_string ("wf_R")) ids in
let wf_rec_arg =
next_ident_away_in_goal
(id_of_string ("Acc_"^(string_of_id rec_arg_id)))
(wf_thm::ids)
in
let hrec = next_ident_away_in_goal hrec_id
(wf_rec_arg::wf_thm::ids) in
let acc_inv =
lazy (
mkApp (
delayed_force acc_inv_id,
[|input_type;relation;mkVar rec_arg_id|]
)
)
in
tclTHEN
(h_intros args_id)
(tclTHENS
(observe_tac
(str "first assert")
(assert_tac
(Name wf_rec_arg)
(mkApp (delayed_force acc_rel,
[|input_type;relation;mkVar rec_arg_id|])
)
)
)
[
(* accesibility proof *)
tclTHENS
(observe_tac
(str "second assert")
(assert_tac
(Name wf_thm)
(mkApp (delayed_force well_founded,[|input_type;relation|]))
)
)
[
(* interactive proof that the relation is well_founded *)
observe_tac (str "wf_tac") (wf_tac is_mes (Some args_id));
(* this gives the accessibility argument *)
observe_tac
(str "apply wf_thm")
(h_simplest_apply (mkApp(mkVar wf_thm,[|mkVar rec_arg_id|]))
)
]
;
(* rest of the proof *)
tclTHENSEQ
[observe_tac (str "generalize")
(onNLastHypsId (nargs+1)
(tclMAP (fun id ->
tclTHEN (h_generalize [mkVar id]) (h_clear false [id]))
))
;
observe_tac (str "h_fix") (h_fix (Some hrec) (nargs+1));
h_intros args_id;
h_intro wf_rec_arg;
observe_tac (str "tac") (tac wf_rec_arg hrec wf_rec_arg acc_inv)
]
]
) g
end
let rec instantiate_lambda t l =
match l with
| [] -> t
| a::l ->
let (_, _, body) = destLambda t in
instantiate_lambda (subst1 a body) l
let whole_start (concl_tac:tactic) nb_args is_mes func input_type relation rec_arg_num : tactic =
begin
fun g ->
let ids = Termops.ids_of_named_context (pf_hyps g) in
let func_body = (def_of_const (constr_of_global func)) in
let (f_name, _, body1) = destLambda func_body in
let f_id =
match f_name with
| Name f_id -> next_ident_away_in_goal f_id ids
| Anonymous -> anomaly "Anonymous function"
in
let n_names_types,_ = decompose_lam_n nb_args body1 in
let n_ids,ids =
List.fold_left
(fun (n_ids,ids) (n_name,_) ->
match n_name with
| Name id ->
let n_id = next_ident_away_in_goal id ids in
n_id::n_ids,n_id::ids
| _ -> anomaly "anonymous argument"
)
([],(f_id::ids))
n_names_types
in
let rec_arg_id = List.nth n_ids (rec_arg_num - 1) in
let expr = instantiate_lambda func_body (mkVar f_id::(List.map mkVar n_ids)) in
termination_proof_header
is_mes
input_type
ids
n_ids
relation
rec_arg_num
rec_arg_id
(fun rec_arg_id hrec acc_id acc_inv g ->
(prove_terminate (fun infos -> tclIDTAC)
{ is_main_branch = true; (* we are on the main branche (i.e. still on a match ... with .... end *)
is_final = true; (* and on leaf (more or less) *)
f_terminate = delayed_force coq_O;
nb_arg = nb_args;
concl_tac = concl_tac;
rec_arg_id = rec_arg_id;
is_mes = is_mes;
ih = hrec;
f_id = f_id;
f_constr = mkVar f_id;
func = func;
info = expr;
acc_inv = acc_inv;
acc_id = acc_id;
values_and_bounds = [];
eqs = [];
forbidden_ids = [];
args_assoc = []
}
)
g
)
(tclUSER_if_not_mes concl_tac)
g
end
let get_current_subgoals_types () =
let p = Proof_global.give_me_the_proof () in
let { Evd.it=sgs ; sigma=sigma } = Proof.V82.subgoals p in
List.map (Goal.V82.abstract_type sigma) sgs
let build_and_l l =
let and_constr = Coqlib.build_coq_and () in
let conj_constr = coq_conj () in
let mk_and p1 p2 =
Term.mkApp(and_constr,[|p1;p2|]) in
let rec is_well_founded t =
match kind_of_term t with
| Prod(_,_,t') -> is_well_founded t'
| App(_,_) ->
let (f,_) = decompose_app t in
eq_constr f (well_founded ())
| _ -> assert false
in
let compare t1 t2 =
let b1,b2= is_well_founded t1,is_well_founded t2 in
if (b1&&b2) || not (b1 || b2) then 0
else if b1 && not b2 then 1 else -1
in
let l = List.sort compare l in
let rec f = function
| [] -> failwith "empty list of subgoals!"
| [p] -> p,tclIDTAC,1
| p1::pl ->
let c,tac,nb = f pl in
mk_and p1 c,
tclTHENS
(apply (constr_of_global conj_constr))
[tclIDTAC;
tac
],nb+1
in f l
let is_rec_res id =
let rec_res_name = string_of_id rec_res_id in
let id_name = string_of_id id in
try
String.sub id_name 0 (String.length rec_res_name) = rec_res_name
with _ -> false
let clear_goals =
let rec clear_goal t =
match kind_of_term t with
| Prod(Name id as na,t',b) ->
let b' = clear_goal b in
if noccurn 1 b' && (is_rec_res id)
then Termops.pop b'
else if b' == b then t
else mkProd(na,t',b')
| _ -> map_constr clear_goal t
in
List.map clear_goal
let build_new_goal_type () =
let sub_gls_types = get_current_subgoals_types () in
Pp.msgnl ( str " sub_gls_types1 : = " + + Util.prlist_with_sep ( fun ( ) - > Pp.fnl ( ) + + Pp.fnl ( ) ) Printer.pr_lconstr sub_gls_types ) ;
let sub_gls_types = clear_goals sub_gls_types in
Pp.msgnl ( str " sub_gls_types2 : = " + + Util.prlist_with_sep ( fun ( ) - > Pp.fnl ( ) + + Pp.fnl ( ) ) Printer.pr_lconstr sub_gls_types ) ;
let res = build_and_l sub_gls_types in
res
let is_opaque_constant c =
let cb = Global.lookup_constant c in
match cb.Declarations.const_body with
| Declarations.OpaqueDef _ -> true
| Declarations.Undef _ -> true
| Declarations.Def _ -> false
| Declarations.Primitive _ -> true
let open_new_goal (build_proof:tactic -> tactic -> unit) using_lemmas ref_ goal_name (gls_type,decompose_and_tac,nb_goal) =
Pp.msgnl ( str " : = " + + ) ;
let current_proof_name = get_current_proof_name () in
let name = match goal_name with
| Some s -> s
| None ->
try (add_suffix current_proof_name "_subproof")
with _ -> anomaly "open_new_goal with an unamed theorem"
in
let sign = initialize_named_context_for_proof () in
let na = next_global_ident_away name [] in
if Termops.occur_existential gls_type then
Errors.error "\"abstract\" cannot handle existentials";
let hook _ _ =
let opacity =
let na_ref = Libnames.Ident (dummy_loc,na) in
let na_global = Nametab.global na_ref in
match na_global with
ConstRef c -> is_opaque_constant c
| _ -> anomaly "equation_lemma: not a constant"
in
let lemma = mkConst (Lib.make_con na) in
ref_ := Some lemma ;
let lid = ref [] in
let h_num = ref (-1) in
Flags.silently Vernacentries.interp (Vernacexpr.VernacAbort None);
build_proof
( fun gls ->
let hid = next_ident_away_in_goal h_id (pf_ids_of_hyps gls) in
tclTHENSEQ
[
h_generalize [lemma];
h_intro hid;
(fun g ->
let ids = pf_ids_of_hyps g in
tclTHEN
(Elim.h_decompose_and (mkVar hid))
(fun g ->
let ids' = pf_ids_of_hyps g in
lid := List.rev (list_subtract ids' ids);
if !lid = [] then lid := [hid];
tclIDTAC g
)
g
);
] gls)
(fun g ->
match kind_of_term (pf_concl g) with
| App(f,_) when eq_constr f (well_founded ()) ->
Auto.h_auto None [] (Some []) g
| _ ->
incr h_num;
(observe_tac (str "finishing using")
(
tclCOMPLETE(
tclFIRST[
tclTHEN
(eapply_with_bindings (mkVar (List.nth !lid !h_num), NoBindings))
e_assumption;
Eauto.eauto_with_bases
(true,5)
[Evd.empty,Lazy.force refl_equal]
[Auto.Hint_db.empty empty_transparent_state false]
]
)
)
)
g)
;
Lemmas.save_named opacity;
in
start_proof
na
(Decl_kinds.Global, Decl_kinds.Proof Decl_kinds.Lemma)
sign
gls_type
hook ;
if Indfun_common.is_strict_tcc ()
then
by (tclIDTAC)
else
begin
by (
fun g ->
tclTHEN
(decompose_and_tac)
(tclORELSE
(tclFIRST
(List.map
(fun c ->
tclTHENSEQ
[intros;
h_simplest_apply (interp_constr Evd.empty (Global.env()) c);
tclCOMPLETE Auto.default_auto
]
)
using_lemmas)
) tclIDTAC)
g)
end;
try
raises UserError _ if the proof is complete
if Flags.is_verbose () then (pp (Printer.pr_open_subgoals()))
with UserError _ ->
defined ()
let com_terminate
tcc_lemma_name
tcc_lemma_ref
is_mes
fonctional_ref
input_type
relation
rec_arg_num
thm_name using_lemmas
nb_args
hook =
let start_proof (tac_start:tactic) (tac_end:tactic) =
let (evmap, env) = Lemmas.get_current_context() in
start_proof thm_name
(Global, Proof Lemma) (Environ.named_context_val env)
(compute_terminate_type nb_args fonctional_ref) hook;
by (observe_tac (str "starting_tac") tac_start);
by (observe_tac (str "whole_start") (whole_start tac_end nb_args is_mes fonctional_ref
input_type relation rec_arg_num ))
in
start_proof tclIDTAC tclIDTAC;
try
let new_goal_type = build_new_goal_type () in
open_new_goal start_proof using_lemmas tcc_lemma_ref
(Some tcc_lemma_name)
(new_goal_type);
with Failure "empty list of subgoals!" ->
(* a non recursive function declared with measure ! *)
defined ()
let start_equation (f:global_reference) (term_f:global_reference)
(cont_tactic:identifier list -> tactic) g =
let ids = pf_ids_of_hyps g in
let terminate_constr = constr_of_global term_f in
let nargs = nb_prod (type_of_const terminate_constr) in
let x = n_x_id ids nargs in
tclTHENLIST [
h_intros x;
unfold_in_concl [(Termops.all_occurrences, evaluable_of_global_reference f)];
observe_tac (str "simplest_case")
(simplest_case (mkApp (terminate_constr,
Array.of_list (List.map mkVar x))));
observe_tac (str "prove_eq") (cont_tactic x)] g;;
let (com_eqn : int -> identifier ->
global_reference -> global_reference -> global_reference
-> constr -> unit) =
fun nb_arg eq_name functional_ref f_ref terminate_ref equation_lemma_type ->
let opacity =
match terminate_ref with
| ConstRef c -> is_opaque_constant c
| _ -> anomaly "terminate_lemma: not a constant"
in
let (evmap, env) = Lemmas.get_current_context() in
let f_constr = constr_of_global f_ref in
let equation_lemma_type = subst1 f_constr equation_lemma_type in
(start_proof eq_name (Global, Proof Lemma)
(Environ.named_context_val env) equation_lemma_type (fun _ _ -> ());
by
(start_equation f_ref terminate_ref
(fun x ->
prove_eq (fun _ -> tclIDTAC)
{nb_arg=nb_arg;
f_terminate = constr_of_global terminate_ref;
f_constr = f_constr;
concl_tac = tclIDTAC;
func=functional_ref;
info=(instantiate_lambda
(def_of_const (constr_of_global functional_ref))
(f_constr::List.map mkVar x)
);
is_main_branch = true;
is_final = true;
values_and_bounds = [];
eqs = [];
forbidden_ids = [];
acc_inv = lazy (assert false);
acc_id = id_of_string "____";
args_assoc = [];
f_id = id_of_string "______";
rec_arg_id = id_of_string "______";
is_mes = false;
ih = id_of_string "______";
}
)
);
( try Vernacentries.interp ( Vernacexpr . . ShowProof ) with _ - > ( ) ) ;
Vernacentries.interp ( Vernacexpr . . ShowScript ) ;
Flags.silently (fun () -> Lemmas.save_named opacity) () ;
Pp.msgnl ( str " eqn finished " ) ;
);;
let recursive_definition is_mes function_name rec_impls type_of_f r rec_arg_num eq
generate_induction_principle using_lemmas : unit =
let previous_label = Lib.current_command_label () in
let function_type = interp_constr Evd.empty (Global.env()) type_of_f in
let env = push_named (function_name,None,function_type) (Global.env()) in
Pp.msgnl ( str " function type : = " + + Printer.pr_lconstr function_type ) ;
let equation_lemma_type =
nf_betaiotazeta
(interp_gen (OfType None) Evd.empty env ~impls:rec_impls eq)
in
Pp.msgnl ( str " lemma type : = " + + Printer.pr_lconstr equation_lemma_type + + fnl ( ) ) ;
let res_vars,eq' = decompose_prod equation_lemma_type in
let env_eq' = Environ.push_rel_context (List.map (fun (x,y) -> (x,None,y)) res_vars) env in
let eq' = nf_zeta env_eq' eq' in
let res =
Pp.msgnl ( str " res_var : = " + + Printer.pr_lconstr_env ( push_rel_context ( List.map ( function ( x , t ) - > ( x , None , t ) ) res_vars ) env ) eq ' ) ;
Pp.msgnl ( str " rec_arg_num : = " + + str ( string_of_int rec_arg_num ) ) ;
Pp.msgnl ( str " eq ' : = " + + str ( string_of_int rec_arg_num ) ) ;
match kind_of_term eq' with
| App(e,[|_;_;eq_fix|]) ->
mkLambda (Name function_name,function_type,subst_var function_name (compose_lam res_vars eq_fix))
| _ -> failwith "Recursive Definition (res not eq)"
in
let pre_rec_args,function_type_before_rec_arg = decompose_prod_n (rec_arg_num - 1) function_type in
let (_, rec_arg_type, _) = destProd function_type_before_rec_arg in
let arg_types = List.rev_map snd (fst (decompose_prod_n (List.length res_vars) function_type)) in
let equation_id = add_suffix function_name "_equation" in
let functional_id = add_suffix function_name "_F" in
let term_id = add_suffix function_name "_terminate" in
let functional_ref = declare_fun functional_id (IsDefinition Decl_kinds.Definition) res in
let env_with_pre_rec_args = push_rel_context(List.map (function (x,t) -> (x,None,t)) pre_rec_args) env in
let relation =
interp_constr
Evd.empty
env_with_pre_rec_args
r
in
let tcc_lemma_name = add_suffix function_name "_tcc" in
let tcc_lemma_constr = ref None in
let _ = Pp.msgnl ( str " relation : = " + + Printer.pr_lconstr_env env_with_pre_rec_args relation ) in
let hook _ _ =
let term_ref = Nametab.locate (qualid_of_ident term_id) in
let f_ref = declare_f function_name (IsProof Lemma) arg_types term_ref in
let _ = Table.extraction_inline true [Ident (dummy_loc,term_id)] in
message " start second proof " ;
let stop =
try com_eqn (List.length res_vars) equation_id functional_ref f_ref term_ref (subst_var function_name equation_lemma_type);
false
with e ->
begin
if do_observe ()
then pperrnl (str "Cannot create equation Lemma " ++ Errors.print e)
else anomaly "Cannot create equation Lemma"
;
true
end
in
if not stop
then
let eq_ref = Nametab.locate (qualid_of_ident equation_id ) in
let f_ref = destConst (constr_of_global f_ref)
and functional_ref = destConst (constr_of_global functional_ref)
and eq_ref = destConst (constr_of_global eq_ref) in
generate_induction_principle f_ref tcc_lemma_constr
functional_ref eq_ref rec_arg_num rec_arg_type (nb_prod res) relation;
if Flags.is_verbose ()
then msgnl (h 1 (Ppconstr.pr_id function_name ++
spc () ++ str"is defined" )++ fnl () ++
h 1 (Ppconstr.pr_id equation_id ++
spc () ++ str"is defined" )
)
in
try
com_terminate
tcc_lemma_name
tcc_lemma_constr
is_mes functional_ref
rec_arg_type
relation rec_arg_num
term_id
using_lemmas
(List.length res_vars)
hook
with e ->
begin
(try ignore (Backtrack.backto previous_label) with _ -> ());
(* anomaly "Cannot create termination Lemma" *)
raise e
end
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/plugins/funind/recdef.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i camlp4deps: "parsing/grammar.cma" i
Ugly things which should not be here
Reductionops.local_strong Reductionops.whd_betaiotazeta
no avoid
no rels
Others ugly things ...
Debuging mechanism
Conclusion tactics
The boolean value is_mes expresses that the termination is expressed
using a measure function instead of a well-founded relation.
Travelling term.
Both definitions of [f_terminate] and [f_equation] use the same generic
travelling mechanism.
[check_not_nested forbidden e] checks that [e] does not contains any variable
of [forbidden]
['a info] contains the local information for travelling
function number of arguments
final tactic to finish proofs
name of the declared recursive argument
type of recursion
induction hypothesis name
function name
function term
termination proof term
functionnal reference
on the main branch or on a matched expression
the arguments of the constructor
infos of the caller
the continuation tactic of the caller
argument of the tactic
journey_info : specifies the actions to do on the different term constructors during the travelling of the term
f is coming from a decompose_app
Termination proof
list_rewrite true
;
proof of args < formal args
Equation proof
dep proofs also:
x < S max proof
dep proofs also:
tclORELSE( h_reflexivity)
x < S (S max) proof
wrappers
[compute_terminate_type] computes the type of the Definition f_terminate from the type of f_F
accesibility proof
interactive proof that the relation is well_founded
this gives the accessibility argument
rest of the proof
we are on the main branche (i.e. still on a match ... with .... end
and on leaf (more or less)
a non recursive function declared with measure !
anomaly "Cannot create termination Lemma" | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Tacexpr
open Term
open Namegen
open Environ
open Declarations
open Entries
open Pp
open Names
open Libnames
open Nameops
open Errors
open Util
open Closure
open RedFlags
open Tacticals
open Typing
open Tacmach
open Tactics
open Nametab
open Decls
open Declare
open Decl_kinds
open Tacred
open Proof_type
open Vernacinterp
open Pfedit
open Topconstr
open Glob_term
open Pretyping
open Safe_typing
open Constrintern
open Hiddentac
open Equality
open Auto
open Eauto
open Genarg
open Indfun_common
let coq_base_constant s =
Coqlib.gen_constant_in_modules "RecursiveDefinition"
(Coqlib.init_modules @ [["Coq";"Arith";"Le"];["Coq";"Arith";"Lt"]]) s;;
let coq_constant s =
Coqlib.gen_constant_in_modules "RecursiveDefinition"
(Coqlib.init_modules @ Coqlib.arith_modules) s;;
let find_reference sl s =
(locate (make_qualid(Names.make_dirpath
(List.map id_of_string (List.rev sl)))
(id_of_string s)));;
let (declare_fun : identifier -> logical_kind -> constr -> global_reference) =
fun f_id kind value ->
let ce = {const_entry_body = value;
const_entry_secctx = None;
const_entry_type = None;
const_entry_opaque = false;
const_entry_inline_code = false} in
ConstRef(declare_constant f_id (DefinitionEntry ce, kind));;
let defined () = Lemmas.save_named false
let def_of_const t =
match (kind_of_term t) with
Const sp ->
(try (match body_of_constant (Global.lookup_constant sp) with
| Some c -> Declarations.force c
| _ -> assert false)
with _ ->
anomaly ("Cannot find definition of constant "^
(string_of_id (id_of_label (con_label sp))))
)
|_ -> assert false
let type_of_const t =
match (kind_of_term t) with
Const sp -> Typeops.type_of_constant (Global.env()) sp
|_ -> assert false
let constant sl s =
constr_of_global
(locate (make_qualid(Names.make_dirpath
(List.map id_of_string (List.rev sl)))
(id_of_string s)));;
let const_of_ref = function
ConstRef kn -> kn
| _ -> anomaly "ConstRef expected"
let nf_zeta env =
Reductionops.clos_norm_flags (Closure.RedFlags.mkflags [Closure.RedFlags.fZETA])
env
Evd.empty
let clos_norm_flags flgs env sigma t =
Closure.norm_val (Closure.create_clos_infos flgs env) (Closure.inject (Reductionops.nf_evar sigma t)) in
clos_norm_flags Closure.betaiotazeta Environ.empty_env Evd.empty
Generic values
let pf_get_new_ids idl g =
let ids = pf_ids_of_hyps g in
List.fold_right
(fun id acc -> next_global_ident_away id (acc@ids)::acc)
idl
[]
let compute_renamed_type gls c =
(pf_type_of gls c)
let h'_id = id_of_string "h'"
let heq_id = id_of_string "Heq"
let teq_id = id_of_string "teq"
let ano_id = id_of_string "anonymous"
let x_id = id_of_string "x"
let k_id = id_of_string "k"
let v_id = id_of_string "v"
let def_id = id_of_string "def"
let p_id = id_of_string "p"
let rec_res_id = id_of_string "rec_res";;
let lt = function () -> (coq_base_constant "lt")
let le = function () -> (coq_base_constant "le")
let ex = function () -> (coq_base_constant "ex")
let nat = function () -> (coq_base_constant "nat")
let coq_sig = function () -> (coq_base_constant "sig")
let iter_ref () =
try find_reference ["Recdef"] "iter"
with Not_found -> error "module Recdef not loaded"
let iter = function () -> (constr_of_global (delayed_force iter_ref))
let eq = function () -> (coq_base_constant "eq")
let le_lt_SS = function () -> (constant ["Recdef"] "le_lt_SS")
let le_lt_n_Sm = function () -> (coq_base_constant "le_lt_n_Sm")
let le_trans = function () -> (coq_base_constant "le_trans")
let le_lt_trans = function () -> (coq_base_constant "le_lt_trans")
let lt_S_n = function () -> (coq_base_constant "lt_S_n")
let le_n = function () -> (coq_base_constant "le_n")
let coq_sig_ref = function () -> (find_reference ["Coq";"Init";"Specif"] "sig")
let coq_O = function () -> (coq_base_constant "O")
let coq_S = function () -> (coq_base_constant "S")
let gt_antirefl = function () -> (coq_constant "gt_irrefl")
let lt_n_O = function () -> (coq_base_constant "lt_n_O")
let lt_n_Sn = function () -> (coq_base_constant "lt_n_Sn")
let f_equal = function () -> (coq_constant "f_equal")
let well_founded_induction = function () -> (coq_constant "well_founded_induction")
let max_ref = function () -> (find_reference ["Recdef"] "max")
let max_constr = function () -> (constr_of_global (delayed_force max_ref))
let coq_conj = function () -> find_reference ["Coq";"Init";"Logic"] "conj"
let f_S t = mkApp(delayed_force coq_S, [|t|]);;
let make_refl_eq constructor type_of_t t =
mkApp(constructor,[|type_of_t;t|])
let rec n_x_id ids n =
if n = 0 then []
else let x = next_ident_away_in_goal x_id ids in
x::n_x_id (x::ids) (n-1);;
let simpl_iter clause =
reduce
(Lazy
{rBeta=true;rIota=true;rZeta= true; rDelta=false;
rConst = [ EvalConstRef (const_of_ref (delayed_force iter_ref))]})
clause
let (value_f:constr list -> global_reference -> constr) =
fun al fterm ->
let d0 = dummy_loc in
let rev_x_id_l =
(
List.fold_left
(fun x_id_l _ ->
let x_id = next_ident_away_in_goal x_id x_id_l in
x_id::x_id_l
)
[]
al
)
in
let context = List.map
(fun (x, c) -> Name x, None, c) (List.combine rev_x_id_l (List.rev al))
in
let env = Environ.push_rel_context context (Global.env ()) in
let glob_body =
GCases
(d0,RegularStyle,None,
[GApp(d0, GRef(d0,fterm), List.rev_map (fun x_id -> GVar(d0, x_id)) rev_x_id_l),
(Anonymous,None)],
[d0, [v_id], [PatCstr(d0,(destIndRef
(delayed_force coq_sig_ref),1),
[PatVar(d0, Name v_id);
PatVar(d0, Anonymous)],
Anonymous)],
GVar(d0,v_id)])
in
let body = understand Evd.empty env glob_body in
it_mkLambda_or_LetIn body context
let (declare_f : identifier -> logical_kind -> constr list -> global_reference -> global_reference) =
fun f_id kind input_type fterm_ref ->
declare_fun f_id kind (value_f input_type fterm_ref);;
let debug_queue = Stack.create ()
let rec print_debug_queue b e =
if not (Stack.is_empty debug_queue)
then
begin
let lmsg,goal = Stack.pop debug_queue in
if b then
Pp.msgnl (lmsg ++ (str " raised exception " ++ Errors.print e) ++ str " on goal " ++ goal)
else
begin
Pp.msgnl (str " from " ++ lmsg ++ str " on goal " ++ goal);
end;
print_debug_queue false e;
end
let observe strm =
if do_observe ()
then Pp.msgnl strm
else ()
let do_observe_tac s tac g =
let goal = Printer.pr_goal g in
let lmsg = (str "recdef : ") ++ s in
observe (s++fnl());
Stack.push (lmsg,goal) debug_queue;
try
let v = tac g in
ignore(Stack.pop debug_queue);
v
with e ->
if not (Stack.is_empty debug_queue)
then
begin
let e : exn = Cerrors.process_vernac_interp_error e in
print_debug_queue true e
end
;
raise e
let observe_tac s tac g =
if do_observe ()
then do_observe_tac s tac g
else tac g
let tclUSER tac is_mes l g =
let clear_tac =
match l with
| None -> h_clear false []
| Some l -> tclMAP (fun id -> tclTRY (h_clear false [id])) (List.rev l)
in
tclTHENSEQ
[
clear_tac;
if is_mes
then tclTHENLIST
[
unfold_in_concl [(Termops.all_occurrences, evaluable_of_global_reference
(delayed_force Indfun_common.ltof_ref))];
tac
]
else tac
]
g
let tclUSER_if_not_mes concl_tac is_mes names_to_suppress =
if is_mes
then tclCOMPLETE (h_simplest_apply (delayed_force well_founded_ltof))
else tclUSER concl_tac is_mes names_to_suppress
let check_not_nested forbidden e =
let rec check_not_nested e =
match kind_of_term e with
| Rel _ -> ()
| Var x -> if List.mem x (forbidden) then error ("check_not_nested : failure "^string_of_id x)
| Meta _ | Evar _ | Sort _ -> ()
| Cast(e,_,t) -> check_not_nested e;check_not_nested t
| Prod(_,t,b) -> check_not_nested t;check_not_nested b
| Lambda(_,t,b) -> check_not_nested t;check_not_nested b
| LetIn(_,v,t,b) -> check_not_nested t;check_not_nested b;check_not_nested v
| App(f,l) -> check_not_nested f;Array.iter check_not_nested l
| Const _ -> ()
| Ind _ -> ()
| Construct _ -> ()
| Case(_,t,e,a) ->
check_not_nested t;check_not_nested e;Array.iter check_not_nested a
| Fix _ -> error "check_not_nested : Fix"
| CoFix _ -> error "check_not_nested : Fix"
in
try
check_not_nested e
with UserError(_,p) ->
errorlabstrm "_" (str "on expr : " ++ Printer.pr_lconstr e ++ str " " ++ p)
type 'a infos =
info : 'a;
final first order term or not
values_and_bounds : (identifier*identifier) list;
eqs : identifier list;
forbidden_ids : identifier list;
acc_inv : constr lazy_t;
acc_id : identifier;
args_assoc : ((constr list)*constr) list;
}
type ('a,'b) journey_info_tac =
tactic
type journey_info =
{ letiN : ((name*constr*types*constr),constr) journey_info_tac;
lambdA : ((name*types*constr),constr) journey_info_tac;
casE : ((constr infos -> tactic) -> constr infos -> tactic) ->
((case_info * constr * constr * constr array),constr) journey_info_tac;
otherS : (unit,constr) journey_info_tac;
apP : (constr*(constr list),constr) journey_info_tac;
app_reC : (constr*(constr list),constr) journey_info_tac;
message : string
}
let rec add_vars forbidden e =
match kind_of_term e with
| Var x -> x::forbidden
| _ -> fold_constr add_vars forbidden e
let treat_case forbid_new_ids to_intros finalize_tac nb_lam e infos : tactic =
fun g ->
let rev_context,b = decompose_lam_n nb_lam e in
let ids = List.fold_left (fun acc (na,_) ->
let pre_id =
match na with
| Name x -> x
| Anonymous -> ano_id
in
pre_id::acc
) [] rev_context in
let rev_ids = pf_get_new_ids (List.rev ids) g in
let new_b = substl (List.map mkVar rev_ids) b in
tclTHENSEQ
[
h_intros (List.rev rev_ids);
intro_using teq_id;
onLastHypId (fun heq ->
tclTHENSEQ[
thin to_intros;
h_intros to_intros;
(fun g' ->
let ty_teq = pf_type_of g' (mkVar heq) in
let teq_lhs,teq_rhs =
let _,args = try destApp ty_teq with _ -> Pp.msgnl (Printer.pr_goal g' ++ fnl () ++ pr_id heq ++ str ":" ++ Printer.pr_lconstr ty_teq); assert false in
args.(1),args.(2)
in
let new_b' = Termops.replace_term teq_lhs teq_rhs new_b in
let new_infos = {
infos with
info = new_b';
eqs = heq::infos.eqs;
forbidden_ids =
if forbid_new_ids
then add_vars infos.forbidden_ids new_b'
else infos.forbidden_ids
} in
finalize_tac new_infos g'
)
]
)
] g
let rec travel_aux jinfo continuation_tac (expr_info:constr infos) =
match kind_of_term expr_info.info with
| CoFix _ | Fix _ -> error "Function cannot treat local fixpoint or cofixpoint"
| LetIn(na,b,t,e) ->
begin
let new_continuation_tac =
jinfo.letiN (na,b,t,e) expr_info continuation_tac
in
travel jinfo new_continuation_tac
{expr_info with info = b; is_final=false}
end
| Rel _ -> anomaly "Free var in goal conclusion !"
| Prod _ ->
begin
try
check_not_nested (expr_info.f_id::expr_info.forbidden_ids) expr_info.info;
jinfo.otherS () expr_info continuation_tac expr_info
with _ ->
errorlabstrm "Recdef.travel" (str "the term " ++ Printer.pr_lconstr expr_info.info ++ str " can not contain a recursive call to " ++ pr_id expr_info.f_id)
end
| Lambda(n,t,b) ->
begin
try
check_not_nested (expr_info.f_id::expr_info.forbidden_ids) expr_info.info;
jinfo.otherS () expr_info continuation_tac expr_info
with _ ->
errorlabstrm "Recdef.travel" (str "the term " ++ Printer.pr_lconstr expr_info.info ++ str " can not contain a recursive call to " ++ pr_id expr_info.f_id)
end
| Case(ci,t,a,l) ->
begin
let continuation_tac_a =
jinfo.casE
(travel jinfo) (ci,t,a,l)
expr_info continuation_tac in
travel
jinfo continuation_tac_a
{expr_info with info = a; is_main_branch = false;
is_final = false}
end
| App _ ->
let f,args = decompose_app expr_info.info in
if eq_constr f (expr_info.f_constr)
then jinfo.app_reC (f,args) expr_info continuation_tac expr_info
else
begin
match kind_of_term f with
| Const _ | Construct _ | Rel _ | Evar _ | Meta _ | Ind _
| Sort _ | Prod _ | Var _ ->
let new_infos = {expr_info with info=(f,args)} in
let new_continuation_tac =
jinfo.apP (f,args) expr_info continuation_tac in
travel_args jinfo
expr_info.is_main_branch new_continuation_tac new_infos
| _ -> assert false
end
| Cast(t,_,_) -> travel jinfo continuation_tac {expr_info with info=t}
| Const _ | Var _ | Meta _ | Evar _ | Sort _ | Construct _ | Ind _ ->
let new_continuation_tac =
jinfo.otherS () expr_info continuation_tac in
new_continuation_tac expr_info
and travel_args jinfo is_final continuation_tac infos =
let (f_args',args) = infos.info in
match args with
| [] ->
continuation_tac {infos with info = f_args'; is_final = is_final}
| arg::args' ->
let new_continuation_tac new_infos =
let new_arg = new_infos.info in
travel_args jinfo is_final
continuation_tac
{new_infos with info = (mkApp(f_args',[|new_arg|]),args')}
in
travel jinfo new_continuation_tac
{infos with info=arg;is_final=false}
and travel jinfo continuation_tac expr_info =
observe_tac
(str jinfo.message ++ Printer.pr_lconstr expr_info.info)
(travel_aux jinfo continuation_tac expr_info)
let rec prove_lt hyple g =
begin
try
let (_,args) = decompose_app (pf_concl g) in
let x = try destVar (List.hd args) with _ -> assert false in
let z = try destVar (List.hd (List.tl args)) with _ -> assert false in
let h =
List.find (fun id ->
let _,args' = decompose_app (pf_type_of g (mkVar id)) in
try x = destVar (List.hd args')
with _ -> false
) hyple
in
let y =
List.hd (List.tl (snd (decompose_app (pf_type_of g (mkVar h))))) in
tclTHENLIST[
apply (mkApp(le_lt_trans (),[|mkVar x;y;mkVar z;mkVar h|]));
observe_tac (str "prove_lt") (prove_lt hyple)
]
with Not_found ->
(
(
tclTHENLIST[
apply (delayed_force lt_S_n);
(observe_tac (str "assumption: " ++ Printer.pr_goal g) (h_assumption))
])
)
end
g
let rec destruct_bounds_aux infos (bound,hyple,rechyps) lbounds g =
match lbounds with
| [] ->
let ids = pf_ids_of_hyps g in
let s_max = mkApp(delayed_force coq_S, [|bound|]) in
let k = next_ident_away_in_goal k_id ids in
let ids = k::ids in
let h' = next_ident_away_in_goal (h'_id) ids in
let ids = h'::ids in
let def = next_ident_away_in_goal def_id ids in
tclTHENLIST[
split (ImplicitBindings [s_max]);
intro_then
(fun id ->
observe_tac (str "destruct_bounds_aux")
(tclTHENS (simplest_case (mkVar id))
[
tclTHENLIST[intro_using h_id;
simplest_elim(mkApp(delayed_force lt_n_O,[|s_max|]));
default_full_auto];
tclTHENLIST[
observe_tac (str "clearing k ") (clear [id]);
h_intros [k;h';def];
observe_tac (str "simple_iter") (simpl_iter onConcl);
observe_tac (str "unfold functional")
(unfold_in_concl[((true,[1]),
evaluable_of_global_reference infos.func)]);
observe_tac (str "test" ) (
tclTHENLIST[
list_rewrite true
(List.fold_right
(fun e acc -> (mkVar e,true)::acc)
infos.eqs
(List.map (fun e -> (e,true)) rechyps)
);
( List.map ( fun e - > ( mkVar e , true ) ) infos.eqs )
(observe_tac (str "finishing")
(tclORELSE
h_reflexivity
(observe_tac (str "calling prove_lt") (prove_lt hyple))))])
]
]
))
] g
| (_,v_bound)::l ->
tclTHENLIST[
simplest_elim (mkVar v_bound);
h_clear false [v_bound];
tclDO 2 intro;
onNthHypId 1
(fun p_hyp ->
(onNthHypId 2
(fun p ->
tclTHENLIST[
simplest_elim
(mkApp(delayed_force max_constr, [| bound; mkVar p|]));
tclDO 3 intro;
onNLastHypsId 3 (fun lids ->
match lids with
[hle2;hle1;pmax] ->
destruct_bounds_aux infos
((mkVar pmax),
hle1::hle2::hyple,(mkVar p_hyp)::rechyps)
l
| _ -> assert false) ;
]
)
)
)
] g
let destruct_bounds infos =
destruct_bounds_aux infos (delayed_force coq_O,[],[]) infos.values_and_bounds
let terminate_app f_and_args expr_info continuation_tac infos =
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST[
continuation_tac infos;
observe_tac (str "first split")
(split (ImplicitBindings [infos.info]));
observe_tac (str "destruct_bounds (1)") (destruct_bounds infos)
]
else continuation_tac infos
let terminate_others _ expr_info continuation_tac infos =
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST[
continuation_tac infos;
observe_tac (str "first split")
(split (ImplicitBindings [infos.info]));
observe_tac (str "destruct_bounds") (destruct_bounds infos)
]
else continuation_tac infos
let terminate_letin (na,b,t,e) expr_info continuation_tac info =
let new_e = subst1 info.info e in
let new_forbidden =
let forbid =
try
check_not_nested (expr_info.f_id::expr_info.forbidden_ids) b;
true
with _ -> false
in
if forbid
then
match na with
| Anonymous -> info.forbidden_ids
| Name id -> id::info.forbidden_ids
else info.forbidden_ids
in
continuation_tac {info with info = new_e; forbidden_ids = new_forbidden}
This is like the previous one except that it also rewrite on all
hypotheses except the ones given in the first argument . All the
modified hypotheses are generalized in the process and should be
introduced back later ; the result is the pair of the tactic and the
list of hypotheses that have been generalized and cleared .
hypotheses except the ones given in the first argument. All the
modified hypotheses are generalized in the process and should be
introduced back later; the result is the pair of the tactic and the
list of hypotheses that have been generalized and cleared. *)
let mkDestructEq :
identifier list -> constr -> goal sigma -> tactic * identifier list =
fun not_on_hyp expr g ->
let hyps = pf_hyps g in
let to_revert =
Util.map_succeed
(fun (id,_,t) ->
if List.mem id not_on_hyp || not (Termops.occur_term expr t)
then failwith "is_expr_context";
id) hyps in
let to_revert_constr = List.rev_map mkVar to_revert in
let type_of_expr = pf_type_of g expr in
let new_hyps = mkApp(Lazy.force refl_equal, [|type_of_expr; expr|])::
to_revert_constr in
tclTHENLIST
[h_generalize new_hyps;
(fun g2 ->
change_in_concl None
(pattern_occs [((false,[1]), expr)] (pf_env g2) Evd.empty (pf_concl g2)) g2);
simplest_case expr], to_revert
let terminate_case next_step (ci,a,t,l) expr_info continuation_tac infos g =
let b =
try
check_not_nested (expr_info.f_id::expr_info.forbidden_ids) a;
false
with _ ->
true
in
let a' = infos.info in
let new_info =
{infos with
info = mkCase(ci,t,a',l);
is_main_branch = expr_info.is_main_branch;
is_final = expr_info.is_final} in
let destruct_tac,rev_to_thin_intro =
mkDestructEq [expr_info.rec_arg_id] a' g in
let to_thin_intro = List.rev rev_to_thin_intro in
observe_tac (str "treating case " ++ int (Array.length l) ++ spc () ++ Printer.pr_lconstr a')
(try
(tclTHENS
destruct_tac
(list_map_i (fun i e -> observe_tac (str "do treat case") (treat_case b to_thin_intro (next_step continuation_tac) ci.ci_cstr_ndecls.(i) e new_info)) 0 (Array.to_list l)
))
with
| UserError("Refiner.thensn_tac3",_)
| UserError("Refiner.tclFAIL_s",_) ->
(observe_tac (str "is computable " ++ Printer.pr_lconstr new_info.info) (next_step continuation_tac {new_info with info = nf_betaiotazeta new_info.info} )
))
g
let terminate_app_rec (f,args) expr_info continuation_tac _ =
List.iter (check_not_nested (expr_info.f_id::expr_info.forbidden_ids))
args;
begin
try
let v = List.assoc args expr_info.args_assoc in
let new_infos = {expr_info with info = v} in
tclTHENLIST[
continuation_tac new_infos;
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST[
observe_tac (str "first split")
(split (ImplicitBindings [new_infos.info]));
observe_tac (str "destruct_bounds (3)")
(destruct_bounds new_infos)
]
else
tclIDTAC
]
with Not_found ->
observe_tac (str "terminate_app_rec not found") (tclTHENS
(simplest_elim (mkApp(mkVar expr_info.ih,Array.of_list args)))
[
tclTHENLIST[
intro_using rec_res_id;
intro;
onNthHypId 1
(fun v_bound ->
(onNthHypId 2
(fun v ->
let new_infos = { expr_info with
info = (mkVar v);
values_and_bounds =
(v,v_bound)::expr_info.values_and_bounds;
args_assoc=(args,mkVar v)::expr_info.args_assoc
} in
tclTHENLIST[
continuation_tac new_infos;
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST[
observe_tac (str "first split")
(split (ImplicitBindings [new_infos.info]));
observe_tac (str "destruct_bounds (2)")
(destruct_bounds new_infos)
]
else
tclIDTAC
]
)
)
)
];
observe_tac (str "proving decreasing") (
(apply (Lazy.force expr_info.acc_inv))
[
observe_tac (str "h_assumption") h_assumption;
tclTHENLIST
[
tclTRY(list_rewrite true
(List.map
(fun e -> mkVar e,true)
expr_info.eqs
)
);
tclUSER expr_info.concl_tac true
(Some (
expr_info.ih::expr_info.acc_id::
(fun (x,y) -> y)
(List.split expr_info.values_and_bounds)
)
);
]
])
])
end
let terminate_info =
{ message = "prove_terminate with term ";
letiN = terminate_letin;
lambdA = (fun _ _ _ _ -> assert false);
casE = terminate_case;
otherS = terminate_others;
apP = terminate_app;
app_reC = terminate_app_rec;
}
let prove_terminate = travel terminate_info
let equation_case next_step (ci,a,t,l) expr_info continuation_tac infos =
terminate_case next_step (ci,a,t,l) expr_info continuation_tac infos
let rec prove_le g =
let x,z =
let _,args = decompose_app (pf_concl g) in
(List.hd args,List.hd (List.tl args))
in
tclFIRST[
h_assumption;
apply (delayed_force le_n);
begin
try
let matching_fun =
pf_is_matching g
(Pattern.PApp(Pattern.PRef (reference_of_constr (le ())),[|Pattern.PVar (destVar x);Pattern.PMeta None|])) in
let (h,t) = List.find (fun (_,t) -> matching_fun t) (pf_hyps_types g)
in
let y =
let _,args = decompose_app t in
List.hd (List.tl args)
in
tclTHENLIST[
apply(mkApp(le_trans (),[|x;y;z;mkVar h|]));
observe_tac (str "prove_le (rec)") (prove_le)
]
with Not_found -> tclFAIL 0 (mt())
end;
]
g
let rec make_rewrite_list expr_info max = function
| [] -> tclIDTAC
| (_,p,hp)::l ->
observe_tac (str "make_rewrite_list") (tclTHENS
(observe_tac (str "rewrite heq on " ++ pr_id p ) (
(fun g ->
let t_eq = compute_renamed_type g (mkVar hp) in
let k,def =
let k_na,_,t = destProd t_eq in
let _,_,t = destProd t in
let def_na,_,_ = destProd t in
Nameops.out_name k_na,Nameops.out_name def_na
in
general_rewrite_bindings false Termops.all_occurrences
(mkVar hp,
ExplicitBindings[dummy_loc,NamedHyp def,
expr_info.f_constr;dummy_loc,NamedHyp k,
(f_S max)]) false g) )
)
[make_rewrite_list expr_info max l;
apply (delayed_force le_lt_n_Sm);
observe_tac (str "prove_le(2)") prove_le
]
] )
let make_rewrite expr_info l hp max =
tclTHENFIRST
(observe_tac (str "make_rewrite") (make_rewrite_list expr_info max l))
(observe_tac (str "make_rewrite") (tclTHENS
(fun g ->
let t_eq = compute_renamed_type g (mkVar hp) in
let k,def =
let k_na,_,t = destProd t_eq in
let _,_,t = destProd t in
let def_na,_,_ = destProd t in
Nameops.out_name k_na,Nameops.out_name def_na
in
observe_tac (str "general_rewrite_bindings") (general_rewrite_bindings false Termops.all_occurrences
(mkVar hp,
ExplicitBindings[dummy_loc,NamedHyp def,
expr_info.f_constr;dummy_loc,NamedHyp k,
(f_S (f_S max))]) false) g)
[observe_tac(str "make_rewrite finalize") (
(tclTHENLIST[
simpl_iter onConcl;
observe_tac (str "unfold functional")
(unfold_in_concl[((true,[1]),
evaluable_of_global_reference expr_info.func)]);
(list_rewrite true
(List.map (fun e -> mkVar e,true) expr_info.eqs));
(observe_tac (str "h_reflexivity") h_reflexivity)]))
;
apply (delayed_force le_lt_SS);
observe_tac (str "prove_le (3)") prove_le
]
])
)
let rec compute_max rew_tac max l =
match l with
| [] -> rew_tac max
| (_,p,_)::l ->
tclTHENLIST[
simplest_elim
(mkApp(delayed_force max_constr, [| max; mkVar p|]));
tclDO 3 intro;
onNLastHypsId 3 (fun lids ->
match lids with
| [hle2;hle1;pmax] -> compute_max rew_tac (mkVar pmax) l
| _ -> assert false
)]
let rec destruct_hex expr_info acc l =
match l with
| [] ->
begin
match List.rev acc with
| [] -> tclIDTAC
| (_,p,hp)::tl ->
observe_tac (str "compute max ") (compute_max (make_rewrite expr_info tl hp) (mkVar p) tl)
end
| (v,hex)::l ->
tclTHENLIST[
simplest_case (mkVar hex);
clear [hex];
tclDO 2 intro;
onNthHypId 1 (fun hp ->
onNthHypId 2 (fun p ->
observe_tac
(str "destruct_hex after " ++ pr_id hp ++ spc () ++ pr_id p)
(destruct_hex expr_info ((v,p,hp)::acc) l)
)
)
]
let rec intros_values_eq expr_info acc =
tclORELSE(
tclTHENLIST[
tclDO 2 intro;
onNthHypId 1 (fun hex ->
(onNthHypId 2 (fun v -> intros_values_eq expr_info ((v,hex)::acc)))
)
])
(tclCOMPLETE (
destruct_hex expr_info [] acc
))
let equation_others _ expr_info continuation_tac infos =
if expr_info.is_final && expr_info.is_main_branch
then
tclTHEN
(continuation_tac infos)
(intros_values_eq expr_info [])
else continuation_tac infos
let equation_letin (na,b,t,e) expr_info continuation_tac info =
let new_e = subst1 info.info e in
continuation_tac {info with info = new_e;}
let equation_app f_and_args expr_info continuation_tac infos =
if expr_info.is_final && expr_info.is_main_branch
then intros_values_eq expr_info []
else continuation_tac infos
let equation_app_rec (f,args) expr_info continuation_tac info =
begin
try
let v = List.assoc args expr_info.args_assoc in
let new_infos = {expr_info with info = v} in
observe_tac (str "app_rec found") (continuation_tac new_infos)
with Not_found ->
if expr_info.is_final && expr_info.is_main_branch
then
tclTHENLIST
[ simplest_case (mkApp (expr_info.f_terminate,Array.of_list args));
continuation_tac {expr_info with args_assoc = (args,delayed_force coq_O)::expr_info.args_assoc};
observe_tac (str "app_rec intros_values_eq") (intros_values_eq expr_info [])
]
else
tclTHENLIST[
simplest_case (mkApp (expr_info.f_terminate,Array.of_list args));
observe_tac (str "app_rec not_found") (continuation_tac {expr_info with args_assoc = (args,delayed_force coq_O)::expr_info.args_assoc})
]
end
let equation_info =
{message = "prove_equation with term ";
letiN = (fun _ -> assert false);
lambdA = (fun _ _ _ _ -> assert false);
casE = equation_case;
otherS = equation_others;
apP = equation_app;
app_reC = equation_app_rec
}
let prove_eq = travel equation_info
let compute_terminate_type nb_args func =
let _,a_arrow_b,_ = destLambda(def_of_const (constr_of_global func)) in
let rev_args,b = decompose_prod_n nb_args a_arrow_b in
let left =
mkApp(delayed_force iter,
Array.of_list
(lift 5 a_arrow_b:: mkRel 3::
constr_of_global func::mkRel 1::
List.rev (list_map_i (fun i _ -> mkRel (6+i)) 0 rev_args)
)
)
in
let right = mkRel 5 in
let equality = mkApp(delayed_force eq, [|lift 5 b; left; right|]) in
let result = (mkProd ((Name def_id) , lift 4 a_arrow_b, equality)) in
let cond = mkApp(delayed_force lt, [|(mkRel 2); (mkRel 1)|]) in
let nb_iter =
mkApp(delayed_force ex,
[|delayed_force nat;
(mkLambda
(Name
p_id,
delayed_force nat,
(mkProd (Name k_id, delayed_force nat,
mkArrow cond result))))|])in
let value = mkApp(delayed_force coq_sig,
[|b;
(mkLambda (Name v_id, b, nb_iter))|]) in
compose_prod rev_args value
let termination_proof_header is_mes input_type ids args_id relation
rec_arg_num rec_arg_id tac wf_tac : tactic =
begin
fun g ->
let nargs = List.length args_id in
let pre_rec_args =
List.rev_map
mkVar (fst (list_chop (rec_arg_num - 1) args_id))
in
let relation = substl pre_rec_args relation in
let input_type = substl pre_rec_args input_type in
let wf_thm = next_ident_away_in_goal (id_of_string ("wf_R")) ids in
let wf_rec_arg =
next_ident_away_in_goal
(id_of_string ("Acc_"^(string_of_id rec_arg_id)))
(wf_thm::ids)
in
let hrec = next_ident_away_in_goal hrec_id
(wf_rec_arg::wf_thm::ids) in
let acc_inv =
lazy (
mkApp (
delayed_force acc_inv_id,
[|input_type;relation;mkVar rec_arg_id|]
)
)
in
tclTHEN
(h_intros args_id)
(tclTHENS
(observe_tac
(str "first assert")
(assert_tac
(Name wf_rec_arg)
(mkApp (delayed_force acc_rel,
[|input_type;relation;mkVar rec_arg_id|])
)
)
)
[
tclTHENS
(observe_tac
(str "second assert")
(assert_tac
(Name wf_thm)
(mkApp (delayed_force well_founded,[|input_type;relation|]))
)
)
[
observe_tac (str "wf_tac") (wf_tac is_mes (Some args_id));
observe_tac
(str "apply wf_thm")
(h_simplest_apply (mkApp(mkVar wf_thm,[|mkVar rec_arg_id|]))
)
]
;
tclTHENSEQ
[observe_tac (str "generalize")
(onNLastHypsId (nargs+1)
(tclMAP (fun id ->
tclTHEN (h_generalize [mkVar id]) (h_clear false [id]))
))
;
observe_tac (str "h_fix") (h_fix (Some hrec) (nargs+1));
h_intros args_id;
h_intro wf_rec_arg;
observe_tac (str "tac") (tac wf_rec_arg hrec wf_rec_arg acc_inv)
]
]
) g
end
let rec instantiate_lambda t l =
match l with
| [] -> t
| a::l ->
let (_, _, body) = destLambda t in
instantiate_lambda (subst1 a body) l
let whole_start (concl_tac:tactic) nb_args is_mes func input_type relation rec_arg_num : tactic =
begin
fun g ->
let ids = Termops.ids_of_named_context (pf_hyps g) in
let func_body = (def_of_const (constr_of_global func)) in
let (f_name, _, body1) = destLambda func_body in
let f_id =
match f_name with
| Name f_id -> next_ident_away_in_goal f_id ids
| Anonymous -> anomaly "Anonymous function"
in
let n_names_types,_ = decompose_lam_n nb_args body1 in
let n_ids,ids =
List.fold_left
(fun (n_ids,ids) (n_name,_) ->
match n_name with
| Name id ->
let n_id = next_ident_away_in_goal id ids in
n_id::n_ids,n_id::ids
| _ -> anomaly "anonymous argument"
)
([],(f_id::ids))
n_names_types
in
let rec_arg_id = List.nth n_ids (rec_arg_num - 1) in
let expr = instantiate_lambda func_body (mkVar f_id::(List.map mkVar n_ids)) in
termination_proof_header
is_mes
input_type
ids
n_ids
relation
rec_arg_num
rec_arg_id
(fun rec_arg_id hrec acc_id acc_inv g ->
(prove_terminate (fun infos -> tclIDTAC)
f_terminate = delayed_force coq_O;
nb_arg = nb_args;
concl_tac = concl_tac;
rec_arg_id = rec_arg_id;
is_mes = is_mes;
ih = hrec;
f_id = f_id;
f_constr = mkVar f_id;
func = func;
info = expr;
acc_inv = acc_inv;
acc_id = acc_id;
values_and_bounds = [];
eqs = [];
forbidden_ids = [];
args_assoc = []
}
)
g
)
(tclUSER_if_not_mes concl_tac)
g
end
let get_current_subgoals_types () =
let p = Proof_global.give_me_the_proof () in
let { Evd.it=sgs ; sigma=sigma } = Proof.V82.subgoals p in
List.map (Goal.V82.abstract_type sigma) sgs
let build_and_l l =
let and_constr = Coqlib.build_coq_and () in
let conj_constr = coq_conj () in
let mk_and p1 p2 =
Term.mkApp(and_constr,[|p1;p2|]) in
let rec is_well_founded t =
match kind_of_term t with
| Prod(_,_,t') -> is_well_founded t'
| App(_,_) ->
let (f,_) = decompose_app t in
eq_constr f (well_founded ())
| _ -> assert false
in
let compare t1 t2 =
let b1,b2= is_well_founded t1,is_well_founded t2 in
if (b1&&b2) || not (b1 || b2) then 0
else if b1 && not b2 then 1 else -1
in
let l = List.sort compare l in
let rec f = function
| [] -> failwith "empty list of subgoals!"
| [p] -> p,tclIDTAC,1
| p1::pl ->
let c,tac,nb = f pl in
mk_and p1 c,
tclTHENS
(apply (constr_of_global conj_constr))
[tclIDTAC;
tac
],nb+1
in f l
let is_rec_res id =
let rec_res_name = string_of_id rec_res_id in
let id_name = string_of_id id in
try
String.sub id_name 0 (String.length rec_res_name) = rec_res_name
with _ -> false
let clear_goals =
let rec clear_goal t =
match kind_of_term t with
| Prod(Name id as na,t',b) ->
let b' = clear_goal b in
if noccurn 1 b' && (is_rec_res id)
then Termops.pop b'
else if b' == b then t
else mkProd(na,t',b')
| _ -> map_constr clear_goal t
in
List.map clear_goal
let build_new_goal_type () =
let sub_gls_types = get_current_subgoals_types () in
Pp.msgnl ( str " sub_gls_types1 : = " + + Util.prlist_with_sep ( fun ( ) - > Pp.fnl ( ) + + Pp.fnl ( ) ) Printer.pr_lconstr sub_gls_types ) ;
let sub_gls_types = clear_goals sub_gls_types in
Pp.msgnl ( str " sub_gls_types2 : = " + + Util.prlist_with_sep ( fun ( ) - > Pp.fnl ( ) + + Pp.fnl ( ) ) Printer.pr_lconstr sub_gls_types ) ;
let res = build_and_l sub_gls_types in
res
let is_opaque_constant c =
let cb = Global.lookup_constant c in
match cb.Declarations.const_body with
| Declarations.OpaqueDef _ -> true
| Declarations.Undef _ -> true
| Declarations.Def _ -> false
| Declarations.Primitive _ -> true
let open_new_goal (build_proof:tactic -> tactic -> unit) using_lemmas ref_ goal_name (gls_type,decompose_and_tac,nb_goal) =
Pp.msgnl ( str " : = " + + ) ;
let current_proof_name = get_current_proof_name () in
let name = match goal_name with
| Some s -> s
| None ->
try (add_suffix current_proof_name "_subproof")
with _ -> anomaly "open_new_goal with an unamed theorem"
in
let sign = initialize_named_context_for_proof () in
let na = next_global_ident_away name [] in
if Termops.occur_existential gls_type then
Errors.error "\"abstract\" cannot handle existentials";
let hook _ _ =
let opacity =
let na_ref = Libnames.Ident (dummy_loc,na) in
let na_global = Nametab.global na_ref in
match na_global with
ConstRef c -> is_opaque_constant c
| _ -> anomaly "equation_lemma: not a constant"
in
let lemma = mkConst (Lib.make_con na) in
ref_ := Some lemma ;
let lid = ref [] in
let h_num = ref (-1) in
Flags.silently Vernacentries.interp (Vernacexpr.VernacAbort None);
build_proof
( fun gls ->
let hid = next_ident_away_in_goal h_id (pf_ids_of_hyps gls) in
tclTHENSEQ
[
h_generalize [lemma];
h_intro hid;
(fun g ->
let ids = pf_ids_of_hyps g in
tclTHEN
(Elim.h_decompose_and (mkVar hid))
(fun g ->
let ids' = pf_ids_of_hyps g in
lid := List.rev (list_subtract ids' ids);
if !lid = [] then lid := [hid];
tclIDTAC g
)
g
);
] gls)
(fun g ->
match kind_of_term (pf_concl g) with
| App(f,_) when eq_constr f (well_founded ()) ->
Auto.h_auto None [] (Some []) g
| _ ->
incr h_num;
(observe_tac (str "finishing using")
(
tclCOMPLETE(
tclFIRST[
tclTHEN
(eapply_with_bindings (mkVar (List.nth !lid !h_num), NoBindings))
e_assumption;
Eauto.eauto_with_bases
(true,5)
[Evd.empty,Lazy.force refl_equal]
[Auto.Hint_db.empty empty_transparent_state false]
]
)
)
)
g)
;
Lemmas.save_named opacity;
in
start_proof
na
(Decl_kinds.Global, Decl_kinds.Proof Decl_kinds.Lemma)
sign
gls_type
hook ;
if Indfun_common.is_strict_tcc ()
then
by (tclIDTAC)
else
begin
by (
fun g ->
tclTHEN
(decompose_and_tac)
(tclORELSE
(tclFIRST
(List.map
(fun c ->
tclTHENSEQ
[intros;
h_simplest_apply (interp_constr Evd.empty (Global.env()) c);
tclCOMPLETE Auto.default_auto
]
)
using_lemmas)
) tclIDTAC)
g)
end;
try
raises UserError _ if the proof is complete
if Flags.is_verbose () then (pp (Printer.pr_open_subgoals()))
with UserError _ ->
defined ()
let com_terminate
tcc_lemma_name
tcc_lemma_ref
is_mes
fonctional_ref
input_type
relation
rec_arg_num
thm_name using_lemmas
nb_args
hook =
let start_proof (tac_start:tactic) (tac_end:tactic) =
let (evmap, env) = Lemmas.get_current_context() in
start_proof thm_name
(Global, Proof Lemma) (Environ.named_context_val env)
(compute_terminate_type nb_args fonctional_ref) hook;
by (observe_tac (str "starting_tac") tac_start);
by (observe_tac (str "whole_start") (whole_start tac_end nb_args is_mes fonctional_ref
input_type relation rec_arg_num ))
in
start_proof tclIDTAC tclIDTAC;
try
let new_goal_type = build_new_goal_type () in
open_new_goal start_proof using_lemmas tcc_lemma_ref
(Some tcc_lemma_name)
(new_goal_type);
with Failure "empty list of subgoals!" ->
defined ()
let start_equation (f:global_reference) (term_f:global_reference)
(cont_tactic:identifier list -> tactic) g =
let ids = pf_ids_of_hyps g in
let terminate_constr = constr_of_global term_f in
let nargs = nb_prod (type_of_const terminate_constr) in
let x = n_x_id ids nargs in
tclTHENLIST [
h_intros x;
unfold_in_concl [(Termops.all_occurrences, evaluable_of_global_reference f)];
observe_tac (str "simplest_case")
(simplest_case (mkApp (terminate_constr,
Array.of_list (List.map mkVar x))));
observe_tac (str "prove_eq") (cont_tactic x)] g;;
let (com_eqn : int -> identifier ->
global_reference -> global_reference -> global_reference
-> constr -> unit) =
fun nb_arg eq_name functional_ref f_ref terminate_ref equation_lemma_type ->
let opacity =
match terminate_ref with
| ConstRef c -> is_opaque_constant c
| _ -> anomaly "terminate_lemma: not a constant"
in
let (evmap, env) = Lemmas.get_current_context() in
let f_constr = constr_of_global f_ref in
let equation_lemma_type = subst1 f_constr equation_lemma_type in
(start_proof eq_name (Global, Proof Lemma)
(Environ.named_context_val env) equation_lemma_type (fun _ _ -> ());
by
(start_equation f_ref terminate_ref
(fun x ->
prove_eq (fun _ -> tclIDTAC)
{nb_arg=nb_arg;
f_terminate = constr_of_global terminate_ref;
f_constr = f_constr;
concl_tac = tclIDTAC;
func=functional_ref;
info=(instantiate_lambda
(def_of_const (constr_of_global functional_ref))
(f_constr::List.map mkVar x)
);
is_main_branch = true;
is_final = true;
values_and_bounds = [];
eqs = [];
forbidden_ids = [];
acc_inv = lazy (assert false);
acc_id = id_of_string "____";
args_assoc = [];
f_id = id_of_string "______";
rec_arg_id = id_of_string "______";
is_mes = false;
ih = id_of_string "______";
}
)
);
( try Vernacentries.interp ( Vernacexpr . . ShowProof ) with _ - > ( ) ) ;
Vernacentries.interp ( Vernacexpr . . ShowScript ) ;
Flags.silently (fun () -> Lemmas.save_named opacity) () ;
Pp.msgnl ( str " eqn finished " ) ;
);;
let recursive_definition is_mes function_name rec_impls type_of_f r rec_arg_num eq
generate_induction_principle using_lemmas : unit =
let previous_label = Lib.current_command_label () in
let function_type = interp_constr Evd.empty (Global.env()) type_of_f in
let env = push_named (function_name,None,function_type) (Global.env()) in
Pp.msgnl ( str " function type : = " + + Printer.pr_lconstr function_type ) ;
let equation_lemma_type =
nf_betaiotazeta
(interp_gen (OfType None) Evd.empty env ~impls:rec_impls eq)
in
Pp.msgnl ( str " lemma type : = " + + Printer.pr_lconstr equation_lemma_type + + fnl ( ) ) ;
let res_vars,eq' = decompose_prod equation_lemma_type in
let env_eq' = Environ.push_rel_context (List.map (fun (x,y) -> (x,None,y)) res_vars) env in
let eq' = nf_zeta env_eq' eq' in
let res =
Pp.msgnl ( str " res_var : = " + + Printer.pr_lconstr_env ( push_rel_context ( List.map ( function ( x , t ) - > ( x , None , t ) ) res_vars ) env ) eq ' ) ;
Pp.msgnl ( str " rec_arg_num : = " + + str ( string_of_int rec_arg_num ) ) ;
Pp.msgnl ( str " eq ' : = " + + str ( string_of_int rec_arg_num ) ) ;
match kind_of_term eq' with
| App(e,[|_;_;eq_fix|]) ->
mkLambda (Name function_name,function_type,subst_var function_name (compose_lam res_vars eq_fix))
| _ -> failwith "Recursive Definition (res not eq)"
in
let pre_rec_args,function_type_before_rec_arg = decompose_prod_n (rec_arg_num - 1) function_type in
let (_, rec_arg_type, _) = destProd function_type_before_rec_arg in
let arg_types = List.rev_map snd (fst (decompose_prod_n (List.length res_vars) function_type)) in
let equation_id = add_suffix function_name "_equation" in
let functional_id = add_suffix function_name "_F" in
let term_id = add_suffix function_name "_terminate" in
let functional_ref = declare_fun functional_id (IsDefinition Decl_kinds.Definition) res in
let env_with_pre_rec_args = push_rel_context(List.map (function (x,t) -> (x,None,t)) pre_rec_args) env in
let relation =
interp_constr
Evd.empty
env_with_pre_rec_args
r
in
let tcc_lemma_name = add_suffix function_name "_tcc" in
let tcc_lemma_constr = ref None in
let _ = Pp.msgnl ( str " relation : = " + + Printer.pr_lconstr_env env_with_pre_rec_args relation ) in
let hook _ _ =
let term_ref = Nametab.locate (qualid_of_ident term_id) in
let f_ref = declare_f function_name (IsProof Lemma) arg_types term_ref in
let _ = Table.extraction_inline true [Ident (dummy_loc,term_id)] in
message " start second proof " ;
let stop =
try com_eqn (List.length res_vars) equation_id functional_ref f_ref term_ref (subst_var function_name equation_lemma_type);
false
with e ->
begin
if do_observe ()
then pperrnl (str "Cannot create equation Lemma " ++ Errors.print e)
else anomaly "Cannot create equation Lemma"
;
true
end
in
if not stop
then
let eq_ref = Nametab.locate (qualid_of_ident equation_id ) in
let f_ref = destConst (constr_of_global f_ref)
and functional_ref = destConst (constr_of_global functional_ref)
and eq_ref = destConst (constr_of_global eq_ref) in
generate_induction_principle f_ref tcc_lemma_constr
functional_ref eq_ref rec_arg_num rec_arg_type (nb_prod res) relation;
if Flags.is_verbose ()
then msgnl (h 1 (Ppconstr.pr_id function_name ++
spc () ++ str"is defined" )++ fnl () ++
h 1 (Ppconstr.pr_id equation_id ++
spc () ++ str"is defined" )
)
in
try
com_terminate
tcc_lemma_name
tcc_lemma_constr
is_mes functional_ref
rec_arg_type
relation rec_arg_num
term_id
using_lemmas
(List.length res_vars)
hook
with e ->
begin
(try ignore (Backtrack.backto previous_label) with _ -> ());
raise e
end
|
cf09406960bcb8f9d1e26db22862532a6bf525fdc4737c8aee4cb8551c0de8ed | aantron/markup.ml | test_js_of_ocaml.ml | This file is part of Markup.ml , released under the MIT license . See
LICENSE.md for details , or visit .
LICENSE.md for details, or visit . *)
let () =
Markup.of_list [1; 2; 3] |> Markup_lwt.to_list |> ignore
| null | https://raw.githubusercontent.com/aantron/markup.ml/420aaa3d38d90ed84d1d7157840f7df5f3b5b349/test/js_of_ocaml/test_js_of_ocaml.ml | ocaml | This file is part of Markup.ml , released under the MIT license . See
LICENSE.md for details , or visit .
LICENSE.md for details, or visit . *)
let () =
Markup.of_list [1; 2; 3] |> Markup_lwt.to_list |> ignore
|
|
5fb7bad7b31f865a1a0c3fb1ed779f293f13b89e5bab32c902af99fbfd0a82f6 | racket/racket7 | path.rkt | #lang racket/base
(require racket/path
racket/file
racket/list
racket/function)
(provide (all-defined-out))
(define (path->bytes* pkg)
(cond
[(path? pkg)
(path->bytes pkg)]
[(string? pkg)
(path->bytes (string->path pkg))]
[(bytes? pkg)
pkg]))
(define (directory-list* d)
(append-map
(λ (pp)
(define p (build-path d pp))
(if (directory-exists? p)
(map (curry build-path pp)
(directory-list* p))
(list pp)))
(directory-list d)))
(define (simple-form-path* p)
(path->string (simple-form-path p)))
(define (pretty-module-path mod)
(if (and (list? mod)
(= 2 (length mod))
(eq? (car mod) 'lib)
(regexp-match? #rx"[.]rkt$" (cadr mod)))
(string->symbol (regexp-replace #rx"[.]rkt$" (cadr mod) ""))
mod))
(define (lift-directory-content pkg-dir path)
(define orig-sub (let ([s (car path)])
(if (string? s)
(string->path s)
s)))
;; Delete everything except `orig-sub`:
(for ([f (in-list (directory-list pkg-dir))])
(unless (equal? f orig-sub)
(delete-directory/files (build-path pkg-dir f))))
;; Get list of files and directories to move:
(define sub-l (directory-list (apply build-path pkg-dir path)))
;; Make sure `sub` doesn't match a name we want to move here:
(define sub
(let loop ([sub orig-sub] [i 0])
(cond
[(member sub sub-l)
;; pick a new name:
(loop (string->path (format "sub~a" i)) (add1 i))]
[(not (equal? sub orig-sub))
(rename-file-or-directory (build-path pkg-dir orig-sub)
(build-path pkg-dir sub))
sub]
[else sub])))
;; Move content of `sub` out:
(define sub-path (apply build-path (cons sub (cdr path))))
(for ([f (in-list sub-l)])
(rename-file-or-directory (build-path pkg-dir sub-path f)
(build-path pkg-dir f)))
;; Remove directory that we moved files out of:
(delete-directory/files (build-path pkg-dir sub)))
(define (remove-extra-directory-layer pkg-dir)
;; Treat a single directory produced in `pkg-dir`
;; as having the content of the package, instead of
;; being included itself in the package content.
(define l (directory-list pkg-dir))
(when (= 1 (length l))
(define orig-sub (car l))
(when (directory-exists? (build-path pkg-dir orig-sub))
(lift-directory-content pkg-dir (list orig-sub)))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/pkg/private/path.rkt | racket | Delete everything except `orig-sub`:
Get list of files and directories to move:
Make sure `sub` doesn't match a name we want to move here:
pick a new name:
Move content of `sub` out:
Remove directory that we moved files out of:
Treat a single directory produced in `pkg-dir`
as having the content of the package, instead of
being included itself in the package content. | #lang racket/base
(require racket/path
racket/file
racket/list
racket/function)
(provide (all-defined-out))
(define (path->bytes* pkg)
(cond
[(path? pkg)
(path->bytes pkg)]
[(string? pkg)
(path->bytes (string->path pkg))]
[(bytes? pkg)
pkg]))
(define (directory-list* d)
(append-map
(λ (pp)
(define p (build-path d pp))
(if (directory-exists? p)
(map (curry build-path pp)
(directory-list* p))
(list pp)))
(directory-list d)))
(define (simple-form-path* p)
(path->string (simple-form-path p)))
(define (pretty-module-path mod)
(if (and (list? mod)
(= 2 (length mod))
(eq? (car mod) 'lib)
(regexp-match? #rx"[.]rkt$" (cadr mod)))
(string->symbol (regexp-replace #rx"[.]rkt$" (cadr mod) ""))
mod))
(define (lift-directory-content pkg-dir path)
(define orig-sub (let ([s (car path)])
(if (string? s)
(string->path s)
s)))
(for ([f (in-list (directory-list pkg-dir))])
(unless (equal? f orig-sub)
(delete-directory/files (build-path pkg-dir f))))
(define sub-l (directory-list (apply build-path pkg-dir path)))
(define sub
(let loop ([sub orig-sub] [i 0])
(cond
[(member sub sub-l)
(loop (string->path (format "sub~a" i)) (add1 i))]
[(not (equal? sub orig-sub))
(rename-file-or-directory (build-path pkg-dir orig-sub)
(build-path pkg-dir sub))
sub]
[else sub])))
(define sub-path (apply build-path (cons sub (cdr path))))
(for ([f (in-list sub-l)])
(rename-file-or-directory (build-path pkg-dir sub-path f)
(build-path pkg-dir f)))
(delete-directory/files (build-path pkg-dir sub)))
(define (remove-extra-directory-layer pkg-dir)
(define l (directory-list pkg-dir))
(when (= 1 (length l))
(define orig-sub (car l))
(when (directory-exists? (build-path pkg-dir orig-sub))
(lift-directory-content pkg-dir (list orig-sub)))))
|
74579afa3fc4f048459d35bd6a010d2f1f564c9bfa463474f86337018a446846 | nikita-volkov/rerebase | Extra.hs | module Data.ByteString.Builder.Extra
(
module Rebase.Data.ByteString.Builder.Extra
)
where
import Rebase.Data.ByteString.Builder.Extra
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Data/ByteString/Builder/Extra.hs | haskell | module Data.ByteString.Builder.Extra
(
module Rebase.Data.ByteString.Builder.Extra
)
where
import Rebase.Data.ByteString.Builder.Extra
|
|
f8b8d8d8f9b910606ae2280cfe03edfa58f4f23f172161f9430b85a3577509cb | gator1/jepsen | counter.clj | (ns cassandra.counter
(:require [clojure [pprint :refer :all]
[string :as str]]
[clojure.java.io :as io]
[clojure.tools.logging :refer [debug info warn]]
[jepsen [core :as jepsen]
[db :as db]
[util :as util :refer [meh timeout]]
[control :as c :refer [| lit]]
[client :as client]
[checker :as checker]
[model :as model]
[generator :as gen]
[nemesis :as nemesis]
[store :as store]
[report :as report]
[tests :as tests]]
[jepsen.checker.timeline :as timeline]
[jepsen.control [net :as net]
[util :as net/util]]
[jepsen.os.debian :as debian]
[knossos.core :as knossos]
[clojurewerkz.cassaforte.client :as cassandra]
[clojurewerkz.cassaforte.query :refer :all]
[clojurewerkz.cassaforte.policies :refer :all]
[clojurewerkz.cassaforte.cql :as cql]
[cassandra.core :refer :all]
[cassandra.conductors :as conductors])
(:import (clojure.lang ExceptionInfo)
(com.datastax.driver.core ConsistencyLevel)
(com.datastax.driver.core.exceptions UnavailableException
WriteTimeoutException
ReadTimeoutException
NoHostAvailableException)
(com.datastax.driver.core.policies FallthroughRetryPolicy)))
(defrecord CQLCounterClient [conn writec]
client/Client
(setup! [_ test node]
(locking setup-lock
(let [conn (cassandra/connect (->> test :nodes (map name)))]
(cql/create-keyspace conn "jepsen_keyspace"
(if-not-exists)
(with {:replication
{:class "SimpleStrategy"
:replication_factor 3}}))
(cql/use-keyspace conn "jepsen_keyspace")
(cql/create-table conn "counters"
(if-not-exists)
(column-definitions {:id :int
:count :counter
:primary-key [:id]})
(with {:compaction
{:class (compaction-strategy)}}))
(cql/update conn "counters" {:count (increment-by 0)}
(where [[= :id 0]]))
(->CQLCounterClient conn writec))))
(invoke! [this test op]
(case (:f op)
:add (try (do
(with-retry-policy FallthroughRetryPolicy/INSTANCE
(with-consistency-level writec
(cql/update conn
"counters"
{:count (increment-by (:value op))}
(where [[= :id 0]]))))
(assoc op :type :ok))
(catch UnavailableException e
(assoc op :type :fail :error (.getMessage e)))
(catch WriteTimeoutException e
(assoc op :type :info :value :timed-out))
(catch NoHostAvailableException e
(info "All the servers are down - waiting 2s")
(Thread/sleep 2000)
(assoc op :type :fail :error (.getMessage e))))
:read (try (let [value (->> (with-retry-policy FallthroughRetryPolicy/INSTANCE
(with-consistency-level ConsistencyLevel/ALL
(cql/select conn
"counters"
(where [[= :id 0]]))))
first
:count)]
(assoc op :type :ok :value value))
(catch UnavailableException e
(info "Not enough replicas - failing")
(assoc op :type :fail :value (.getMessage e)))
(catch ReadTimeoutException e
(assoc op :type :fail :value :timed-out))
(catch NoHostAvailableException e
(info "All the servers are down - waiting 2s")
(Thread/sleep 2000)
(assoc op :type :fail :error (.getMessage e))))))
(teardown! [_ _]
(info "Tearing down client with conn" conn)
(cassandra/disconnect! conn)))
(defn cql-counter-client
"A counter implemented using CQL counters"
([] (->CQLCounterClient nil ConsistencyLevel/ONE))
([writec] (->CQLCounterClient nil writec)))
(defn cql-counter-inc-test
[name opts]
(merge (cassandra-test (str "cql counter inc " name)
{:client (cql-counter-client)
:model nil
:generator (->> (repeat 100 add)
(cons r)
gen/mix
(gen/delay 1/10)
std-gen)
:checker (checker/compose
{:counter checker/counter})})
opts))
(defn cql-counter-inc-dec-test
[name opts]
(merge (cassandra-test (str "cql counter inc dec " name)
{:client (cql-counter-client)
:model nil
:generator (->> (take 100 (cycle [add sub]))
(cons r)
gen/mix
(gen/delay 1/10)
std-gen)
:checker (checker/compose
{:counter checker/counter})})
opts))
(def bridge-inc-test
(cql-counter-inc-test "bridge"
{:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))}}))
(def halves-inc-test
(cql-counter-inc-test "halves"
{:conductors {:nemesis (nemesis/partition-random-halves)}}))
(def isolate-node-inc-test
(cql-counter-inc-test "isolate node"
{:conductors {:nemesis (nemesis/partition-random-node)}}))
(def flush-compact-inc-test
(cql-counter-inc-test "flush and compact"
{:conductors {:nemesis (conductors/flush-and-compacter)}}))
(def crash-subset-inc-test
(cql-counter-inc-test "crash"
{:conductors {:nemesis (crash-nemesis)}}))
(def bridge-inc-dec-test
(cql-counter-inc-dec-test "bridge"
{:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))}}))
(def halves-inc-dec-test
(cql-counter-inc-dec-test "halves"
{:conductors {:nemesis (nemesis/partition-random-halves)}}))
(def isolate-node-inc-dec-test
(cql-counter-inc-dec-test "isolate node"
{:conductors {:nemesis (nemesis/partition-random-node)}}))
(def crash-subset-inc-dec-test
(cql-counter-inc-dec-test "crash"
{:conductors {:nemesis (crash-nemesis)}}))
(def flush-compact-inc-dec-test
(cql-counter-inc-dec-test "flush and compact"
{:conductors {:nemesis (conductors/flush-and-compacter)}}))
(def bridge-inc-test-bootstrap
(cql-counter-inc-test "bridge bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))
:bootstrapper (conductors/bootstrapper)}}))
(def halves-inc-test-bootstrap
(cql-counter-inc-test "halves bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partition-random-halves)
:bootstrapper (conductors/bootstrapper)}}))
(def isolate-node-inc-test-bootstrap
(cql-counter-inc-test "isolate node bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partition-random-node)
:bootstrapper (conductors/bootstrapper)}}))
(def crash-subset-inc-test-bootstrap
(cql-counter-inc-test "crash bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (crash-nemesis)
:bootstrapper (conductors/bootstrapper)}}))
(def bridge-inc-dec-test-bootstrap
(cql-counter-inc-dec-test "bridge bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))
:bootstrapper (conductors/bootstrapper)}}))
(def halves-inc-dec-test-bootstrap
(cql-counter-inc-dec-test "halves bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partition-random-halves)
:bootstrapper (conductors/bootstrapper)}}))
(def isolate-node-inc-dec-test-bootstrap
(cql-counter-inc-dec-test "isolate node bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partition-random-node)
:bootstrapper (conductors/bootstrapper)}}))
(def crash-subset-inc-dec-test-bootstrap
(cql-counter-inc-dec-test "crash bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (crash-nemesis)
:bootstrapper (conductors/bootstrapper)}}))
(def bridge-inc-test-decommission
(cql-counter-inc-test "bridge decommission"
{:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))
:bootstrapper (conductors/bootstrapper)}}))
(def halves-inc-test-decommission
(cql-counter-inc-test "halves decommission"
{:conductors {:nemesis (nemesis/partition-random-halves)
:decommissioner (conductors/decommissioner)}}))
(def isolate-node-inc-test-decommission
(cql-counter-inc-test "isolate node decommission"
{:conductors {:nemesis (nemesis/partition-random-node)
:decommissioner (conductors/decommissioner)}}))
(def crash-subset-inc-test-decommission
(cql-counter-inc-test "crash decommission"
{:client (cql-counter-client ConsistencyLevel/QUORUM)
:conductors {:nemesis (crash-nemesis)
:decommissioner (conductors/decommissioner)}}))
(def bridge-inc-dec-test-decommission
(cql-counter-inc-dec-test "bridge decommission"
{:conductors {:nemesis (nemesis/partitioner
(comp nemesis/bridge shuffle))
:decommissioner (conductors/decommissioner)}}))
(def halves-inc-dec-test-decommission
(cql-counter-inc-dec-test "halves decommission"
{:conductors {:nemesis (nemesis/partition-random-halves)
:decommissioner (conductors/decommissioner)}}))
(def isolate-node-inc-dec-test-decommission
(cql-counter-inc-dec-test "isolate node decommission"
{:conductors {:nemesis (nemesis/partition-random-node)
:decommissioner (conductors/decommissioner)}}))
(def crash-subset-inc-dec-test-decommission
(cql-counter-inc-dec-test "crash decommission"
{:client (cql-counter-client ConsistencyLevel/QUORUM)
:conductors {:nemesis (crash-nemesis)
:decommissioner (conductors/decommissioner)}}))
| null | https://raw.githubusercontent.com/gator1/jepsen/1932cbd72cbc1f6c2a27abe0fe347ea989f0cfbb/cassandra/src/cassandra/counter.clj | clojure | (ns cassandra.counter
(:require [clojure [pprint :refer :all]
[string :as str]]
[clojure.java.io :as io]
[clojure.tools.logging :refer [debug info warn]]
[jepsen [core :as jepsen]
[db :as db]
[util :as util :refer [meh timeout]]
[control :as c :refer [| lit]]
[client :as client]
[checker :as checker]
[model :as model]
[generator :as gen]
[nemesis :as nemesis]
[store :as store]
[report :as report]
[tests :as tests]]
[jepsen.checker.timeline :as timeline]
[jepsen.control [net :as net]
[util :as net/util]]
[jepsen.os.debian :as debian]
[knossos.core :as knossos]
[clojurewerkz.cassaforte.client :as cassandra]
[clojurewerkz.cassaforte.query :refer :all]
[clojurewerkz.cassaforte.policies :refer :all]
[clojurewerkz.cassaforte.cql :as cql]
[cassandra.core :refer :all]
[cassandra.conductors :as conductors])
(:import (clojure.lang ExceptionInfo)
(com.datastax.driver.core ConsistencyLevel)
(com.datastax.driver.core.exceptions UnavailableException
WriteTimeoutException
ReadTimeoutException
NoHostAvailableException)
(com.datastax.driver.core.policies FallthroughRetryPolicy)))
(defrecord CQLCounterClient [conn writec]
client/Client
(setup! [_ test node]
(locking setup-lock
(let [conn (cassandra/connect (->> test :nodes (map name)))]
(cql/create-keyspace conn "jepsen_keyspace"
(if-not-exists)
(with {:replication
{:class "SimpleStrategy"
:replication_factor 3}}))
(cql/use-keyspace conn "jepsen_keyspace")
(cql/create-table conn "counters"
(if-not-exists)
(column-definitions {:id :int
:count :counter
:primary-key [:id]})
(with {:compaction
{:class (compaction-strategy)}}))
(cql/update conn "counters" {:count (increment-by 0)}
(where [[= :id 0]]))
(->CQLCounterClient conn writec))))
(invoke! [this test op]
(case (:f op)
:add (try (do
(with-retry-policy FallthroughRetryPolicy/INSTANCE
(with-consistency-level writec
(cql/update conn
"counters"
{:count (increment-by (:value op))}
(where [[= :id 0]]))))
(assoc op :type :ok))
(catch UnavailableException e
(assoc op :type :fail :error (.getMessage e)))
(catch WriteTimeoutException e
(assoc op :type :info :value :timed-out))
(catch NoHostAvailableException e
(info "All the servers are down - waiting 2s")
(Thread/sleep 2000)
(assoc op :type :fail :error (.getMessage e))))
:read (try (let [value (->> (with-retry-policy FallthroughRetryPolicy/INSTANCE
(with-consistency-level ConsistencyLevel/ALL
(cql/select conn
"counters"
(where [[= :id 0]]))))
first
:count)]
(assoc op :type :ok :value value))
(catch UnavailableException e
(info "Not enough replicas - failing")
(assoc op :type :fail :value (.getMessage e)))
(catch ReadTimeoutException e
(assoc op :type :fail :value :timed-out))
(catch NoHostAvailableException e
(info "All the servers are down - waiting 2s")
(Thread/sleep 2000)
(assoc op :type :fail :error (.getMessage e))))))
(teardown! [_ _]
(info "Tearing down client with conn" conn)
(cassandra/disconnect! conn)))
(defn cql-counter-client
"A counter implemented using CQL counters"
([] (->CQLCounterClient nil ConsistencyLevel/ONE))
([writec] (->CQLCounterClient nil writec)))
(defn cql-counter-inc-test
[name opts]
(merge (cassandra-test (str "cql counter inc " name)
{:client (cql-counter-client)
:model nil
:generator (->> (repeat 100 add)
(cons r)
gen/mix
(gen/delay 1/10)
std-gen)
:checker (checker/compose
{:counter checker/counter})})
opts))
(defn cql-counter-inc-dec-test
[name opts]
(merge (cassandra-test (str "cql counter inc dec " name)
{:client (cql-counter-client)
:model nil
:generator (->> (take 100 (cycle [add sub]))
(cons r)
gen/mix
(gen/delay 1/10)
std-gen)
:checker (checker/compose
{:counter checker/counter})})
opts))
(def bridge-inc-test
(cql-counter-inc-test "bridge"
{:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))}}))
(def halves-inc-test
(cql-counter-inc-test "halves"
{:conductors {:nemesis (nemesis/partition-random-halves)}}))
(def isolate-node-inc-test
(cql-counter-inc-test "isolate node"
{:conductors {:nemesis (nemesis/partition-random-node)}}))
(def flush-compact-inc-test
(cql-counter-inc-test "flush and compact"
{:conductors {:nemesis (conductors/flush-and-compacter)}}))
(def crash-subset-inc-test
(cql-counter-inc-test "crash"
{:conductors {:nemesis (crash-nemesis)}}))
(def bridge-inc-dec-test
(cql-counter-inc-dec-test "bridge"
{:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))}}))
(def halves-inc-dec-test
(cql-counter-inc-dec-test "halves"
{:conductors {:nemesis (nemesis/partition-random-halves)}}))
(def isolate-node-inc-dec-test
(cql-counter-inc-dec-test "isolate node"
{:conductors {:nemesis (nemesis/partition-random-node)}}))
(def crash-subset-inc-dec-test
(cql-counter-inc-dec-test "crash"
{:conductors {:nemesis (crash-nemesis)}}))
(def flush-compact-inc-dec-test
(cql-counter-inc-dec-test "flush and compact"
{:conductors {:nemesis (conductors/flush-and-compacter)}}))
(def bridge-inc-test-bootstrap
(cql-counter-inc-test "bridge bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))
:bootstrapper (conductors/bootstrapper)}}))
(def halves-inc-test-bootstrap
(cql-counter-inc-test "halves bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partition-random-halves)
:bootstrapper (conductors/bootstrapper)}}))
(def isolate-node-inc-test-bootstrap
(cql-counter-inc-test "isolate node bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partition-random-node)
:bootstrapper (conductors/bootstrapper)}}))
(def crash-subset-inc-test-bootstrap
(cql-counter-inc-test "crash bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (crash-nemesis)
:bootstrapper (conductors/bootstrapper)}}))
(def bridge-inc-dec-test-bootstrap
(cql-counter-inc-dec-test "bridge bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))
:bootstrapper (conductors/bootstrapper)}}))
(def halves-inc-dec-test-bootstrap
(cql-counter-inc-dec-test "halves bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partition-random-halves)
:bootstrapper (conductors/bootstrapper)}}))
(def isolate-node-inc-dec-test-bootstrap
(cql-counter-inc-dec-test "isolate node bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (nemesis/partition-random-node)
:bootstrapper (conductors/bootstrapper)}}))
(def crash-subset-inc-dec-test-bootstrap
(cql-counter-inc-dec-test "crash bootstrap"
{:bootstrap (atom #{:n4 :n5})
:conductors {:nemesis (crash-nemesis)
:bootstrapper (conductors/bootstrapper)}}))
(def bridge-inc-test-decommission
(cql-counter-inc-test "bridge decommission"
{:conductors {:nemesis (nemesis/partitioner (comp nemesis/bridge shuffle))
:bootstrapper (conductors/bootstrapper)}}))
(def halves-inc-test-decommission
(cql-counter-inc-test "halves decommission"
{:conductors {:nemesis (nemesis/partition-random-halves)
:decommissioner (conductors/decommissioner)}}))
(def isolate-node-inc-test-decommission
(cql-counter-inc-test "isolate node decommission"
{:conductors {:nemesis (nemesis/partition-random-node)
:decommissioner (conductors/decommissioner)}}))
(def crash-subset-inc-test-decommission
(cql-counter-inc-test "crash decommission"
{:client (cql-counter-client ConsistencyLevel/QUORUM)
:conductors {:nemesis (crash-nemesis)
:decommissioner (conductors/decommissioner)}}))
(def bridge-inc-dec-test-decommission
(cql-counter-inc-dec-test "bridge decommission"
{:conductors {:nemesis (nemesis/partitioner
(comp nemesis/bridge shuffle))
:decommissioner (conductors/decommissioner)}}))
(def halves-inc-dec-test-decommission
(cql-counter-inc-dec-test "halves decommission"
{:conductors {:nemesis (nemesis/partition-random-halves)
:decommissioner (conductors/decommissioner)}}))
(def isolate-node-inc-dec-test-decommission
(cql-counter-inc-dec-test "isolate node decommission"
{:conductors {:nemesis (nemesis/partition-random-node)
:decommissioner (conductors/decommissioner)}}))
(def crash-subset-inc-dec-test-decommission
(cql-counter-inc-dec-test "crash decommission"
{:client (cql-counter-client ConsistencyLevel/QUORUM)
:conductors {:nemesis (crash-nemesis)
:decommissioner (conductors/decommissioner)}}))
|
|
4cbdbc3e9a0f257e2311237f7b845969e38acf3b37993605a40d7adfcbf0788d | w3ntao/programming-in-haskell | Exercise_10_10_3.hs | # OPTIONS_GHC -Wall #
module Exercise_10_10_3 where
import Exercise_10_10_2 hiding (putBoard)
putBoard :: Board -> IO ()
putBoard xs = sequence_ [putRow n x | (n, x) <- zip [1..] xs] | null | https://raw.githubusercontent.com/w3ntao/programming-in-haskell/c2769fa19d8507aad209818c83f67e82c3698f07/Chapter-10/Exercise_10_10_3.hs | haskell | # OPTIONS_GHC -Wall #
module Exercise_10_10_3 where
import Exercise_10_10_2 hiding (putBoard)
putBoard :: Board -> IO ()
putBoard xs = sequence_ [putRow n x | (n, x) <- zip [1..] xs] |
|
aedfb691bf6cc77382f18eb8a2127166f091784a4487300c35aaf4189e3a232e | luminus-framework/examples | core.clj | ;---
Excerpted from " Web Development with Clojure , Second Edition " ,
published by The Pragmatic Bookshelf .
Copyrights apply to this code . It may not be used to create training material ,
; courses, books, articles, and the like. Contact us if you are in doubt.
; We make no guarantees that this code is fit for any purpose.
; Visit for more book information.
;---
(ns reporting-example.test.db.core
(:require [reporting-example.db.core :as db]
[reporting-example.db.migrations :as migrations]
[clojure.test :refer :all]
[clojure.java.jdbc :as jdbc]
[conman.core :refer [with-transaction]]
[config.core :refer [env]]
[mount.core :as mount]))
(use-fixtures
:once
(fn [f]
(mount/start #'reporting-example.db.core/*db*)
(migrations/migrate ["migrate"])
(f)))
(deftest test-users
(with-transaction [t-conn db/*db*]
(jdbc/db-set-rollback-only! t-conn)
(is (= 1 (db/create-user!
{:id "1"
:first_name "Sam"
:last_name "Smith"
:email ""
:pass "pass"})))
(is (= {:id "1"
:first_name "Sam"
:last_name "Smith"
:email ""
:pass "pass"
:admin nil
:last_login nil
:is_active nil}
(db/get-user {:id "1"})))))
| null | https://raw.githubusercontent.com/luminus-framework/examples/cbeee2fef8f457a6a6bac2cae0b640370ae2499b/reporting-example/test/clj/reporting_example/test/db/core.clj | clojure | ---
courses, books, articles, and the like. Contact us if you are in doubt.
We make no guarantees that this code is fit for any purpose.
Visit for more book information.
--- | Excerpted from " Web Development with Clojure , Second Edition " ,
published by The Pragmatic Bookshelf .
Copyrights apply to this code . It may not be used to create training material ,
(ns reporting-example.test.db.core
(:require [reporting-example.db.core :as db]
[reporting-example.db.migrations :as migrations]
[clojure.test :refer :all]
[clojure.java.jdbc :as jdbc]
[conman.core :refer [with-transaction]]
[config.core :refer [env]]
[mount.core :as mount]))
(use-fixtures
:once
(fn [f]
(mount/start #'reporting-example.db.core/*db*)
(migrations/migrate ["migrate"])
(f)))
(deftest test-users
(with-transaction [t-conn db/*db*]
(jdbc/db-set-rollback-only! t-conn)
(is (= 1 (db/create-user!
{:id "1"
:first_name "Sam"
:last_name "Smith"
:email ""
:pass "pass"})))
(is (= {:id "1"
:first_name "Sam"
:last_name "Smith"
:email ""
:pass "pass"
:admin nil
:last_login nil
:is_active nil}
(db/get-user {:id "1"})))))
|
ee4a2be4ea1346000f5605cf4330367e7ef519caffb0ea7c9c09817413a3b4da | AccelerateHS/accelerate-io | ForeignPtr.hs | {-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
-- |
-- Module : Data.Array.Accelerate.IO.Foreign.ForeignPtr
Copyright : [ 2017 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
module Data.Array.Accelerate.IO.Foreign.ForeignPtr
where
import Data.Array.Accelerate.Array.Data ( ArrayData, GArrayDataR )
import Data.Array.Accelerate.Array.Unique
import Data.Array.Accelerate.Lifetime
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Sugar.Array
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Shape
import qualified Data.Array.Accelerate.Representation.Array as R
import Data.Array.Accelerate.IO.Foreign.Internal
import Foreign.ForeignPtr
import System.IO.Unsafe
-- | A family of types which represent a collection of 'ForeignPtr's. The
-- structure of the collection depends on the element type @e@.
--
type ForeignPtrs e = GArrayDataR ForeignPtr e
| /O(1)/. Treat the set of ' ForeignPtrs ' as an Accelerate array . The type of
elements in the output Accelerate array determines the structure of the
-- collection.
--
-- Data is considered to be in row-major order. You must ensure that each of the
-- input pointers contains the right number of elements.
--
-- The data may not be modified through the 'ForeignPtr's afterwards.
--
-- You should make sure that the data is suitably aligned.
--
@since 1.1.0.0@
--
# INLINE fromForeignPtrs #
fromForeignPtrs :: forall sh e. (Shape sh, Elt e) => sh -> ForeignPtrs (EltR e) -> Array sh e
fromForeignPtrs sh fps = Array (R.Array (fromElt sh) (go (eltR @e) fps))
where
go :: TypeR a -> ForeignPtrs a -> ArrayData a
go TupRunit () = ()
go (TupRpair aR1 aR2) (a1, a2) = (go aR1 a1, go aR2 a2)
go (TupRsingle t) a
| ScalarArrayDict{} <- scalarArrayDict t
= unsafePerformIO $ newUniqueArray a
| /O(1)/. Yield the ' ForeignPtr 's underlying the given Accelerate ' Array ' .
The element type @e@ will determine the structure of the output collection .
--
-- Data is considered to be in row-major order.
--
@since 1.1.0.0@
--
# INLINE toForeignPtrs #
toForeignPtrs :: forall sh e. (Shape sh, Elt e) => Array sh e -> ForeignPtrs (EltR e)
toForeignPtrs (Array (R.Array _ adata)) = go (eltR @e) adata
where
go :: TypeR a -> ArrayData a -> ForeignPtrs a
go TupRunit () = ()
go (TupRpair aR1 aR2) (a1, a2) = (go aR1 a1, go aR2 a2)
go (TupRsingle t) a
| ScalarArrayDict{} <- scalarArrayDict t
= unsafeGetValue (uniqueArrayData a)
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-io/d62e543a1156b63b242387ca8348836efca744f4/accelerate-io/src/Data/Array/Accelerate/IO/Foreign/ForeignPtr.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE ScopedTypeVariables #
|
Module : Data.Array.Accelerate.IO.Foreign.ForeignPtr
License : BSD3
Stability : experimental
| A family of types which represent a collection of 'ForeignPtr's. The
structure of the collection depends on the element type @e@.
collection.
Data is considered to be in row-major order. You must ensure that each of the
input pointers contains the right number of elements.
The data may not be modified through the 'ForeignPtr's afterwards.
You should make sure that the data is suitably aligned.
Data is considered to be in row-major order.
| # LANGUAGE TypeApplications #
Copyright : [ 2017 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.IO.Foreign.ForeignPtr
where
import Data.Array.Accelerate.Array.Data ( ArrayData, GArrayDataR )
import Data.Array.Accelerate.Array.Unique
import Data.Array.Accelerate.Lifetime
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Sugar.Array
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Shape
import qualified Data.Array.Accelerate.Representation.Array as R
import Data.Array.Accelerate.IO.Foreign.Internal
import Foreign.ForeignPtr
import System.IO.Unsafe
type ForeignPtrs e = GArrayDataR ForeignPtr e
| /O(1)/. Treat the set of ' ForeignPtrs ' as an Accelerate array . The type of
elements in the output Accelerate array determines the structure of the
@since 1.1.0.0@
# INLINE fromForeignPtrs #
fromForeignPtrs :: forall sh e. (Shape sh, Elt e) => sh -> ForeignPtrs (EltR e) -> Array sh e
fromForeignPtrs sh fps = Array (R.Array (fromElt sh) (go (eltR @e) fps))
where
go :: TypeR a -> ForeignPtrs a -> ArrayData a
go TupRunit () = ()
go (TupRpair aR1 aR2) (a1, a2) = (go aR1 a1, go aR2 a2)
go (TupRsingle t) a
| ScalarArrayDict{} <- scalarArrayDict t
= unsafePerformIO $ newUniqueArray a
| /O(1)/. Yield the ' ForeignPtr 's underlying the given Accelerate ' Array ' .
The element type @e@ will determine the structure of the output collection .
@since 1.1.0.0@
# INLINE toForeignPtrs #
toForeignPtrs :: forall sh e. (Shape sh, Elt e) => Array sh e -> ForeignPtrs (EltR e)
toForeignPtrs (Array (R.Array _ adata)) = go (eltR @e) adata
where
go :: TypeR a -> ArrayData a -> ForeignPtrs a
go TupRunit () = ()
go (TupRpair aR1 aR2) (a1, a2) = (go aR1 a1, go aR2 a2)
go (TupRsingle t) a
| ScalarArrayDict{} <- scalarArrayDict t
= unsafeGetValue (uniqueArrayData a)
|
7b306d589917a764c0f2f672388e658913949920e31893644248d828544239ac | hellonico/origami-fun | matchingshapes.clj | (ns opencv4.matchingshapes
(:require
[opencv4.utils :as u]
[opencv4.core :refer :all]))
(def t1 (->
"resources/white-blue-triangle.png"
(imread 0)
(threshold! 210 240 1)))
(def t2
(->
"-Sweden_road_sign_A20.svg.png"
u/mat-from-url
(cvt-color! COLOR_RGB2GRAY)
(threshold! 210 240 1)))
(match-shapes (.t t1) (.t t2) CV_CONTOURS_MATCH_I1 0)
| null | https://raw.githubusercontent.com/hellonico/origami-fun/80117788530d942eaa9a80e2995b37409fa24889/test/opencv4/matchingshapes.clj | clojure | (ns opencv4.matchingshapes
(:require
[opencv4.utils :as u]
[opencv4.core :refer :all]))
(def t1 (->
"resources/white-blue-triangle.png"
(imread 0)
(threshold! 210 240 1)))
(def t2
(->
"-Sweden_road_sign_A20.svg.png"
u/mat-from-url
(cvt-color! COLOR_RGB2GRAY)
(threshold! 210 240 1)))
(match-shapes (.t t1) (.t t2) CV_CONTOURS_MATCH_I1 0)
|
|
2d95c774ed648e9903f02a09dea44da6145c90ab912ce5fb97ae8b1b4ee93fd2 | jsoo1/guix-channel | termonad.scm | (define-module (termonad)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix build-system haskell)
#:use-module (ghc-keys)
#:use-module (ghc-pointed)
#:use-module (ghc-instances)
#:use-module (gnu packages glib)
#:use-module (gnu packages gtk)
#:use-module (gnu packages haskell)
#:use-module (gnu packages haskell-xyz)
#:use-module (gnu packages haskell-check)
#:use-module (gnu packages haskell-web)
#:use-module (gnu packages pkg-config)
#:export (termonad))
;; PUBLIC
(define termonad
(package
(name "termonad")
(version "0.2.1.0")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256 (base32 "1js9sj0gj4igigdnbc5ygbn5l2wfhbrm1k565y3advi99imidsd3"))))
(build-system haskell-build-system)
(inputs
`(("ghc-classy-prelude" ,ghc-classy-prelude)
("ghc-colour" ,ghc-colour)
("ghc-constraints" ,ghc-constraints)
("ghc-data-default" ,ghc-data-default)
("ghc-dyre" ,ghc-dyre)
("ghc-gi-gdk" ,ghc-gi-gdk)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-glib" ,ghc-gi-glib)
("ghc-gi-gtk" ,ghc-gi-gtk)
("ghc-gi-pango" ,ghc-gi-pango)
("ghc-gi-vte" ,ghc-gi-vte)
("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-lens" ,ghc-lens)
("ghc-pretty-simple" ,ghc-pretty-simple)
("ghc-quickcheck" ,ghc-quickcheck)
("ghc-xml-conduit" ,ghc-xml-conduit)
("ghc-xml-html-qq" ,ghc-xml-html-qq)))
(native-inputs
`(("cabal-doctest" ,cabal-doctest)))
(arguments `(#:tests? #f))
(home-page "")
(synopsis "Terminal emulator configurable in Haskell")
(description "Please see <#readme README.md>.")
(license license:bsd-3)))
;; DEPENDENCIES
(define ghc-gi-gobject
(package
(name "ghc-gi-gobject")
(version "2.0.16")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gobject/gi-gobject-" version ".tar.gz"))
(sha256 (base32 "1bgn4ywx94py0v213iv7mbjjvvy3y7gvpgw4wpn38s2np7al8y65"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "GObject bindings")
(description "Bindings for GObject, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-gdkpixbuf
(package
(name "ghc-gi-gdkpixbuf")
(version "2.0.16")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gdkpixbuf/gi-gdkpixbuf-" version ".tar.gz"))
(sha256 (base32 "0vqnskshbfp9nsgyfg4pifrh007rb7k176ci8niik96kxh95zfzx"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "GdkPixbuf bindings")
(description "Bindings for GdkPixbuf, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-gio
(package
(name "ghc-gi-gio")
(version "2.0.18")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gio/gi-gio-" version ".tar.gz"))
(sha256 (base32 "0h7liqxf63wmhjzgbjshv7pa4fx743jpvkphn5yyjkc0bnfcvsqk"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Gio bindings")
(description "Bindings for Gio, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-cairo
(package
(name "ghc-gi-cairo")
(version "1.0.17")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-cairo/gi-cairo-" version ".tar.gz"))
(sha256 (base32 "1ax7aly9ahvb18m3zjmy0dk47qfdx5yl15q52c3wp4wa0c5aggax"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading"
,ghc-haskell-gi-overloading)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Cairo bindings")
(description "Bindings for Cairo, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-haskell-gi-overloading
(package
(name "ghc-haskell-gi-overloading")
(version "1.0")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-gi-overloading/haskell-gi-overloading-"
version ".tar.gz"))
(sha256 (base32 "0ak8f79ia9zlk94zr02sq8bqi5n5pd8ria8w1dj3adcdvpw9gmry"))))
(build-system haskell-build-system)
(arguments `(#:tests? #f
#:haddock? #f))
(home-page "-gi/haskell-gi")
(synopsis "Overloading support for haskell-gi")
(description "Control overloading support in haskell-gi generated bindings")
(license license:bsd-3)))
(define ghc-haskell-gi
(package
(name "ghc-haskell-gi")
(version "0.21.5")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gi/haskell-gi-" version ".tar.gz"))
(sha256 (base32 "1rvi9bmgxq7q6js8yb5yb156yxmnm9px9amgjwzxmr7sxz31dl8j"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-attoparsec" ,ghc-attoparsec)
("ghc-pretty-show" ,ghc-pretty-show)
("ghc-safe" ,ghc-safe)
("ghc-xdg-basedir" ,ghc-xdg-basedir)
("ghc-xml-conduit" ,ghc-xml-conduit)
("ghc-regex-tdfa" ,ghc-regex-tdfa)))
(native-inputs
`(("pkg-config" ,pkg-config)
("gobject-introspection" ,gobject-introspection)
("glib" ,glib)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Generate Haskell bindings for GObject Introspection capable libraries")
(description
"Generate Haskell bindings for GObject Introspection capable libraries. This includes most notably Gtk+, but many other libraries in the GObject ecosystem provide introspection data too.")
(license license:lgpl2.1)))
(define ghc-gi-gtk
(package
(name "ghc-gi-gtk")
(version "3.0.25")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gtk/gi-gtk-" version ".tar.gz"))
(sha256 (base32 "0l6xnh85agjagdmjy72akvxviwkzyngh7rii5idrsd62bb27abx1"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-cairo" ,ghc-gi-cairo)
("ghc-gi-pango" ,ghc-gi-pango)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-gdkpixbuf" ,ghc-gi-gdkpixbuf)
("ghc-gi-gdk" ,ghc-gi-gdk)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)
("ghc-gi-atk" ,ghc-gi-atk)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Gtk bindings")
(description "Bindings for Gtk, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-gdk
(package
(name "ghc-gi-gdk")
(version "3.0.16")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gdk/gi-gdk-" version ".tar.gz"))
(sha256 (base32 "0jp3d3zfm20b4ax1g5k1wzh8fxxzsw4ssw7zqx0d13167m4smc3y"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-cairo" ,ghc-gi-cairo)
("ghc-gi-pango" ,ghc-gi-pango)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-gdkpixbuf" ,ghc-gi-gdkpixbuf)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Gdk bindings")
(description "Bindings for Gdk, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-pango
(package
(name "ghc-gi-pango")
(version "1.0.16")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-pango/gi-pango-" version ".tar.gz"))
(sha256 (base32 "1x3q1q4ww1v6v42p1wcaghxsja8cigqaqvklkfg4gxyp2f2cdg57"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Pango bindings")
(description
"Bindings for Pango, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-io-storage
(package
(name "ghc-io-storage")
(version "0.3")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-storage/io-storage-" version ".tar.gz"))
(sha256 (base32 "1ga9bd7iri6vlsxnjx765yy3bxc4lbz644wyw88yzvpjgz6ga3cs"))))
(build-system haskell-build-system)
(arguments `(#:tests? #f))
(home-page "-storage")
(synopsis "A key-value store in the IO monad.")
(description
"This library allows an application to extend the 'global state' hidden inside the IO monad with semi-arbitrary data. Data is required to be 'Typeable'. The library provides an essentially unbounded number of key-value stores indexed by strings, with each key within the stores also being a string.")
(license license:bsd-3)))
(define ghc-gi-glib
(package
(name "ghc-gi-glib")
(version "2.0.17")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-glib/gi-glib-" version ".tar.gz"))
(sha256 (base32 "0rxbkrwlwnjf46z0qpw0vjw1nv9kl91xp7k2098rqs36kl5bwylx"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)))
(arguments
`(#:tests? #f
#:haddock? #f))
(home-page "-gi/haskell-gi")
(synopsis "GLib bindings")
(description
"Bindings for GLib, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-dyre
(package
(name "ghc-dyre")
(version "0.8.12")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256 (base32 "10hnlysy4bjvvznk8v902mlk4jx95qf972clyi1l32xkqrf30972"))))
(build-system haskell-build-system)
(inputs
`(("ghc-paths" ,ghc-paths)
("ghc-executable-path" ,ghc-executable-path)
("ghc-xdg-basedir" ,ghc-xdg-basedir)
("ghc-io-storage" ,ghc-io-storage)))
(arguments `(#:tests? #f))
(home-page "")
(synopsis "Dynamic reconfiguration in Haskell")
(description
"Dyre implements dynamic reconfiguration facilities after the style of Xmonad. Dyre aims to be as simple as possible without sacrificing features, and places an emphasis on simplicity of integration with an application. A full introduction with a complete example project can be found in the documentation for 'Config.Dyre'")
(license license:bsd-3)))
(define ghc-basic-prelude
(package
(name "ghc-basic-prelude")
(version "0.7.0")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-prelude/basic-prelude-" version ".tar.gz"))
(sha256 (base32 "0yckmnvm6i4vw0mykj4fzl4ldsf67v8d2h0vp1bakyj84n4myx8h"))))
(build-system haskell-build-system)
(inputs
`(("ghc-hashable" ,ghc-hashable)
("ghc-unordered-containers" ,ghc-unordered-containers)
("ghc-vector" ,ghc-vector)))
(arguments `(#:tests? #f))
(home-page "-prelude#readme")
(synopsis "An enhanced core prelude; a common foundation for alternate preludes.")
(description "Please see the README on Github at <-prelude#readme>")
(license license:expat)))
(define ghc-dlist-instances
(package
(name "ghc-dlist-instances")
(version "0.1.1.1")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-instances/dlist-instances-" version ".tar.gz"))
(sha256 (base32 "0nsgrr25r4qxv2kpn7i20hra8jjkyllxfrhh5hml3ysjdz010jni"))))
(build-system haskell-build-system)
(inputs
`(("ghc-semigroups" ,ghc-semigroups)
("ghc-dlist" ,ghc-dlist)))
(arguments `(#:tests? #f))
(home-page "-instances")
(synopsis "Difference lists instances")
(description
"See the dlist packages. This package is the canonical source for some orphan instances. Orphan instances are placed here to avoid dependencies elsewhere.")
(license license:bsd-3)))
(define ghc-gi-atk
(package
(name "ghc-gi-atk")
(version "2.0.15")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-atk/gi-atk-" version ".tar.gz"))
(sha256 (base32 "1vmzby12nvbrka6f44pr1pjwccl0p6s984pxvibajzp72x2knxc9"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Atk bindings")
(description "Bindings for Atk, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-mono-traversable-instances
(package
(name "ghc-mono-traversable-instances")
(version "0.1.0.0")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-traversable-instances/mono-traversable-instances-"
version ".tar.gz"))
(sha256 (base32 "0zh81hvqnracil2nvkx14xzwv9vavsnx739acp6gycdyrs5jpzxm"))))
(build-system haskell-build-system)
(inputs
`(("ghc-mono-traversable" ,ghc-mono-traversable)
("ghc-semigroupoids" ,ghc-semigroupoids)
("ghc-comonad" ,ghc-comonad)
("ghc-vector-instances" ,ghc-vector-instances)
("ghc-dlist" ,ghc-dlist)
("ghc-dlist-instances" ,ghc-dlist-instances)
("ghc-semigroups" ,ghc-semigroups)))
(arguments `(#:tests? #f))
(home-page "-traversable#readme")
(synopsis "Extra typeclass instances for mono-traversable")
(description "Please see README.md")
(license license:expat)))
(define ghc-mutable-containers
(package
(name "ghc-mutable-containers")
(version "0.3.4")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-containers/mutable-containers-"
version
".tar.gz"))
(sha256
(base32
"0zhkhlvg9yw45fg3srvzx7j81547djpkfw7higdvlj7fmph6c6b4"))))
(build-system haskell-build-system)
(inputs
`(("ghc-mono-traversable" ,ghc-mono-traversable)
("ghc-primitive" ,ghc-primitive)
("ghc-vector" ,ghc-vector)))
(arguments `(#:tests? #f))
(home-page "-traversable#readme")
(synopsis "Abstactions and concrete implementations of mutable containers")
(description "See docs and README at <-containers>")
(license license:expat)))
(define ghc-say
(package
(name "ghc-say")
(version "0.1.0.1")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256 (base32 "1r5kffjfwpas45g74sip8glrj1m9nygrnxjm7xgw898rq9pnafgn"))))
(build-system haskell-build-system)
(arguments `(#:tests? #f))
(home-page "#readme")
(synopsis "Send textual messages to a Handle in a thread-friendly way")
(description "Please see the README and documentation at <>")
(license license:expat)))
(define ghc-gi-vte
(package
(name "ghc-gi-vte")
(version "2.91.19")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-vte/gi-vte-" version ".tar.gz"))
(sha256 (base32 "1hnhidjr7jh7i826lj6kdn264i592sfl5kwvymnpiycmcb37dd4y"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-pango" ,ghc-gi-pango)
("ghc-gi-gtk" ,ghc-gi-gtk)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-gdk" ,ghc-gi-gdk)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)
("ghc-gi-atk" ,ghc-gi-atk)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Vte bindings")
(description "Bindings for Vte, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-haskell-gi-base
(package
(name "ghc-haskell-gi-base")
(version "0.21.4")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-gi-base/haskell-gi-base-" version ".tar.gz"))
(sha256 (base32 "0vrl0cqws1l0ba7avf16c9zyfsvq7gd8wv4sjzd7rjk6jmg38vds"))))
(native-inputs
`(("pkg-config" ,pkg-config)
("gobject-introspection" ,gobject-introspection)
("glib" ,glib)))
(build-system haskell-build-system)
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi-base")
(synopsis "Foundation for libraries generated by haskell-gi")
(description "Foundation for libraries generated by haskell-gi")
(license license:lgpl2.1)))
(define ghc-from-sum
(package
(name "ghc-from-sum")
(version "0.2.1.0")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-sum/from-sum-" version ".tar.gz"))
(sha256 (base32 "0rv66a7mhswb4sqkyarg9kxxfpiymsmrk49gprq8mpwq7d1qmvd1"))))
(build-system haskell-build-system)
(arguments `(#:tests? #f))
(home-page "-sum")
(synopsis "Canonical fromMaybeM and fromEitherM functions.")
(description "Please see README.md")
(license license:bsd-3)))
(define ghc-heterocephalus
(package
(name "ghc-heterocephalus")
(version "1.0.5.2")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256 (base32 "08sr2ps3kb2v6pglkls814w6fpvwkysd3k2s15pj9fhmhx82kf2h"))))
(build-system haskell-build-system)
(inputs
`(("ghc-blaze-html" ,ghc-blaze-html)
("ghc-blaze-markup" ,ghc-blaze-markup)
("ghc-dlist" ,ghc-dlist)
("ghc-shakespeare" ,ghc-shakespeare)))
(arguments `(#:tests? #f))
(home-page "#readme")
(synopsis "A type-safe template engine for working with popular front end development tools")
(description
"Recent front end development tools and languages are growing fast and have quite a complicated ecosystem. Few front end developers want to be forced use Shakespeare templates. Instead, they would rather use @node@-friendly engines such that @pug@, @slim@, and @haml@. However, in using these template engines, we lose the compile-time variable interpolation and type checking from Shakespeare. . Heterocephalus is intended for use with another feature rich template engine and provides a way to interpolate server side variables into a precompiled template file with @forall@, @if@, and @case@ statements.")
(license license:expat)))
(define ghc-html-conduit
(package
(name "ghc-html-conduit")
(version "1.3.2")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-conduit/html-conduit-" version ".tar.gz"))
(sha256 (base32 "0l5hc7bf57p5jiqh3wvnqapc27ibnlv00zm6szc0nqbvknzvvz85"))))
(build-system haskell-build-system)
(inputs
`(("ghc-resourcet" ,ghc-resourcet)
("ghc-conduit" ,ghc-conduit)
("ghc-xml-conduit" ,ghc-xml-conduit)
("ghc-xml-types" ,ghc-xml-types)
("ghc-attoparsec" ,ghc-attoparsec)
("ghc-conduit-extra" ,ghc-conduit-extra)))
(arguments `(#:tests? #f))
(home-page "")
(synopsis "Parse HTML documents using xml-conduit datatypes.")
(description
"This package uses tagstream-conduit for its parser. It automatically balances mismatched tags, so that there shouldn't be any parse failures. It does not handle a full HTML document rendering, such as adding missing html and head tags. Note that, since version 1.3.1, it uses an inlined copy of tagstream-conduit with entity decoding bugfixes applied.")
(license license:expat)))
(define ghc-xml-html-qq
(package
(name "ghc-xml-html-qq")
(version "0.1.0.1")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-html-qq/xml-html-qq-" version ".tar.gz"))
(sha256 (base32 "0ni354ihiaax7dlghq0qsili0sqy4z9vc3a75i24z2m59hgvnbhs"))))
(build-system haskell-build-system)
(inputs
`(("ghc-blaze-markup" ,ghc-blaze-markup)
("ghc-conduit" ,ghc-conduit)
("ghc-data-default" ,ghc-data-default)
("ghc-from-sum" ,ghc-from-sum)
("ghc-heterocephalus" ,ghc-heterocephalus)
("ghc-html-conduit" ,ghc-html-conduit)
("ghc-resourcet" ,ghc-resourcet)
("ghc-th-lift" ,ghc-th-lift)
("ghc-th-lift-instances" ,ghc-th-lift-instances)
("ghc-xml-conduit" ,ghc-xml-conduit)))
(arguments `(#:tests? #f))
(home-page "-html-qq")
(synopsis "Quasi-quoters for XML and HTML Documents")
(description "Please see <-html-qq#readme README.md>.")
(license license:bsd-3)))
(define ghc-classy-prelude
(package
(name "ghc-classy-prelude")
(version "1.5.0")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-prelude/classy-prelude-" version ".tar.gz"))
(sha256 (base32 "1nm4lygxqb1wq503maki6dsah2gpn5rd22jmbwjxfwyzgyqy9fnk"))))
(build-system haskell-build-system)
(inputs
`(("ghc-async" ,ghc-async)
("ghc-basic-prelude" ,ghc-basic-prelude)
("ghc-bifunctors" ,ghc-bifunctors)
("ghc-chunked-data" ,ghc-chunked-data)
("ghc-dlist" ,ghc-dlist)
("ghc-hashable" ,ghc-hashable)
("ghc-mono-traversable" ,ghc-mono-traversable)
("ghc-mono-traversable-instances" ,ghc-mono-traversable-instances)
("ghc-mutable-containers" ,ghc-mutable-containers)
("ghc-primitive" ,ghc-primitive)
("ghc-say" ,ghc-say)
("ghc-semigroups" ,ghc-semigroups)
("ghc-stm-chans" ,ghc-stm-chans)
("ghc-unliftio" ,ghc-unliftio)
("ghc-unordered-containers" ,ghc-unordered-containers)
("ghc-vector" ,ghc-vector)
("ghc-vector-instances" ,ghc-vector-instances)))
(arguments `(#:tests? #f))
(home-page "-traversable#readme")
(synopsis "A typeclass-based Prelude.")
(description "See docs and README at <-prelude>")
(license license:expat)))
| null | https://raw.githubusercontent.com/jsoo1/guix-channel/934b830110f4f7169257f107311cd10f628e0682/termonad.scm | scheme | PUBLIC
DEPENDENCIES | (define-module (termonad)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix build-system haskell)
#:use-module (ghc-keys)
#:use-module (ghc-pointed)
#:use-module (ghc-instances)
#:use-module (gnu packages glib)
#:use-module (gnu packages gtk)
#:use-module (gnu packages haskell)
#:use-module (gnu packages haskell-xyz)
#:use-module (gnu packages haskell-check)
#:use-module (gnu packages haskell-web)
#:use-module (gnu packages pkg-config)
#:export (termonad))
(define termonad
(package
(name "termonad")
(version "0.2.1.0")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256 (base32 "1js9sj0gj4igigdnbc5ygbn5l2wfhbrm1k565y3advi99imidsd3"))))
(build-system haskell-build-system)
(inputs
`(("ghc-classy-prelude" ,ghc-classy-prelude)
("ghc-colour" ,ghc-colour)
("ghc-constraints" ,ghc-constraints)
("ghc-data-default" ,ghc-data-default)
("ghc-dyre" ,ghc-dyre)
("ghc-gi-gdk" ,ghc-gi-gdk)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-glib" ,ghc-gi-glib)
("ghc-gi-gtk" ,ghc-gi-gtk)
("ghc-gi-pango" ,ghc-gi-pango)
("ghc-gi-vte" ,ghc-gi-vte)
("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-lens" ,ghc-lens)
("ghc-pretty-simple" ,ghc-pretty-simple)
("ghc-quickcheck" ,ghc-quickcheck)
("ghc-xml-conduit" ,ghc-xml-conduit)
("ghc-xml-html-qq" ,ghc-xml-html-qq)))
(native-inputs
`(("cabal-doctest" ,cabal-doctest)))
(arguments `(#:tests? #f))
(home-page "")
(synopsis "Terminal emulator configurable in Haskell")
(description "Please see <#readme README.md>.")
(license license:bsd-3)))
(define ghc-gi-gobject
(package
(name "ghc-gi-gobject")
(version "2.0.16")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gobject/gi-gobject-" version ".tar.gz"))
(sha256 (base32 "1bgn4ywx94py0v213iv7mbjjvvy3y7gvpgw4wpn38s2np7al8y65"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "GObject bindings")
(description "Bindings for GObject, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-gdkpixbuf
(package
(name "ghc-gi-gdkpixbuf")
(version "2.0.16")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gdkpixbuf/gi-gdkpixbuf-" version ".tar.gz"))
(sha256 (base32 "0vqnskshbfp9nsgyfg4pifrh007rb7k176ci8niik96kxh95zfzx"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "GdkPixbuf bindings")
(description "Bindings for GdkPixbuf, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-gio
(package
(name "ghc-gi-gio")
(version "2.0.18")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gio/gi-gio-" version ".tar.gz"))
(sha256 (base32 "0h7liqxf63wmhjzgbjshv7pa4fx743jpvkphn5yyjkc0bnfcvsqk"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Gio bindings")
(description "Bindings for Gio, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-cairo
(package
(name "ghc-gi-cairo")
(version "1.0.17")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-cairo/gi-cairo-" version ".tar.gz"))
(sha256 (base32 "1ax7aly9ahvb18m3zjmy0dk47qfdx5yl15q52c3wp4wa0c5aggax"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading"
,ghc-haskell-gi-overloading)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Cairo bindings")
(description "Bindings for Cairo, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-haskell-gi-overloading
(package
(name "ghc-haskell-gi-overloading")
(version "1.0")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-gi-overloading/haskell-gi-overloading-"
version ".tar.gz"))
(sha256 (base32 "0ak8f79ia9zlk94zr02sq8bqi5n5pd8ria8w1dj3adcdvpw9gmry"))))
(build-system haskell-build-system)
(arguments `(#:tests? #f
#:haddock? #f))
(home-page "-gi/haskell-gi")
(synopsis "Overloading support for haskell-gi")
(description "Control overloading support in haskell-gi generated bindings")
(license license:bsd-3)))
(define ghc-haskell-gi
(package
(name "ghc-haskell-gi")
(version "0.21.5")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gi/haskell-gi-" version ".tar.gz"))
(sha256 (base32 "1rvi9bmgxq7q6js8yb5yb156yxmnm9px9amgjwzxmr7sxz31dl8j"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-attoparsec" ,ghc-attoparsec)
("ghc-pretty-show" ,ghc-pretty-show)
("ghc-safe" ,ghc-safe)
("ghc-xdg-basedir" ,ghc-xdg-basedir)
("ghc-xml-conduit" ,ghc-xml-conduit)
("ghc-regex-tdfa" ,ghc-regex-tdfa)))
(native-inputs
`(("pkg-config" ,pkg-config)
("gobject-introspection" ,gobject-introspection)
("glib" ,glib)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Generate Haskell bindings for GObject Introspection capable libraries")
(description
"Generate Haskell bindings for GObject Introspection capable libraries. This includes most notably Gtk+, but many other libraries in the GObject ecosystem provide introspection data too.")
(license license:lgpl2.1)))
(define ghc-gi-gtk
(package
(name "ghc-gi-gtk")
(version "3.0.25")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gtk/gi-gtk-" version ".tar.gz"))
(sha256 (base32 "0l6xnh85agjagdmjy72akvxviwkzyngh7rii5idrsd62bb27abx1"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-cairo" ,ghc-gi-cairo)
("ghc-gi-pango" ,ghc-gi-pango)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-gdkpixbuf" ,ghc-gi-gdkpixbuf)
("ghc-gi-gdk" ,ghc-gi-gdk)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)
("ghc-gi-atk" ,ghc-gi-atk)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Gtk bindings")
(description "Bindings for Gtk, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-gdk
(package
(name "ghc-gi-gdk")
(version "3.0.16")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-gdk/gi-gdk-" version ".tar.gz"))
(sha256 (base32 "0jp3d3zfm20b4ax1g5k1wzh8fxxzsw4ssw7zqx0d13167m4smc3y"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-cairo" ,ghc-gi-cairo)
("ghc-gi-pango" ,ghc-gi-pango)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-gdkpixbuf" ,ghc-gi-gdkpixbuf)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Gdk bindings")
(description "Bindings for Gdk, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-gi-pango
(package
(name "ghc-gi-pango")
(version "1.0.16")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-pango/gi-pango-" version ".tar.gz"))
(sha256 (base32 "1x3q1q4ww1v6v42p1wcaghxsja8cigqaqvklkfg4gxyp2f2cdg57"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Pango bindings")
(description
"Bindings for Pango, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-io-storage
(package
(name "ghc-io-storage")
(version "0.3")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-storage/io-storage-" version ".tar.gz"))
(sha256 (base32 "1ga9bd7iri6vlsxnjx765yy3bxc4lbz644wyw88yzvpjgz6ga3cs"))))
(build-system haskell-build-system)
(arguments `(#:tests? #f))
(home-page "-storage")
(synopsis "A key-value store in the IO monad.")
(description
"This library allows an application to extend the 'global state' hidden inside the IO monad with semi-arbitrary data. Data is required to be 'Typeable'. The library provides an essentially unbounded number of key-value stores indexed by strings, with each key within the stores also being a string.")
(license license:bsd-3)))
(define ghc-gi-glib
(package
(name "ghc-gi-glib")
(version "2.0.17")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-glib/gi-glib-" version ".tar.gz"))
(sha256 (base32 "0rxbkrwlwnjf46z0qpw0vjw1nv9kl91xp7k2098rqs36kl5bwylx"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)))
(arguments
`(#:tests? #f
#:haddock? #f))
(home-page "-gi/haskell-gi")
(synopsis "GLib bindings")
(description
"Bindings for GLib, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-dyre
(package
(name "ghc-dyre")
(version "0.8.12")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256 (base32 "10hnlysy4bjvvznk8v902mlk4jx95qf972clyi1l32xkqrf30972"))))
(build-system haskell-build-system)
(inputs
`(("ghc-paths" ,ghc-paths)
("ghc-executable-path" ,ghc-executable-path)
("ghc-xdg-basedir" ,ghc-xdg-basedir)
("ghc-io-storage" ,ghc-io-storage)))
(arguments `(#:tests? #f))
(home-page "")
(synopsis "Dynamic reconfiguration in Haskell")
(description
"Dyre implements dynamic reconfiguration facilities after the style of Xmonad. Dyre aims to be as simple as possible without sacrificing features, and places an emphasis on simplicity of integration with an application. A full introduction with a complete example project can be found in the documentation for 'Config.Dyre'")
(license license:bsd-3)))
(define ghc-basic-prelude
(package
(name "ghc-basic-prelude")
(version "0.7.0")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-prelude/basic-prelude-" version ".tar.gz"))
(sha256 (base32 "0yckmnvm6i4vw0mykj4fzl4ldsf67v8d2h0vp1bakyj84n4myx8h"))))
(build-system haskell-build-system)
(inputs
`(("ghc-hashable" ,ghc-hashable)
("ghc-unordered-containers" ,ghc-unordered-containers)
("ghc-vector" ,ghc-vector)))
(arguments `(#:tests? #f))
(home-page "-prelude#readme")
(synopsis "An enhanced core prelude; a common foundation for alternate preludes.")
(description "Please see the README on Github at <-prelude#readme>")
(license license:expat)))
(define ghc-dlist-instances
(package
(name "ghc-dlist-instances")
(version "0.1.1.1")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-instances/dlist-instances-" version ".tar.gz"))
(sha256 (base32 "0nsgrr25r4qxv2kpn7i20hra8jjkyllxfrhh5hml3ysjdz010jni"))))
(build-system haskell-build-system)
(inputs
`(("ghc-semigroups" ,ghc-semigroups)
("ghc-dlist" ,ghc-dlist)))
(arguments `(#:tests? #f))
(home-page "-instances")
(synopsis "Difference lists instances")
(description
"See the dlist packages. This package is the canonical source for some orphan instances. Orphan instances are placed here to avoid dependencies elsewhere.")
(license license:bsd-3)))
(define ghc-gi-atk
(package
(name "ghc-gi-atk")
(version "2.0.15")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-atk/gi-atk-" version ".tar.gz"))
(sha256 (base32 "1vmzby12nvbrka6f44pr1pjwccl0p6s984pxvibajzp72x2knxc9"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Atk bindings")
(description "Bindings for Atk, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-mono-traversable-instances
(package
(name "ghc-mono-traversable-instances")
(version "0.1.0.0")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-traversable-instances/mono-traversable-instances-"
version ".tar.gz"))
(sha256 (base32 "0zh81hvqnracil2nvkx14xzwv9vavsnx739acp6gycdyrs5jpzxm"))))
(build-system haskell-build-system)
(inputs
`(("ghc-mono-traversable" ,ghc-mono-traversable)
("ghc-semigroupoids" ,ghc-semigroupoids)
("ghc-comonad" ,ghc-comonad)
("ghc-vector-instances" ,ghc-vector-instances)
("ghc-dlist" ,ghc-dlist)
("ghc-dlist-instances" ,ghc-dlist-instances)
("ghc-semigroups" ,ghc-semigroups)))
(arguments `(#:tests? #f))
(home-page "-traversable#readme")
(synopsis "Extra typeclass instances for mono-traversable")
(description "Please see README.md")
(license license:expat)))
(define ghc-mutable-containers
(package
(name "ghc-mutable-containers")
(version "0.3.4")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-containers/mutable-containers-"
version
".tar.gz"))
(sha256
(base32
"0zhkhlvg9yw45fg3srvzx7j81547djpkfw7higdvlj7fmph6c6b4"))))
(build-system haskell-build-system)
(inputs
`(("ghc-mono-traversable" ,ghc-mono-traversable)
("ghc-primitive" ,ghc-primitive)
("ghc-vector" ,ghc-vector)))
(arguments `(#:tests? #f))
(home-page "-traversable#readme")
(synopsis "Abstactions and concrete implementations of mutable containers")
(description "See docs and README at <-containers>")
(license license:expat)))
(define ghc-say
(package
(name "ghc-say")
(version "0.1.0.1")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256 (base32 "1r5kffjfwpas45g74sip8glrj1m9nygrnxjm7xgw898rq9pnafgn"))))
(build-system haskell-build-system)
(arguments `(#:tests? #f))
(home-page "#readme")
(synopsis "Send textual messages to a Handle in a thread-friendly way")
(description "Please see the README and documentation at <>")
(license license:expat)))
(define ghc-gi-vte
(package
(name "ghc-gi-vte")
(version "2.91.19")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-vte/gi-vte-" version ".tar.gz"))
(sha256 (base32 "1hnhidjr7jh7i826lj6kdn264i592sfl5kwvymnpiycmcb37dd4y"))))
(build-system haskell-build-system)
(inputs
`(("ghc-haskell-gi-base" ,ghc-haskell-gi-base)
("ghc-haskell-gi" ,ghc-haskell-gi)
("ghc-haskell-gi-overloading" ,ghc-haskell-gi-overloading)
("ghc-gi-pango" ,ghc-gi-pango)
("ghc-gi-gtk" ,ghc-gi-gtk)
("ghc-gi-gio" ,ghc-gi-gio)
("ghc-gi-gdk" ,ghc-gi-gdk)
("ghc-gi-gobject" ,ghc-gi-gobject)
("ghc-gi-glib" ,ghc-gi-glib)
("ghc-gi-atk" ,ghc-gi-atk)))
(native-inputs
`(("ghc-haskell-gi" ,ghc-haskell-gi)))
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi")
(synopsis "Vte bindings")
(description "Bindings for Vte, autogenerated by haskell-gi.")
(license license:lgpl2.1)))
(define ghc-haskell-gi-base
(package
(name "ghc-haskell-gi-base")
(version "0.21.4")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-gi-base/haskell-gi-base-" version ".tar.gz"))
(sha256 (base32 "0vrl0cqws1l0ba7avf16c9zyfsvq7gd8wv4sjzd7rjk6jmg38vds"))))
(native-inputs
`(("pkg-config" ,pkg-config)
("gobject-introspection" ,gobject-introspection)
("glib" ,glib)))
(build-system haskell-build-system)
(arguments `(#:tests? #f))
(home-page "-gi/haskell-gi-base")
(synopsis "Foundation for libraries generated by haskell-gi")
(description "Foundation for libraries generated by haskell-gi")
(license license:lgpl2.1)))
(define ghc-from-sum
(package
(name "ghc-from-sum")
(version "0.2.1.0")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-sum/from-sum-" version ".tar.gz"))
(sha256 (base32 "0rv66a7mhswb4sqkyarg9kxxfpiymsmrk49gprq8mpwq7d1qmvd1"))))
(build-system haskell-build-system)
(arguments `(#:tests? #f))
(home-page "-sum")
(synopsis "Canonical fromMaybeM and fromEitherM functions.")
(description "Please see README.md")
(license license:bsd-3)))
(define ghc-heterocephalus
(package
(name "ghc-heterocephalus")
(version "1.0.5.2")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-" version ".tar.gz"))
(sha256 (base32 "08sr2ps3kb2v6pglkls814w6fpvwkysd3k2s15pj9fhmhx82kf2h"))))
(build-system haskell-build-system)
(inputs
`(("ghc-blaze-html" ,ghc-blaze-html)
("ghc-blaze-markup" ,ghc-blaze-markup)
("ghc-dlist" ,ghc-dlist)
("ghc-shakespeare" ,ghc-shakespeare)))
(arguments `(#:tests? #f))
(home-page "#readme")
(synopsis "A type-safe template engine for working with popular front end development tools")
(description
"Recent front end development tools and languages are growing fast and have quite a complicated ecosystem. Few front end developers want to be forced use Shakespeare templates. Instead, they would rather use @node@-friendly engines such that @pug@, @slim@, and @haml@. However, in using these template engines, we lose the compile-time variable interpolation and type checking from Shakespeare. . Heterocephalus is intended for use with another feature rich template engine and provides a way to interpolate server side variables into a precompiled template file with @forall@, @if@, and @case@ statements.")
(license license:expat)))
(define ghc-html-conduit
(package
(name "ghc-html-conduit")
(version "1.3.2")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-conduit/html-conduit-" version ".tar.gz"))
(sha256 (base32 "0l5hc7bf57p5jiqh3wvnqapc27ibnlv00zm6szc0nqbvknzvvz85"))))
(build-system haskell-build-system)
(inputs
`(("ghc-resourcet" ,ghc-resourcet)
("ghc-conduit" ,ghc-conduit)
("ghc-xml-conduit" ,ghc-xml-conduit)
("ghc-xml-types" ,ghc-xml-types)
("ghc-attoparsec" ,ghc-attoparsec)
("ghc-conduit-extra" ,ghc-conduit-extra)))
(arguments `(#:tests? #f))
(home-page "")
(synopsis "Parse HTML documents using xml-conduit datatypes.")
(description
"This package uses tagstream-conduit for its parser. It automatically balances mismatched tags, so that there shouldn't be any parse failures. It does not handle a full HTML document rendering, such as adding missing html and head tags. Note that, since version 1.3.1, it uses an inlined copy of tagstream-conduit with entity decoding bugfixes applied.")
(license license:expat)))
(define ghc-xml-html-qq
(package
(name "ghc-xml-html-qq")
(version "0.1.0.1")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-html-qq/xml-html-qq-" version ".tar.gz"))
(sha256 (base32 "0ni354ihiaax7dlghq0qsili0sqy4z9vc3a75i24z2m59hgvnbhs"))))
(build-system haskell-build-system)
(inputs
`(("ghc-blaze-markup" ,ghc-blaze-markup)
("ghc-conduit" ,ghc-conduit)
("ghc-data-default" ,ghc-data-default)
("ghc-from-sum" ,ghc-from-sum)
("ghc-heterocephalus" ,ghc-heterocephalus)
("ghc-html-conduit" ,ghc-html-conduit)
("ghc-resourcet" ,ghc-resourcet)
("ghc-th-lift" ,ghc-th-lift)
("ghc-th-lift-instances" ,ghc-th-lift-instances)
("ghc-xml-conduit" ,ghc-xml-conduit)))
(arguments `(#:tests? #f))
(home-page "-html-qq")
(synopsis "Quasi-quoters for XML and HTML Documents")
(description "Please see <-html-qq#readme README.md>.")
(license license:bsd-3)))
(define ghc-classy-prelude
(package
(name "ghc-classy-prelude")
(version "1.5.0")
(source
(origin
(method url-fetch)
(uri (string-append
"mirror-prelude/classy-prelude-" version ".tar.gz"))
(sha256 (base32 "1nm4lygxqb1wq503maki6dsah2gpn5rd22jmbwjxfwyzgyqy9fnk"))))
(build-system haskell-build-system)
(inputs
`(("ghc-async" ,ghc-async)
("ghc-basic-prelude" ,ghc-basic-prelude)
("ghc-bifunctors" ,ghc-bifunctors)
("ghc-chunked-data" ,ghc-chunked-data)
("ghc-dlist" ,ghc-dlist)
("ghc-hashable" ,ghc-hashable)
("ghc-mono-traversable" ,ghc-mono-traversable)
("ghc-mono-traversable-instances" ,ghc-mono-traversable-instances)
("ghc-mutable-containers" ,ghc-mutable-containers)
("ghc-primitive" ,ghc-primitive)
("ghc-say" ,ghc-say)
("ghc-semigroups" ,ghc-semigroups)
("ghc-stm-chans" ,ghc-stm-chans)
("ghc-unliftio" ,ghc-unliftio)
("ghc-unordered-containers" ,ghc-unordered-containers)
("ghc-vector" ,ghc-vector)
("ghc-vector-instances" ,ghc-vector-instances)))
(arguments `(#:tests? #f))
(home-page "-traversable#readme")
(synopsis "A typeclass-based Prelude.")
(description "See docs and README at <-prelude>")
(license license:expat)))
|
a378d2f7691cddcbe7963913caecf6ae8c59d1cee2dbec8bdbedda5d7c59a58f | joshuamiller/cljs-react-navigation-example | events.cljs | (ns nav-example.events
(:require
[re-frame.core :refer [reg-event-db after]]
[clojure.spec.alpha :as s]
[nav-example.db :as db :refer [app-db]]))
;; -- Interceptors ------------------------------------------------------------
;;
;; See -frame/blob/master/docs/Interceptors.md
;;
(defn check-and-throw
"Throw an exception if db doesn't have a valid spec."
[spec db [event]]
(when-not (s/valid? spec db)
(let [explain-data (s/explain-data spec db)]
(throw (ex-info (str "Spec check after " event " failed: " explain-data) explain-data)))))
(def validate-spec
(if goog.DEBUG
(after (partial check-and-throw ::db/app-db))
[]))
;; -- Handlers --------------------------------------------------------------
(reg-event-db
:initialize-db
validate-spec
(fn [_ _]
app-db))
(reg-event-db
:set-greeting
validate-spec
(fn [db [_ value]]
(assoc db :greeting value)))
| null | https://raw.githubusercontent.com/joshuamiller/cljs-react-navigation-example/45568ed191e782c3f8c0580d2d8774c6b2add52f/src/nav_example/events.cljs | clojure | -- Interceptors ------------------------------------------------------------
See -frame/blob/master/docs/Interceptors.md
-- Handlers -------------------------------------------------------------- | (ns nav-example.events
(:require
[re-frame.core :refer [reg-event-db after]]
[clojure.spec.alpha :as s]
[nav-example.db :as db :refer [app-db]]))
(defn check-and-throw
"Throw an exception if db doesn't have a valid spec."
[spec db [event]]
(when-not (s/valid? spec db)
(let [explain-data (s/explain-data spec db)]
(throw (ex-info (str "Spec check after " event " failed: " explain-data) explain-data)))))
(def validate-spec
(if goog.DEBUG
(after (partial check-and-throw ::db/app-db))
[]))
(reg-event-db
:initialize-db
validate-spec
(fn [_ _]
app-db))
(reg-event-db
:set-greeting
validate-spec
(fn [db [_ value]]
(assoc db :greeting value)))
|
d04248d87c2497ed2fdbf969a2d22d5547053fb8715cd8431d6e2f9666281b86 | hmac/kite | Error.hs | -- All errors that can be raised by the compiler are represented here
module Error
( Error(..)
) where
import GHC.Generics ( Generic )
import Prettyprinter
import qualified Chez.Compile
import qualified Interpret
import qualified ModuleLoader
import qualified Package
import qualified Type
import qualified Type.Print
data Error =
PackageError Package.Error
| LoadError ModuleLoader.Error
| ParseError String
| TypeError Type.LocatedError
| CompileError Chez.Compile.Error
| InterpretError Interpret.Error
deriving (Eq, Generic, Show)
instance Pretty Error where
pretty = \case
PackageError err -> pretty err
LoadError err -> pretty err
ParseError err -> pretty err
TypeError err -> Type.Print.printLocatedError err
CompileError err -> pretty err
InterpretError err -> pretty err
| null | https://raw.githubusercontent.com/hmac/kite/a48839fa5a4edce3bc7a758e4fcb1bda38a556f0/src/Error.hs | haskell | All errors that can be raised by the compiler are represented here | module Error
( Error(..)
) where
import GHC.Generics ( Generic )
import Prettyprinter
import qualified Chez.Compile
import qualified Interpret
import qualified ModuleLoader
import qualified Package
import qualified Type
import qualified Type.Print
data Error =
PackageError Package.Error
| LoadError ModuleLoader.Error
| ParseError String
| TypeError Type.LocatedError
| CompileError Chez.Compile.Error
| InterpretError Interpret.Error
deriving (Eq, Generic, Show)
instance Pretty Error where
pretty = \case
PackageError err -> pretty err
LoadError err -> pretty err
ParseError err -> pretty err
TypeError err -> Type.Print.printLocatedError err
CompileError err -> pretty err
InterpretError err -> pretty err
|
9ba41ccb9f5446fdf18b7cc22feb524285a428af9c2ad3f827ab1363cd129e50 | Aeva/snake-oil | test.rkt | #lang racket/base
(require snake-oil)
; Import functions, etc from python source files!
(require-py "test.py" fnord)
(fnord 1 2 3)
; Or from modules!
(require-py "math" radians)
(radians 90)
; Or just vibe!
(py-eval "(min(123, 456), [456, 789], 'Hail Eris!', {'a':1, 'b':2})")
; Or if you need to get really fancy,
(define math (py-import "math"))
(py-eval "sqrt(2)" math)
| null | https://raw.githubusercontent.com/Aeva/snake-oil/d21a794653036d8e870b5b6e8cc14c574e75f9e7/example/test.rkt | racket | Import functions, etc from python source files!
Or from modules!
Or just vibe!
Or if you need to get really fancy, | #lang racket/base
(require snake-oil)
(require-py "test.py" fnord)
(fnord 1 2 3)
(require-py "math" radians)
(radians 90)
(py-eval "(min(123, 456), [456, 789], 'Hail Eris!', {'a':1, 'b':2})")
(define math (py-import "math"))
(py-eval "sqrt(2)" math)
|
6bd2d6bd270e68e613b2467ddf24c04d0953e258f43969444b21b1b8b54f2c32 | Gabriella439/turtle | Shell.hs | {-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
# LANGUAGE ExistentialQuantification #
{-# LANGUAGE RankNTypes #-}
# OPTIONS_GHC -fno - warn - missing - methods #
| You can think of ` Shell ` as @[]@ + ` IO ` + ` Managed ` . In fact , you can embed
all three of them within a ` Shell ` :
> select : : [ a ] - > Shell a
> liftIO : : IO a - > Shell a
> using : : Managed a - > Shell a
Those three embeddings obey these laws :
> do { x < - select m ; select ( f x ) } = select ( do { x < - m ; f x } )
> do { x < - liftIO m ; ( f x ) } = liftIO ( do { x < - m ; f x } )
> do { x < - with m ; using ( f x ) } = using ( do { x < - m ; f x } )
>
> select ( return x ) = return x
> liftIO ( return x ) = return x
> using ( return x ) = return x
... and ` select ` obeys these additional laws :
> select xs < | > select ys = select ( xs < | > ys )
> select empty = empty
You typically wo n't build ` Shell`s using the ` Shell ` constructor . Instead ,
use these functions to generate primitive ` Shell`s :
* ` empty ` , to create a ` Shell ` that outputs nothing
* ` return ` , to create a ` Shell ` that outputs a single value
* ` select ` , to range over a list of values within a ` Shell `
* ` liftIO ` , to embed an ` IO ` action within a ` Shell `
* ` using ` , to acquire a ` Managed ` resource within a ` Shell `
Then use these classes to combine those primitive ` Shell`s into larger
` Shell`s :
* ` Alternative ` , to concatenate ` Shell ` outputs using ( ` < | > ` )
* ` Monad ` , to build ` Shell ` comprehensions using @do@ notation
If you still insist on building your own ` Shell ` from scratch , then the
` Shell ` you build must satisfy this law :
> -- For every shell ` s ` :
> _ foldShell s ( FoldShell step begin done ) = do
> x ' < - _ foldShell s ( FoldShell step begin return )
> done x '
... which is a fancy way of saying that your ` Shell ` must call @\'begin\'@
exactly once when it begins and call @\'done\'@ exactly once when it ends .
all three of them within a `Shell`:
> select :: [a] -> Shell a
> liftIO :: IO a -> Shell a
> using :: Managed a -> Shell a
Those three embeddings obey these laws:
> do { x <- select m; select (f x) } = select (do { x <- m; f x })
> do { x <- liftIO m; liftIO (f x) } = liftIO (do { x <- m; f x })
> do { x <- with m; using (f x) } = using (do { x <- m; f x })
>
> select (return x) = return x
> liftIO (return x) = return x
> using (return x) = return x
... and `select` obeys these additional laws:
> select xs <|> select ys = select (xs <|> ys)
> select empty = empty
You typically won't build `Shell`s using the `Shell` constructor. Instead,
use these functions to generate primitive `Shell`s:
* `empty`, to create a `Shell` that outputs nothing
* `return`, to create a `Shell` that outputs a single value
* `select`, to range over a list of values within a `Shell`
* `liftIO`, to embed an `IO` action within a `Shell`
* `using`, to acquire a `Managed` resource within a `Shell`
Then use these classes to combine those primitive `Shell`s into larger
`Shell`s:
* `Alternative`, to concatenate `Shell` outputs using (`<|>`)
* `Monad`, to build `Shell` comprehensions using @do@ notation
If you still insist on building your own `Shell` from scratch, then the
`Shell` you build must satisfy this law:
> -- For every shell `s`:
> _foldShell s (FoldShell step begin done) = do
> x' <- _foldShell s (FoldShell step begin return)
> done x'
... which is a fancy way of saying that your `Shell` must call @\'begin\'@
exactly once when it begins and call @\'done\'@ exactly once when it ends.
-}
module Turtle.Shell (
-- * Shell
Shell(..)
, FoldShell(..)
, _foldIO
, _Shell
, foldIO
, foldShell
, fold
, reduce
, sh
, view
*
, select
, liftIO
, using
, fromIO
) where
import Control.Applicative
import Control.Monad (MonadPlus(..), ap)
import Control.Monad.Catch (MonadThrow(..), MonadCatch(..))
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Managed (MonadManaged(..), with)
import qualified Control.Monad.Fail as Fail
import Control.Foldl (Fold(..), FoldM(..))
import qualified Control.Foldl as Foldl
import Data.Foldable (Foldable)
import qualified Data.Foldable
import Data.Monoid
import Data.String (IsString(..))
import Prelude -- Fix redundant import warnings
| This is similar to @`Control . . FoldM ` ` IO`@ except that the @begin@
field is pure
This small difference is necessary to implement a well - behaved ` MonadCatch `
instance for ` Shell `
field is pure
This small difference is necessary to implement a well-behaved `MonadCatch`
instance for `Shell`
-}
data FoldShell a b = forall x . FoldShell (x -> a -> IO x) x (x -> IO b)
-- | A @(Shell a)@ is a protected stream of @a@'s with side effects
newtype Shell a = Shell { _foldShell:: forall r . FoldShell a r -> IO r }
data Maybe' a = Just' !a | Nothing'
translate :: FoldM IO a b -> FoldShell a b
translate (FoldM step begin done) = FoldShell step' Nothing' done'
where
step' Nothing' a = do
x <- begin
x' <- step x a
return $! Just' x'
step' (Just' x) a = do
x' <- step x a
return $! Just' x'
done' Nothing' = do
x <- begin
done x
done' (Just' x) = do
done x
| Use a @`FoldM ` ` IO`@ to reduce the stream of @a@ 's produced by a ` Shell `
foldIO :: MonadIO io => Shell a -> FoldM IO a r -> io r
foldIO s f = liftIO (_foldIO s f)
| Provided for backwards compatibility with versions of @turtle-1.4.*@ and
older
older
-}
_foldIO :: Shell a -> FoldM IO a r -> IO r
_foldIO s foldM = _foldShell s (translate foldM)
| Provided for ease of migration from versions of @turtle-1.4.*@ and older
_Shell :: (forall r . FoldM IO a r -> IO r) -> Shell a
_Shell f = Shell (f . adapt)
where
adapt (FoldShell step begin done) = FoldM step (return begin) done
| Use a ` FoldShell ` to reduce the stream of @a@ 's produced by a ` Shell `
foldShell :: MonadIO io => Shell a -> FoldShell a b -> io b
foldShell s f = liftIO (_foldShell s f)
| Use a ` Fold ` to reduce the stream of @a@ 's produced by a ` Shell `
fold :: MonadIO io => Shell a -> Fold a b -> io b
fold s f = foldIO s (Foldl.generalize f)
-- | Flipped version of 'fold'. Useful for reducing a stream of data
--
-- ==== __Example__
Sum a ` Shell ` of numbers :
--
> > > select [ 1 , 2 , 3 ] & reduce Fold.sum
6
reduce :: MonadIO io => Fold a b -> Shell a -> io b
reduce = flip fold
| Run a ` Shell ` to completion , discarding any unused values
sh :: MonadIO io => Shell a -> io ()
sh s = fold s (pure ())
| Run a ` Shell ` to completion , ` print`ing any unused values
view :: (MonadIO io, Show a) => Shell a -> io ()
view s = sh (do
x <- s
liftIO (print x) )
instance Functor Shell where
fmap f s = Shell (\(FoldShell step begin done) ->
let step' x a = step x (f a)
in _foldShell s (FoldShell step' begin done) )
instance Applicative Shell where
pure = return
(<*>) = ap
instance Monad Shell where
return a = Shell (\(FoldShell step begin done) -> do
x <- step begin a
done x )
m >>= f = Shell (\(FoldShell step0 begin0 done0) -> do
let step1 x a = _foldShell (f a) (FoldShell step0 x return)
_foldShell m (FoldShell step1 begin0 done0) )
#if!(MIN_VERSION_base(4,13,0))
fail = Fail.fail
#endif
instance Alternative Shell where
empty = Shell (\(FoldShell _ begin done) -> done begin)
s1 <|> s2 = Shell (\(FoldShell step begin done) -> do
x <- _foldShell s1 (FoldShell step begin return)
_foldShell s2 (FoldShell step x done) )
instance MonadPlus Shell where
mzero = empty
mplus = (<|>)
instance MonadIO Shell where
liftIO io = Shell (\(FoldShell step begin done) -> do
a <- io
x <- step begin a
done x )
instance MonadManaged Shell where
using resource = Shell (\(FoldShell step begin done) -> do
x <- with resource (step begin)
done x )
instance MonadThrow Shell where
throwM e = Shell (\_ -> throwM e)
instance MonadCatch Shell where
m `catch` k = Shell (\f-> _foldShell m f `catch` (\e -> _foldShell (k e) f))
instance Fail.MonadFail Shell where
fail _ = mzero
#if __GLASGOW_HASKELL__ >= 804
instance Monoid a => Semigroup (Shell a) where
(<>) = mappend
#endif
instance Monoid a => Monoid (Shell a) where
mempty = pure mempty
mappend = liftA2 mappend
-- | Shell forms a semiring, this is the closest approximation
instance Monoid a => Num (Shell a) where
fromInteger n = select (replicate (fromInteger n) mempty)
(+) = (<|>)
(*) = (<>)
instance IsString a => IsString (Shell a) where
fromString str = pure (fromString str)
| Convert a list to a ` Shell ` that emits each element of the list
select :: Foldable f => f a -> Shell a
select as = Shell (\(FoldShell step begin done) -> do
let step' a k x = do
x' <- step x a
k $! x'
Data.Foldable.foldr step' done as $! begin )
| Convert an ` IO ` action that returns a ` Maybe ` into a ` Shell `
fromIO :: IO (Maybe a) -> Shell a
fromIO io =
Shell
(\(FoldShell step begin done) -> do
let loop x = do
m <- io
case m of
Just a -> do
x' <- step x a
loop x'
Nothing -> do
done x
loop begin
)
| null | https://raw.githubusercontent.com/Gabriella439/turtle/d387014ffc8382d23c54bf6f3a5d94a11044f3a6/src/Turtle/Shell.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE CPP #
# LANGUAGE RankNTypes #
For every shell ` s ` :
For every shell `s`:
* Shell
Fix redundant import warnings
| A @(Shell a)@ is a protected stream of @a@'s with side effects
| Flipped version of 'fold'. Useful for reducing a stream of data
==== __Example__
| Shell forms a semiring, this is the closest approximation | # LANGUAGE ExistentialQuantification #
# OPTIONS_GHC -fno - warn - missing - methods #
| You can think of ` Shell ` as @[]@ + ` IO ` + ` Managed ` . In fact , you can embed
all three of them within a ` Shell ` :
> select : : [ a ] - > Shell a
> liftIO : : IO a - > Shell a
> using : : Managed a - > Shell a
Those three embeddings obey these laws :
> do { x < - select m ; select ( f x ) } = select ( do { x < - m ; f x } )
> do { x < - liftIO m ; ( f x ) } = liftIO ( do { x < - m ; f x } )
> do { x < - with m ; using ( f x ) } = using ( do { x < - m ; f x } )
>
> select ( return x ) = return x
> liftIO ( return x ) = return x
> using ( return x ) = return x
... and ` select ` obeys these additional laws :
> select xs < | > select ys = select ( xs < | > ys )
> select empty = empty
You typically wo n't build ` Shell`s using the ` Shell ` constructor . Instead ,
use these functions to generate primitive ` Shell`s :
* ` empty ` , to create a ` Shell ` that outputs nothing
* ` return ` , to create a ` Shell ` that outputs a single value
* ` select ` , to range over a list of values within a ` Shell `
* ` liftIO ` , to embed an ` IO ` action within a ` Shell `
* ` using ` , to acquire a ` Managed ` resource within a ` Shell `
Then use these classes to combine those primitive ` Shell`s into larger
` Shell`s :
* ` Alternative ` , to concatenate ` Shell ` outputs using ( ` < | > ` )
* ` Monad ` , to build ` Shell ` comprehensions using @do@ notation
If you still insist on building your own ` Shell ` from scratch , then the
` Shell ` you build must satisfy this law :
> _ foldShell s ( FoldShell step begin done ) = do
> x ' < - _ foldShell s ( FoldShell step begin return )
> done x '
... which is a fancy way of saying that your ` Shell ` must call @\'begin\'@
exactly once when it begins and call @\'done\'@ exactly once when it ends .
all three of them within a `Shell`:
> select :: [a] -> Shell a
> liftIO :: IO a -> Shell a
> using :: Managed a -> Shell a
Those three embeddings obey these laws:
> do { x <- select m; select (f x) } = select (do { x <- m; f x })
> do { x <- liftIO m; liftIO (f x) } = liftIO (do { x <- m; f x })
> do { x <- with m; using (f x) } = using (do { x <- m; f x })
>
> select (return x) = return x
> liftIO (return x) = return x
> using (return x) = return x
... and `select` obeys these additional laws:
> select xs <|> select ys = select (xs <|> ys)
> select empty = empty
You typically won't build `Shell`s using the `Shell` constructor. Instead,
use these functions to generate primitive `Shell`s:
* `empty`, to create a `Shell` that outputs nothing
* `return`, to create a `Shell` that outputs a single value
* `select`, to range over a list of values within a `Shell`
* `liftIO`, to embed an `IO` action within a `Shell`
* `using`, to acquire a `Managed` resource within a `Shell`
Then use these classes to combine those primitive `Shell`s into larger
`Shell`s:
* `Alternative`, to concatenate `Shell` outputs using (`<|>`)
* `Monad`, to build `Shell` comprehensions using @do@ notation
If you still insist on building your own `Shell` from scratch, then the
`Shell` you build must satisfy this law:
> _foldShell s (FoldShell step begin done) = do
> x' <- _foldShell s (FoldShell step begin return)
> done x'
... which is a fancy way of saying that your `Shell` must call @\'begin\'@
exactly once when it begins and call @\'done\'@ exactly once when it ends.
-}
module Turtle.Shell (
Shell(..)
, FoldShell(..)
, _foldIO
, _Shell
, foldIO
, foldShell
, fold
, reduce
, sh
, view
*
, select
, liftIO
, using
, fromIO
) where
import Control.Applicative
import Control.Monad (MonadPlus(..), ap)
import Control.Monad.Catch (MonadThrow(..), MonadCatch(..))
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Managed (MonadManaged(..), with)
import qualified Control.Monad.Fail as Fail
import Control.Foldl (Fold(..), FoldM(..))
import qualified Control.Foldl as Foldl
import Data.Foldable (Foldable)
import qualified Data.Foldable
import Data.Monoid
import Data.String (IsString(..))
| This is similar to @`Control . . FoldM ` ` IO`@ except that the @begin@
field is pure
This small difference is necessary to implement a well - behaved ` MonadCatch `
instance for ` Shell `
field is pure
This small difference is necessary to implement a well-behaved `MonadCatch`
instance for `Shell`
-}
data FoldShell a b = forall x . FoldShell (x -> a -> IO x) x (x -> IO b)
newtype Shell a = Shell { _foldShell:: forall r . FoldShell a r -> IO r }
data Maybe' a = Just' !a | Nothing'
translate :: FoldM IO a b -> FoldShell a b
translate (FoldM step begin done) = FoldShell step' Nothing' done'
where
step' Nothing' a = do
x <- begin
x' <- step x a
return $! Just' x'
step' (Just' x) a = do
x' <- step x a
return $! Just' x'
done' Nothing' = do
x <- begin
done x
done' (Just' x) = do
done x
| Use a @`FoldM ` ` IO`@ to reduce the stream of @a@ 's produced by a ` Shell `
foldIO :: MonadIO io => Shell a -> FoldM IO a r -> io r
foldIO s f = liftIO (_foldIO s f)
| Provided for backwards compatibility with versions of @turtle-1.4.*@ and
older
older
-}
_foldIO :: Shell a -> FoldM IO a r -> IO r
_foldIO s foldM = _foldShell s (translate foldM)
| Provided for ease of migration from versions of @turtle-1.4.*@ and older
_Shell :: (forall r . FoldM IO a r -> IO r) -> Shell a
_Shell f = Shell (f . adapt)
where
adapt (FoldShell step begin done) = FoldM step (return begin) done
| Use a ` FoldShell ` to reduce the stream of @a@ 's produced by a ` Shell `
foldShell :: MonadIO io => Shell a -> FoldShell a b -> io b
foldShell s f = liftIO (_foldShell s f)
| Use a ` Fold ` to reduce the stream of @a@ 's produced by a ` Shell `
fold :: MonadIO io => Shell a -> Fold a b -> io b
fold s f = foldIO s (Foldl.generalize f)
Sum a ` Shell ` of numbers :
> > > select [ 1 , 2 , 3 ] & reduce Fold.sum
6
reduce :: MonadIO io => Fold a b -> Shell a -> io b
reduce = flip fold
| Run a ` Shell ` to completion , discarding any unused values
sh :: MonadIO io => Shell a -> io ()
sh s = fold s (pure ())
| Run a ` Shell ` to completion , ` print`ing any unused values
view :: (MonadIO io, Show a) => Shell a -> io ()
view s = sh (do
x <- s
liftIO (print x) )
instance Functor Shell where
fmap f s = Shell (\(FoldShell step begin done) ->
let step' x a = step x (f a)
in _foldShell s (FoldShell step' begin done) )
instance Applicative Shell where
pure = return
(<*>) = ap
instance Monad Shell where
return a = Shell (\(FoldShell step begin done) -> do
x <- step begin a
done x )
m >>= f = Shell (\(FoldShell step0 begin0 done0) -> do
let step1 x a = _foldShell (f a) (FoldShell step0 x return)
_foldShell m (FoldShell step1 begin0 done0) )
#if!(MIN_VERSION_base(4,13,0))
fail = Fail.fail
#endif
instance Alternative Shell where
empty = Shell (\(FoldShell _ begin done) -> done begin)
s1 <|> s2 = Shell (\(FoldShell step begin done) -> do
x <- _foldShell s1 (FoldShell step begin return)
_foldShell s2 (FoldShell step x done) )
instance MonadPlus Shell where
mzero = empty
mplus = (<|>)
instance MonadIO Shell where
liftIO io = Shell (\(FoldShell step begin done) -> do
a <- io
x <- step begin a
done x )
instance MonadManaged Shell where
using resource = Shell (\(FoldShell step begin done) -> do
x <- with resource (step begin)
done x )
instance MonadThrow Shell where
throwM e = Shell (\_ -> throwM e)
instance MonadCatch Shell where
m `catch` k = Shell (\f-> _foldShell m f `catch` (\e -> _foldShell (k e) f))
instance Fail.MonadFail Shell where
fail _ = mzero
#if __GLASGOW_HASKELL__ >= 804
instance Monoid a => Semigroup (Shell a) where
(<>) = mappend
#endif
instance Monoid a => Monoid (Shell a) where
mempty = pure mempty
mappend = liftA2 mappend
instance Monoid a => Num (Shell a) where
fromInteger n = select (replicate (fromInteger n) mempty)
(+) = (<|>)
(*) = (<>)
instance IsString a => IsString (Shell a) where
fromString str = pure (fromString str)
| Convert a list to a ` Shell ` that emits each element of the list
select :: Foldable f => f a -> Shell a
select as = Shell (\(FoldShell step begin done) -> do
let step' a k x = do
x' <- step x a
k $! x'
Data.Foldable.foldr step' done as $! begin )
| Convert an ` IO ` action that returns a ` Maybe ` into a ` Shell `
fromIO :: IO (Maybe a) -> Shell a
fromIO io =
Shell
(\(FoldShell step begin done) -> do
let loop x = do
m <- io
case m of
Just a -> do
x' <- step x a
loop x'
Nothing -> do
done x
loop begin
)
|
b65ab597c56de3cabe37b8a8cc7113aa548ac4b186d6b39e6b4f2346b72f3e44 | ocaml-sf/learn-ocaml-corpus | term_no_sub.ml | (* The type [parser] satisfies the monad API: [delay], [return], [>>=]. *)
(* [delay p] behaves like [p()], except the construction of the monadic
computation is delayed until the moment when this computation is run. *)
let delay (p : unit -> 'a parser) : 'a parser =
fun cursor ->
NonDet.delay (fun () -> p () cursor)
(* [return a] always succeeds, consumes no input, and returns [a]. *)
let return (a : 'a) : 'a parser =
fun cursor ->
NonDet.return (a, cursor)
(* [p >>= f] is the sequential composition of the parsers [p] and [f]. *)
let (>>=) (p : 'a parser) (f : 'a -> 'b parser) : 'b parser =
fun cursor ->
let open NonDet in
p cursor >>= fun (a, cursor) ->
f a cursor
(* The type [parser] supports the nondeterminism monad API: [fail], [choose],
[at_most_once]. *)
(* The parser [fail] accepts the empty language: it always fails. *)
let fail : 'a parser =
fun cursor ->
NonDet.fail
(* The parser [choose p q] accepts the union of the languages accepted
by the parsers [p] and [q]. *)
let choose (p : 'a parser) (q : 'a parser) : 'a parser =
fun cursor ->
NonDet.choose (p cursor) (q cursor)
(* The parser [at_most_once p] accepts the same language as [p], but
accepts each input string in at most one way. *)
let at_most_once (p : 'a parser) : 'a parser =
fun cursor ->
NonDet.at_most_once (p cursor)
(* The type [parser] supports the applicative functor API: [map], [<*>],
[<&>]. *)
(* [map f p] accepts the same language as the parser [p], and applies the
function [f] to every result produced by [p]. *)
let map (f : 'a -> 'b) (p : 'a parser) : 'b parser =
p >>= fun a ->
return (f a)
(* The parser [p <*> q] accepts the concatenation of the languages accepted
by the parsers [p] and [q]. For each value [f] returned by [p] and for
each value [x] returned by [q], it returns the result of the application
[f x]. *)
let (<*>) (p : ('a -> 'b) parser) (q : 'a parser) : 'b parser =
p >>= fun f ->
q >>= fun x ->
return (f x)
(* The parser [p <&> q] accepts the concatenation of the languages accepted
by the parsers [p] and [q]. For each value [a] returned by [p] and for
each value [b] returned by [q], it returns the pair [(a, b)]. *)
let (<&>) (p : 'a parser) (q : 'b parser) : ('a * 'b) parser =
p >>= fun a ->
q >>= fun b ->
return (a, b)
(* The parser [p >> q] accepts the concatenation of the languages accepted
by the parsers [p] and [q]. For each value [a] returned by [p] and for
each value [b] returned by [q], it returns just [b]. *)
let (>>) (p : 'a parser) (q : 'b parser) : 'b parser =
p >>= fun _ -> q
(* The parser [p << q] accepts the concatenation of the languages accepted
by the parsers [p] and [q]. For each value [a] returned by [p] and for
each value [b] returned by [q], it returns just [a]. *)
let (<<) (p : 'a parser) (q : 'b parser) : 'a parser =
p >>= fun a ->
q >> return a
(* The parser combinator [list] is an n-ary version of [<&>]. If [ps] is
a list of parsers, then the parser [list ps] accepts the concatenation
of the languages accepted by the parsers in the list [ps]. *)
let cons (x, xs) =
x :: xs
let rec list (ps : 'a parser list) : 'a list parser =
match ps with
| [] ->
return []
| p :: ps ->
map cons (p <&> list ps)
The type [ parser ] supports a number of operations that are specific of the
parser combinator monad . The most basic two are [ any ] and [ eof ] . On top of
these two , more combinators are defined , including [ sat ] , [ char ] , [ string ] ,
[ digit ] , and so on .
parser combinator monad. The most basic two are [any] and [eof]. On top of
these two, more combinators are defined, including [sat], [char], [string],
[digit], and so on. *)
(* [any] succeeds if and only if the cursor is currently not at the end of the
input stream. It consumes and returns the next input token. *)
let any : token parser =
fun cursor ->
match cursor() with
| Seq.Nil ->
NonDet.fail
| Seq.Cons (c, cursor) ->
NonDet.return (c, cursor)
[ eof ] succeeds if and only if the cursor is currently at the end of the
input stream . It consumes nothing , and returns [ ( ) ] . It is idempotent :
[ eof > > eof ] is the same as [ eof ] .
input stream. It consumes nothing, and returns [()]. It is idempotent:
[eof >> eof] is the same as [eof]. *)
let eof : unit parser =
fun cursor ->
match cursor() with
| Seq.Nil ->
NonDet.return ((), cursor)
| Seq.Cons _ ->
NonDet.fail
(* The parser [sat p] consumes and returns the next input token if this
token satisfies the predicate [p]. It fails otherwise. *)
let sat (p : token -> bool) : token parser =
any >>= fun c ->
if p c then return c else fail
(* The parser [char c] consumes and returns the next input token if this
token is the character [c]. It fails otherwise. *)
let char (c : token) : token parser =
sat ((=) c)
(* The parser [string cs] consumes and returns the list of characters [cs]
if this exact list is found at the front of the input stream. It fails
otherwise. *)
let string (cs : token list) : token list parser =
list (List.map char cs)
The parser [ digit ] consumes the next token if this token is a character
in the range [ ' 0' .. '9 ' ] . It returns an integer between 0 and 9 .
in the range ['0'..'9']. It returns an integer between 0 and 9. *)
let is_digit c : bool =
Char.code '0' <= Char.code c && Char.code c <= Char.code '9'
let decode_digit c : int =
Char.code c - Char.code '0'
let digit: int parser =
sat is_digit |> map decode_digit
(* Iteration. *)
(* The parser [star p] accepts the concatenation of any number of strings
accepted by the parser [p]. The parser [plus p] accepts the concatenation
of a nonzero number of strings accepted by the parser [p]. *)
The parser [ p ] must be non - nullable , that is , must not accept the empty
string . This ensures that the mutual recursion in the definitions of [ star ]
and [ plus ] is well - founded : before a recursive call takes place , at list
one input token is consumed .
string. This ensures that the mutual recursion in the definitions of [star]
and [plus] is well-founded: before a recursive call takes place, at list
one input token is consumed. *)
let rec star (p : 'a parser) : 'a list parser =
choose
(plus p)
(return [])
and plus (p : 'a parser) : 'a list parser =
p >>= fun a ->
star p >>= fun aas ->
return (a :: aas)
(* The parser [number] recognizes a nonempty sequence of digits and returns
their meaning as an integer. *)
let decode_digits (digits : int list) : int =
List.fold_left (fun accu digit -> 10 * accu + digit) 0 digits
let number_lax : int parser =
plus digit |> map decode_digits
let number : int parser =
at_most_once number_lax
This works because , in the definition of [ star ] , we explore
the longest match first .
the longest match first. *)
(* Support for iterated applications of left-associative operators. *)
The parser [ ] recognizes the language [ p ( op p ) * ] . A string in
this language is interpreted as a left - associative chain of applications of
operators to values .
this language is interpreted as a left-associative chain of applications of
operators to values. *)
type 'a op =
'a -> 'a -> 'a
let chainl1 (p : 'a parser) (op : 'a op parser) : 'a parser =
p <&> star (op <&> p)
|> map (fun (p, ops) ->
List.fold_left (fun p1 (op, p2) -> op p1 p2) p ops
)
The parser [ additive_op ] recognizes one of the characters ' + ' or ' - '
and interprets it as the corresponding operation on integers .
and interprets it as the corresponding operation on integers. *)
let additive_op : int op parser =
choose
(char '+' >> return ( + ))
(char '-' >> return ( - ))
The parser [ multiplicative_op ] recognizes one of the characters ' * ' or ' / '
and interprets it as the corresponding operation on integers .
and interprets it as the corresponding operation on integers. *)
let multiplicative_op : int op parser =
choose
(char '*' >> return ( * ))
(char '/' >> return ( / ))
(* A simple grammar of additions and subtractions of constants. *)
(* A sum is a nonempty list of numbers, separated by additive operators, which
are considered left-associative. *)
let sum : int parser =
chainl1 number additive_op
(* The higher-order function [fix] allows defining a recursive parser,
that is, a parser whose definition refers to itself. Left recursion
is forbidden: that is, a recursive call is permitted only after a
nonempty segment of the input has been consumed. *)
let fix (pp : 'a parser -> 'a parser) : 'a parser =
let rec p cursor = pp p cursor in
p
(* A simple grammar of arithmetic expressions. *)
(* A term is a nonempty list of factors, separated by additive operators,
which are left-associative. *)
(* A factor is a nonempty list of atoms, separated by multiplicative
operators, which are left-associative. *)
(* An atom is either a number or a term surrounded with parentheses. *)
let rec term : int parser =
fix (fun term ->
let atom : int parser =
choose
number
(char '(' >> term << char ')')
in
let factor : int parser =
chainl1 atom multiplicative_op
in
let additive_op = char '+' >> return ( + ) in (* wrong *)
let term : int parser =
chainl1 factor additive_op
in
term
)
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/parser_combinators/wrong/term_no_sub.ml | ocaml | The type [parser] satisfies the monad API: [delay], [return], [>>=].
[delay p] behaves like [p()], except the construction of the monadic
computation is delayed until the moment when this computation is run.
[return a] always succeeds, consumes no input, and returns [a].
[p >>= f] is the sequential composition of the parsers [p] and [f].
The type [parser] supports the nondeterminism monad API: [fail], [choose],
[at_most_once].
The parser [fail] accepts the empty language: it always fails.
The parser [choose p q] accepts the union of the languages accepted
by the parsers [p] and [q].
The parser [at_most_once p] accepts the same language as [p], but
accepts each input string in at most one way.
The type [parser] supports the applicative functor API: [map], [<*>],
[<&>].
[map f p] accepts the same language as the parser [p], and applies the
function [f] to every result produced by [p].
The parser [p <*> q] accepts the concatenation of the languages accepted
by the parsers [p] and [q]. For each value [f] returned by [p] and for
each value [x] returned by [q], it returns the result of the application
[f x].
The parser [p <&> q] accepts the concatenation of the languages accepted
by the parsers [p] and [q]. For each value [a] returned by [p] and for
each value [b] returned by [q], it returns the pair [(a, b)].
The parser [p >> q] accepts the concatenation of the languages accepted
by the parsers [p] and [q]. For each value [a] returned by [p] and for
each value [b] returned by [q], it returns just [b].
The parser [p << q] accepts the concatenation of the languages accepted
by the parsers [p] and [q]. For each value [a] returned by [p] and for
each value [b] returned by [q], it returns just [a].
The parser combinator [list] is an n-ary version of [<&>]. If [ps] is
a list of parsers, then the parser [list ps] accepts the concatenation
of the languages accepted by the parsers in the list [ps].
[any] succeeds if and only if the cursor is currently not at the end of the
input stream. It consumes and returns the next input token.
The parser [sat p] consumes and returns the next input token if this
token satisfies the predicate [p]. It fails otherwise.
The parser [char c] consumes and returns the next input token if this
token is the character [c]. It fails otherwise.
The parser [string cs] consumes and returns the list of characters [cs]
if this exact list is found at the front of the input stream. It fails
otherwise.
Iteration.
The parser [star p] accepts the concatenation of any number of strings
accepted by the parser [p]. The parser [plus p] accepts the concatenation
of a nonzero number of strings accepted by the parser [p].
The parser [number] recognizes a nonempty sequence of digits and returns
their meaning as an integer.
Support for iterated applications of left-associative operators.
A simple grammar of additions and subtractions of constants.
A sum is a nonempty list of numbers, separated by additive operators, which
are considered left-associative.
The higher-order function [fix] allows defining a recursive parser,
that is, a parser whose definition refers to itself. Left recursion
is forbidden: that is, a recursive call is permitted only after a
nonempty segment of the input has been consumed.
A simple grammar of arithmetic expressions.
A term is a nonempty list of factors, separated by additive operators,
which are left-associative.
A factor is a nonempty list of atoms, separated by multiplicative
operators, which are left-associative.
An atom is either a number or a term surrounded with parentheses.
wrong |
let delay (p : unit -> 'a parser) : 'a parser =
fun cursor ->
NonDet.delay (fun () -> p () cursor)
let return (a : 'a) : 'a parser =
fun cursor ->
NonDet.return (a, cursor)
let (>>=) (p : 'a parser) (f : 'a -> 'b parser) : 'b parser =
fun cursor ->
let open NonDet in
p cursor >>= fun (a, cursor) ->
f a cursor
let fail : 'a parser =
fun cursor ->
NonDet.fail
let choose (p : 'a parser) (q : 'a parser) : 'a parser =
fun cursor ->
NonDet.choose (p cursor) (q cursor)
let at_most_once (p : 'a parser) : 'a parser =
fun cursor ->
NonDet.at_most_once (p cursor)
let map (f : 'a -> 'b) (p : 'a parser) : 'b parser =
p >>= fun a ->
return (f a)
let (<*>) (p : ('a -> 'b) parser) (q : 'a parser) : 'b parser =
p >>= fun f ->
q >>= fun x ->
return (f x)
let (<&>) (p : 'a parser) (q : 'b parser) : ('a * 'b) parser =
p >>= fun a ->
q >>= fun b ->
return (a, b)
let (>>) (p : 'a parser) (q : 'b parser) : 'b parser =
p >>= fun _ -> q
let (<<) (p : 'a parser) (q : 'b parser) : 'a parser =
p >>= fun a ->
q >> return a
let cons (x, xs) =
x :: xs
let rec list (ps : 'a parser list) : 'a list parser =
match ps with
| [] ->
return []
| p :: ps ->
map cons (p <&> list ps)
The type [ parser ] supports a number of operations that are specific of the
parser combinator monad . The most basic two are [ any ] and [ eof ] . On top of
these two , more combinators are defined , including [ sat ] , [ char ] , [ string ] ,
[ digit ] , and so on .
parser combinator monad. The most basic two are [any] and [eof]. On top of
these two, more combinators are defined, including [sat], [char], [string],
[digit], and so on. *)
let any : token parser =
fun cursor ->
match cursor() with
| Seq.Nil ->
NonDet.fail
| Seq.Cons (c, cursor) ->
NonDet.return (c, cursor)
[ eof ] succeeds if and only if the cursor is currently at the end of the
input stream . It consumes nothing , and returns [ ( ) ] . It is idempotent :
[ eof > > eof ] is the same as [ eof ] .
input stream. It consumes nothing, and returns [()]. It is idempotent:
[eof >> eof] is the same as [eof]. *)
let eof : unit parser =
fun cursor ->
match cursor() with
| Seq.Nil ->
NonDet.return ((), cursor)
| Seq.Cons _ ->
NonDet.fail
let sat (p : token -> bool) : token parser =
any >>= fun c ->
if p c then return c else fail
let char (c : token) : token parser =
sat ((=) c)
let string (cs : token list) : token list parser =
list (List.map char cs)
The parser [ digit ] consumes the next token if this token is a character
in the range [ ' 0' .. '9 ' ] . It returns an integer between 0 and 9 .
in the range ['0'..'9']. It returns an integer between 0 and 9. *)
let is_digit c : bool =
Char.code '0' <= Char.code c && Char.code c <= Char.code '9'
let decode_digit c : int =
Char.code c - Char.code '0'
let digit: int parser =
sat is_digit |> map decode_digit
The parser [ p ] must be non - nullable , that is , must not accept the empty
string . This ensures that the mutual recursion in the definitions of [ star ]
and [ plus ] is well - founded : before a recursive call takes place , at list
one input token is consumed .
string. This ensures that the mutual recursion in the definitions of [star]
and [plus] is well-founded: before a recursive call takes place, at list
one input token is consumed. *)
let rec star (p : 'a parser) : 'a list parser =
choose
(plus p)
(return [])
and plus (p : 'a parser) : 'a list parser =
p >>= fun a ->
star p >>= fun aas ->
return (a :: aas)
let decode_digits (digits : int list) : int =
List.fold_left (fun accu digit -> 10 * accu + digit) 0 digits
let number_lax : int parser =
plus digit |> map decode_digits
let number : int parser =
at_most_once number_lax
This works because , in the definition of [ star ] , we explore
the longest match first .
the longest match first. *)
The parser [ ] recognizes the language [ p ( op p ) * ] . A string in
this language is interpreted as a left - associative chain of applications of
operators to values .
this language is interpreted as a left-associative chain of applications of
operators to values. *)
type 'a op =
'a -> 'a -> 'a
let chainl1 (p : 'a parser) (op : 'a op parser) : 'a parser =
p <&> star (op <&> p)
|> map (fun (p, ops) ->
List.fold_left (fun p1 (op, p2) -> op p1 p2) p ops
)
The parser [ additive_op ] recognizes one of the characters ' + ' or ' - '
and interprets it as the corresponding operation on integers .
and interprets it as the corresponding operation on integers. *)
let additive_op : int op parser =
choose
(char '+' >> return ( + ))
(char '-' >> return ( - ))
The parser [ multiplicative_op ] recognizes one of the characters ' * ' or ' / '
and interprets it as the corresponding operation on integers .
and interprets it as the corresponding operation on integers. *)
let multiplicative_op : int op parser =
choose
(char '*' >> return ( * ))
(char '/' >> return ( / ))
let sum : int parser =
chainl1 number additive_op
let fix (pp : 'a parser -> 'a parser) : 'a parser =
let rec p cursor = pp p cursor in
p
let rec term : int parser =
fix (fun term ->
let atom : int parser =
choose
number
(char '(' >> term << char ')')
in
let factor : int parser =
chainl1 atom multiplicative_op
in
let term : int parser =
chainl1 factor additive_op
in
term
)
|
4cc15d8d1efbdb175e86fffaeffaafcd644a21570cf89265e972f203a0803946 | jqueiroz/lojban.io | Exercises.hs | {-# LANGUAGE OverloadedStrings #-}
-- | This module defines the course exercuses.
module Study.Courses.English.Vocabulary.Attitudinals.Exercises where
import Core
import Util (shuffle, chooseItemUniformly, combineGeneratorsUniformly, mapRandom)
import Study.Courses.English.Vocabulary.Attitudinals.Model
import Study.Courses.English.Vocabulary.Attitudinals.Vocabulary
import Study.Courses.English.Vocabulary.Attitudinals.Util
import qualified Data.Text as T
-- * Exercise templates
generatePositiveAttitudinalBackwardMeaningExercise :: [Attitudinal] -> ExerciseGenerator
generatePositiveAttitudinalBackwardMeaningExercise attitudinals r0 = TypingExercise title [] (== expectedAttitudinal) (expectedAttitudinal) where
(attitudinal, r1) = chooseItemUniformly r0 attitudinals
title = "Provide the attitudinal for <b>" `T.append` (attitudinalPositiveMeaning attitudinal) `T.append` "</b>"
expectedAttitudinal = attitudinalWord attitudinal
generatePositiveAttitudinalForwardMeaningExercise :: [Attitudinal] -> ExerciseGenerator
generatePositiveAttitudinalForwardMeaningExercise attitudinals r0 = SingleChoiceExercise title [] correctMeaning incorrectMeanings False where
(correctAttitudinal, r1) = chooseItemUniformly r0 attitudinals
incorrectAttitudinals = filter (/= correctAttitudinal) attitudinals
(shuffledIncorrectAttitudinals, r2) = shuffle r1 incorrectAttitudinals
title = "Select the meaning of <b>" `T.append` (attitudinalWord correctAttitudinal) `T.append` "</b>"
correctMeaning = attitudinalPositiveMeaning correctAttitudinal
incorrectMeanings = map attitudinalPositiveMeaning (take 4 incorrectAttitudinals)
generateAttitudinalBackwardMeaningExercise :: [Attitudinal] -> ExerciseGenerator
generateAttitudinalBackwardMeaningExercise attitudinals r0 = TypingExercise title [] (== expectedAttitudinalExpression) (expectedAttitudinalExpression) where
(attitudinal, r1) = chooseItemUniformly r0 attitudinals
(attitudinalModifier, meaningOfModifiedAttitudinal, r2) = randomlyPickAttitudinalModifier r1 attitudinal
expectedAttitudinalExpression = (attitudinalWord attitudinal) `T.append` attitudinalModifier
title = "Provide the attitudinal expression for <b>" `T.append` meaningOfModifiedAttitudinal `T.append` "</b>"
generateAttitudinalForwardMeaningExercise :: [Attitudinal] -> ExerciseGenerator
generateAttitudinalForwardMeaningExercise attitudinals r0 = SingleChoiceExercise title [] correctMeaning incorrectMeanings False where
title = "Select the meaning of <b>" `T.append` correctAttitudinalExpression `T.append` "</b>"
-- Correct attitudinal
(correctAttitudinal, r1) = chooseItemUniformly r0 attitudinals
(correctAttitudinalModifier, meaningOfModifiedCorrectAttitudinal, r2) = randomlyPickAttitudinalModifier r1 correctAttitudinal
correctAttitudinalExpression = (attitudinalWord correctAttitudinal) `T.append` correctAttitudinalModifier
correctMeaning = meaningOfModifiedCorrectAttitudinal
Incorrect attitudinals
incorrectAttitudinals = filter (/= correctAttitudinal) attitudinals
(shuffledIncorrectAttitudinals, r3) = shuffle r2 incorrectAttitudinals
(incorrectMeanings, r4) = mapRandom r3 randomlyPickAttitudinalMeaning (take 4 incorrectAttitudinals)
generateAttitudinalClassificationExercise :: [Attitudinal] -> ExerciseGenerator
generateAttitudinalClassificationExercise attitudinals r0 = SingleChoiceExercise title [] correctClassification [incorrectClassification] True where
title = "Classify the attitudinal <b>" `T.append` (attitudinalWord attitudinal) `T.append` "</b>"
(attitudinal, r1) = chooseItemUniformly r0 attitudinals
(correctClassification, incorrectClassification)
| (attitudinalType attitudinal) == PureEmotion = ("Pure", "Propositional")
| otherwise = ("Propositional", "Pure")
-- * Exercises per lesson
| Exercises for the first lesson .
exercises1 :: ExerciseGenerator
exercises1 = combineGeneratorsUniformly
[ generatePositiveAttitudinalBackwardMeaningExercise attitudinals1
, generatePositiveAttitudinalForwardMeaningExercise attitudinals1
]
| Exercises for the second lesson .
exercises2 :: ExerciseGenerator
exercises2 = combineGeneratorsUniformly
[ generatePositiveAttitudinalBackwardMeaningExercise attitudinals2
, generatePositiveAttitudinalForwardMeaningExercise attitudinals2
, generateAttitudinalClassificationExercise attitudinals2_cumulative
]
| Exercises for the third lesson .
exercises3 :: ExerciseGenerator
exercises3 = combineGeneratorsUniformly
[ generateAttitudinalBackwardMeaningExercise attitudinals3_cumulative
, generateAttitudinalForwardMeaningExercise attitudinals3_cumulative
, generateAttitudinalClassificationExercise attitudinals3_cumulative
]
| null | https://raw.githubusercontent.com/jqueiroz/lojban.io/68c3e919f92ea1294f32ee7772662ab5667ecef6/haskell/src/Study/Courses/English/Vocabulary/Attitudinals/Exercises.hs | haskell | # LANGUAGE OverloadedStrings #
| This module defines the course exercuses.
* Exercise templates
Correct attitudinal
* Exercises per lesson |
module Study.Courses.English.Vocabulary.Attitudinals.Exercises where
import Core
import Util (shuffle, chooseItemUniformly, combineGeneratorsUniformly, mapRandom)
import Study.Courses.English.Vocabulary.Attitudinals.Model
import Study.Courses.English.Vocabulary.Attitudinals.Vocabulary
import Study.Courses.English.Vocabulary.Attitudinals.Util
import qualified Data.Text as T
generatePositiveAttitudinalBackwardMeaningExercise :: [Attitudinal] -> ExerciseGenerator
generatePositiveAttitudinalBackwardMeaningExercise attitudinals r0 = TypingExercise title [] (== expectedAttitudinal) (expectedAttitudinal) where
(attitudinal, r1) = chooseItemUniformly r0 attitudinals
title = "Provide the attitudinal for <b>" `T.append` (attitudinalPositiveMeaning attitudinal) `T.append` "</b>"
expectedAttitudinal = attitudinalWord attitudinal
generatePositiveAttitudinalForwardMeaningExercise :: [Attitudinal] -> ExerciseGenerator
generatePositiveAttitudinalForwardMeaningExercise attitudinals r0 = SingleChoiceExercise title [] correctMeaning incorrectMeanings False where
(correctAttitudinal, r1) = chooseItemUniformly r0 attitudinals
incorrectAttitudinals = filter (/= correctAttitudinal) attitudinals
(shuffledIncorrectAttitudinals, r2) = shuffle r1 incorrectAttitudinals
title = "Select the meaning of <b>" `T.append` (attitudinalWord correctAttitudinal) `T.append` "</b>"
correctMeaning = attitudinalPositiveMeaning correctAttitudinal
incorrectMeanings = map attitudinalPositiveMeaning (take 4 incorrectAttitudinals)
generateAttitudinalBackwardMeaningExercise :: [Attitudinal] -> ExerciseGenerator
generateAttitudinalBackwardMeaningExercise attitudinals r0 = TypingExercise title [] (== expectedAttitudinalExpression) (expectedAttitudinalExpression) where
(attitudinal, r1) = chooseItemUniformly r0 attitudinals
(attitudinalModifier, meaningOfModifiedAttitudinal, r2) = randomlyPickAttitudinalModifier r1 attitudinal
expectedAttitudinalExpression = (attitudinalWord attitudinal) `T.append` attitudinalModifier
title = "Provide the attitudinal expression for <b>" `T.append` meaningOfModifiedAttitudinal `T.append` "</b>"
generateAttitudinalForwardMeaningExercise :: [Attitudinal] -> ExerciseGenerator
generateAttitudinalForwardMeaningExercise attitudinals r0 = SingleChoiceExercise title [] correctMeaning incorrectMeanings False where
title = "Select the meaning of <b>" `T.append` correctAttitudinalExpression `T.append` "</b>"
(correctAttitudinal, r1) = chooseItemUniformly r0 attitudinals
(correctAttitudinalModifier, meaningOfModifiedCorrectAttitudinal, r2) = randomlyPickAttitudinalModifier r1 correctAttitudinal
correctAttitudinalExpression = (attitudinalWord correctAttitudinal) `T.append` correctAttitudinalModifier
correctMeaning = meaningOfModifiedCorrectAttitudinal
Incorrect attitudinals
incorrectAttitudinals = filter (/= correctAttitudinal) attitudinals
(shuffledIncorrectAttitudinals, r3) = shuffle r2 incorrectAttitudinals
(incorrectMeanings, r4) = mapRandom r3 randomlyPickAttitudinalMeaning (take 4 incorrectAttitudinals)
generateAttitudinalClassificationExercise :: [Attitudinal] -> ExerciseGenerator
generateAttitudinalClassificationExercise attitudinals r0 = SingleChoiceExercise title [] correctClassification [incorrectClassification] True where
title = "Classify the attitudinal <b>" `T.append` (attitudinalWord attitudinal) `T.append` "</b>"
(attitudinal, r1) = chooseItemUniformly r0 attitudinals
(correctClassification, incorrectClassification)
| (attitudinalType attitudinal) == PureEmotion = ("Pure", "Propositional")
| otherwise = ("Propositional", "Pure")
| Exercises for the first lesson .
exercises1 :: ExerciseGenerator
exercises1 = combineGeneratorsUniformly
[ generatePositiveAttitudinalBackwardMeaningExercise attitudinals1
, generatePositiveAttitudinalForwardMeaningExercise attitudinals1
]
| Exercises for the second lesson .
exercises2 :: ExerciseGenerator
exercises2 = combineGeneratorsUniformly
[ generatePositiveAttitudinalBackwardMeaningExercise attitudinals2
, generatePositiveAttitudinalForwardMeaningExercise attitudinals2
, generateAttitudinalClassificationExercise attitudinals2_cumulative
]
| Exercises for the third lesson .
exercises3 :: ExerciseGenerator
exercises3 = combineGeneratorsUniformly
[ generateAttitudinalBackwardMeaningExercise attitudinals3_cumulative
, generateAttitudinalForwardMeaningExercise attitudinals3_cumulative
, generateAttitudinalClassificationExercise attitudinals3_cumulative
]
|
92a78d4d2aa60ee95fb5185e80acd7d98c8cb0c9bcb00955582832b6ea053e53 | foretspaisibles/cl-kaputt | entrypoint.lisp | entrypoint.lisp — A Testsuite for the Kaputt Test Framework
( -kaputt )
This file is part of Kaputt .
;;;;
Copyright © 2019–2021
;;;; All rights reserved.
This software is governed by the CeCILL - B license under French law and
;;;; abiding by the rules of distribution of free software. You can use,
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
;;;; "-B_V1-en.txt"
(in-package #:kaputt/testsuite)
(define-testcase run-all-tests ()
(testsuite-string-match)
(testsuite-assert)
(testsuite-testcase))
(defun run-all-tests-batch ()
(if (run-all-tests)
(uiop:quit 0)
(uiop:quit 1)))
End of file ` entrypoint.lisp '
| null | https://raw.githubusercontent.com/foretspaisibles/cl-kaputt/94ff2a96ced6576e3995b445b78ab2a4bf09c57f/testsuite/entrypoint.lisp | lisp |
All rights reserved.
abiding by the rules of distribution of free software. You can use,
"-B_V1-en.txt" | entrypoint.lisp — A Testsuite for the Kaputt Test Framework
( -kaputt )
This file is part of Kaputt .
Copyright © 2019–2021
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
(in-package #:kaputt/testsuite)
(define-testcase run-all-tests ()
(testsuite-string-match)
(testsuite-assert)
(testsuite-testcase))
(defun run-all-tests-batch ()
(if (run-all-tests)
(uiop:quit 0)
(uiop:quit 1)))
End of file ` entrypoint.lisp '
|
f4593aa864fd8bb3a4e3b526b43348a4fdc14e18b2548427dd45fff7312fb98d | dakrone/cheshire | parse.clj | (ns cheshire.parse
(:import (com.fasterxml.jackson.core JsonParser JsonToken)))
(declare parse*)
(def ^:dynamic *chunk-size* 32)
(def ^{:doc "Flag to determine whether float values should be returned as
BigDecimals to retain precision. Defaults to false."
:dynamic true}
*use-bigdecimals?* false)
(defmacro ^:private tag
([obj]
`(vary-meta ~obj assoc :tag `JsonParser)))
(definline parse-object [^JsonParser jp key-fn bd? array-coerce-fn]
(let [jp (tag jp)]
`(do
(.nextToken ~jp)
(loop [mmap# (transient {})]
(if-not (identical? (.getCurrentToken ~jp)
JsonToken/END_OBJECT)
(let [key-str# (.getText ~jp)
_# (.nextToken ~jp)
key# (~key-fn key-str#)
mmap# (assoc! mmap# key#
(parse* ~jp ~key-fn ~bd? ~array-coerce-fn))]
(.nextToken ~jp)
(recur mmap#))
(persistent! mmap#))))))
(definline parse-array [^JsonParser jp key-fn bd? array-coerce-fn]
(let [jp (tag jp)]
`(let [array-field-name# (.getCurrentName ~jp)]
(.nextToken ~jp)
(loop [coll# (transient (if ~array-coerce-fn
(~array-coerce-fn array-field-name#)
[]))]
(if-not (identical? (.getCurrentToken ~jp)
JsonToken/END_ARRAY)
(let [coll# (conj! coll#
(parse* ~jp ~key-fn ~bd? ~array-coerce-fn))]
(.nextToken ~jp)
(recur coll#))
(persistent! coll#))))))
(defn lazily-parse-array [^JsonParser jp key-fn bd? array-coerce-fn]
(lazy-seq
(loop [chunk-idx 0, buf (chunk-buffer *chunk-size*)]
(if (identical? (.getCurrentToken jp) JsonToken/END_ARRAY)
(chunk-cons (chunk buf) nil)
(do
(chunk-append buf (parse* jp key-fn bd? array-coerce-fn))
(.nextToken jp)
(let [chunk-idx* (unchecked-inc chunk-idx)]
(if (< chunk-idx* *chunk-size*)
(recur chunk-idx* buf)
(chunk-cons
(chunk buf)
(lazily-parse-array jp key-fn bd? array-coerce-fn)))))))))
(defn parse* [^JsonParser jp key-fn bd? array-coerce-fn]
(condp identical? (.getCurrentToken jp)
JsonToken/START_OBJECT (parse-object jp key-fn bd? array-coerce-fn)
JsonToken/START_ARRAY (parse-array jp key-fn bd? array-coerce-fn)
JsonToken/VALUE_STRING (.getText jp)
JsonToken/VALUE_NUMBER_INT (.getNumberValue jp)
JsonToken/VALUE_NUMBER_FLOAT (if bd?
(.getDecimalValue jp)
(.getNumberValue jp))
JsonToken/VALUE_EMBEDDED_OBJECT (.getBinaryValue jp)
JsonToken/VALUE_TRUE true
JsonToken/VALUE_FALSE false
JsonToken/VALUE_NULL nil
(throw
(Exception.
(str "Cannot parse " (pr-str (.getCurrentToken jp)))))))
(defn parse-strict [^JsonParser jp key-fn eof array-coerce-fn]
(let [key-fn (or (if (identical? key-fn true) keyword key-fn) identity)]
(.nextToken jp)
(condp identical? (.getCurrentToken jp)
nil
eof
(parse* jp key-fn *use-bigdecimals?* array-coerce-fn))))
(defn parse [^JsonParser jp key-fn eof array-coerce-fn]
(let [key-fn (or (if (and (instance? Boolean key-fn) key-fn) keyword key-fn) identity)]
(.nextToken jp)
(condp identical? (.getCurrentToken jp)
nil
eof
JsonToken/START_ARRAY
(do
(.nextToken jp)
(lazily-parse-array jp key-fn *use-bigdecimals?* array-coerce-fn))
(parse* jp key-fn *use-bigdecimals?* array-coerce-fn))))
| null | https://raw.githubusercontent.com/dakrone/cheshire/d2153a60ff242afabbbe5499ecf1d2674e8c568a/src/cheshire/parse.clj | clojure | (ns cheshire.parse
(:import (com.fasterxml.jackson.core JsonParser JsonToken)))
(declare parse*)
(def ^:dynamic *chunk-size* 32)
(def ^{:doc "Flag to determine whether float values should be returned as
BigDecimals to retain precision. Defaults to false."
:dynamic true}
*use-bigdecimals?* false)
(defmacro ^:private tag
([obj]
`(vary-meta ~obj assoc :tag `JsonParser)))
(definline parse-object [^JsonParser jp key-fn bd? array-coerce-fn]
(let [jp (tag jp)]
`(do
(.nextToken ~jp)
(loop [mmap# (transient {})]
(if-not (identical? (.getCurrentToken ~jp)
JsonToken/END_OBJECT)
(let [key-str# (.getText ~jp)
_# (.nextToken ~jp)
key# (~key-fn key-str#)
mmap# (assoc! mmap# key#
(parse* ~jp ~key-fn ~bd? ~array-coerce-fn))]
(.nextToken ~jp)
(recur mmap#))
(persistent! mmap#))))))
(definline parse-array [^JsonParser jp key-fn bd? array-coerce-fn]
(let [jp (tag jp)]
`(let [array-field-name# (.getCurrentName ~jp)]
(.nextToken ~jp)
(loop [coll# (transient (if ~array-coerce-fn
(~array-coerce-fn array-field-name#)
[]))]
(if-not (identical? (.getCurrentToken ~jp)
JsonToken/END_ARRAY)
(let [coll# (conj! coll#
(parse* ~jp ~key-fn ~bd? ~array-coerce-fn))]
(.nextToken ~jp)
(recur coll#))
(persistent! coll#))))))
(defn lazily-parse-array [^JsonParser jp key-fn bd? array-coerce-fn]
(lazy-seq
(loop [chunk-idx 0, buf (chunk-buffer *chunk-size*)]
(if (identical? (.getCurrentToken jp) JsonToken/END_ARRAY)
(chunk-cons (chunk buf) nil)
(do
(chunk-append buf (parse* jp key-fn bd? array-coerce-fn))
(.nextToken jp)
(let [chunk-idx* (unchecked-inc chunk-idx)]
(if (< chunk-idx* *chunk-size*)
(recur chunk-idx* buf)
(chunk-cons
(chunk buf)
(lazily-parse-array jp key-fn bd? array-coerce-fn)))))))))
(defn parse* [^JsonParser jp key-fn bd? array-coerce-fn]
(condp identical? (.getCurrentToken jp)
JsonToken/START_OBJECT (parse-object jp key-fn bd? array-coerce-fn)
JsonToken/START_ARRAY (parse-array jp key-fn bd? array-coerce-fn)
JsonToken/VALUE_STRING (.getText jp)
JsonToken/VALUE_NUMBER_INT (.getNumberValue jp)
JsonToken/VALUE_NUMBER_FLOAT (if bd?
(.getDecimalValue jp)
(.getNumberValue jp))
JsonToken/VALUE_EMBEDDED_OBJECT (.getBinaryValue jp)
JsonToken/VALUE_TRUE true
JsonToken/VALUE_FALSE false
JsonToken/VALUE_NULL nil
(throw
(Exception.
(str "Cannot parse " (pr-str (.getCurrentToken jp)))))))
(defn parse-strict [^JsonParser jp key-fn eof array-coerce-fn]
(let [key-fn (or (if (identical? key-fn true) keyword key-fn) identity)]
(.nextToken jp)
(condp identical? (.getCurrentToken jp)
nil
eof
(parse* jp key-fn *use-bigdecimals?* array-coerce-fn))))
(defn parse [^JsonParser jp key-fn eof array-coerce-fn]
(let [key-fn (or (if (and (instance? Boolean key-fn) key-fn) keyword key-fn) identity)]
(.nextToken jp)
(condp identical? (.getCurrentToken jp)
nil
eof
JsonToken/START_ARRAY
(do
(.nextToken jp)
(lazily-parse-array jp key-fn *use-bigdecimals?* array-coerce-fn))
(parse* jp key-fn *use-bigdecimals?* array-coerce-fn))))
|
|
f72e15997182ffec0f8cc3d1c62d247a546c2bd8201907f93590d29b3903f18a | samrocketman/home | Gloss-Orb-light.scm | Author :
Version : 1.0
;Homepage: Split-visionz.net
;License: Released under the GPL included in the file with the scripts.
(define (script-fu-sv-gloss-orb-light myradius bgcolor)
(let* (
(buffer (* myradius 0.2))
(image (car (gimp-image-new (+ buffer myradius) (+ buffer myradius) RGB)))
(shadow-layer (car (gimp-layer-new image myradius myradius RGBA-IMAGE "shadowLayer" 100 NORMAL-MODE)))
(grad-layer (car (gimp-layer-new image myradius myradius RGBA-IMAGE "gradLayer" 100 NORMAL-MODE)))
(dark-layer (car (gimp-layer-new image myradius myradius RGBA-IMAGE "darkLayer" 100 NORMAL-MODE)))
(hl-layer (car (gimp-layer-new image myradius myradius RGBA-IMAGE "hlLayer" 100 NORMAL-MODE)))
(shrink-size (* myradius 0.01))
(hl-width (* myradius 0.7))
(hl-height (* myradius 0.6))
(offset (- myradius hl-width))
( / ( - myradius hl - width 2 ) ) )
(hl-y 0)
(quarterheight (/ myradius 4))
(blur-radius (* myradius 0.1))
);end variable defines
(gimp-image-add-layer image shadow-layer 0)
(gimp-edit-clear shadow-layer)
(gimp-image-add-layer image grad-layer 0)
(gimp-edit-clear grad-layer)
(gimp-image-add-layer image dark-layer 0)
(gimp-edit-clear dark-layer)
(gimp-image-add-layer image hl-layer 0)
(gimp-edit-clear hl-layer)
;//////////////////////////////////////
;shadow layer
(gimp-ellipse-select image 0 0 myradius myradius 0 TRUE FALSE 0)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(0 0 0))
(gimp-edit-bucket-fill shadow-layer 0 0 100 0 FALSE 0 0)
;//////////////////////////////////////
;gradient layer
(gimp-context-set-background bgcolor)
( gimp - context - set - background ' ( 255 255 255 ) )
(gimp-image-set-active-layer image grad-layer)
(gimp-edit-blend grad-layer 0 0 0 100 0 0 FALSE FALSE 0 0 TRUE 0 (- 1(/ myradius 2)) 0 myradius)
;//////////////////////////////////////
; highlight layer
(gimp-image-set-active-layer image hl-layer)
(gimp-context-set-foreground '(255 255 255))
(gimp-edit-blend hl-layer 2 0 0 100 0 0 FALSE FALSE 0 0 TRUE 0 0 0 myradius )
;//////////////////////////////
;dark layer
(gimp-image-set-active-layer image dark-layer)
(gimp-context-set-foreground '(255 255 255))
(gimp-context-set-background '(255 255 255))
(gimp-edit-bucket-fill dark-layer 0 0 100 0 FALSE 0 0)
(gimp-selection-grow image shrink-size )
(gimp-selection-feather image (/ myradius 4))
(gimp-edit-cut dark-layer)
;Shrink highlight layer and move to proper position
(gimp-image-set-active-layer image hl-layer)
(gimp-layer-scale hl-layer hl-width hl-height FALSE)
(gimp-layer-translate hl-layer hl-x hl-y)
(gimp-layer-set-opacity hl-layer 75)
(gimp-layer-resize-to-image-size hl-layer)
;Move and blur shadow layer
(gimp-image-set-active-layer image shadow-layer)
(gimp-layer-translate shadow-layer (/ hl-x 4) (/ hl-x 4))
(gimp-layer-resize-to-image-size shadow-layer)
(plug-in-gauss-rle 1 image shadow-layer blur-radius 1 1)
(gimp-display-new image)
(gimp-displays-flush)
(gimp-image-clean-all image)
); end let scope
); end function define
(script-fu-register "script-fu-sv-gloss-orb-light"
_"<Toolbox>/Xtns/SV-Scripts/Gloss-Orb-Light"
"Creates a Web2.0 style gloss orb"
"Mike Pippin"
"copyright 2007-8, Mike Pippin"
"Dec 2007"
""
SF-ADJUSTMENT _"Orb Radius" '(100 1 2000 1 10 0 1)
SF-COLOR "Background Color" '(22 22 125)
)
| null | https://raw.githubusercontent.com/samrocketman/home/63a8668a71dc594ea9ed76ec56bf8ca43b2a86ca/dotfiles/.gimp/scripts/Gloss-Orb-light.scm | scheme | Homepage: Split-visionz.net
License: Released under the GPL included in the file with the scripts.
end variable defines
//////////////////////////////////////
shadow layer
//////////////////////////////////////
gradient layer
//////////////////////////////////////
highlight layer
//////////////////////////////
dark layer
Shrink highlight layer and move to proper position
Move and blur shadow layer
end let scope
end function define | Author :
Version : 1.0
(define (script-fu-sv-gloss-orb-light myradius bgcolor)
(let* (
(buffer (* myradius 0.2))
(image (car (gimp-image-new (+ buffer myradius) (+ buffer myradius) RGB)))
(shadow-layer (car (gimp-layer-new image myradius myradius RGBA-IMAGE "shadowLayer" 100 NORMAL-MODE)))
(grad-layer (car (gimp-layer-new image myradius myradius RGBA-IMAGE "gradLayer" 100 NORMAL-MODE)))
(dark-layer (car (gimp-layer-new image myradius myradius RGBA-IMAGE "darkLayer" 100 NORMAL-MODE)))
(hl-layer (car (gimp-layer-new image myradius myradius RGBA-IMAGE "hlLayer" 100 NORMAL-MODE)))
(shrink-size (* myradius 0.01))
(hl-width (* myradius 0.7))
(hl-height (* myradius 0.6))
(offset (- myradius hl-width))
( / ( - myradius hl - width 2 ) ) )
(hl-y 0)
(quarterheight (/ myradius 4))
(blur-radius (* myradius 0.1))
(gimp-image-add-layer image shadow-layer 0)
(gimp-edit-clear shadow-layer)
(gimp-image-add-layer image grad-layer 0)
(gimp-edit-clear grad-layer)
(gimp-image-add-layer image dark-layer 0)
(gimp-edit-clear dark-layer)
(gimp-image-add-layer image hl-layer 0)
(gimp-edit-clear hl-layer)
(gimp-ellipse-select image 0 0 myradius myradius 0 TRUE FALSE 0)
(gimp-context-set-foreground '(0 0 0))
(gimp-context-set-background '(0 0 0))
(gimp-edit-bucket-fill shadow-layer 0 0 100 0 FALSE 0 0)
(gimp-context-set-background bgcolor)
( gimp - context - set - background ' ( 255 255 255 ) )
(gimp-image-set-active-layer image grad-layer)
(gimp-edit-blend grad-layer 0 0 0 100 0 0 FALSE FALSE 0 0 TRUE 0 (- 1(/ myradius 2)) 0 myradius)
(gimp-image-set-active-layer image hl-layer)
(gimp-context-set-foreground '(255 255 255))
(gimp-edit-blend hl-layer 2 0 0 100 0 0 FALSE FALSE 0 0 TRUE 0 0 0 myradius )
(gimp-image-set-active-layer image dark-layer)
(gimp-context-set-foreground '(255 255 255))
(gimp-context-set-background '(255 255 255))
(gimp-edit-bucket-fill dark-layer 0 0 100 0 FALSE 0 0)
(gimp-selection-grow image shrink-size )
(gimp-selection-feather image (/ myradius 4))
(gimp-edit-cut dark-layer)
(gimp-image-set-active-layer image hl-layer)
(gimp-layer-scale hl-layer hl-width hl-height FALSE)
(gimp-layer-translate hl-layer hl-x hl-y)
(gimp-layer-set-opacity hl-layer 75)
(gimp-layer-resize-to-image-size hl-layer)
(gimp-image-set-active-layer image shadow-layer)
(gimp-layer-translate shadow-layer (/ hl-x 4) (/ hl-x 4))
(gimp-layer-resize-to-image-size shadow-layer)
(plug-in-gauss-rle 1 image shadow-layer blur-radius 1 1)
(gimp-display-new image)
(gimp-displays-flush)
(gimp-image-clean-all image)
(script-fu-register "script-fu-sv-gloss-orb-light"
_"<Toolbox>/Xtns/SV-Scripts/Gloss-Orb-Light"
"Creates a Web2.0 style gloss orb"
"Mike Pippin"
"copyright 2007-8, Mike Pippin"
"Dec 2007"
""
SF-ADJUSTMENT _"Orb Radius" '(100 1 2000 1 10 0 1)
SF-COLOR "Background Color" '(22 22 125)
)
|
ca2b1c9ae4433dff6aa924e0c7155a1d3c52725d007b2fe62b35f18ec92c529a | ruHaskell-learn/lhx | TestTemplate.hs | module TestTemplate (tests) where
import Data.Bifunctor (first)
import Data.Either (isLeft, isRight, fromRight)
import Data.Text qualified as T
import Data.Text.Arbitrary ()
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase, (@?), (@?=))
import Test.Tasty.QuickCheck qualified as QC
import Lhx (Separator(..))
import Lhx qualified
import Lhx.Parser qualified as LP
templateMakingTests :: TestTree
templateMakingTests =
testGroup
"Making of templates"
[ testGroup
"Broken templates"
[ testCase "Unclosed function call" $
isLeft (Lhx.makeTemplate "$foo")
@? "Shouldn't accept non-closed function call"
, testCase "Unknown function" $
isLeft (Lhx.makeTemplate "$foo;")
@? "Shouldn't accept unknown function"
, testCase "Several unknown functions" $
case Lhx.makeTemplate "$foo:bar:rev:baz:rev:bazzz:rev;" of
Right _ -> error "impossible"
Left e -> Lhx.errorText e @?= T.unlines
[ "Unknown function: foo"
, "Unknown function: bar"
, "Unknown function: baz"
, "Unknown function: bazzz"
]
]
, testGroup
"Correct templates"
[ testCase "All known functions" $
isRight (Lhx.makeTemplate $ mconcat
[ "$"
, T.intercalate ":" $ map (LP.unFName . fst) Lhx.functions
, ";"
]) @? "Should accept any registered function"
]
]
inputMakingTests :: TestTree
inputMakingTests =
testGroup
"Make input"
[ testCase "Separating by ','" $
Lhx.iFields (Lhx.makeInput (Lhx.Separator ",") "a, b, c")
@?= ["a", " b", " c"]
]
functionPropertyTests :: TestTree
functionPropertyTests =
testGroup
"Function properties"
[ QC.testProperty "'rev' function" \s ->
fromRight False do
template <- Lhx.makeTemplate "$rev;"
result <- Lhx.apply template (Lhx.makeInput (Separator ",") s)
pure $ result == T.reverse s
]
indexingTests :: TestTree
indexingTests =
testGroup
"Indexing"
[ testCase "Zero index should capture the whole input" $
"$0" `appliedTo` "abcd" @?= Right "abcd"
, testCase "Two fields should be swaped" $
"$2,$1" `appliedTo` "a,b" @?= Right "b,a"
, testCase "Functions should work well with indices" $
"$2:rev:rev;,$1:rev;" `appliedTo` "abc,de" @?= Right "de,cba"
, testCase "Index out of range" $
"$20" `appliedTo` "a,b,c" @?= Left "Index is out of range: 20\n"
, testCase "Negate index -1" $
"$-1" `appliedTo` "a,b,c,d,e,f" @?= Right "f"
, testCase "Negate index -3" $
"$-3" `appliedTo` "a,b,c,d,e,f" @?= Right "d"
, testCase "Negate index out of range" $
"$-3" `appliedTo` "a,b" @?= Left "Index is out of range: -3\n"
, testCase "To apply the function on the negate index" $
"$-3:rev;" `appliedTo` "a,b,c,abcd,e,f" @?= Right "dcba"
]
where
appliedTo templateT inputString = first Lhx.errorText do
template <- Lhx.makeTemplate templateT
Lhx.apply template (Lhx.makeInput (Separator ",") inputString)
tests :: TestTree
tests =
testGroup
"Templating tests"
[ templateMakingTests
, inputMakingTests
, functionPropertyTests
, indexingTests
]
| null | https://raw.githubusercontent.com/ruHaskell-learn/lhx/95e8e83db5a60ba74615e8ff7df52672bf5cc524/test/TestTemplate.hs | haskell | module TestTemplate (tests) where
import Data.Bifunctor (first)
import Data.Either (isLeft, isRight, fromRight)
import Data.Text qualified as T
import Data.Text.Arbitrary ()
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase, (@?), (@?=))
import Test.Tasty.QuickCheck qualified as QC
import Lhx (Separator(..))
import Lhx qualified
import Lhx.Parser qualified as LP
templateMakingTests :: TestTree
templateMakingTests =
testGroup
"Making of templates"
[ testGroup
"Broken templates"
[ testCase "Unclosed function call" $
isLeft (Lhx.makeTemplate "$foo")
@? "Shouldn't accept non-closed function call"
, testCase "Unknown function" $
isLeft (Lhx.makeTemplate "$foo;")
@? "Shouldn't accept unknown function"
, testCase "Several unknown functions" $
case Lhx.makeTemplate "$foo:bar:rev:baz:rev:bazzz:rev;" of
Right _ -> error "impossible"
Left e -> Lhx.errorText e @?= T.unlines
[ "Unknown function: foo"
, "Unknown function: bar"
, "Unknown function: baz"
, "Unknown function: bazzz"
]
]
, testGroup
"Correct templates"
[ testCase "All known functions" $
isRight (Lhx.makeTemplate $ mconcat
[ "$"
, T.intercalate ":" $ map (LP.unFName . fst) Lhx.functions
, ";"
]) @? "Should accept any registered function"
]
]
inputMakingTests :: TestTree
inputMakingTests =
testGroup
"Make input"
[ testCase "Separating by ','" $
Lhx.iFields (Lhx.makeInput (Lhx.Separator ",") "a, b, c")
@?= ["a", " b", " c"]
]
functionPropertyTests :: TestTree
functionPropertyTests =
testGroup
"Function properties"
[ QC.testProperty "'rev' function" \s ->
fromRight False do
template <- Lhx.makeTemplate "$rev;"
result <- Lhx.apply template (Lhx.makeInput (Separator ",") s)
pure $ result == T.reverse s
]
indexingTests :: TestTree
indexingTests =
testGroup
"Indexing"
[ testCase "Zero index should capture the whole input" $
"$0" `appliedTo` "abcd" @?= Right "abcd"
, testCase "Two fields should be swaped" $
"$2,$1" `appliedTo` "a,b" @?= Right "b,a"
, testCase "Functions should work well with indices" $
"$2:rev:rev;,$1:rev;" `appliedTo` "abc,de" @?= Right "de,cba"
, testCase "Index out of range" $
"$20" `appliedTo` "a,b,c" @?= Left "Index is out of range: 20\n"
, testCase "Negate index -1" $
"$-1" `appliedTo` "a,b,c,d,e,f" @?= Right "f"
, testCase "Negate index -3" $
"$-3" `appliedTo` "a,b,c,d,e,f" @?= Right "d"
, testCase "Negate index out of range" $
"$-3" `appliedTo` "a,b" @?= Left "Index is out of range: -3\n"
, testCase "To apply the function on the negate index" $
"$-3:rev;" `appliedTo` "a,b,c,abcd,e,f" @?= Right "dcba"
]
where
appliedTo templateT inputString = first Lhx.errorText do
template <- Lhx.makeTemplate templateT
Lhx.apply template (Lhx.makeInput (Separator ",") inputString)
tests :: TestTree
tests =
testGroup
"Templating tests"
[ templateMakingTests
, inputMakingTests
, functionPropertyTests
, indexingTests
]
|
|
1b4b045365731ef7b7c70a9a372bdfcbd9450a85faf1d61b317a030e173fc3a8 | clingen-data-model/genegraph | response_cache.clj | (ns genegraph.response-cache
(:require [genegraph.rocksdb :as rocksdb]
[genegraph.env :as env]
[mount.core :refer [defstate] :as mount]
[io.pedestal.interceptor.chain :refer [terminate]]
[io.pedestal.log :as log]
[clojure.core.async
:as a
:refer [>! <! >!! <!! go chan buffer close! thread
alts! alts!! timeout]]))
(def db-name "response_cache")
(def expiration-notification-chan (atom (chan (a/dropping-buffer 1))))
(declare cache-store)
(defn running? []
(and env/use-response-cache ((mount/running-states) (str #'cache-store))))
(defn clear-response-cache! []
(log/debug :fn ::clear-respsonse-cache! :msg "clearing response cache")
(when (running?)
(mount/stop #'cache-store)
(try
(rocksdb/rocks-destroy! db-name)
(catch Exception e
(log/debug :fn clear-response-cache! :msg (str "Caught exception: " (.getMessage e)) :exception e)))
(mount/start #'cache-store)))
(defstate cache-store
:start (when env/use-response-cache
(reset! expiration-notification-chan (chan (a/dropping-buffer 1)))
(.start (Thread. #(while (<!! @expiration-notification-chan)
(clear-response-cache!))))
(rocksdb/open db-name))
:stop (when env/use-response-cache
(close! @expiration-notification-chan)
(rocksdb/close cache-store)))
(defn check-for-cached-response [context]
(let [body (get-in context [:request :body])]
(if (running?)
(let [cached-response (rocksdb/rocks-get cache-store body)]
(if (= ::rocksdb/miss cached-response)
(do
(log/debug :fn ::check-for-cached-response :msg "request cache miss!")
context)
(do
(log/debug :fn ::check-for-cached-response :msg "request cache hit")
(-> context
(assoc :response cached-response)
terminate))))
context)))
(defn store-processed-response [context]
(when (running?)
(log/debug :fn ::store-processed-response :msg "storing processed response")
(rocksdb/rocks-put! cache-store
(get-in context [:request :body])
(:response context)))
context)
(defn response-cache-interceptor []
{:name ::response-cache
:enter check-for-cached-response
:leave store-processed-response})
(def expire-response-cache-interceptor
"Interceptor for expiring cached http responses."
{:name ::expire-response-cache
:enter (fn [event]
(when (running?)
(>!! @expiration-notification-chan true))
event)})
| null | https://raw.githubusercontent.com/clingen-data-model/genegraph/8c217e4c3820b3bd0a0937a6e331a6e6a49b8c14/src/genegraph/response_cache.clj | clojure | (ns genegraph.response-cache
(:require [genegraph.rocksdb :as rocksdb]
[genegraph.env :as env]
[mount.core :refer [defstate] :as mount]
[io.pedestal.interceptor.chain :refer [terminate]]
[io.pedestal.log :as log]
[clojure.core.async
:as a
:refer [>! <! >!! <!! go chan buffer close! thread
alts! alts!! timeout]]))
(def db-name "response_cache")
(def expiration-notification-chan (atom (chan (a/dropping-buffer 1))))
(declare cache-store)
(defn running? []
(and env/use-response-cache ((mount/running-states) (str #'cache-store))))
(defn clear-response-cache! []
(log/debug :fn ::clear-respsonse-cache! :msg "clearing response cache")
(when (running?)
(mount/stop #'cache-store)
(try
(rocksdb/rocks-destroy! db-name)
(catch Exception e
(log/debug :fn clear-response-cache! :msg (str "Caught exception: " (.getMessage e)) :exception e)))
(mount/start #'cache-store)))
(defstate cache-store
:start (when env/use-response-cache
(reset! expiration-notification-chan (chan (a/dropping-buffer 1)))
(.start (Thread. #(while (<!! @expiration-notification-chan)
(clear-response-cache!))))
(rocksdb/open db-name))
:stop (when env/use-response-cache
(close! @expiration-notification-chan)
(rocksdb/close cache-store)))
(defn check-for-cached-response [context]
(let [body (get-in context [:request :body])]
(if (running?)
(let [cached-response (rocksdb/rocks-get cache-store body)]
(if (= ::rocksdb/miss cached-response)
(do
(log/debug :fn ::check-for-cached-response :msg "request cache miss!")
context)
(do
(log/debug :fn ::check-for-cached-response :msg "request cache hit")
(-> context
(assoc :response cached-response)
terminate))))
context)))
(defn store-processed-response [context]
(when (running?)
(log/debug :fn ::store-processed-response :msg "storing processed response")
(rocksdb/rocks-put! cache-store
(get-in context [:request :body])
(:response context)))
context)
(defn response-cache-interceptor []
{:name ::response-cache
:enter check-for-cached-response
:leave store-processed-response})
(def expire-response-cache-interceptor
"Interceptor for expiring cached http responses."
{:name ::expire-response-cache
:enter (fn [event]
(when (running?)
(>!! @expiration-notification-chan true))
event)})
|
|
22179311b7b37b1cc9343c3d02692a1588500c80198039ff7822bf7d48eb5cf5 | ocurrent/citty | utils.ml | let rec interleave sep = function
| ([] | [ _ ]) as tail -> tail
| hd :: tail ->
let tail = interleave sep tail in
hd :: sep :: tail
let failwithf fmt = Printf.ksprintf failwith fmt
let rec filter_map f = function
| [] -> []
| x :: xs -> (
match f x with
| None -> filter_map f xs
| Some x' -> x' :: filter_map f xs )
let update_if_changed v x = if Lwd.peek v <> x then Lwd.set v x
| null | https://raw.githubusercontent.com/ocurrent/citty/25141643a417c412573fca6fcd918cd7ceba5363/src/utils.ml | ocaml | let rec interleave sep = function
| ([] | [ _ ]) as tail -> tail
| hd :: tail ->
let tail = interleave sep tail in
hd :: sep :: tail
let failwithf fmt = Printf.ksprintf failwith fmt
let rec filter_map f = function
| [] -> []
| x :: xs -> (
match f x with
| None -> filter_map f xs
| Some x' -> x' :: filter_map f xs )
let update_if_changed v x = if Lwd.peek v <> x then Lwd.set v x
|
|
8164228c4d1ef176f619f4c08ed04124be3dda2ab2199f9041848e27d5ac8c49 | mchakravarty/language-c-inline | Error.hs | # LANGUAGE TemplateHaskell , QuasiQuotes #
-- |
-- Module : Language.C.Inline.Error
Copyright : [ 2013 ]
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
-- This module provides support for error reporting.
module Language.C.Inline.Error (
-- * Error reporting
reportErrorWithLang, reportErrorAndFail,
-- * Exception handling
tryWithPlaceholder,
-- * Pretty printing for error messages
prettyQC
) where
import Language.Haskell.TH as TH
-- quasi-quotation libraries
import Language.C.Quote as QC
import Text.PrettyPrint.Mainland as QC
reportErrorWithLang :: QC.Extensions -> String -> Q ()
reportErrorWithLang lang msg
= do
{ _loc <- location
FIXME : define a Show instance for ' ' and use it to prefix position to error
; TH.reportError $ "Inline " ++ showLang lang ++ ": " ++ msg
}
reportErrorAndFail :: QC.Extensions -> String -> Q a
reportErrorAndFail lang msg
= reportErrorAndFail' $ "Inline " ++ showLang lang ++ ": " ++ msg
reportErrorAndFail' :: String -> Q a
reportErrorAndFail' msg
= do
{ TH.reportError msg
; fail "Fatal error due to inline code"
}
reportErrorAndBail : : String - > Q
-- reportErrorAndBail msg
-- = do
-- { reportError msg
-- ; Just undefinedName <- TH.lookupValueName "Prelude.undefined"
; return $ VarE undefinedName
-- }
showLang :: QC.Extensions -> String
showLang QC.Antiquotation = "C"
showLang QC.C11 = "C 11"
showLang QC.Gcc = "GCC C"
showLang QC.CUDA = "CUDA C"
showLang QC.OpenCL = "OpenCL"
showLang QC.ObjC = "Objective-C"
-- If the tried computation fails, insert a placeholder expression.
--
-- We report all errors explicitly. Failing would just duplicate errors.
--
tryWithPlaceholder :: Q TH.Exp -> Q TH.Exp
tryWithPlaceholder = ([| error "language-c-quote: internal error: tryWithPlaceholder" |] `recover`)
prettyQC :: QC.Pretty a => a -> String
prettyQC = QC.pretty 80 . QC.ppr
| null | https://raw.githubusercontent.com/mchakravarty/language-c-inline/034128f80abc917040f42a10ce982775ae5e7387/Language/C/Inline/Error.hs | haskell | |
Module : Language.C.Inline.Error
License : BSD3
Stability : experimental
This module provides support for error reporting.
* Error reporting
* Exception handling
* Pretty printing for error messages
quasi-quotation libraries
reportErrorAndBail msg
= do
{ reportError msg
; Just undefinedName <- TH.lookupValueName "Prelude.undefined"
}
If the tried computation fails, insert a placeholder expression.
We report all errors explicitly. Failing would just duplicate errors.
| # LANGUAGE TemplateHaskell , QuasiQuotes #
Copyright : [ 2013 ]
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Language.C.Inline.Error (
reportErrorWithLang, reportErrorAndFail,
tryWithPlaceholder,
prettyQC
) where
import Language.Haskell.TH as TH
import Language.C.Quote as QC
import Text.PrettyPrint.Mainland as QC
reportErrorWithLang :: QC.Extensions -> String -> Q ()
reportErrorWithLang lang msg
= do
{ _loc <- location
FIXME : define a Show instance for ' ' and use it to prefix position to error
; TH.reportError $ "Inline " ++ showLang lang ++ ": " ++ msg
}
reportErrorAndFail :: QC.Extensions -> String -> Q a
reportErrorAndFail lang msg
= reportErrorAndFail' $ "Inline " ++ showLang lang ++ ": " ++ msg
reportErrorAndFail' :: String -> Q a
reportErrorAndFail' msg
= do
{ TH.reportError msg
; fail "Fatal error due to inline code"
}
reportErrorAndBail : : String - > Q
; return $ VarE undefinedName
showLang :: QC.Extensions -> String
showLang QC.Antiquotation = "C"
showLang QC.C11 = "C 11"
showLang QC.Gcc = "GCC C"
showLang QC.CUDA = "CUDA C"
showLang QC.OpenCL = "OpenCL"
showLang QC.ObjC = "Objective-C"
tryWithPlaceholder :: Q TH.Exp -> Q TH.Exp
tryWithPlaceholder = ([| error "language-c-quote: internal error: tryWithPlaceholder" |] `recover`)
prettyQC :: QC.Pretty a => a -> String
prettyQC = QC.pretty 80 . QC.ppr
|
1ca926e4c4a1f7212af8b6dbc199a07a872a718ad9bf482a2bb40d3f1e68e674 | udem-dlteam/ribbit | 25-cdr.scm | (putchar (cdr (cons 65 66)))
(putchar 10)
;;;options: -l min
;;;expected:
;;;B
| null | https://raw.githubusercontent.com/udem-dlteam/ribbit/3e88b58706dba9eac2bbb841f947b4cd9c47d6ec/src/tests/25-cdr.scm | scheme | options: -l min
expected:
B | (putchar (cdr (cons 65 66)))
(putchar 10)
|
1a42bb23e6a1f8a6401e59a261d47f7a71be268c5d8dd8cb4ad453ddac5174c3 | stepcut/plugins | API.hs | module API where
-- just a dummy for the build system
| null | https://raw.githubusercontent.com/stepcut/plugins/52c660b5bc71182627d14c1d333d0234050cac01/testsuite/hier/hier2/api/API.hs | haskell | just a dummy for the build system | module API where
|
5a4816cd980614c5023ff7037baa51c875e16f62ab699c79042cb017b678f990 | janestreet/vcaml | message.mli | open Core
module Custom : sig
type t =
{ type_id : int
; data : Bytes.t
}
[@@deriving compare, sexp]
end
type t =
| Nil
| Integer of int
| Int64 of Int64.t
| UInt64 of Int64.t
| Boolean of bool
| Floating of float
| Array of t list
| Map of (t * t) list
| String of string
| Binary of Bytes.t
| Extension of Custom.t
[@@deriving compare, sexp]
include Comparable.S with type t := t
val quickcheck_generator
: only_string_keys:bool
-> only_finite_floats:bool
-> t Quickcheck.Generator.t
| null | https://raw.githubusercontent.com/janestreet/vcaml/b02fc56c48746fa18a6bc9a0f8fb85776db76977/msgpack/protocol/src/message.mli | ocaml | open Core
module Custom : sig
type t =
{ type_id : int
; data : Bytes.t
}
[@@deriving compare, sexp]
end
type t =
| Nil
| Integer of int
| Int64 of Int64.t
| UInt64 of Int64.t
| Boolean of bool
| Floating of float
| Array of t list
| Map of (t * t) list
| String of string
| Binary of Bytes.t
| Extension of Custom.t
[@@deriving compare, sexp]
include Comparable.S with type t := t
val quickcheck_generator
: only_string_keys:bool
-> only_finite_floats:bool
-> t Quickcheck.Generator.t
|
|
23e48283dbb04ba325cbc1aade7cd2678525954de7c0b731197639193451089d | janestreet/bonsai | knobs.ml | open! Core
open! Bonsai_web
open Bonsai.Let_syntax
module Form = Bonsai_web_ui_form
module Style =
[%css
stylesheet
{|
.form-title {
justify-content:center;
padding: 3px;
}
.card-content {
flex-grow: 1;
}
|}]
module Shared = struct
type t =
{ left : [ `Hex of string ]
; right : [ `Hex of string ]
}
[@@deriving typed_fields]
let form =
Form.Typed.Record.make
(module struct
module Typed_field = Typed_field
let label_for_field = `Inferred
let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function
| Left -> Form.Elements.Color_picker.hex ()
| Right -> Form.Elements.Color_picker.hex ()
;;
end)
;;
end
module For_gradient = struct
type t = { steps : int } [@@deriving typed_fields]
let form =
Form.Typed.Record.make
(module struct
module Typed_field = Typed_field
let label_for_field = `Inferred
let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function
| Steps -> Form.Elements.Range.int ~min:1 ~max:200 ~default:50 ~step:1 ()
;;
end)
;;
end
module For_overlay = struct
type t =
{ left_alpha : float
; right_alpha : float
}
[@@deriving typed_fields]
let form =
Form.Typed.Record.make
(module struct
module Typed_field = Typed_field
let label_for_field : type a. a Typed_field.t -> string = function
| Typed_field.Left_alpha -> "left alpha"
| Right_alpha -> "right alpha"
;;
let label_for_field = `Computed label_for_field
let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function
| Left_alpha ->
Form.Elements.Range.float ~min:0.0 ~max:1.0 ~default:0.5 ~step:0.01 ()
| Right_alpha ->
Form.Elements.Range.float ~min:0.0 ~max:1.0 ~default:0.5 ~step:0.01 ()
;;
end)
;;
end
type t =
{ shared : Shared.t
; for_gradient : For_gradient.t
; for_overlay : For_overlay.t
}
[@@deriving typed_fields]
let initial_params =
{ shared = { left = `Hex "#FFFF00"; right = `Hex "#0000FF" }
; for_gradient = { steps = 10 }
; for_overlay = { left_alpha = 0.5; right_alpha = 0.5 }
}
;;
let form =
let%sub shared = Shared.form in
let%sub for_gradient = For_gradient.form in
let%sub for_overlay = For_overlay.form in
let%sub all =
Form.Typed.Record.make
(module struct
module Typed_field = Typed_field
let label_for_field = `Inferred
let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function
| Shared -> return shared
| For_gradient -> return for_gradient
| For_overlay -> return for_overlay
;;
end)
in
let%sub all = Form.Dynamic.with_default (Value.return initial_params) all in
let%sub value =
let%arr all = all in
(match Form.value all with
| Error e -> print_s [%message (e : Error.t)]
| _ -> ());
Form.value_or_default all ~default:initial_params
in
let card_helper theme title form =
View.card'
theme
~title_attr:Style.form_title
~content_attr:Style.card_content
~title:[ Vdom.Node.text title ]
[ Form.view_as_vdom form ]
in
let%sub view =
let%sub theme = View.Theme.current in
let%arr shared = shared
and for_gradient = for_gradient
and for_overlay = for_overlay
and theme = theme in
View.hbox
~gap:(`Em 1)
~main_axis_alignment:Center
[ card_helper theme "shared" shared
; card_helper theme "for gradient" for_gradient
; card_helper theme "for overlay" for_overlay
]
in
return (Value.both value view)
;;
| null | https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/examples/oklab/knobs.ml | ocaml | open! Core
open! Bonsai_web
open Bonsai.Let_syntax
module Form = Bonsai_web_ui_form
module Style =
[%css
stylesheet
{|
.form-title {
justify-content:center;
padding: 3px;
}
.card-content {
flex-grow: 1;
}
|}]
module Shared = struct
type t =
{ left : [ `Hex of string ]
; right : [ `Hex of string ]
}
[@@deriving typed_fields]
let form =
Form.Typed.Record.make
(module struct
module Typed_field = Typed_field
let label_for_field = `Inferred
let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function
| Left -> Form.Elements.Color_picker.hex ()
| Right -> Form.Elements.Color_picker.hex ()
;;
end)
;;
end
module For_gradient = struct
type t = { steps : int } [@@deriving typed_fields]
let form =
Form.Typed.Record.make
(module struct
module Typed_field = Typed_field
let label_for_field = `Inferred
let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function
| Steps -> Form.Elements.Range.int ~min:1 ~max:200 ~default:50 ~step:1 ()
;;
end)
;;
end
module For_overlay = struct
type t =
{ left_alpha : float
; right_alpha : float
}
[@@deriving typed_fields]
let form =
Form.Typed.Record.make
(module struct
module Typed_field = Typed_field
let label_for_field : type a. a Typed_field.t -> string = function
| Typed_field.Left_alpha -> "left alpha"
| Right_alpha -> "right alpha"
;;
let label_for_field = `Computed label_for_field
let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function
| Left_alpha ->
Form.Elements.Range.float ~min:0.0 ~max:1.0 ~default:0.5 ~step:0.01 ()
| Right_alpha ->
Form.Elements.Range.float ~min:0.0 ~max:1.0 ~default:0.5 ~step:0.01 ()
;;
end)
;;
end
type t =
{ shared : Shared.t
; for_gradient : For_gradient.t
; for_overlay : For_overlay.t
}
[@@deriving typed_fields]
let initial_params =
{ shared = { left = `Hex "#FFFF00"; right = `Hex "#0000FF" }
; for_gradient = { steps = 10 }
; for_overlay = { left_alpha = 0.5; right_alpha = 0.5 }
}
;;
let form =
let%sub shared = Shared.form in
let%sub for_gradient = For_gradient.form in
let%sub for_overlay = For_overlay.form in
let%sub all =
Form.Typed.Record.make
(module struct
module Typed_field = Typed_field
let label_for_field = `Inferred
let form_for_field : type a. a Typed_field.t -> a Form.t Computation.t = function
| Shared -> return shared
| For_gradient -> return for_gradient
| For_overlay -> return for_overlay
;;
end)
in
let%sub all = Form.Dynamic.with_default (Value.return initial_params) all in
let%sub value =
let%arr all = all in
(match Form.value all with
| Error e -> print_s [%message (e : Error.t)]
| _ -> ());
Form.value_or_default all ~default:initial_params
in
let card_helper theme title form =
View.card'
theme
~title_attr:Style.form_title
~content_attr:Style.card_content
~title:[ Vdom.Node.text title ]
[ Form.view_as_vdom form ]
in
let%sub view =
let%sub theme = View.Theme.current in
let%arr shared = shared
and for_gradient = for_gradient
and for_overlay = for_overlay
and theme = theme in
View.hbox
~gap:(`Em 1)
~main_axis_alignment:Center
[ card_helper theme "shared" shared
; card_helper theme "for gradient" for_gradient
; card_helper theme "for overlay" for_overlay
]
in
return (Value.both value view)
;;
|
|
ca6b65fe189d30e9041272c50826e6c5734f9f95039f91a72a177b1eb7ed6210 | wireapp/wire-server | Teams.hs | # OPTIONS_GHC -Wno - incomplete - uni - patterns #
-- Disabling to stop warnings on HasCallStack
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- 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 </>.
module API.Teams
( tests,
)
where
import API.SQS
import API.Util hiding (deleteTeam)
import qualified API.Util as Util
import qualified API.Util.TeamFeature as Util
import Bilge hiding (head, timeout)
import Bilge.Assert
import Brig.Types.Intra (fromAccountStatusResp)
import qualified Brig.Types.Intra as Brig
import Control.Arrow ((>>>))
import Control.Lens hiding ((#), (.=))
import Control.Monad.Catch
import Data.Aeson hiding (json)
import Data.ByteString.Conversion
import Data.ByteString.Lazy (fromStrict)
import qualified Data.Code as Code
import Data.Csv (FromNamedRecord (..), decodeByName)
import qualified Data.Currency as Currency
import Data.Default
import Data.Id
import Data.Json.Util hiding ((#))
import qualified Data.LegalHold as LH
import Data.List.NonEmpty (NonEmpty ((:|)))
import Data.List1 hiding (head)
import qualified Data.List1 as List1
import qualified Data.Map as Map
import Data.Misc (HttpsUrl, PlainTextPassword (..), mkHttpsUrl)
import Data.Qualified
import Data.Range
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Ascii (AsciiChars (validate))
import qualified Data.UUID as UUID
import qualified Data.UUID.Util as UUID
import qualified Data.UUID.V1 as UUID
import qualified Data.Vector as V
import GHC.TypeLits (KnownSymbol)
import qualified Galley.Env as Galley
import Galley.Options (optSettings, setEnableIndexedBillingTeamMembers, setFeatureFlags, setMaxConvSize, setMaxFanoutSize)
import Galley.Types.Conversations.Roles
import Galley.Types.Teams
import Imports
import Network.HTTP.Types.Status (status403)
import qualified Network.Wai.Utilities.Error as Error
import qualified Network.Wai.Utilities.Error as Wai
import qualified Proto.TeamEvents as E
import qualified Proto.TeamEvents_Fields as E
import qualified SAML2.WebSSO.Types as SAML
import Test.Tasty
import Test.Tasty.Cannon (TimeoutUnit (..), (#))
import qualified Test.Tasty.Cannon as WS
import Test.Tasty.HUnit
import TestHelpers
import TestSetup
import UnliftIO (mapConcurrently)
import Wire.API.Conversation
import Wire.API.Conversation.Protocol
import Wire.API.Conversation.Role
import Wire.API.Event.Team
import Wire.API.Internal.Notification hiding (target)
import Wire.API.Routes.Internal.Galley.TeamsIntra as TeamsIntra
import Wire.API.Team
import Wire.API.Team.Export (TeamExportUser (..))
import qualified Wire.API.Team.Feature as Public
import Wire.API.Team.Member
import qualified Wire.API.Team.Member as Member
import qualified Wire.API.Team.Member as TM
import qualified Wire.API.Team.Member as Teams
import Wire.API.Team.Permission
import Wire.API.Team.Role
import Wire.API.Team.SearchVisibility
import qualified Wire.API.User as Public
import qualified Wire.API.User as U
import qualified Wire.API.User.Client as C
import qualified Wire.API.User.Client.Prekey as PC
tests :: IO TestSetup -> TestTree
tests s =
testGroup "Teams API" $
[ test s "create team" testCreateTeam,
test s "GET /teams (deprecated)" testGetTeams,
test s "create binding team with currency" testCreateBindingTeamWithCurrency,
testGroup "List Team Members" $
[ test s "a member should be able to list their team" testListTeamMembersDefaultLimit,
let numMembers = 5
in test
s
("admins should be able to get a csv stream with their team (" <> show numMembers <> " members)")
(testListTeamMembersCsv numMembers),
test s "the list should be limited to the number requested (hard truncation is not tested here)" testListTeamMembersTruncated,
test s "pagination" testListTeamMembersPagination
],
testGroup "List Team Members (by ids)" $
[ test s "a member should be able to list their team" testListTeamMembersDefaultLimitByIds,
test s "id list length limit is enforced" testListTeamMembersTruncatedByIds
],
testGroup "List Team members unchecked" $
[test s "the list should be truncated" testUncheckedListTeamMembers],
test s "enable/disable SSO" testEnableSSOPerTeam,
test s "enable/disable Custom Search Visibility" testEnableTeamSearchVisibilityPerTeam,
test s "create 1-1 conversation between non-team members (fail)" testCreateOne2OneFailForNonTeamMembers,
test s "create 1-1 conversation between binding team members" (testCreateOne2OneWithMembers RoleMember),
test s "create 1-1 conversation between binding team members as partner" (testCreateOne2OneWithMembers RoleExternalPartner),
test s "poll team-level event queue" testTeamQueue,
test s "add new team member internal" testAddTeamMemberInternal,
test s "remove aka delete team member (binding, owner has passwd)" (testRemoveBindingTeamMember True),
test s "remove aka delete team member (binding, owner has no passwd)" (testRemoveBindingTeamMember False),
test s "remove aka delete team owner (binding)" testRemoveBindingTeamOwner,
test s "add team conversation (no role as argument)" testAddTeamConvLegacy,
test s "add team conversation with role" testAddTeamConvWithRole,
test s "add team conversation as partner (fail)" testAddTeamConvAsExternalPartner,
test s "add team MLS conversation" testCreateTeamMLSConv,
test s "add team member to conversation without connection" testAddTeamMemberToConv,
test s "update conversation as member" (testUpdateTeamConv RoleMember roleNameWireAdmin),
test s "update conversation as partner" (testUpdateTeamConv RoleExternalPartner roleNameWireMember),
test s "delete binding team internal single member" testDeleteBindingTeamSingleMember,
test s "delete binding team internal no members" testDeleteBindingTeamNoMembers,
test s "delete binding team more than one member" testDeleteBindingTeamMoreThanOneMember,
test s "delete binding team (owner has passwd)" (testDeleteBindingTeam True),
test s "delete binding team (owner has no passwd)" (testDeleteBindingTeam False),
testGroup
"delete team - verification code"
[ test s "success" testDeleteTeamVerificationCodeSuccess,
test s "wrong code" testDeleteTeamVerificationCodeWrongCode,
test s "missing code" testDeleteTeamVerificationCodeMissingCode,
test s "expired code" testDeleteTeamVerificationCodeExpiredCode
],
test s "delete team conversation" testDeleteTeamConv,
test s "update team data" testUpdateTeam,
test s "update team data icon validation" testUpdateTeamIconValidation,
test s "update team member" testUpdateTeamMember,
test s "update team status" testUpdateTeamStatus,
test s "team tests around truncation limits - no events, too large team" testTeamAddRemoveMemberAboveThresholdNoEvents,
test s "send billing events to owners even in large teams" testBillingInLargeTeam,
test s "send billing events to some owners in large teams (indexedBillingTeamMembers disabled)" testBillingInLargeTeamWithoutIndexedBillingTeamMembers,
testGroup "broadcast" $
[ (BroadcastLegacyBody, BroadcastJSON),
(BroadcastLegacyQueryParams, BroadcastJSON),
(BroadcastLegacyBody, BroadcastProto),
(BroadcastQualified, BroadcastProto)
]
<&> \(api, ty) ->
let bcast = def {bAPI = api, bType = ty}
in testGroup
(broadcastAPIName api <> " - " <> broadcastTypeName ty)
[ test s "message" (postCryptoBroadcastMessage bcast),
test s "filtered only, too large team" (postCryptoBroadcastMessageFilteredTooLargeTeam bcast),
test s "report missing in body" (postCryptoBroadcastMessageReportMissingBody bcast),
test s "redundant/missing" (postCryptoBroadcastMessage2 bcast),
test s "no-team" (postCryptoBroadcastMessageNoTeam bcast),
test s "100 (or max conns)" (postCryptoBroadcastMessage100OrMaxConns bcast)
]
]
timeout :: WS.Timeout
timeout = 3 # Second
testCreateTeam :: TestM ()
testCreateTeam = do
owner <- Util.randomUser
tid <- Util.createBindingTeamInternal "foo" owner
team <- Util.getTeam owner tid
assertTeamActivate "create team" tid
liftIO $ assertEqual "owner" owner (team ^. teamCreator)
testGetTeams :: TestM ()
testGetTeams = do
owner <- Util.randomUser
Util.getTeams owner [] >>= checkTeamList Nothing
tid <- Util.createBindingTeamInternal "foo" owner
assertTeamActivate "create team" tid
wrongTid <- Util.randomUser >>= Util.createBindingTeamInternal "foobar"
assertTeamActivate "create team" wrongTid
Util.getTeams owner [] >>= checkTeamList (Just tid)
Util.getTeams owner [("size", Just "1")] >>= checkTeamList (Just tid)
Util.getTeams owner [("ids", Just $ toByteString' tid)] >>= checkTeamList (Just tid)
Util.getTeams owner [("ids", Just $ toByteString' tid <> "," <> toByteString' wrongTid)] >>= checkTeamList (Just tid)
these two queries do not yield responses that are equivalent to the old wai route API
Util.getTeams owner [("ids", Just $ toByteString' wrongTid)] >>= checkTeamList (Just tid)
Util.getTeams owner [("start", Just $ toByteString' tid)] >>= checkTeamList (Just tid)
where
checkTeamList :: Maybe TeamId -> TeamList -> TestM ()
checkTeamList mbTid tl = liftIO $ do
let teams = tl ^. teamListTeams
assertEqual "teamListHasMore" False (tl ^. teamListHasMore)
case mbTid of
Just tid -> assertEqual "teamId" tid (Imports.head teams ^. teamId)
Nothing -> assertEqual "teams size" 0 (length teams)
testCreateBindingTeamWithCurrency :: TestM ()
testCreateBindingTeamWithCurrency = do
owner1 <- Util.randomUser
tid1 <- Util.createBindingTeamInternal "foo" owner1
-- Backwards compatible
assertTeamActivateWithCurrency "create team" tid1 Nothing
-- Ensure currency is properly journaled
owner2 <- Util.randomUser
tid2 <- Util.createBindingTeamInternalWithCurrency "foo" owner2 Currency.USD
assertTeamActivateWithCurrency "create team" tid2 (Just Currency.USD)
testListTeamMembersDefaultLimit :: TestM ()
testListTeamMembersDefaultLimit = do
(owner, tid, [member1, member2]) <- Util.createBindingTeamWithNMembers 2
listFromServer <- Util.getTeamMembers owner tid
liftIO $
assertEqual
"list members"
(Set.fromList [owner, member1, member2])
(Set.fromList (map (^. Teams.userId) $ listFromServer ^. teamMembers))
liftIO $
assertBool
"member list indicates that there are no more members"
(listFromServer ^. teamMemberListType == ListComplete)
| for ad - hoc load - testing , set @numMembers@ to , say , 10k and see what
-- happens. but please don't give that number to our ci! :)
for additional tests of the CSV download particularly with SCIM users , please refer to ' Test . Spar . Scim . UserSpec '
testListTeamMembersCsv :: HasCallStack => Int -> TestM ()
testListTeamMembersCsv numMembers = do
let teamSize = numMembers + 1
(owner, tid, mbs) <- Util.createBindingTeamWithNMembersWithHandles True numMembers
let numClientMappings = Map.fromList $ (owner : mbs) `zip` (cycle [1, 2, 3] :: [Int])
addClients numClientMappings
resp <- Util.getTeamMembersCsv owner tid
let rbody = fromMaybe (error "no body") . responseBody $ resp
usersInCsv <- either (error "could not decode csv") pure (decodeCSV @TeamExportUser rbody)
liftIO $ do
assertEqual "total number of team members" teamSize (length usersInCsv)
assertEqual "owners in team" 1 (countOn tExportRole (Just RoleOwner) usersInCsv)
assertEqual "members in team" numMembers (countOn tExportRole (Just RoleMember) usersInCsv)
do
let someUsersInCsv = take 50 usersInCsv
someHandles = tExportHandle <$> someUsersInCsv
users <- Util.getUsersByHandle (catMaybes someHandles)
mbrs <- view teamMembers <$> Util.bulkGetTeamMembers owner tid (U.userId <$> users)
let check :: Eq a => String -> (TeamExportUser -> Maybe a) -> UserId -> Maybe a -> IO ()
check msg getTeamExportUserAttr uid userAttr = do
assertBool msg (isJust userAttr)
assertEqual (msg <> ": " <> show uid) 1 (countOn getTeamExportUserAttr userAttr usersInCsv)
liftIO . forM_ (zip users mbrs) $ \(user, mbr) -> do
assertEqual "user/member id match" (U.userId user) (mbr ^. TM.userId)
check "tExportDisplayName" (Just . tExportDisplayName) (U.userId user) (Just $ U.userDisplayName user)
check "tExportEmail" tExportEmail (U.userId user) (U.userEmail user)
liftIO . forM_ (zip3 someUsersInCsv users mbrs) $ \(export, user, mbr) -> do
FUTUREWORK : there are a lot of cases we do n't cover here ( manual invitation , saml , other roles , ... ) .
assertEqual ("tExportDisplayName: " <> show (U.userId user)) (U.userDisplayName user) (tExportDisplayName export)
assertEqual ("tExportHandle: " <> show (U.userId user)) (U.userHandle user) (tExportHandle export)
assertEqual ("tExportEmail: " <> show (U.userId user)) (U.userEmail user) (tExportEmail export)
assertEqual ("tExportRole: " <> show (U.userId user)) (permissionsRole $ view permissions mbr) (tExportRole export)
assertEqual ("tExportCreatedOn: " <> show (U.userId user)) (snd <$> view invitation mbr) (tExportCreatedOn export)
assertEqual ("tExportInvitedBy: " <> show (U.userId user)) Nothing (tExportInvitedBy export)
assertEqual ("tExportIdpIssuer: " <> show (U.userId user)) (userToIdPIssuer user) (tExportIdpIssuer export)
assertEqual ("tExportManagedBy: " <> show (U.userId user)) (U.userManagedBy user) (tExportManagedBy export)
assertEqual ("tExportUserId: " <> show (U.userId user)) (U.userId user) (tExportUserId export)
assertEqual "tExportNumDevices: " (Map.findWithDefault (-1) (U.userId user) numClientMappings) (tExportNumDevices export)
where
userToIdPIssuer :: HasCallStack => U.User -> Maybe HttpsUrl
userToIdPIssuer usr = case (U.userIdentity >=> U.ssoIdentity) usr of
Just (U.UserSSOId (SAML.UserRef (SAML.Issuer issuer) _)) -> either (const $ error "shouldn't happen") Just $ mkHttpsUrl issuer
Just _ -> Nothing
Nothing -> Nothing
decodeCSV :: FromNamedRecord a => LByteString -> Either String [a]
decodeCSV bstr = decodeByName bstr <&> (snd >>> V.toList)
countOn :: Eq b => (a -> b) -> b -> [a] -> Int
countOn prop val xs = sum $ fmap (bool 0 1 . (== val) . prop) xs
addClients :: Map.Map UserId Int -> TestM ()
addClients xs = forM_ (Map.toList xs) addClientForUser
addClientForUser :: (UserId, Int) -> TestM ()
addClientForUser (uid, n) = forM_ [0 .. (n - 1)] (addClient uid)
addClient :: UserId -> Int -> TestM ()
addClient uid i = do
brig <- viewBrig
post (brig . paths ["i", "clients", toByteString' uid] . contentJson . json (newClient (someLastPrekeys !! i)) . queryItem "skip_reauth" "true") !!! const 201 === statusCode
newClient :: PC.LastPrekey -> C.NewClient
newClient lpk = C.newClient C.PermanentClientType lpk
testListTeamMembersPagination :: TestM ()
testListTeamMembersPagination = do
(owner, tid, _) <- Util.createBindingTeamWithNMembers 18
allMembers <- Util.getTeamMembersPaginated owner tid 100 Nothing
liftIO $ do
let actualTeamSize = length (rpResults allMembers)
let expectedTeamSize = 19
assertEqual ("expected team size of 19 (18 members + 1 owner), but got " <> show actualTeamSize) expectedTeamSize actualTeamSize
page1 <- Util.getTeamMembersPaginated owner tid 5 Nothing
check 1 5 True page1
page2 <- Util.getTeamMembersPaginated owner tid 5 (Just . rpPagingState $ page1)
check 2 5 True page2
page3 <- Util.getTeamMembersPaginated owner tid 5 (Just . rpPagingState $ page2)
check 3 5 True page3
page4 <- Util.getTeamMembersPaginated owner tid 5 (Just . rpPagingState $ page3)
check 4 4 False page4
where
check :: Int -> Int -> Bool -> ResultPage -> TestM ()
check n expectedSize expectedHasMore page = liftIO $ do
let actualSize = length (rpResults page)
assertEqual ("page " <> show n <> ": expected " <> show expectedSize <> " members, but got " <> show actualSize) expectedSize actualSize
let actualHasMore = rpHasMore page
assertEqual ("page " <> show n <> " (hasMore): expected " <> show expectedHasMore <> ", but got" <> "") expectedHasMore actualHasMore
testListTeamMembersTruncated :: TestM ()
testListTeamMembersTruncated = do
(owner, tid, _) <- Util.createBindingTeamWithNMembers 4
listFromServer <- Util.getTeamMembersTruncated owner tid 2
liftIO $
assertEqual
"member list is not limited to the requested number"
2
(length $ listFromServer ^. teamMembers)
liftIO $
assertBool
"member list does not indicate that there are more members"
(listFromServer ^. teamMemberListType == ListTruncated)
testListTeamMembersDefaultLimitByIds :: TestM ()
testListTeamMembersDefaultLimitByIds = do
(owner, tid, [member1, member2]) <- Util.createBindingTeamWithNMembers 2
(_, _, [alien]) <- Util.createBindingTeamWithNMembers 1
let phantom :: UserId = read "686f427a-7e56-11ea-a639-07a531a95937"
check owner tid [owner, member1, member2] [owner, member1, member2]
check owner tid [member1, member2] [member1, member2]
check owner tid [member1] [member1]
check owner tid [] [] -- a bit silly, but hey.
check owner tid [alien] []
check owner tid [phantom] []
check owner tid [owner, alien, phantom] [owner]
where
check :: HasCallStack => UserId -> TeamId -> [UserId] -> [UserId] -> TestM ()
check owner tid uidsIn uidsOut = do
listFromServer <- Util.bulkGetTeamMembers owner tid uidsIn
liftIO $
assertEqual
"list members"
(Set.fromList uidsOut)
(Set.fromList (map (^. userId) $ listFromServer ^. teamMembers))
liftIO $
assertBool
"has_more is always false"
(listFromServer ^. teamMemberListType == ListComplete)
testListTeamMembersTruncatedByIds :: TestM ()
testListTeamMembersTruncatedByIds = do
(owner, tid, mems) <- Util.createBindingTeamWithNMembers 4
Util.bulkGetTeamMembersTruncated owner tid (owner : mems) 3 !!! do
const 400 === statusCode
const "too-many-uids" === Error.label . responseJsonUnsafeWithMsg "error label"
testUncheckedListTeamMembers :: TestM ()
testUncheckedListTeamMembers = do
(_, tid, _) <- Util.createBindingTeamWithNMembers 4
listFromServer <- Util.getTeamMembersInternalTruncated tid 2
liftIO $
assertEqual
"member list is not limited to the requested number"
2
(length $ listFromServer ^. teamMembers)
liftIO $
assertBool
"member list does not indicate that there are more members"
(listFromServer ^. teamMemberListType == ListTruncated)
testEnableSSOPerTeam :: TestM ()
testEnableSSOPerTeam = do
owner <- Util.randomUser
tid <- Util.createBindingTeamInternal "foo" owner
assertTeamActivate "create team" tid
let check :: HasCallStack => String -> Public.FeatureStatus -> TestM ()
check msg enabledness = do
status :: Public.WithStatusNoLock Public.SSOConfig <- responseJsonUnsafe <$> (getSSOEnabledInternal tid <!! testResponse 200 Nothing)
let statusValue = Public.wssStatus status
liftIO $ assertEqual msg enabledness statusValue
let putSSOEnabledInternalCheckNotImplemented :: HasCallStack => TestM ()
putSSOEnabledInternalCheckNotImplemented = do
g <- viewGalley
Wai.Error status label _ _ <-
responseJsonUnsafe
<$> put
( g
. paths ["i", "teams", toByteString' tid, "features", "sso"]
. json (Public.WithStatusNoLock Public.FeatureStatusDisabled Public.SSOConfig Public.FeatureTTLUnlimited)
)
liftIO $ do
assertEqual "bad status" status403 status
assertEqual "bad label" "not-implemented" label
featureSSO <- view (tsGConf . optSettings . setFeatureFlags . flagSSO)
case featureSSO of
FeatureSSOEnabledByDefault -> check "Teams should start with SSO enabled" Public.FeatureStatusEnabled
FeatureSSODisabledByDefault -> check "Teams should start with SSO disabled" Public.FeatureStatusDisabled
putSSOEnabledInternal tid Public.FeatureStatusEnabled
check "Calling 'putEnabled True' should enable SSO" Public.FeatureStatusEnabled
putSSOEnabledInternalCheckNotImplemented
testEnableTeamSearchVisibilityPerTeam :: TestM ()
testEnableTeamSearchVisibilityPerTeam = do
(tid, owner, member : _) <- Util.createBindingTeamWithMembers 2
let check :: String -> Public.FeatureStatus -> TestM ()
check msg enabledness = do
g <- viewGalley
status :: Public.WithStatusNoLock Public.SearchVisibilityAvailableConfig <- responseJsonUnsafe <$> (Util.getTeamSearchVisibilityAvailableInternal g tid <!! testResponse 200 Nothing)
let statusValue = Public.wssStatus status
liftIO $ assertEqual msg enabledness statusValue
let putSearchVisibilityCheckNotAllowed :: TestM ()
putSearchVisibilityCheckNotAllowed = do
g <- viewGalley
Wai.Error status label _ _ <- responseJsonUnsafe <$> putSearchVisibility g owner tid SearchVisibilityNoNameOutsideTeam
liftIO $ do
assertEqual "bad status" status403 status
assertEqual "bad label" "team-search-visibility-not-enabled" label
let getSearchVisibilityCheck :: TeamSearchVisibility -> TestM ()
getSearchVisibilityCheck vis = do
g <- viewGalley
getSearchVisibility g owner tid !!! do
const 200 === statusCode
const (Just (TeamSearchVisibilityView vis)) === responseJsonUnsafe
Util.withCustomSearchFeature FeatureTeamSearchVisibilityAvailableByDefault $ do
g <- viewGalley
check "Teams should start with Custom Search Visibility enabled" Public.FeatureStatusEnabled
putSearchVisibility g owner tid SearchVisibilityNoNameOutsideTeam !!! const 204 === statusCode
putSearchVisibility g owner tid SearchVisibilityStandard !!! const 204 === statusCode
Util.withCustomSearchFeature FeatureTeamSearchVisibilityUnavailableByDefault $ do
check "Teams should start with Custom Search Visibility disabled" Public.FeatureStatusDisabled
putSearchVisibilityCheckNotAllowed
g <- viewGalley
Util.putTeamSearchVisibilityAvailableInternal g tid Public.FeatureStatusEnabled
-- Nothing was set, default value
getSearchVisibilityCheck SearchVisibilityStandard
putSearchVisibility g owner tid SearchVisibilityNoNameOutsideTeam !!! testResponse 204 Nothing
getSearchVisibilityCheck SearchVisibilityNoNameOutsideTeam
-- Check only admins can change the setting
putSearchVisibility g member tid SearchVisibilityStandard !!! testResponse 403 (Just "operation-denied")
getSearchVisibilityCheck SearchVisibilityNoNameOutsideTeam
-- Members can also see it?
getSearchVisibility g member tid !!! testResponse 200 Nothing
-- Once we disable the feature, team setting is back to the default value
Util.putTeamSearchVisibilityAvailableInternal g tid Public.FeatureStatusDisabled
getSearchVisibilityCheck SearchVisibilityStandard
testCreateOne2OneFailForNonTeamMembers :: TestM ()
testCreateOne2OneFailForNonTeamMembers = do
owner <- Util.randomUser
let p1 = Util.symmPermissions [CreateConversation, DoNotUseDeprecatedAddRemoveConvMember]
let p2 = Util.symmPermissions [CreateConversation, DoNotUseDeprecatedAddRemoveConvMember, AddTeamMember]
mem1 <- newTeamMember' p1 <$> Util.randomUser
mem2 <- newTeamMember' p2 <$> Util.randomUser
Util.connectUsers owner (list1 (mem1 ^. userId) [mem2 ^. userId])
-- Both have a binding team but not the same team
owner1 <- Util.randomUser
tid1 <- Util.createBindingTeamInternal "foo" owner1
assertTeamActivate "create team" tid1
owner2 <- Util.randomUser
tid2 <- Util.createBindingTeamInternal "foo" owner2
assertTeamActivate "create another team" tid2
Util.createOne2OneTeamConv owner1 owner2 Nothing tid1 !!! do
const 403 === statusCode
const "non-binding-team-members" === (Error.label . responseJsonUnsafeWithMsg "error label")
testCreateOne2OneWithMembers ::
HasCallStack =>
-- | Role of the user who creates the conversation
Role ->
TestM ()
testCreateOne2OneWithMembers (rolePermissions -> perms) = do
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
mem1 <- newTeamMember' perms <$> Util.randomUser
WS.bracketR c (mem1 ^. userId) $ \wsMem1 -> do
Util.addTeamMemberInternal tid (mem1 ^. userId) (mem1 ^. permissions) (mem1 ^. invitation)
checkTeamMemberJoin tid (mem1 ^. userId) wsMem1
assertTeamUpdate "team member join" tid 2 [owner]
void $ retryWhileN 10 repeatIf (Util.createOne2OneTeamConv owner (mem1 ^. userId) Nothing tid)
Recreating a One2One is a no - op , returns a 200
Util.createOne2OneTeamConv owner (mem1 ^. userId) Nothing tid !!! const 200 === statusCode
where
repeatIf :: ResponseLBS -> Bool
repeatIf r = statusCode r /= 201
-- | At the time of writing this test, the only event sent to this queue is 'MemberJoin'.
testTeamQueue :: TestM ()
testTeamQueue = do
(owner, tid) <- createBindingTeam
eventually $ do
queue <- getTeamQueue owner Nothing Nothing False
liftIO $ assertEqual "team queue: []" [] (snd <$> queue)
mem1 :: UserId <- view userId <$> addUserToTeam owner tid
eventually $ do
queue1 <- getTeamQueue owner Nothing Nothing False
queue2 <- getTeamQueue mem1 Nothing Nothing False
liftIO $ assertEqual "team queue: owner sees [mem1]" [mem1] (snd <$> queue1)
liftIO $ assertEqual "team queue: mem1 sees the same thing" queue1 queue2
mem2 :: UserId <- view userId <$> addUserToTeam owner tid
eventually $ do
known ' NotificationId 's
[(n1, u1), (n2, u2)] <- getTeamQueue owner Nothing Nothing False
liftIO $ assertEqual "team queue: queue0" (mem1, mem2) (u1, u2)
queue1 <- getTeamQueue owner (Just n1) Nothing False
queue2 <- getTeamQueue owner (Just n2) Nothing False
liftIO $ assertEqual "team queue: from 1" [mem1, mem2] (snd <$> queue1)
liftIO $ assertEqual "team queue: from 2" [mem2] (snd <$> queue2)
do
unknown old ' NotificationId '
let Just n1 = Id <$> UUID.fromText "615c4e38-950d-11ea-b0fc-7b04ea9f81c0"
queue <- getTeamQueue owner (Just n1) Nothing False
liftIO $ assertEqual "team queue: from old unknown" (snd <$> queue) [mem1, mem2]
do
unknown younger ' NotificationId '
[(Id n1, _), (Id n2, _)] <- getTeamQueue owner Nothing Nothing False
nu <-
create new UUIDv1 in the gap between n1 , n2 .
let Just time1 = UUID.extractTime n1
Just time2 = UUID.extractTime n2
timeu = time1 + (time2 - time1) `div` 2
in Id . fromJust . (`UUID.setTime` timeu) . fromJust <$> liftIO UUID.nextUUID
queue <- getTeamQueue owner (Just nu) Nothing False
liftIO $ assertEqual "team queue: from old unknown" (snd <$> queue) [mem2]
mem3 :: UserId <- view userId <$> addUserToTeam owner tid
mem4 :: UserId <- view userId <$> addUserToTeam owner tid
eventually $ do
-- response size limit
[_, (n2, _), _, _] <- getTeamQueue owner Nothing Nothing False
getTeamQueue' owner Nothing (Just (-1)) False !!! const 400 === statusCode
getTeamQueue' owner Nothing (Just 0) False !!! const 400 === statusCode
queue1 <- getTeamQueue owner (Just n2) (Just (1, True)) False
queue2 <- getTeamQueue owner (Just n2) (Just (2, False)) False
queue3 <- getTeamQueue owner (Just n2) (Just (3, False)) False
queue4 <- getTeamQueue owner Nothing (Just (1, True)) False
liftIO $ assertEqual "team queue: size limit 1" (snd <$> queue1) [mem2, mem3]
liftIO $ assertEqual "team queue: size limit 2" (snd <$> queue2) [mem2, mem3, mem4]
liftIO $ assertEqual "team queue: size limit 3" (snd <$> queue3) [mem2, mem3, mem4]
liftIO $ assertEqual "team queue: size limit 1, no start id" (snd <$> queue4) [mem1]
testAddTeamMemberInternal :: TestM ()
testAddTeamMemberInternal = do
c <- view tsCannon
(owner, tid) <- createBindingTeam
let p1 = Util.symmPermissions [GetBilling] -- permissions are irrelevant on internal endpoint
mem1 <- newTeamMember' p1 <$> Util.randomUser
WS.bracketRN c [owner, mem1 ^. userId] $ \[wsOwner, wsMem1] -> do
Util.addTeamMemberInternal tid (mem1 ^. userId) (mem1 ^. permissions) (mem1 ^. invitation)
liftIO . void $ mapConcurrently (checkJoinEvent tid (mem1 ^. userId)) [wsOwner, wsMem1]
assertTeamUpdate "team member join" tid 2 [owner]
void $ Util.getTeamMemberInternal tid (mem1 ^. userId)
testRemoveBindingTeamMember :: Bool -> TestM ()
testRemoveBindingTeamMember ownerHasPassword = do
localDomain <- viewFederationDomain
g <- viewGalley
c <- view tsCannon
Owner who creates the team must have an email , This is why we run all tests with a second
-- owner
(ownerWithPassword, tid) <- Util.createBindingTeam
ownerMem <-
if ownerHasPassword
then Util.addUserToTeam ownerWithPassword tid
else Util.addUserToTeamWithSSO True tid
assertTeamUpdate "second member join" tid 2 [ownerWithPassword]
refreshIndex
Util.makeOwner ownerWithPassword ownerMem tid
let owner = view userId ownerMem
assertTeamUpdate "second member promoted to owner" tid 2 [ownerWithPassword, owner]
refreshIndex
mext <- Util.randomUser
mem1 <- Util.addUserToTeam owner tid
assertTeamUpdate "team member join" tid 3 [ownerWithPassword, owner]
refreshIndex
Util.connectUsers owner (List1.singleton mext)
cid1 <- Util.createTeamConv owner tid [mem1 ^. userId, mext] (Just "blaa") Nothing Nothing
when ownerHasPassword $ do
-- Deleting from a binding team with empty body is invalid
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
)
!!! const 400
=== statusCode
-- Deleting from a binding team without a password is forbidden
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData Nothing)
)
!!! do
const 403 === statusCode
const "access-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
-- Deleting from a binding team with wrong password
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData (Just $ PlainTextPassword "wrong passwd"))
)
!!! do
const 403 === statusCode
const "access-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
Mem1 is still part of Wire
Util.ensureDeletedState False owner (mem1 ^. userId)
WS.bracketR2 c owner mext $ \(wsOwner, wsMext) -> do
if ownerHasPassword
then do
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData (Just $ Util.defPassword))
)
!!! const 202
=== statusCode
else do
-- Deleting from a binding team without a password is fine if the owner is
-- authenticated, but has none.
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData Nothing)
)
!!! const 202
=== statusCode
checkTeamMemberLeave tid (mem1 ^. userId) wsOwner
checkConvMemberLeaveEvent (Qualified cid1 localDomain) (Qualified (mem1 ^. userId) localDomain) wsMext
assertTeamUpdate "team member leave" tid 2 [ownerWithPassword, owner]
WS.assertNoEvent timeout [wsMext]
Mem1 is now gone from Wire
Util.ensureDeletedState True owner (mem1 ^. userId)
testRemoveBindingTeamOwner :: TestM ()
testRemoveBindingTeamOwner = do
(ownerA, tid) <- Util.createBindingTeam
refreshIndex
ownerB <-
view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) ownerA tid
assertTeamUpdate "Add owner" tid 2 [ownerA, ownerB]
refreshIndex
ownerWithoutEmail <- do
users must have a ' UserIdentity ' , or @get /i / users@ wo n't find it , so we use
-- 'UserSSOId'.
mem <- Util.addUserToTeamWithSSO False tid
refreshIndex
assertTeamUpdate "Add user with SSO" tid 3 [ownerA, ownerB]
Util.makeOwner ownerA mem tid
pure $ view userId mem
assertTeamUpdate "Promote user to owner" tid 3 [ownerA, ownerB, ownerWithoutEmail]
admin <-
view userId <$> Util.addUserToTeamWithRole (Just RoleAdmin) ownerA tid
assertTeamUpdate "Add admin" tid 4 [ownerA, ownerB, ownerWithoutEmail]
refreshIndex
-- non-owner can NOT delete owner
check tid admin ownerWithoutEmail (Just Util.defPassword) (Just "access-denied")
-- owners can NOT delete themselves
check tid ownerA ownerA (Just Util.defPassword) (Just "access-denied")
check tid ownerWithoutEmail ownerWithoutEmail Nothing (Just "access-denied")
-- owners can delete other owners (no matter who has emails)
check tid ownerWithoutEmail ownerA Nothing Nothing
Util.waitForMemberDeletion ownerB tid ownerA
assertTeamUpdate "Remove ownerA" tid 3 [ownerB, ownerWithoutEmail]
refreshIndex
check tid ownerB ownerWithoutEmail (Just Util.defPassword) Nothing
Util.waitForMemberDeletion ownerB tid ownerWithoutEmail
assertTeamUpdate "Remove ownerWithoutEmail" tid 2 [ownerB]
where
check :: HasCallStack => TeamId -> UserId -> UserId -> Maybe PlainTextPassword -> Maybe LText -> TestM ()
check tid deleter deletee pass maybeError = do
g <- viewGalley
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' deletee]
. zUser deleter
. zConn "conn"
. json (newTeamMemberDeleteData pass)
)
!!! case maybeError of
Nothing ->
const 202 === statusCode
Just label -> do
const 403 === statusCode
const label === (Error.label . responseJsonUnsafeWithMsg "error label")
testAddTeamConvLegacy :: TestM ()
testAddTeamConvLegacy = do
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
extern <- Util.randomUser
let p = Util.symmPermissions [CreateConversation, DoNotUseDeprecatedAddRemoveConvMember]
mem1 <- newTeamMember' p <$> Util.randomUser
mem2 <- newTeamMember' p <$> Util.randomUser
Util.connectUsers owner (list1 (mem1 ^. userId) [extern, mem2 ^. userId])
allUserIds <- for [owner, extern, mem1 ^. userId, mem2 ^. userId] $
\u -> Qualified u <$> viewFederationDomain
WS.bracketRN c (qUnqualified <$> allUserIds) $ \wss -> do
cid <- Util.createTeamConvLegacy owner tid (qUnqualified <$> allUserIds) (Just "blaa")
mapM_ (checkConvCreateEvent cid) wss
-- All members become admin by default
mapM_ (assertConvMemberWithRole roleNameWireAdmin cid) allUserIds
testAddTeamConvWithRole :: TestM ()
testAddTeamConvWithRole = do
c <- view tsCannon
(tid, owner, mem2 : _) <- Util.createBindingTeamWithMembers 2
qOwner <- Qualified owner <$> viewFederationDomain
extern <- Util.randomUser
qExtern <- Qualified extern <$> viewFederationDomain
Util.connectUsers owner (list1 extern [])
Util.connectUsers mem2 (list1 extern [])
WS.bracketRN c [owner, extern, mem2] $ \[wsOwner, wsExtern, wsMem2] -> do
-- Regular conversation:
cid2 <- Util.createTeamConvWithRole owner tid [extern] (Just "blaa") Nothing Nothing roleNameWireAdmin
checkConvCreateEvent cid2 wsOwner
checkConvCreateEvent cid2 wsExtern
mapM_ (assertConvMemberWithRole roleNameWireAdmin cid2) [qOwner, qExtern]
-- Regular conversation (using member role for participants):
cid3 <- Util.createTeamConvWithRole owner tid [extern] (Just "blaa") Nothing Nothing roleNameWireMember
checkConvCreateEvent cid3 wsOwner
checkConvCreateEvent cid3 wsExtern
assertConvMemberWithRole roleNameWireAdmin cid3 qOwner
assertConvMemberWithRole roleNameWireMember cid3 qExtern
-- mem2 is not a conversation member and no longer receives
-- an event that a new team conversation has been created
mem1 <- Util.addUserToTeam owner tid
checkTeamMemberJoin tid (mem1 ^. userId) wsOwner
checkTeamMemberJoin tid (mem1 ^. userId) wsMem2
-- ... but not to regular ones.
Util.assertNotConvMember (mem1 ^. userId) cid2
testCreateTeamMLSConv :: TestM ()
testCreateTeamMLSConv = do
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
lOwner <- flip toLocalUnsafe owner <$> viewFederationDomain
extern <- Util.randomUser
WS.bracketR2 c owner extern $ \(wsOwner, wsExtern) -> do
lConvId <-
Util.createMLSTeamConv
lOwner
(newClientId 0)
tid
mempty
(Just "Team MLS conversation")
Nothing
Nothing
Nothing
Nothing
Right conv <- responseJsonError <$> getConvQualified owner (tUntagged lConvId)
liftIO $ do
assertEqual "protocol mismatch" ProtocolMLSTag (protocolTag (cnvProtocol conv))
checkConvCreateEvent (tUnqualified lConvId) wsOwner
WS.assertNoEvent (2 # Second) [wsExtern]
testAddTeamConvAsExternalPartner :: TestM ()
testAddTeamConvAsExternalPartner = do
(owner, tid) <- Util.createBindingTeam
memMember1 <- Util.addUserToTeamWithRole (Just RoleMember) owner tid
assertTeamUpdate "team member join 2" tid 2 [owner]
refreshIndex
memMember2 <- Util.addUserToTeamWithRole (Just RoleMember) owner tid
assertTeamUpdate "team member join 3" tid 3 [owner]
refreshIndex
memExternalPartner <- Util.addUserToTeamWithRole (Just RoleExternalPartner) owner tid
assertTeamUpdate "team member join 4" tid 4 [owner]
refreshIndex
let acc = Just $ Set.fromList [InviteAccess, CodeAccess]
Util.createTeamConvAccessRaw
(memExternalPartner ^. userId)
tid
[memMember1 ^. userId, memMember2 ^. userId]
(Just "blaa")
acc
(Just (Set.fromList [TeamMemberAccessRole]))
Nothing
Nothing
!!! do
const 403 === statusCode
const "operation-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
testAddTeamMemberToConv :: TestM ()
testAddTeamMemberToConv = do
personalUser <- Util.randomUser
(ownerT1, qOwnerT1) <- Util.randomUserTuple
let p = Util.symmPermissions [DoNotUseDeprecatedAddRemoveConvMember]
mem1T1 <- Util.randomUser
qMem1T1 <- Qualified mem1T1 <$> viewFederationDomain
mem2T1 <- Util.randomUser
qMem2T1 <- Qualified mem2T1 <$> viewFederationDomain
let pEmpty = Util.symmPermissions []
mem3T1 <- Util.randomUser
qMem3T1 <- Qualified mem3T1 <$> viewFederationDomain
mem4T1 <- newTeamMember' pEmpty <$> Util.randomUser
qMem4T1 <- Qualified (mem4T1 ^. userId) <$> viewFederationDomain
(ownerT2, qOwnerT2) <- Util.randomUserTuple
mem1T2 <- newTeamMember' p <$> Util.randomUser
qMem1T2 <- Qualified (mem1T2 ^. userId) <$> viewFederationDomain
Util.connectUsers ownerT1 (list1 mem1T1 [mem2T1, mem3T1, ownerT2, personalUser])
tidT1 <- createBindingTeamInternal "foo" ownerT1
do
Util.addTeamMemberInternal tidT1 mem1T1 p Nothing
Util.addTeamMemberInternal tidT1 mem2T1 p Nothing
Util.addTeamMemberInternal tidT1 mem3T1 pEmpty Nothing
tidT2 <- Util.createBindingTeamInternal "foo" ownerT2
Util.addTeamMemberInternal tidT2 (mem1T2 ^. userId) (mem1T2 ^. permissions) (mem1T2 ^. invitation)
-- Team owners create new regular team conversation:
cidT1 <- Util.createTeamConv ownerT1 tidT1 [] (Just "blaa") Nothing Nothing
qcidT1 <- Qualified cidT1 <$> viewFederationDomain
cidT2 <- Util.createTeamConv ownerT2 tidT2 [] (Just "blaa") Nothing Nothing
qcidT2 <- Qualified cidT2 <$> viewFederationDomain
cidPersonal <- decodeConvId <$> Util.postConv personalUser [] (Just "blaa") [] Nothing Nothing
qcidPersonal <- Qualified cidPersonal <$> viewFederationDomain
-- NOTE: This functionality was _changed_ as there was no need for it...
-- mem1T1 (who is *not* a member of the new conversation) can *not* add other team members
-- despite being a team member and having the permission `DoNotUseDeprecatedAddRemoveConvMember`.
Util.assertNotConvMember mem1T1 cidT1
Util.postMembers mem1T1 (pure qMem2T1) qcidT1 !!! const 404 === statusCode
Util.assertNotConvMember mem2T1 cidT1
OTOH , mem3T1 _ can _ add another team member despite lacking the required team permission
-- since conversation roles trump any team roles. Note that all users are admins by default
Util.assertConvMember qOwnerT1 cidT1
Util.postMembers ownerT1 (pure qMem2T1) qcidT1 !!! const 200 === statusCode
Util.assertConvMember qMem2T1 cidT1
-- The following tests check the logic: users can add other users to a conversation
-- iff:
-- - *the adding user is connected to the users being added*
-- OR
-- - *the adding user is part of the team of the users being added*
-- Now we add someone from T2 that we are connected to
Util.postMembers ownerT1 (pure qOwnerT2) qcidT1 !!! const 200 === statusCode
Util.assertConvMember qOwnerT2 cidT1
-- And they can add their own team members
Util.postMembers ownerT2 (pure qMem1T2) qcidT1 !!! const 200 === statusCode
Util.assertConvMember qMem1T2 cidT1
-- Still, they cannot add random members without a connection from T1, despite the conversation being "hosted" there
Util.postMembers ownerT2 (pure qMem4T1) qcidT1 !!! const 403 === statusCode
Util.assertNotConvMember (mem4T1 ^. userId) cidT1
Now let 's look at convs hosted on team2
-- ownerT2 *is* connected to ownerT1
Util.postMembers ownerT2 (pure qOwnerT1) qcidT2 !!! const 200 === statusCode
Util.assertConvMember qOwnerT1 cidT2
-- and mem1T2 is on the same team, but mem1T1 is *not*
Util.postMembers ownerT2 (qMem1T2 :| [qMem1T1]) qcidT2 !!! const 403 === statusCode
Util.assertNotConvMember mem1T1 cidT2
Util.assertNotConvMember (mem1T2 ^. userId) cidT2
-- mem1T2 is on the same team, so that is fine too
Util.postMembers ownerT2 (pure qMem1T2) qcidT2 !!! const 200 === statusCode
Util.assertConvMember qMem1T2 cidT2
-- ownerT2 is *NOT* connected to mem3T1 and not on the same team, so should not be allowed to add
Util.postMembers ownerT2 (pure qMem3T1) qcidT2 !!! const 403 === statusCode
Util.assertNotConvMember mem3T1 cidT2
-- For personal conversations, same logic applies
-- Can add connected users
Util.postMembers personalUser (pure qOwnerT1) qcidPersonal !!! const 200 === statusCode
Util.assertConvMember qOwnerT1 cidPersonal
-- Can *not* add users that are *not* connected
Util.postMembers personalUser (pure qOwnerT2) qcidPersonal !!! const 403 === statusCode
Util.assertNotConvMember ownerT2 cidPersonal
Users of the same team can add one another
Util.postMembers ownerT1 (pure qMem1T1) qcidPersonal !!! const 200 === statusCode
Util.assertConvMember qMem1T1 cidPersonal
-- Users can not add across teams if *not* connected
Util.postMembers mem1T1 (pure qOwnerT2) qcidPersonal !!! const 403 === statusCode
Util.assertNotConvMember ownerT2 cidPersonal
-- Users *can* add across teams if *connected*
Util.postMembers ownerT1 (pure qOwnerT2) qcidPersonal !!! const 200 === statusCode
Util.assertConvMember qOwnerT2 cidPersonal
testUpdateTeamConv ::
-- | Team role of the user who creates the conversation
Role ->
-- | Conversation role of the user who creates the conversation
RoleName ->
TestM ()
testUpdateTeamConv _ convRole = do
(tid, owner, member : _) <- Util.createBindingTeamWithMembers 2
cid <- Util.createTeamConvWithRole owner tid [member] (Just "gossip") Nothing Nothing convRole
resp <- updateTeamConv member cid (ConversationRename "not gossip")
-- FUTUREWORK: Ensure that the team role _really_ does not matter
liftIO $ assertEqual "status conv" convRoleCheck (statusCode resp)
where
convRoleCheck = if isActionAllowed ModifyConversationName convRole == Just True then 200 else 403
testDeleteBindingTeamSingleMember :: TestM ()
testDeleteBindingTeamSingleMember = do
g <- viewGalley
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
other <- Util.addUserToTeam owner tid
assertTeamUpdate "team member leave 1" tid 2 [owner]
refreshIndex
-- Useful for tests
extern <- Util.randomUser
delete
( g
. paths ["/i/teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json (newTeamDeleteData (Just $ Util.defPassword))
)
!!! do
const 403 === statusCode
const "not-one-member-team" === (Error.label . responseJsonUnsafeWithMsg "error label when deleting a team")
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (other ^. userId)]
. zUser owner
. zConn "conn"
. json
( newTeamMemberDeleteData (Just Util.defPassword)
)
)
!!! const 202
=== statusCode
assertTeamUpdate "team member leave 1" tid 1 [owner]
-- Async things are hard...
void $
retryWhileN
10
(/= Just True)
(getDeletedState extern (other ^. userId))
void . WS.bracketRN c [owner, extern] $ \[wsOwner, wsExtern] -> do
delete
( g
. paths ["/i/teams", toByteString' tid]
. zUser owner
. zConn "conn"
)
!!! const 202
=== statusCode
checkUserDeleteEvent owner wsOwner
WS.assertNoEvent (1 # Second) [wsExtern]
-- Note that given the async nature of team deletion, we may
-- have other events in the queue (such as TEAM_UPDATE)
assertTeamDelete 10 "team delete, should be there" tid
-- Ensure users are marked as deleted; since we already
-- received the event, should _really_ be deleted
-- Let's clean the queue, just in case
Util.ensureDeletedState True extern owner
testDeleteBindingTeamNoMembers :: TestM ()
testDeleteBindingTeamNoMembers = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam
deleteUser owner !!! const 200 === statusCode
refreshIndex
delete (g . paths ["/i/teams", toByteString' tid]) !!! const 202 === statusCode
assertTeamDelete 10 "team delete, should be there" tid
testDeleteBindingTeamMoreThanOneMember :: TestM ()
testDeleteBindingTeamMoreThanOneMember = do
g <- viewGalley
b <- viewBrig
c <- view tsCannon
(alice, tid, members) <- Util.createBindingTeamWithNMembers 10
void . WS.bracketRN c (alice : members) $ \(wsAlice : wsMembers) -> do
deleting a team with more than one member should be forbidden
delete (g . paths ["/i/teams", toByteString' tid]) !!! do
const 403 === statusCode
const "not-one-member-team" === (Error.label . responseJsonUnsafeWithMsg "error label when deleting a team")
-- now try again with the 'force' query flag, which should work
delete (g . paths ["/i/teams", toByteString' tid] . queryItem "force" "true") !!! do
const 202 === statusCode
checkUserDeleteEvent alice wsAlice
zipWithM_ checkUserDeleteEvent members wsMembers
assertTeamDelete 10 "team delete, should be there" tid
let ensureDeleted :: UserId -> TestM ()
ensureDeleted uid = do
resp <- get (b . paths ["/i/users", toByteString' uid, "status"]) <!! const 200 === statusCode
let mbStatus = fmap fromAccountStatusResp . responseJsonUnsafe $ resp
liftIO $ mbStatus @?= Just Brig.Deleted
ensureDeleted alice
for_ members ensureDeleted
testDeleteTeamVerificationCodeSuccess :: TestM ()
testDeleteTeamVerificationCodeSuccess = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam'
let Just email = U.userEmail owner
setFeatureLockStatus @Public.SndFactorPasswordChallengeConfig tid Public.LockStatusUnlocked
setTeamSndFactorPasswordChallenge tid Public.FeatureStatusEnabled
generateVerificationCode $ Public.SendVerificationCode Public.DeleteTeam email
code <- getVerificationCode (U.userId owner) Public.DeleteTeam
delete
( g
. paths ["teams", toByteString' tid]
. zUser (U.userId owner)
. zConn "conn"
. json (newTeamDeleteDataWithCode (Just Util.defPassword) (Just code))
)
!!! do
const 202 === statusCode
assertTeamDelete 10 "team delete, should be there" tid
@SF.Channel @TSFI.RESTfulAPI @S2
--
Test that team can not be deleted with missing second factor email verification code when this feature is enabled
testDeleteTeamVerificationCodeMissingCode :: TestM ()
testDeleteTeamVerificationCodeMissingCode = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam'
setFeatureLockStatus @Public.SndFactorPasswordChallengeConfig tid Public.LockStatusUnlocked
setTeamSndFactorPasswordChallenge tid Public.FeatureStatusEnabled
let Just email = U.userEmail owner
generateVerificationCode $ Public.SendVerificationCode Public.DeleteTeam email
delete
( g
. paths ["teams", toByteString' tid]
. zUser (U.userId owner)
. zConn "conn"
. json (newTeamMemberDeleteData (Just Util.defPassword))
)
!!! do
const 403 === statusCode
const "code-authentication-required" === (Error.label . responseJsonUnsafeWithMsg "error label")
@END
@SF.Channel @TSFI.RESTfulAPI @S2
--
Test that team can not be deleted with expired second factor email verification code when this feature is enabled
testDeleteTeamVerificationCodeExpiredCode :: TestM ()
testDeleteTeamVerificationCodeExpiredCode = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam'
setFeatureLockStatus @Public.SndFactorPasswordChallengeConfig tid Public.LockStatusUnlocked
setTeamSndFactorPasswordChallenge tid Public.FeatureStatusEnabled
let Just email = U.userEmail owner
generateVerificationCode $ Public.SendVerificationCode Public.DeleteTeam email
code <- getVerificationCode (U.userId owner) Public.DeleteTeam
wait > 5 sec for the code to expire ( assumption : setVerificationTimeout in brig.integration.yaml is set to < = 5 sec )
threadDelay $ (10 * 1000 * 1000) + 600 * 1000
delete
( g
. paths ["teams", toByteString' tid]
. zUser (U.userId owner)
. zConn "conn"
. json (newTeamDeleteDataWithCode (Just Util.defPassword) (Just code))
)
!!! do
const 403 === statusCode
const "code-authentication-failed" === (Error.label . responseJsonUnsafeWithMsg "error label")
@END
@SF.Channel @TSFI.RESTfulAPI @S2
--
Test that team can not be deleted with wrong second factor email verification code when this feature is enabled
testDeleteTeamVerificationCodeWrongCode :: TestM ()
testDeleteTeamVerificationCodeWrongCode = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam'
setFeatureLockStatus @Public.SndFactorPasswordChallengeConfig tid Public.LockStatusUnlocked
setTeamSndFactorPasswordChallenge tid Public.FeatureStatusEnabled
let Just email = U.userEmail owner
generateVerificationCode $ Public.SendVerificationCode Public.DeleteTeam email
let wrongCode = Code.Value $ unsafeRange (fromRight undefined (validate "123456"))
delete
( g
. paths ["teams", toByteString' tid]
. zUser (U.userId owner)
. zConn "conn"
. json (newTeamDeleteDataWithCode (Just Util.defPassword) (Just wrongCode))
)
!!! do
const 403 === statusCode
const "code-authentication-failed" === (Error.label . responseJsonUnsafeWithMsg "error label")
@END
setFeatureLockStatus :: forall cfg. (KnownSymbol (Public.FeatureSymbol cfg)) => TeamId -> Public.LockStatus -> TestM ()
setFeatureLockStatus tid status = do
g <- viewGalley
put (g . paths ["i", "teams", toByteString' tid, "features", Public.featureNameBS @cfg, toByteString' status]) !!! const 200 === statusCode
generateVerificationCode :: Public.SendVerificationCode -> TestM ()
generateVerificationCode req = do
brig <- viewBrig
let js = RequestBodyLBS $ encode req
post (brig . paths ["verification-code", "send"] . contentJson . body js) !!! const 200 === statusCode
setTeamSndFactorPasswordChallenge :: TeamId -> Public.FeatureStatus -> TestM ()
setTeamSndFactorPasswordChallenge tid status = do
g <- viewGalley
let js = RequestBodyLBS $ encode $ Public.WithStatusNoLock status Public.SndFactorPasswordChallengeConfig Public.FeatureTTLUnlimited
put (g . paths ["i", "teams", toByteString' tid, "features", Public.featureNameBS @Public.SndFactorPasswordChallengeConfig] . contentJson . body js) !!! const 200 === statusCode
getVerificationCode :: UserId -> Public.VerificationAction -> TestM Code.Value
getVerificationCode uid action = do
brig <- viewBrig
resp <-
get (brig . paths ["i", "users", toByteString' uid, "verification-code", toByteString' action])
<!! const 200
=== statusCode
pure $ responseJsonUnsafe @Code.Value resp
testDeleteBindingTeam :: Bool -> TestM ()
testDeleteBindingTeam ownerHasPassword = do
g <- viewGalley
c <- view tsCannon
(ownerWithPassword, tid) <- Util.createBindingTeam
ownerMem <-
if ownerHasPassword
then Util.addUserToTeam ownerWithPassword tid
else Util.addUserToTeamWithSSO True tid
assertTeamUpdate "team member join 2" tid 2 [ownerWithPassword]
refreshIndex
Util.makeOwner ownerWithPassword ownerMem tid
let owner = view userId ownerMem
assertTeamUpdate "team member promoted" tid 2 [ownerWithPassword, owner]
refreshIndex
mem1 <- Util.addUserToTeam owner tid
assertTeamUpdate "team member join 3" tid 3 [ownerWithPassword, owner]
refreshIndex
mem2 <- Util.addUserToTeam owner tid
assertTeamUpdate "team member join 4" tid 4 [ownerWithPassword, owner]
refreshIndex
mem3 <- Util.addUserToTeam owner tid
assertTeamUpdate "team member join 5" tid 5 [ownerWithPassword, owner]
refreshIndex
extern <- Util.randomUser
delete
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json (newTeamDeleteData (Just $ PlainTextPassword "wrong passwd"))
)
!!! do
const 403 === statusCode
const "access-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem3 ^. userId)]
. zUser owner
. zConn "conn"
. json
( newTeamMemberDeleteData
( if ownerHasPassword
then Just Util.defPassword
else Nothing
)
)
)
!!! const 202
=== statusCode
assertTeamUpdate "team member leave 1" tid 4 [ownerWithPassword, owner]
void . WS.bracketRN c [owner, mem1 ^. userId, mem2 ^. userId, extern] $ \[wsOwner, wsMember1, wsMember2, wsExtern] -> do
delete
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json
( newTeamDeleteData
( if ownerHasPassword
then Just Util.defPassword
else Nothing
)
)
)
!!! const 202
=== statusCode
checkUserDeleteEvent owner wsOwner
checkUserDeleteEvent (mem1 ^. userId) wsMember1
checkUserDeleteEvent (mem2 ^. userId) wsMember2
checkTeamDeleteEvent tid wsOwner
checkTeamDeleteEvent tid wsMember1
checkTeamDeleteEvent tid wsMember2
WS.assertNoEvent (1 # Second) [wsExtern]
-- Note that given the async nature of team deletion, we may
-- have other events in the queue (such as TEAM_UPDATE)
assertTeamDelete 10 "team delete, should be there" tid
forM_ [owner, mem1 ^. userId, mem2 ^. userId] $
-- Ensure users are marked as deleted; since we already
-- received the event, should _really_ be deleted
Util.ensureDeletedState True extern
testDeleteTeamConv :: TestM ()
testDeleteTeamConv = do
localDomain <- viewFederationDomain
c <- view tsCannon
(tid, owner, _) <- Util.createBindingTeamWithMembers 2
qOwner <- Qualified owner <$> viewFederationDomain
let p = Util.symmPermissions [DoNotUseDeprecatedDeleteConversation]
member <- newTeamMember' p <$> Util.randomUser
qMember <- Qualified (member ^. userId) <$> viewFederationDomain
Util.addTeamMemberInternal tid (member ^. userId) (member ^. permissions) Nothing
let members = [qOwner, qMember]
extern <- Util.randomUser
qExtern <- Qualified extern <$> viewFederationDomain
for_ members $ \m -> Util.connectUsers (m & qUnqualified) (list1 extern [])
cid1 <- Util.createTeamConv owner tid [] (Just "blaa") Nothing Nothing
qcid1 <- Qualified cid1 <$> viewFederationDomain
let access = ConversationAccessData (Set.fromList [InviteAccess, CodeAccess]) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole])
putQualifiedAccessUpdate owner qcid1 access !!! const 200 === statusCode
code <- decodeConvCodeEvent <$> (postConvCode owner cid1 <!! const 201 === statusCode)
cid2 <- Util.createTeamConv owner tid (qUnqualified <$> members) (Just "blup") Nothing Nothing
Util.postMembers owner (qExtern :| [qMember]) qcid1 !!! const 200 === statusCode
for_ (qExtern : members) $ \u -> Util.assertConvMember u cid1
for_ members $ flip Util.assertConvMember cid2
WS.bracketR3 c owner extern (member ^. userId) $ \(wsOwner, wsExtern, wsMember) -> do
deleteTeamConv tid cid2 (member ^. userId)
!!! const 200
=== statusCode
-- We no longer send duplicate conv deletion events
i.e. , as both a regular " conversation.delete " to all
-- conversation members and as "team.conversation-delete"
-- to all team members not part of the conversation
let qcid2 = Qualified cid2 localDomain
checkConvDeleteEvent qcid2 wsOwner
checkConvDeleteEvent qcid2 wsMember
WS.assertNoEvent timeout [wsOwner, wsMember]
deleteTeamConv tid cid1 (member ^. userId)
!!! const 200
=== statusCode
-- We no longer send duplicate conv deletion events
i.e. , as both a regular " conversation.delete " to all
-- conversation members and as "team.conversation-delete"
-- to all team members not part of the conversation
checkConvDeleteEvent qcid1 wsOwner
checkConvDeleteEvent qcid1 wsMember
checkConvDeleteEvent qcid1 wsExtern
WS.assertNoEvent timeout [wsOwner, wsMember, wsExtern]
for_ [cid1, cid2] $ \x ->
for_ [owner, member ^. userId, extern] $ \u -> do
Util.getConv u x !!! const 404 === statusCode
Util.assertNotConvMember u x
postConvCodeCheck code !!! const 404 === statusCode
testUpdateTeamIconValidation :: TestM ()
testUpdateTeamIconValidation = do
g <- viewGalley
(tid, owner, _) <- Util.createBindingTeamWithMembers 2
let update payload expectedStatusCode =
put
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json payload
)
!!! const expectedStatusCode
=== statusCode
let payloadWithInvalidIcon = object ["name" .= String "name", "icon" .= String "invalid"]
update payloadWithInvalidIcon 400
let payloadWithValidIcon =
object
[ "name" .= String "name",
"icon" .= String "3-1-47de4580-ae51-4650-acbb-d10c028cb0ac"
]
update payloadWithValidIcon 200
let payloadSetIconToDefault = object ["icon" .= String "default"]
update payloadSetIconToDefault 200
testUpdateTeam :: TestM ()
testUpdateTeam = do
g <- viewGalley
c <- view tsCannon
(tid, owner, [member]) <- Util.createBindingTeamWithMembers 2
let doPut :: LByteString -> Int -> TestM ()
doPut payload code =
put
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. contentJson
. body (RequestBodyLBS payload)
)
!!! const code
=== statusCode
let bad = object ["name" .= T.replicate 100 "too large"]
doPut (encode bad) 400
let u =
newTeamUpdateData
& nameUpdate ?~ unsafeRange "bar"
& iconUpdate .~ fromByteString "3-1-47de4580-ae51-4650-acbb-d10c028cb0ac"
& iconKeyUpdate ?~ unsafeRange "yyy"
& splashScreenUpdate .~ fromByteString "3-1-e1c89a56-882e-4694-bab3-c4f57803c57a"
WS.bracketR2 c owner member $ \(wsOwner, wsMember) -> do
doPut (encode u) 200
checkTeamUpdateEvent tid u wsOwner
checkTeamUpdateEvent tid u wsMember
WS.assertNoEvent timeout [wsOwner, wsMember]
t <- Util.getTeam owner tid
liftIO $ assertEqual "teamSplashScreen" (t ^. teamSplashScreen) (fromJust $ fromByteString "3-1-e1c89a56-882e-4694-bab3-c4f57803c57a")
do
-- setting fields to `null` is the same as omitting the them from the update json record.
-- ("name" is set because a completely empty update object is rejected.)
doPut "{\"name\": \"new team name\", \"splash_screen\": null}" 200
t' <- Util.getTeam owner tid
liftIO $ assertEqual "teamSplashScreen" (t' ^. teamSplashScreen) (fromJust $ fromByteString "3-1-e1c89a56-882e-4694-bab3-c4f57803c57a")
do
-- setting splash screen to `"default"` will delete the splash screen.
doPut "{\"splash_screen\": \"default\"}" 200
t' <- Util.getTeam owner tid
liftIO $ assertEqual "teamSplashScreen" (t' ^. teamSplashScreen) DefaultIcon
testTeamAddRemoveMemberAboveThresholdNoEvents :: HasCallStack => TestM ()
testTeamAddRemoveMemberAboveThresholdNoEvents = do
localDomain <- viewFederationDomain
o <- view tsGConf
c <- view tsCannon
let fanoutLimit = fromIntegral . fromRange $ Galley.currentFanoutLimit o
(owner, tid) <- Util.createBindingTeam
member1 <- addTeamMemberAndExpectEvent True tid owner
Now last fill the team until truncationSize - 2
replicateM_ (fanoutLimit - 4) $ Util.addUserToTeam owner tid
(extern, qextern) <- Util.randomUserTuple
modifyTeamDataAndExpectEvent True tid owner
-- Let's create and remove a member
member2 <- do
temp <- addTeamMemberAndExpectEvent True tid owner
Util.connectUsers extern (list1 temp [])
removeTeamMemberAndExpectEvent True owner tid temp [extern]
addTeamMemberAndExpectEvent True tid owner
modifyUserProfileAndExpectEvent True owner [member1, member2]
-- Let's connect an external to test the different behavior
Util.connectUsers extern (list1 owner [member1, member2])
_memLastWithFanout <- addTeamMemberAndExpectEvent True tid owner
-- We should really wait until we see that the team is of full size
Due to the async nature of pushes , waiting even a second might not
-- be enough...
WS.bracketR c owner $ \wsOwner -> WS.assertNoEvent (1 # Second) [wsOwner]
-- No events are now expected
-- Team member added also not
_memWithoutFanout <- addTeamMemberAndExpectEvent False tid owner
-- Team updates are not propagated
modifyTeamDataAndExpectEvent False tid owner
-- User event updates are not propagated in the team
modifyUserProfileAndExpectEvent False owner [member1, member2]
Let us remove 1 member that exceeds the limit , verify that team users
-- do not get the deletion event but the connections do!
removeTeamMemberAndExpectEvent False owner tid member2 [extern]
-- Now we are just on the limit, events are back!
removeTeamMemberAndExpectEvent True owner tid member1 [extern]
-- Let's go back to having a very large team
_memLastWithFanout <- addTeamMemberAndExpectEvent True tid owner
-- We should really wait until we see that the team is of full size
Due to the async nature of pushes , waiting even a second might not
-- be enough...
WS.bracketR c owner $ \wsOwner -> WS.assertNoEvent (1 # Second) [wsOwner]
_memWithoutFanout <- addTeamMemberAndExpectEvent False tid owner
-- Add extern to a team conversation
cid1 <- Util.createTeamConv owner tid [] (Just "blaa") Nothing Nothing
qcid1 <- Qualified cid1 <$> viewFederationDomain
Util.postMembers owner (pure qextern) qcid1 !!! const 200 === statusCode
-- Test team deletion (should contain only conv. removal and user.deletion for _non_ team members)
deleteTeam tid owner [] [Qualified cid1 localDomain] extern
where
modifyUserProfileAndExpectEvent :: HasCallStack => Bool -> UserId -> [UserId] -> TestM ()
modifyUserProfileAndExpectEvent expect target listeners = do
c <- view tsCannon
b <- viewBrig
WS.bracketRN c listeners $ \wsListeners -> do
-- Do something
let u = U.UserUpdate (Just $ U.Name "name") Nothing Nothing Nothing
put
( b
. paths ["self"]
. zUser target
. zConn "conn"
. json u
)
!!! const 200
=== statusCode
if expect
then mapM_ (checkUserUpdateEvent target) wsListeners
else WS.assertNoEvent (1 # Second) wsListeners
modifyTeamDataAndExpectEvent :: HasCallStack => Bool -> TeamId -> UserId -> TestM ()
modifyTeamDataAndExpectEvent expect tid origin = do
c <- view tsCannon
g <- viewGalley
let u = newTeamUpdateData & nameUpdate ?~ unsafeRange "bar"
WS.bracketR c origin $ \wsOrigin -> do
put
( g
. paths ["teams", toByteString' tid]
. zUser origin
. zConn "conn"
. json u
)
!!! const 200
=== statusCode
-- Due to the fact that the team is too large, we expect no events!
if expect
then checkTeamUpdateEvent tid u wsOrigin
else WS.assertNoEvent (1 # Second) [wsOrigin]
addTeamMemberAndExpectEvent :: HasCallStack => Bool -> TeamId -> UserId -> TestM UserId
addTeamMemberAndExpectEvent expect tid origin = do
c <- view tsCannon
WS.bracketR c origin $ \wsOrigin -> do
member <- view userId <$> Util.addUserToTeam origin tid
refreshIndex
if expect
then checkTeamMemberJoin tid member wsOrigin
else WS.assertNoEvent (1 # Second) [wsOrigin]
pure member
removeTeamMemberAndExpectEvent :: HasCallStack => Bool -> UserId -> TeamId -> UserId -> [UserId] -> TestM ()
removeTeamMemberAndExpectEvent expect owner tid victim others = do
c <- view tsCannon
g <- viewGalley
WS.bracketRN c (owner : victim : others) $ \(wsOwner : _wsVictim : wsOthers) -> do
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' victim]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData (Just $ Util.defPassword))
)
!!! const 202
=== statusCode
if expect
then checkTeamMemberLeave tid victim wsOwner
else WS.assertNoEvent (1 # Second) [wsOwner]
-- User deletion events
mapM_ (checkUserDeleteEvent victim) wsOthers
Util.ensureDeletedState True owner victim
deleteTeam :: HasCallStack => TeamId -> UserId -> [UserId] -> [Qualified ConvId] -> UserId -> TestM ()
deleteTeam tid owner otherRealUsersInTeam teamCidsThatExternBelongsTo extern = do
c <- view tsCannon
g <- viewGalley
void . WS.bracketRN c (owner : extern : otherRealUsersInTeam) $ \(_wsOwner : wsExtern : _wsotherRealUsersInTeam) -> do
delete
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json (newTeamDeleteData (Just Util.defPassword))
)
!!! const 202
=== statusCode
for_ (owner : otherRealUsersInTeam) $ \u -> checkUserDeleteEvent u wsExtern
-- Ensure users are marked as deleted; since we already
-- received the event, should _really_ be deleted
for_ (owner : otherRealUsersInTeam) $ Util.ensureDeletedState True extern
mapM_ (flip checkConvDeleteEvent wsExtern) teamCidsThatExternBelongsTo
-- ensure the team has a deleted status
void $
retryWhileN
10
((/= TeamsIntra.Deleted) . TeamsIntra.tdStatus)
(getTeamInternal tid)
testBillingInLargeTeam :: TestM ()
testBillingInLargeTeam = do
(firstOwner, team) <- Util.createBindingTeam
refreshIndex
opts <- view tsGConf
galley <- viewGalley
let fanoutLimit = fromRange $ Galley.currentFanoutLimit opts
allOwnersBeforeFanoutLimit <-
foldM
( \billingMembers n -> do
newBillingMemberId <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
let allBillingMembers = newBillingMemberId : billingMembers
assertTeamUpdate ("add " <> show n <> "th billing member: " <> show newBillingMemberId) team n allBillingMembers
refreshIndex
pure allBillingMembers
)
[firstOwner]
[2 .. (fanoutLimit + 1)]
-- Additions after the fanout limit should still send events to all owners
ownerFanoutPlusTwo <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate ("add fanoutLimit + 2nd billing member: " <> show ownerFanoutPlusTwo) team (fanoutLimit + 2) (ownerFanoutPlusTwo : allOwnersBeforeFanoutLimit)
refreshIndex
-- Deletions after the fanout limit should still send events to all owners
ownerFanoutPlusThree <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate ("add fanoutLimit + 3rd billing member: " <> show ownerFanoutPlusThree) team (fanoutLimit + 3) (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusTwo, ownerFanoutPlusThree])
refreshIndex
Util.deleteTeamMember galley team firstOwner ownerFanoutPlusThree
assertTeamUpdate ("delete fanoutLimit + 3rd billing member: " <> show ownerFanoutPlusThree) team (fanoutLimit + 2) (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusTwo])
refreshIndex
testBillingInLargeTeamWithoutIndexedBillingTeamMembers :: TestM ()
testBillingInLargeTeamWithoutIndexedBillingTeamMembers = do
(firstOwner, team) <- Util.createBindingTeam
refreshIndex
opts <- view tsGConf
galley <- viewGalley
let withoutIndexedBillingTeamMembers =
withSettingsOverrides (\o -> o & optSettings . setEnableIndexedBillingTeamMembers ?~ False)
let fanoutLimit = fromRange $ Galley.currentFanoutLimit opts
-- Billing should work properly upto fanout limit
billingUsers <- mapM (\n -> (n,) <$> randomUser) [2 .. (fanoutLimit + 1)]
allOwnersBeforeFanoutLimit <-
withoutIndexedBillingTeamMembers $
foldM
( \billingMembers (n, newBillingMemberId) -> do
let mem = json $ Member.mkNewTeamMember newBillingMemberId (rolePermissions RoleOwner) Nothing
-- We cannot add the new owner with an invite as we don't have a way
-- to override galley settings while making a call to brig, so we use
-- the internal API here.
post (galley . paths ["i", "teams", toByteString' team, "members"] . mem)
!!! const 200
=== statusCode
let allBillingMembers = newBillingMemberId : billingMembers
-- We don't make a call to brig to add member, this prevents new
members from being indexed . Hence the count of team is always 2
assertTeamUpdate ("add " <> show n <> "th billing member: " <> show newBillingMemberId) team 2 allBillingMembers
pure allBillingMembers
)
[firstOwner]
billingUsers
refreshIndex
If we add another owner , one of them wo n't get notified
ownerFanoutPlusTwo <- randomUser
let memFanoutPlusTwo = json $ Member.mkNewTeamMember ownerFanoutPlusTwo (rolePermissions RoleOwner) Nothing
-- We cannot add the new owner with an invite as we don't have a way to
-- override galley settings while making a call to brig, so we use the
-- internal API here.
withoutIndexedBillingTeamMembers $ do
g <- viewGalley
post (g . paths ["i", "teams", toByteString' team, "members"] . memFanoutPlusTwo)
!!! const 200
=== statusCode
assertIfWatcher ("add " <> show (fanoutLimit + 2) <> "th billing member: " <> show ownerFanoutPlusTwo) (updateMatcher team) $
\s maybeEvent ->
liftIO $ case maybeEvent of
Nothing -> assertFailure "Expected 1 TeamUpdate, got nothing"
Just event -> do
assertEqual (s <> ": eventType") E.TeamEvent'TEAM_UPDATE (event ^. E.eventType)
assertEqual (s <> ": count") 2 (event ^. E.eventData . E.memberCount)
let reportedBillingUserIds = mapMaybe (UUID.fromByteString . fromStrict) (event ^. E.eventData . E.billingUser)
assertEqual (s <> ": number of billing users") (fromIntegral fanoutLimit + 1) (length reportedBillingUserIds)
refreshIndex
-- While members are added with indexedBillingTeamMembers disabled, new owners must still be
-- indexed, just not used. When the feature is enabled, we should be able to send billing to
-- all the owners
ownerFanoutPlusThree <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate
("add fanoutLimit + 3rd billing member: " <> show ownerFanoutPlusThree)
team
2
(allOwnersBeforeFanoutLimit <> [ownerFanoutPlusTwo, ownerFanoutPlusThree])
refreshIndex
-- Deletions with indexedBillingTeamMembers disabled should still remove owners from the
-- indexed table
withoutIndexedBillingTeamMembers $ Util.deleteTeamMember galley team firstOwner ownerFanoutPlusTwo
Util.waitForMemberDeletion firstOwner team ownerFanoutPlusTwo
assertTeamUpdate "delete 1 owner" team 1 (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusThree])
ownerFanoutPlusFour <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate
("add billing member to test deletion: " <> show ownerFanoutPlusFour)
team
3
(allOwnersBeforeFanoutLimit <> [ownerFanoutPlusThree, ownerFanoutPlusFour])
refreshIndex
-- Promotions and demotion should also be kept track of regardless of feature being enabled
let demoteFanoutPlusThree = Member.mkNewTeamMember ownerFanoutPlusThree (rolePermissions RoleAdmin) Nothing
withoutIndexedBillingTeamMembers $ updateTeamMember galley team firstOwner demoteFanoutPlusThree !!! const 200 === statusCode
assertTeamUpdate "demote 1 user" team 3 (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusFour])
ownerFanoutPlusFive <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate
("add billing member to test demotion: " <> show ownerFanoutPlusFive)
team
4
(allOwnersBeforeFanoutLimit <> [ownerFanoutPlusFour, ownerFanoutPlusFive])
refreshIndex
let promoteFanoutPlusThree = Member.mkNewTeamMember ownerFanoutPlusThree (rolePermissions RoleOwner) Nothing
withoutIndexedBillingTeamMembers $ updateTeamMember galley team firstOwner promoteFanoutPlusThree !!! const 200 === statusCode
assertTeamUpdate "demote 1 user" team 4 (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusThree, ownerFanoutPlusFour, ownerFanoutPlusFive])
ownerFanoutPlusSix <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate
("add billing member to test promotion: " <> show ownerFanoutPlusSix)
team
5
(allOwnersBeforeFanoutLimit <> [ownerFanoutPlusThree, ownerFanoutPlusFour, ownerFanoutPlusFive, ownerFanoutPlusSix])
where
updateTeamMember g tid zusr change =
put
( g
. paths ["teams", toByteString' tid, "members"]
. zUser zusr
. zConn "conn"
. json change
)
| @SF.Management @TSFI.RESTfulAPI @S2
-- This test covers:
-- Promotion, demotion of team roles.
-- Demotion by superior roles is allowed.
-- Demotion by inferior roles is NOT allowed.
testUpdateTeamMember :: TestM ()
testUpdateTeamMember = do
g <- viewGalley
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
member <- Util.addUserToTeamWithRole (Just RoleAdmin) owner tid
assertTeamUpdate "add member" tid 2 [owner]
refreshIndex
-- non-owner can **NOT** demote owner
let demoteOwner = Member.mkNewTeamMember owner (rolePermissions RoleAdmin) Nothing
updateTeamMember g tid (member ^. userId) demoteOwner !!! do
const 403 === statusCode
const "access-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
-- owner can demote non-owner
let demoteMember = Member.mkNewTeamMember (member ^. userId) noPermissions (member ^. invitation)
WS.bracketR2 c owner (member ^. userId) $ \(wsOwner, wsMember) -> do
updateTeamMember g tid owner demoteMember !!! do
const 200 === statusCode
member' <- Util.getTeamMember owner tid (member ^. userId)
liftIO $ assertEqual "permissions" (member' ^. permissions) (demoteMember ^. nPermissions)
checkTeamMemberUpdateEvent tid (member ^. userId) wsOwner (pure noPermissions)
checkTeamMemberUpdateEvent tid (member ^. userId) wsMember (pure noPermissions)
WS.assertNoEvent timeout [wsOwner, wsMember]
assertTeamUpdate "Member demoted" tid 2 [owner]
-- owner can promote non-owner
let promoteMember = Member.mkNewTeamMember (member ^. userId) fullPermissions (member ^. invitation)
WS.bracketR2 c owner (member ^. userId) $ \(wsOwner, wsMember) -> do
updateTeamMember g tid owner promoteMember !!! do
const 200 === statusCode
member' <- Util.getTeamMember owner tid (member ^. userId)
liftIO $ assertEqual "permissions" (member' ^. permissions) (promoteMember ^. nPermissions)
checkTeamMemberUpdateEvent tid (member ^. userId) wsOwner (pure fullPermissions)
checkTeamMemberUpdateEvent tid (member ^. userId) wsMember (pure fullPermissions)
WS.assertNoEvent timeout [wsOwner, wsMember]
assertTeamUpdate "Member promoted to owner" tid 2 [owner, member ^. userId]
-- owner can **NOT** demote herself, even when another owner exists
updateTeamMember g tid owner demoteOwner !!! do
const 403 === statusCode
-- Now that the other member has full permissions, she can demote the owner
WS.bracketR2 c (member ^. userId) owner $ \(wsMember, wsOwner) -> do
updateTeamMember g tid (member ^. userId) demoteOwner !!! do
const 200 === statusCode
owner' <- Util.getTeamMember (member ^. userId) tid owner
liftIO $ assertEqual "permissions" (owner' ^. permissions) (demoteOwner ^. nPermissions)
owner no longer has GetPermissions , but she can still see the update because it 's about her !
checkTeamMemberUpdateEvent tid owner wsOwner (pure (rolePermissions RoleAdmin))
checkTeamMemberUpdateEvent tid owner wsMember (pure (rolePermissions RoleAdmin))
WS.assertNoEvent timeout [wsOwner, wsMember]
assertTeamUpdate "Owner demoted" tid 2 [member ^. userId]
where
updateTeamMember g tid zusr change =
put
( g
. paths ["teams", toByteString' tid, "members"]
. zUser zusr
. zConn "conn"
. json change
)
checkTeamMemberUpdateEvent tid uid w mPerm = WS.assertMatch_ timeout w $ \notif -> do
ntfTransient notif @?= False
let e = List1.head (WS.unpackPayload notif)
e ^. eventTeam @?= tid
e ^. eventData @?= EdMemberUpdate uid mPerm
@END
testUpdateTeamStatus :: TestM ()
testUpdateTeamStatus = do
g <- viewGalley
(_, tid) <- Util.createBindingTeam
-- Check for idempotency
Util.changeTeamStatus tid TeamsIntra.Active
Util.changeTeamStatus tid TeamsIntra.Suspended
assertTeamSuspend "suspend first time" tid
Util.changeTeamStatus tid TeamsIntra.Suspended
Util.changeTeamStatus tid TeamsIntra.Suspended
Util.changeTeamStatus tid TeamsIntra.Active
assertTeamActivate "activate again" tid
void $
put
( g
. paths ["i", "teams", toByteString' tid, "status"]
. json (TeamStatusUpdate TeamsIntra.Deleted Nothing)
)
!!! do
const 403 === statusCode
const "invalid-team-status-update" === (Error.label . responseJsonUnsafeWithMsg "error label")
postCryptoBroadcastMessage :: Broadcast -> TestM ()
postCryptoBroadcastMessage bcast = do
localDomain <- viewFederationDomain
let q :: Id a -> Qualified (Id a)
q = (`Qualified` localDomain)
c <- view tsCannon
Team1 : , . Team2 : . Regular user : . Connect , ,
(alice, tid) <- Util.createBindingTeam
bob <- view userId <$> Util.addUserToTeam alice tid
assertTeamUpdate "add bob" tid 2 [alice]
refreshIndex
(charlie, _) <- Util.createBindingTeam
refreshIndex
ac <- Util.randomClient alice (head someLastPrekeys)
bc <- Util.randomClient bob (someLastPrekeys !! 1)
cc <- Util.randomClient charlie (someLastPrekeys !! 2)
(dan, dc) <- randomUserWithClient (someLastPrekeys !! 3)
connectUsers alice (list1 charlie [dan])
A second client for
ac2 <- randomClient alice (someLastPrekeys !! 4)
Complete : broadcasts a message to , , and herself
let t = 1 # Second -- WS receive timeout
let msg =
[ (alice, ac2, toBase64Text "ciphertext0"),
(bob, bc, toBase64Text "ciphertext1"),
(charlie, cc, toBase64Text "ciphertext2"),
(dan, dc, toBase64Text "ciphertext3")
]
WS.bracketRN c [bob, charlie, dan] $ \[wsB, wsC, wsD] ->
's clients 1 and 2 listen to their own messages only
WS.bracketR (c . queryItem "client" (toByteString' ac2)) alice $ \wsA2 ->
WS.bracketR (c . queryItem "client" (toByteString' ac)) alice $ \wsA1 -> do
Util.postBroadcast (q alice) ac bcast {bMessage = msg} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] []
should get the broadcast ( team member of alice )
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext1"))
should get the broadcast ( contact of alice and user of teams feature )
void . liftIO $
WS.assertMatch t wsC (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext2"))
should get the broadcast ( contact of alice and not user of teams feature )
void . liftIO $
WS.assertMatch t wsD (wsAssertOtr (q (selfConv dan)) (q alice) ac dc (toBase64Text "ciphertext3"))
's first client should not get the broadcast
assertNoMsg wsA1 (wsAssertOtr (q (selfConv alice)) (q alice) ac ac (toBase64Text "ciphertext0"))
's second client should get the broadcast
void . liftIO $
WS.assertMatch t wsA2 (wsAssertOtr (q (selfConv alice)) (q alice) ac ac2 (toBase64Text "ciphertext0"))
postCryptoBroadcastMessageFilteredTooLargeTeam :: Broadcast -> TestM ()
postCryptoBroadcastMessageFilteredTooLargeTeam bcast = do
localDomain <- viewFederationDomain
let q :: Id a -> Qualified (Id a)
q = (`Qualified` localDomain)
c <- view tsCannon
Team1 : alice , and 3 unnamed
(alice, tid) <- Util.createBindingTeam
bob <- view userId <$> Util.addUserToTeam alice tid
assertTeamUpdate "add bob" tid 2 [alice]
refreshIndex
forM_ [3 .. 5] $ \count -> do
void $ Util.addUserToTeam alice tid
assertTeamUpdate "add user" tid count [alice]
refreshIndex
Team2 :
(charlie, _) <- Util.createBindingTeam
refreshIndex
ac <- Util.randomClient alice (head someLastPrekeys)
bc <- Util.randomClient bob (someLastPrekeys !! 1)
cc <- Util.randomClient charlie (someLastPrekeys !! 2)
(dan, dc) <- randomUserWithClient (someLastPrekeys !! 3)
connectUsers alice (list1 charlie [dan])
A second client for
ac2 <- randomClient alice (someLastPrekeys !! 4)
Complete : broadcasts a message to , , and herself
let t = 1 # Second -- WS receive timeout
let msg =
[ (alice, ac2, toBase64Text "ciphertext0"),
(bob, bc, toBase64Text "ciphertext1"),
(charlie, cc, toBase64Text "ciphertext2"),
(dan, dc, toBase64Text "ciphertext3")
]
WS.bracketRN c [bob, charlie, dan] $ \[wsB, wsC, wsD] ->
's clients 1 and 2 listen to their own messages only
WS.bracketR (c . queryItem "client" (toByteString' ac2)) alice $ \wsA2 ->
WS.bracketR (c . queryItem "client" (toByteString' ac)) alice $ \wsA1 -> do
-- We change also max conv size due to the invariants that galley forces us to keep
let newOpts =
((optSettings . setMaxFanoutSize) ?~ unsafeRange 4)
. (optSettings . setMaxConvSize .~ 4)
withSettingsOverrides newOpts $ do
Untargeted , 's team is too large
Util.postBroadcast (q alice) ac bcast {bMessage = msg} !!! do
const 400 === statusCode
const "too-many-users-to-broadcast" === Error.label . responseJsonUnsafeWithMsg "error label"
We target the message to the 4 users , that should be fine
let inbody = Just [alice, bob, charlie, dan]
Util.postBroadcast (q alice) ac bcast {bReport = inbody, bMessage = msg} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] []
should get the broadcast ( team member of alice )
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext1"))
should get the broadcast ( contact of alice and user of teams feature )
void . liftIO $
WS.assertMatch t wsC (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext2"))
should get the broadcast ( contact of alice and not user of teams feature )
void . liftIO $
WS.assertMatch t wsD (wsAssertOtr (q (selfConv dan)) (q alice) ac dc (toBase64Text "ciphertext3"))
's first client should not get the broadcast
assertNoMsg wsA1 (wsAssertOtr (q (selfConv alice)) (q alice) ac ac (toBase64Text "ciphertext0"))
's second client should get the broadcast
void . liftIO $
WS.assertMatch t wsA2 (wsAssertOtr (q (selfConv alice)) (q alice) ac ac2 (toBase64Text "ciphertext0"))
postCryptoBroadcastMessageReportMissingBody :: Broadcast -> TestM ()
postCryptoBroadcastMessageReportMissingBody bcast = do
localDomain <- viewFederationDomain
(alice, tid) <- Util.createBindingTeam
let qalice = Qualified alice localDomain
bob <- view userId <$> Util.addUserToTeam alice tid
_bc <- Util.randomClient bob (someLastPrekeys !! 1) -- this is important!
assertTeamUpdate "add bob" tid 2 [alice]
refreshIndex
ac <- Util.randomClient alice (head someLastPrekeys)
let -- add extraneous query parameter (unless using query parameter API)
inquery = case bAPI bcast of
BroadcastLegacyQueryParams -> id
_ -> queryItem "report_missing" (toByteString' alice)
msg = [(alice, ac, "ciphertext0")]
Util.postBroadcast qalice ac bcast {bReport = Just [bob], bMessage = msg, bReq = inquery}
!!! const 412
=== statusCode
postCryptoBroadcastMessage2 :: Broadcast -> TestM ()
postCryptoBroadcastMessage2 bcast = do
localDomain <- viewFederationDomain
let q :: Id a -> Qualified (Id a)
q = (`Qualified` localDomain)
c <- view tsCannon
Team1 : , . Team2 : . Connect ,
(alice, tid) <- Util.createBindingTeam
bob <- view userId <$> Util.addUserToTeam alice tid
assertTeamUpdate "add bob" tid 2 [alice]
refreshIndex
(charlie, _) <- Util.createBindingTeam
refreshIndex
ac <- Util.randomClient alice (head someLastPrekeys)
bc <- Util.randomClient bob (someLastPrekeys !! 1)
cc <- Util.randomClient charlie (someLastPrekeys !! 2)
connectUsers alice (list1 charlie [])
let t = 3 # Second -- WS receive timeout
Missing
let m1 = [(bob, bc, toBase64Text "ciphertext1")]
Util.postBroadcast (q alice) ac bcast {bMessage = m1} !!! do
const 412 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [(charlie, Set.singleton cc)] [] []
-- Complete
WS.bracketR2 c bob charlie $ \(wsB, wsE) -> do
let m2 = [(bob, bc, toBase64Text "ciphertext2"), (charlie, cc, toBase64Text "ciphertext2")]
Util.postBroadcast (q alice) ac bcast {bMessage = m2} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] []
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext2"))
void . liftIO $
WS.assertMatch t wsE (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext2"))
-- Redundant self
WS.bracketR3 c alice bob charlie $ \(wsA, wsB, wsE) -> do
let m3 =
[ (alice, ac, toBase64Text "ciphertext3"),
(bob, bc, toBase64Text "ciphertext3"),
(charlie, cc, toBase64Text "ciphertext3")
]
Util.postBroadcast (q alice) ac bcast {bMessage = m3} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [(alice, Set.singleton ac)] []
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext3"))
void . liftIO $
WS.assertMatch t wsE (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext3"))
should not get it
assertNoMsg wsA (wsAssertOtr (q (selfConv alice)) (q alice) ac ac (toBase64Text "ciphertext3"))
Deleted
WS.bracketR2 c bob charlie $ \(wsB, wsE) -> do
deleteClient charlie cc (Just defPassword) !!! const 200 === statusCode
liftIO $
WS.assertMatch_ (5 # WS.Second) wsE $
wsAssertClientRemoved cc
let m4 = [(bob, bc, toBase64Text "ciphertext4"), (charlie, cc, toBase64Text "ciphertext4")]
Util.postBroadcast (q alice) ac bcast {bMessage = m4} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] [(charlie, Set.singleton cc)]
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext4"))
-- charlie should not get it
assertNoMsg wsE (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext4"))
postCryptoBroadcastMessageNoTeam :: Broadcast -> TestM ()
postCryptoBroadcastMessageNoTeam bcast = do
localDomain <- viewFederationDomain
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
let qalice = Qualified alice localDomain
(bob, bc) <- randomUserWithClient (someLastPrekeys !! 1)
connectUsers alice (list1 bob [])
let msg = [(bob, bc, toBase64Text "ciphertext1")]
Util.postBroadcast qalice ac bcast {bMessage = msg} !!! const 404 === statusCode
postCryptoBroadcastMessage100OrMaxConns :: Broadcast -> TestM ()
postCryptoBroadcastMessage100OrMaxConns bcast = do
localDomain <- viewFederationDomain
c <- view tsCannon
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
let qalice = Qualified alice localDomain
tid <- createBindingTeamInternal "foo" alice
assertTeamActivate "" tid
((bob, bc), others) <- createAndConnectUserWhileLimitNotReached alice (100 :: Int) [] (someLastPrekeys !! 1)
connectUsers alice (list1 bob (fst <$> others))
let t = 3 # Second -- WS receive timeout
WS.bracketRN c (bob : (fst <$> others)) $ \ws -> do
let f (u, clt) = (u, clt, toBase64Text "ciphertext")
let msg = (bob, bc, toBase64Text "ciphertext") : (f <$> others)
Util.postBroadcast qalice ac bcast {bMessage = msg} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] []
let qbobself = Qualified (selfConv bob) localDomain
void . liftIO $
WS.assertMatch t (Imports.head ws) (wsAssertOtr qbobself qalice ac bc (toBase64Text "ciphertext"))
for_ (zip (tail ws) others) $ \(wsU, (u, clt)) -> do
let qself = Qualified (selfConv u) localDomain
liftIO $ WS.assertMatch t wsU (wsAssertOtr qself qalice ac clt (toBase64Text "ciphertext"))
where
createAndConnectUserWhileLimitNotReached alice remaining acc pk = do
(uid, cid) <- randomUserWithClient pk
(r1, r2) <- List1.head <$> connectUsersUnchecked alice (List1.singleton uid)
case (statusCode r1, statusCode r2, remaining, acc) of
(201, 200, 0, []) -> error "Need to connect with at least 1 user"
(201, 200, 0, x : xs) -> pure (x, xs)
(201, 200, _, _) -> createAndConnectUserWhileLimitNotReached alice (remaining - 1) ((uid, cid) : acc) pk
(403, 403, _, []) -> error "Need to connect with at least 1 user"
(403, 403, _, x : xs) -> pure (x, xs)
(xxx, yyy, _, _) -> error ("Unexpected while connecting users: " ++ show xxx ++ " and " ++ show yyy)
newTeamMember' :: Permissions -> UserId -> TeamMember
newTeamMember' perms uid = Member.mkTeamMember uid perms Nothing LH.defUserLegalHoldStatus
-- NOTE: all client functions calling @{/i,}/teams/*/features/*@ can be replaced by
-- hypothetical functions 'getTeamFeatureFlag', 'getTeamFeatureFlagInternal',
-- 'putTeamFeatureFlagInternal'. Since these functions all work in slightly different monads
-- and with different kinds of internal checks, it's quite tedious to do so.
getSSOEnabledInternal :: HasCallStack => TeamId -> TestM ResponseLBS
getSSOEnabledInternal = Util.getTeamFeatureFlagInternal @Public.SSOConfig
putSSOEnabledInternal :: HasCallStack => TeamId -> Public.FeatureStatus -> TestM ()
putSSOEnabledInternal tid statusValue =
void $ Util.putTeamFeatureFlagInternal @Public.SSOConfig expect2xx tid (Public.WithStatusNoLock statusValue Public.SSOConfig Public.FeatureTTLUnlimited)
getSearchVisibility :: HasCallStack => (Request -> Request) -> UserId -> TeamId -> MonadHttp m => m ResponseLBS
getSearchVisibility g uid tid = do
get $
g
. paths ["teams", toByteString' tid, "search-visibility"]
. zUser uid
putSearchVisibility :: HasCallStack => (Request -> Request) -> UserId -> TeamId -> TeamSearchVisibility -> MonadHttp m => m ResponseLBS
putSearchVisibility g uid tid vis = do
put $
g
. paths ["teams", toByteString' tid, "search-visibility"]
. zUser uid
. json (TeamSearchVisibilityView vis)
checkJoinEvent :: (MonadIO m, MonadCatch m) => TeamId -> UserId -> WS.WebSocket -> m ()
checkJoinEvent tid usr w = WS.assertMatch_ timeout w $ \notif -> do
ntfTransient notif @?= False
let e = List1.head (WS.unpackPayload notif)
e ^. eventTeam @?= tid
e ^. eventData @?= EdMemberJoin usr
| null | https://raw.githubusercontent.com/wireapp/wire-server/bd9d33f7650f1bc47700601a029df2672d4998a6/services/galley/test/integration/API/Teams.hs | haskell | Disabling to stop warnings on HasCallStack
# OPTIONS_GHC -Wno-redundant-constraints #
This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
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.
with this program. If not, see </>.
Backwards compatible
Ensure currency is properly journaled
happens. but please don't give that number to our ci! :)
a bit silly, but hey.
Nothing was set, default value
Check only admins can change the setting
Members can also see it?
Once we disable the feature, team setting is back to the default value
Both have a binding team but not the same team
| Role of the user who creates the conversation
| At the time of writing this test, the only event sent to this queue is 'MemberJoin'.
response size limit
permissions are irrelevant on internal endpoint
owner
Deleting from a binding team with empty body is invalid
Deleting from a binding team without a password is forbidden
Deleting from a binding team with wrong password
Deleting from a binding team without a password is fine if the owner is
authenticated, but has none.
'UserSSOId'.
non-owner can NOT delete owner
owners can NOT delete themselves
owners can delete other owners (no matter who has emails)
All members become admin by default
Regular conversation:
Regular conversation (using member role for participants):
mem2 is not a conversation member and no longer receives
an event that a new team conversation has been created
... but not to regular ones.
Team owners create new regular team conversation:
NOTE: This functionality was _changed_ as there was no need for it...
mem1T1 (who is *not* a member of the new conversation) can *not* add other team members
despite being a team member and having the permission `DoNotUseDeprecatedAddRemoveConvMember`.
since conversation roles trump any team roles. Note that all users are admins by default
The following tests check the logic: users can add other users to a conversation
iff:
- *the adding user is connected to the users being added*
OR
- *the adding user is part of the team of the users being added*
Now we add someone from T2 that we are connected to
And they can add their own team members
Still, they cannot add random members without a connection from T1, despite the conversation being "hosted" there
ownerT2 *is* connected to ownerT1
and mem1T2 is on the same team, but mem1T1 is *not*
mem1T2 is on the same team, so that is fine too
ownerT2 is *NOT* connected to mem3T1 and not on the same team, so should not be allowed to add
For personal conversations, same logic applies
Can add connected users
Can *not* add users that are *not* connected
Users can not add across teams if *not* connected
Users *can* add across teams if *connected*
| Team role of the user who creates the conversation
| Conversation role of the user who creates the conversation
FUTUREWORK: Ensure that the team role _really_ does not matter
Useful for tests
Async things are hard...
Note that given the async nature of team deletion, we may
have other events in the queue (such as TEAM_UPDATE)
Ensure users are marked as deleted; since we already
received the event, should _really_ be deleted
Let's clean the queue, just in case
now try again with the 'force' query flag, which should work
Note that given the async nature of team deletion, we may
have other events in the queue (such as TEAM_UPDATE)
Ensure users are marked as deleted; since we already
received the event, should _really_ be deleted
We no longer send duplicate conv deletion events
conversation members and as "team.conversation-delete"
to all team members not part of the conversation
We no longer send duplicate conv deletion events
conversation members and as "team.conversation-delete"
to all team members not part of the conversation
setting fields to `null` is the same as omitting the them from the update json record.
("name" is set because a completely empty update object is rejected.)
setting splash screen to `"default"` will delete the splash screen.
Let's create and remove a member
Let's connect an external to test the different behavior
We should really wait until we see that the team is of full size
be enough...
No events are now expected
Team member added also not
Team updates are not propagated
User event updates are not propagated in the team
do not get the deletion event but the connections do!
Now we are just on the limit, events are back!
Let's go back to having a very large team
We should really wait until we see that the team is of full size
be enough...
Add extern to a team conversation
Test team deletion (should contain only conv. removal and user.deletion for _non_ team members)
Do something
Due to the fact that the team is too large, we expect no events!
User deletion events
Ensure users are marked as deleted; since we already
received the event, should _really_ be deleted
ensure the team has a deleted status
Additions after the fanout limit should still send events to all owners
Deletions after the fanout limit should still send events to all owners
Billing should work properly upto fanout limit
We cannot add the new owner with an invite as we don't have a way
to override galley settings while making a call to brig, so we use
the internal API here.
We don't make a call to brig to add member, this prevents new
We cannot add the new owner with an invite as we don't have a way to
override galley settings while making a call to brig, so we use the
internal API here.
While members are added with indexedBillingTeamMembers disabled, new owners must still be
indexed, just not used. When the feature is enabled, we should be able to send billing to
all the owners
Deletions with indexedBillingTeamMembers disabled should still remove owners from the
indexed table
Promotions and demotion should also be kept track of regardless of feature being enabled
This test covers:
Promotion, demotion of team roles.
Demotion by superior roles is allowed.
Demotion by inferior roles is NOT allowed.
non-owner can **NOT** demote owner
owner can demote non-owner
owner can promote non-owner
owner can **NOT** demote herself, even when another owner exists
Now that the other member has full permissions, she can demote the owner
Check for idempotency
WS receive timeout
WS receive timeout
We change also max conv size due to the invariants that galley forces us to keep
this is important!
add extraneous query parameter (unless using query parameter API)
WS receive timeout
Complete
Redundant self
charlie should not get it
WS receive timeout
NOTE: all client functions calling @{/i,}/teams/*/features/*@ can be replaced by
hypothetical functions 'getTeamFeatureFlag', 'getTeamFeatureFlagInternal',
'putTeamFeatureFlagInternal'. Since these functions all work in slightly different monads
and with different kinds of internal checks, it's quite tedious to do so. | # OPTIONS_GHC -Wno - incomplete - uni - patterns #
Copyright ( C ) 2022 Wire Swiss GmbH < >
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
You should have received a copy of the GNU Affero General Public License along
module API.Teams
( tests,
)
where
import API.SQS
import API.Util hiding (deleteTeam)
import qualified API.Util as Util
import qualified API.Util.TeamFeature as Util
import Bilge hiding (head, timeout)
import Bilge.Assert
import Brig.Types.Intra (fromAccountStatusResp)
import qualified Brig.Types.Intra as Brig
import Control.Arrow ((>>>))
import Control.Lens hiding ((#), (.=))
import Control.Monad.Catch
import Data.Aeson hiding (json)
import Data.ByteString.Conversion
import Data.ByteString.Lazy (fromStrict)
import qualified Data.Code as Code
import Data.Csv (FromNamedRecord (..), decodeByName)
import qualified Data.Currency as Currency
import Data.Default
import Data.Id
import Data.Json.Util hiding ((#))
import qualified Data.LegalHold as LH
import Data.List.NonEmpty (NonEmpty ((:|)))
import Data.List1 hiding (head)
import qualified Data.List1 as List1
import qualified Data.Map as Map
import Data.Misc (HttpsUrl, PlainTextPassword (..), mkHttpsUrl)
import Data.Qualified
import Data.Range
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Ascii (AsciiChars (validate))
import qualified Data.UUID as UUID
import qualified Data.UUID.Util as UUID
import qualified Data.UUID.V1 as UUID
import qualified Data.Vector as V
import GHC.TypeLits (KnownSymbol)
import qualified Galley.Env as Galley
import Galley.Options (optSettings, setEnableIndexedBillingTeamMembers, setFeatureFlags, setMaxConvSize, setMaxFanoutSize)
import Galley.Types.Conversations.Roles
import Galley.Types.Teams
import Imports
import Network.HTTP.Types.Status (status403)
import qualified Network.Wai.Utilities.Error as Error
import qualified Network.Wai.Utilities.Error as Wai
import qualified Proto.TeamEvents as E
import qualified Proto.TeamEvents_Fields as E
import qualified SAML2.WebSSO.Types as SAML
import Test.Tasty
import Test.Tasty.Cannon (TimeoutUnit (..), (#))
import qualified Test.Tasty.Cannon as WS
import Test.Tasty.HUnit
import TestHelpers
import TestSetup
import UnliftIO (mapConcurrently)
import Wire.API.Conversation
import Wire.API.Conversation.Protocol
import Wire.API.Conversation.Role
import Wire.API.Event.Team
import Wire.API.Internal.Notification hiding (target)
import Wire.API.Routes.Internal.Galley.TeamsIntra as TeamsIntra
import Wire.API.Team
import Wire.API.Team.Export (TeamExportUser (..))
import qualified Wire.API.Team.Feature as Public
import Wire.API.Team.Member
import qualified Wire.API.Team.Member as Member
import qualified Wire.API.Team.Member as TM
import qualified Wire.API.Team.Member as Teams
import Wire.API.Team.Permission
import Wire.API.Team.Role
import Wire.API.Team.SearchVisibility
import qualified Wire.API.User as Public
import qualified Wire.API.User as U
import qualified Wire.API.User.Client as C
import qualified Wire.API.User.Client.Prekey as PC
tests :: IO TestSetup -> TestTree
tests s =
testGroup "Teams API" $
[ test s "create team" testCreateTeam,
test s "GET /teams (deprecated)" testGetTeams,
test s "create binding team with currency" testCreateBindingTeamWithCurrency,
testGroup "List Team Members" $
[ test s "a member should be able to list their team" testListTeamMembersDefaultLimit,
let numMembers = 5
in test
s
("admins should be able to get a csv stream with their team (" <> show numMembers <> " members)")
(testListTeamMembersCsv numMembers),
test s "the list should be limited to the number requested (hard truncation is not tested here)" testListTeamMembersTruncated,
test s "pagination" testListTeamMembersPagination
],
testGroup "List Team Members (by ids)" $
[ test s "a member should be able to list their team" testListTeamMembersDefaultLimitByIds,
test s "id list length limit is enforced" testListTeamMembersTruncatedByIds
],
testGroup "List Team members unchecked" $
[test s "the list should be truncated" testUncheckedListTeamMembers],
test s "enable/disable SSO" testEnableSSOPerTeam,
test s "enable/disable Custom Search Visibility" testEnableTeamSearchVisibilityPerTeam,
test s "create 1-1 conversation between non-team members (fail)" testCreateOne2OneFailForNonTeamMembers,
test s "create 1-1 conversation between binding team members" (testCreateOne2OneWithMembers RoleMember),
test s "create 1-1 conversation between binding team members as partner" (testCreateOne2OneWithMembers RoleExternalPartner),
test s "poll team-level event queue" testTeamQueue,
test s "add new team member internal" testAddTeamMemberInternal,
test s "remove aka delete team member (binding, owner has passwd)" (testRemoveBindingTeamMember True),
test s "remove aka delete team member (binding, owner has no passwd)" (testRemoveBindingTeamMember False),
test s "remove aka delete team owner (binding)" testRemoveBindingTeamOwner,
test s "add team conversation (no role as argument)" testAddTeamConvLegacy,
test s "add team conversation with role" testAddTeamConvWithRole,
test s "add team conversation as partner (fail)" testAddTeamConvAsExternalPartner,
test s "add team MLS conversation" testCreateTeamMLSConv,
test s "add team member to conversation without connection" testAddTeamMemberToConv,
test s "update conversation as member" (testUpdateTeamConv RoleMember roleNameWireAdmin),
test s "update conversation as partner" (testUpdateTeamConv RoleExternalPartner roleNameWireMember),
test s "delete binding team internal single member" testDeleteBindingTeamSingleMember,
test s "delete binding team internal no members" testDeleteBindingTeamNoMembers,
test s "delete binding team more than one member" testDeleteBindingTeamMoreThanOneMember,
test s "delete binding team (owner has passwd)" (testDeleteBindingTeam True),
test s "delete binding team (owner has no passwd)" (testDeleteBindingTeam False),
testGroup
"delete team - verification code"
[ test s "success" testDeleteTeamVerificationCodeSuccess,
test s "wrong code" testDeleteTeamVerificationCodeWrongCode,
test s "missing code" testDeleteTeamVerificationCodeMissingCode,
test s "expired code" testDeleteTeamVerificationCodeExpiredCode
],
test s "delete team conversation" testDeleteTeamConv,
test s "update team data" testUpdateTeam,
test s "update team data icon validation" testUpdateTeamIconValidation,
test s "update team member" testUpdateTeamMember,
test s "update team status" testUpdateTeamStatus,
test s "team tests around truncation limits - no events, too large team" testTeamAddRemoveMemberAboveThresholdNoEvents,
test s "send billing events to owners even in large teams" testBillingInLargeTeam,
test s "send billing events to some owners in large teams (indexedBillingTeamMembers disabled)" testBillingInLargeTeamWithoutIndexedBillingTeamMembers,
testGroup "broadcast" $
[ (BroadcastLegacyBody, BroadcastJSON),
(BroadcastLegacyQueryParams, BroadcastJSON),
(BroadcastLegacyBody, BroadcastProto),
(BroadcastQualified, BroadcastProto)
]
<&> \(api, ty) ->
let bcast = def {bAPI = api, bType = ty}
in testGroup
(broadcastAPIName api <> " - " <> broadcastTypeName ty)
[ test s "message" (postCryptoBroadcastMessage bcast),
test s "filtered only, too large team" (postCryptoBroadcastMessageFilteredTooLargeTeam bcast),
test s "report missing in body" (postCryptoBroadcastMessageReportMissingBody bcast),
test s "redundant/missing" (postCryptoBroadcastMessage2 bcast),
test s "no-team" (postCryptoBroadcastMessageNoTeam bcast),
test s "100 (or max conns)" (postCryptoBroadcastMessage100OrMaxConns bcast)
]
]
timeout :: WS.Timeout
timeout = 3 # Second
testCreateTeam :: TestM ()
testCreateTeam = do
owner <- Util.randomUser
tid <- Util.createBindingTeamInternal "foo" owner
team <- Util.getTeam owner tid
assertTeamActivate "create team" tid
liftIO $ assertEqual "owner" owner (team ^. teamCreator)
testGetTeams :: TestM ()
testGetTeams = do
owner <- Util.randomUser
Util.getTeams owner [] >>= checkTeamList Nothing
tid <- Util.createBindingTeamInternal "foo" owner
assertTeamActivate "create team" tid
wrongTid <- Util.randomUser >>= Util.createBindingTeamInternal "foobar"
assertTeamActivate "create team" wrongTid
Util.getTeams owner [] >>= checkTeamList (Just tid)
Util.getTeams owner [("size", Just "1")] >>= checkTeamList (Just tid)
Util.getTeams owner [("ids", Just $ toByteString' tid)] >>= checkTeamList (Just tid)
Util.getTeams owner [("ids", Just $ toByteString' tid <> "," <> toByteString' wrongTid)] >>= checkTeamList (Just tid)
these two queries do not yield responses that are equivalent to the old wai route API
Util.getTeams owner [("ids", Just $ toByteString' wrongTid)] >>= checkTeamList (Just tid)
Util.getTeams owner [("start", Just $ toByteString' tid)] >>= checkTeamList (Just tid)
where
checkTeamList :: Maybe TeamId -> TeamList -> TestM ()
checkTeamList mbTid tl = liftIO $ do
let teams = tl ^. teamListTeams
assertEqual "teamListHasMore" False (tl ^. teamListHasMore)
case mbTid of
Just tid -> assertEqual "teamId" tid (Imports.head teams ^. teamId)
Nothing -> assertEqual "teams size" 0 (length teams)
testCreateBindingTeamWithCurrency :: TestM ()
testCreateBindingTeamWithCurrency = do
owner1 <- Util.randomUser
tid1 <- Util.createBindingTeamInternal "foo" owner1
assertTeamActivateWithCurrency "create team" tid1 Nothing
owner2 <- Util.randomUser
tid2 <- Util.createBindingTeamInternalWithCurrency "foo" owner2 Currency.USD
assertTeamActivateWithCurrency "create team" tid2 (Just Currency.USD)
testListTeamMembersDefaultLimit :: TestM ()
testListTeamMembersDefaultLimit = do
(owner, tid, [member1, member2]) <- Util.createBindingTeamWithNMembers 2
listFromServer <- Util.getTeamMembers owner tid
liftIO $
assertEqual
"list members"
(Set.fromList [owner, member1, member2])
(Set.fromList (map (^. Teams.userId) $ listFromServer ^. teamMembers))
liftIO $
assertBool
"member list indicates that there are no more members"
(listFromServer ^. teamMemberListType == ListComplete)
| for ad - hoc load - testing , set @numMembers@ to , say , 10k and see what
for additional tests of the CSV download particularly with SCIM users , please refer to ' Test . Spar . Scim . UserSpec '
testListTeamMembersCsv :: HasCallStack => Int -> TestM ()
testListTeamMembersCsv numMembers = do
let teamSize = numMembers + 1
(owner, tid, mbs) <- Util.createBindingTeamWithNMembersWithHandles True numMembers
let numClientMappings = Map.fromList $ (owner : mbs) `zip` (cycle [1, 2, 3] :: [Int])
addClients numClientMappings
resp <- Util.getTeamMembersCsv owner tid
let rbody = fromMaybe (error "no body") . responseBody $ resp
usersInCsv <- either (error "could not decode csv") pure (decodeCSV @TeamExportUser rbody)
liftIO $ do
assertEqual "total number of team members" teamSize (length usersInCsv)
assertEqual "owners in team" 1 (countOn tExportRole (Just RoleOwner) usersInCsv)
assertEqual "members in team" numMembers (countOn tExportRole (Just RoleMember) usersInCsv)
do
let someUsersInCsv = take 50 usersInCsv
someHandles = tExportHandle <$> someUsersInCsv
users <- Util.getUsersByHandle (catMaybes someHandles)
mbrs <- view teamMembers <$> Util.bulkGetTeamMembers owner tid (U.userId <$> users)
let check :: Eq a => String -> (TeamExportUser -> Maybe a) -> UserId -> Maybe a -> IO ()
check msg getTeamExportUserAttr uid userAttr = do
assertBool msg (isJust userAttr)
assertEqual (msg <> ": " <> show uid) 1 (countOn getTeamExportUserAttr userAttr usersInCsv)
liftIO . forM_ (zip users mbrs) $ \(user, mbr) -> do
assertEqual "user/member id match" (U.userId user) (mbr ^. TM.userId)
check "tExportDisplayName" (Just . tExportDisplayName) (U.userId user) (Just $ U.userDisplayName user)
check "tExportEmail" tExportEmail (U.userId user) (U.userEmail user)
liftIO . forM_ (zip3 someUsersInCsv users mbrs) $ \(export, user, mbr) -> do
FUTUREWORK : there are a lot of cases we do n't cover here ( manual invitation , saml , other roles , ... ) .
assertEqual ("tExportDisplayName: " <> show (U.userId user)) (U.userDisplayName user) (tExportDisplayName export)
assertEqual ("tExportHandle: " <> show (U.userId user)) (U.userHandle user) (tExportHandle export)
assertEqual ("tExportEmail: " <> show (U.userId user)) (U.userEmail user) (tExportEmail export)
assertEqual ("tExportRole: " <> show (U.userId user)) (permissionsRole $ view permissions mbr) (tExportRole export)
assertEqual ("tExportCreatedOn: " <> show (U.userId user)) (snd <$> view invitation mbr) (tExportCreatedOn export)
assertEqual ("tExportInvitedBy: " <> show (U.userId user)) Nothing (tExportInvitedBy export)
assertEqual ("tExportIdpIssuer: " <> show (U.userId user)) (userToIdPIssuer user) (tExportIdpIssuer export)
assertEqual ("tExportManagedBy: " <> show (U.userId user)) (U.userManagedBy user) (tExportManagedBy export)
assertEqual ("tExportUserId: " <> show (U.userId user)) (U.userId user) (tExportUserId export)
assertEqual "tExportNumDevices: " (Map.findWithDefault (-1) (U.userId user) numClientMappings) (tExportNumDevices export)
where
userToIdPIssuer :: HasCallStack => U.User -> Maybe HttpsUrl
userToIdPIssuer usr = case (U.userIdentity >=> U.ssoIdentity) usr of
Just (U.UserSSOId (SAML.UserRef (SAML.Issuer issuer) _)) -> either (const $ error "shouldn't happen") Just $ mkHttpsUrl issuer
Just _ -> Nothing
Nothing -> Nothing
decodeCSV :: FromNamedRecord a => LByteString -> Either String [a]
decodeCSV bstr = decodeByName bstr <&> (snd >>> V.toList)
countOn :: Eq b => (a -> b) -> b -> [a] -> Int
countOn prop val xs = sum $ fmap (bool 0 1 . (== val) . prop) xs
addClients :: Map.Map UserId Int -> TestM ()
addClients xs = forM_ (Map.toList xs) addClientForUser
addClientForUser :: (UserId, Int) -> TestM ()
addClientForUser (uid, n) = forM_ [0 .. (n - 1)] (addClient uid)
addClient :: UserId -> Int -> TestM ()
addClient uid i = do
brig <- viewBrig
post (brig . paths ["i", "clients", toByteString' uid] . contentJson . json (newClient (someLastPrekeys !! i)) . queryItem "skip_reauth" "true") !!! const 201 === statusCode
newClient :: PC.LastPrekey -> C.NewClient
newClient lpk = C.newClient C.PermanentClientType lpk
testListTeamMembersPagination :: TestM ()
testListTeamMembersPagination = do
(owner, tid, _) <- Util.createBindingTeamWithNMembers 18
allMembers <- Util.getTeamMembersPaginated owner tid 100 Nothing
liftIO $ do
let actualTeamSize = length (rpResults allMembers)
let expectedTeamSize = 19
assertEqual ("expected team size of 19 (18 members + 1 owner), but got " <> show actualTeamSize) expectedTeamSize actualTeamSize
page1 <- Util.getTeamMembersPaginated owner tid 5 Nothing
check 1 5 True page1
page2 <- Util.getTeamMembersPaginated owner tid 5 (Just . rpPagingState $ page1)
check 2 5 True page2
page3 <- Util.getTeamMembersPaginated owner tid 5 (Just . rpPagingState $ page2)
check 3 5 True page3
page4 <- Util.getTeamMembersPaginated owner tid 5 (Just . rpPagingState $ page3)
check 4 4 False page4
where
check :: Int -> Int -> Bool -> ResultPage -> TestM ()
check n expectedSize expectedHasMore page = liftIO $ do
let actualSize = length (rpResults page)
assertEqual ("page " <> show n <> ": expected " <> show expectedSize <> " members, but got " <> show actualSize) expectedSize actualSize
let actualHasMore = rpHasMore page
assertEqual ("page " <> show n <> " (hasMore): expected " <> show expectedHasMore <> ", but got" <> "") expectedHasMore actualHasMore
testListTeamMembersTruncated :: TestM ()
testListTeamMembersTruncated = do
(owner, tid, _) <- Util.createBindingTeamWithNMembers 4
listFromServer <- Util.getTeamMembersTruncated owner tid 2
liftIO $
assertEqual
"member list is not limited to the requested number"
2
(length $ listFromServer ^. teamMembers)
liftIO $
assertBool
"member list does not indicate that there are more members"
(listFromServer ^. teamMemberListType == ListTruncated)
testListTeamMembersDefaultLimitByIds :: TestM ()
testListTeamMembersDefaultLimitByIds = do
(owner, tid, [member1, member2]) <- Util.createBindingTeamWithNMembers 2
(_, _, [alien]) <- Util.createBindingTeamWithNMembers 1
let phantom :: UserId = read "686f427a-7e56-11ea-a639-07a531a95937"
check owner tid [owner, member1, member2] [owner, member1, member2]
check owner tid [member1, member2] [member1, member2]
check owner tid [member1] [member1]
check owner tid [alien] []
check owner tid [phantom] []
check owner tid [owner, alien, phantom] [owner]
where
check :: HasCallStack => UserId -> TeamId -> [UserId] -> [UserId] -> TestM ()
check owner tid uidsIn uidsOut = do
listFromServer <- Util.bulkGetTeamMembers owner tid uidsIn
liftIO $
assertEqual
"list members"
(Set.fromList uidsOut)
(Set.fromList (map (^. userId) $ listFromServer ^. teamMembers))
liftIO $
assertBool
"has_more is always false"
(listFromServer ^. teamMemberListType == ListComplete)
testListTeamMembersTruncatedByIds :: TestM ()
testListTeamMembersTruncatedByIds = do
(owner, tid, mems) <- Util.createBindingTeamWithNMembers 4
Util.bulkGetTeamMembersTruncated owner tid (owner : mems) 3 !!! do
const 400 === statusCode
const "too-many-uids" === Error.label . responseJsonUnsafeWithMsg "error label"
testUncheckedListTeamMembers :: TestM ()
testUncheckedListTeamMembers = do
(_, tid, _) <- Util.createBindingTeamWithNMembers 4
listFromServer <- Util.getTeamMembersInternalTruncated tid 2
liftIO $
assertEqual
"member list is not limited to the requested number"
2
(length $ listFromServer ^. teamMembers)
liftIO $
assertBool
"member list does not indicate that there are more members"
(listFromServer ^. teamMemberListType == ListTruncated)
testEnableSSOPerTeam :: TestM ()
testEnableSSOPerTeam = do
owner <- Util.randomUser
tid <- Util.createBindingTeamInternal "foo" owner
assertTeamActivate "create team" tid
let check :: HasCallStack => String -> Public.FeatureStatus -> TestM ()
check msg enabledness = do
status :: Public.WithStatusNoLock Public.SSOConfig <- responseJsonUnsafe <$> (getSSOEnabledInternal tid <!! testResponse 200 Nothing)
let statusValue = Public.wssStatus status
liftIO $ assertEqual msg enabledness statusValue
let putSSOEnabledInternalCheckNotImplemented :: HasCallStack => TestM ()
putSSOEnabledInternalCheckNotImplemented = do
g <- viewGalley
Wai.Error status label _ _ <-
responseJsonUnsafe
<$> put
( g
. paths ["i", "teams", toByteString' tid, "features", "sso"]
. json (Public.WithStatusNoLock Public.FeatureStatusDisabled Public.SSOConfig Public.FeatureTTLUnlimited)
)
liftIO $ do
assertEqual "bad status" status403 status
assertEqual "bad label" "not-implemented" label
featureSSO <- view (tsGConf . optSettings . setFeatureFlags . flagSSO)
case featureSSO of
FeatureSSOEnabledByDefault -> check "Teams should start with SSO enabled" Public.FeatureStatusEnabled
FeatureSSODisabledByDefault -> check "Teams should start with SSO disabled" Public.FeatureStatusDisabled
putSSOEnabledInternal tid Public.FeatureStatusEnabled
check "Calling 'putEnabled True' should enable SSO" Public.FeatureStatusEnabled
putSSOEnabledInternalCheckNotImplemented
testEnableTeamSearchVisibilityPerTeam :: TestM ()
testEnableTeamSearchVisibilityPerTeam = do
(tid, owner, member : _) <- Util.createBindingTeamWithMembers 2
let check :: String -> Public.FeatureStatus -> TestM ()
check msg enabledness = do
g <- viewGalley
status :: Public.WithStatusNoLock Public.SearchVisibilityAvailableConfig <- responseJsonUnsafe <$> (Util.getTeamSearchVisibilityAvailableInternal g tid <!! testResponse 200 Nothing)
let statusValue = Public.wssStatus status
liftIO $ assertEqual msg enabledness statusValue
let putSearchVisibilityCheckNotAllowed :: TestM ()
putSearchVisibilityCheckNotAllowed = do
g <- viewGalley
Wai.Error status label _ _ <- responseJsonUnsafe <$> putSearchVisibility g owner tid SearchVisibilityNoNameOutsideTeam
liftIO $ do
assertEqual "bad status" status403 status
assertEqual "bad label" "team-search-visibility-not-enabled" label
let getSearchVisibilityCheck :: TeamSearchVisibility -> TestM ()
getSearchVisibilityCheck vis = do
g <- viewGalley
getSearchVisibility g owner tid !!! do
const 200 === statusCode
const (Just (TeamSearchVisibilityView vis)) === responseJsonUnsafe
Util.withCustomSearchFeature FeatureTeamSearchVisibilityAvailableByDefault $ do
g <- viewGalley
check "Teams should start with Custom Search Visibility enabled" Public.FeatureStatusEnabled
putSearchVisibility g owner tid SearchVisibilityNoNameOutsideTeam !!! const 204 === statusCode
putSearchVisibility g owner tid SearchVisibilityStandard !!! const 204 === statusCode
Util.withCustomSearchFeature FeatureTeamSearchVisibilityUnavailableByDefault $ do
check "Teams should start with Custom Search Visibility disabled" Public.FeatureStatusDisabled
putSearchVisibilityCheckNotAllowed
g <- viewGalley
Util.putTeamSearchVisibilityAvailableInternal g tid Public.FeatureStatusEnabled
getSearchVisibilityCheck SearchVisibilityStandard
putSearchVisibility g owner tid SearchVisibilityNoNameOutsideTeam !!! testResponse 204 Nothing
getSearchVisibilityCheck SearchVisibilityNoNameOutsideTeam
putSearchVisibility g member tid SearchVisibilityStandard !!! testResponse 403 (Just "operation-denied")
getSearchVisibilityCheck SearchVisibilityNoNameOutsideTeam
getSearchVisibility g member tid !!! testResponse 200 Nothing
Util.putTeamSearchVisibilityAvailableInternal g tid Public.FeatureStatusDisabled
getSearchVisibilityCheck SearchVisibilityStandard
testCreateOne2OneFailForNonTeamMembers :: TestM ()
testCreateOne2OneFailForNonTeamMembers = do
owner <- Util.randomUser
let p1 = Util.symmPermissions [CreateConversation, DoNotUseDeprecatedAddRemoveConvMember]
let p2 = Util.symmPermissions [CreateConversation, DoNotUseDeprecatedAddRemoveConvMember, AddTeamMember]
mem1 <- newTeamMember' p1 <$> Util.randomUser
mem2 <- newTeamMember' p2 <$> Util.randomUser
Util.connectUsers owner (list1 (mem1 ^. userId) [mem2 ^. userId])
owner1 <- Util.randomUser
tid1 <- Util.createBindingTeamInternal "foo" owner1
assertTeamActivate "create team" tid1
owner2 <- Util.randomUser
tid2 <- Util.createBindingTeamInternal "foo" owner2
assertTeamActivate "create another team" tid2
Util.createOne2OneTeamConv owner1 owner2 Nothing tid1 !!! do
const 403 === statusCode
const "non-binding-team-members" === (Error.label . responseJsonUnsafeWithMsg "error label")
testCreateOne2OneWithMembers ::
HasCallStack =>
Role ->
TestM ()
testCreateOne2OneWithMembers (rolePermissions -> perms) = do
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
mem1 <- newTeamMember' perms <$> Util.randomUser
WS.bracketR c (mem1 ^. userId) $ \wsMem1 -> do
Util.addTeamMemberInternal tid (mem1 ^. userId) (mem1 ^. permissions) (mem1 ^. invitation)
checkTeamMemberJoin tid (mem1 ^. userId) wsMem1
assertTeamUpdate "team member join" tid 2 [owner]
void $ retryWhileN 10 repeatIf (Util.createOne2OneTeamConv owner (mem1 ^. userId) Nothing tid)
Recreating a One2One is a no - op , returns a 200
Util.createOne2OneTeamConv owner (mem1 ^. userId) Nothing tid !!! const 200 === statusCode
where
repeatIf :: ResponseLBS -> Bool
repeatIf r = statusCode r /= 201
testTeamQueue :: TestM ()
testTeamQueue = do
(owner, tid) <- createBindingTeam
eventually $ do
queue <- getTeamQueue owner Nothing Nothing False
liftIO $ assertEqual "team queue: []" [] (snd <$> queue)
mem1 :: UserId <- view userId <$> addUserToTeam owner tid
eventually $ do
queue1 <- getTeamQueue owner Nothing Nothing False
queue2 <- getTeamQueue mem1 Nothing Nothing False
liftIO $ assertEqual "team queue: owner sees [mem1]" [mem1] (snd <$> queue1)
liftIO $ assertEqual "team queue: mem1 sees the same thing" queue1 queue2
mem2 :: UserId <- view userId <$> addUserToTeam owner tid
eventually $ do
known ' NotificationId 's
[(n1, u1), (n2, u2)] <- getTeamQueue owner Nothing Nothing False
liftIO $ assertEqual "team queue: queue0" (mem1, mem2) (u1, u2)
queue1 <- getTeamQueue owner (Just n1) Nothing False
queue2 <- getTeamQueue owner (Just n2) Nothing False
liftIO $ assertEqual "team queue: from 1" [mem1, mem2] (snd <$> queue1)
liftIO $ assertEqual "team queue: from 2" [mem2] (snd <$> queue2)
do
unknown old ' NotificationId '
let Just n1 = Id <$> UUID.fromText "615c4e38-950d-11ea-b0fc-7b04ea9f81c0"
queue <- getTeamQueue owner (Just n1) Nothing False
liftIO $ assertEqual "team queue: from old unknown" (snd <$> queue) [mem1, mem2]
do
unknown younger ' NotificationId '
[(Id n1, _), (Id n2, _)] <- getTeamQueue owner Nothing Nothing False
nu <-
create new UUIDv1 in the gap between n1 , n2 .
let Just time1 = UUID.extractTime n1
Just time2 = UUID.extractTime n2
timeu = time1 + (time2 - time1) `div` 2
in Id . fromJust . (`UUID.setTime` timeu) . fromJust <$> liftIO UUID.nextUUID
queue <- getTeamQueue owner (Just nu) Nothing False
liftIO $ assertEqual "team queue: from old unknown" (snd <$> queue) [mem2]
mem3 :: UserId <- view userId <$> addUserToTeam owner tid
mem4 :: UserId <- view userId <$> addUserToTeam owner tid
eventually $ do
[_, (n2, _), _, _] <- getTeamQueue owner Nothing Nothing False
getTeamQueue' owner Nothing (Just (-1)) False !!! const 400 === statusCode
getTeamQueue' owner Nothing (Just 0) False !!! const 400 === statusCode
queue1 <- getTeamQueue owner (Just n2) (Just (1, True)) False
queue2 <- getTeamQueue owner (Just n2) (Just (2, False)) False
queue3 <- getTeamQueue owner (Just n2) (Just (3, False)) False
queue4 <- getTeamQueue owner Nothing (Just (1, True)) False
liftIO $ assertEqual "team queue: size limit 1" (snd <$> queue1) [mem2, mem3]
liftIO $ assertEqual "team queue: size limit 2" (snd <$> queue2) [mem2, mem3, mem4]
liftIO $ assertEqual "team queue: size limit 3" (snd <$> queue3) [mem2, mem3, mem4]
liftIO $ assertEqual "team queue: size limit 1, no start id" (snd <$> queue4) [mem1]
testAddTeamMemberInternal :: TestM ()
testAddTeamMemberInternal = do
c <- view tsCannon
(owner, tid) <- createBindingTeam
mem1 <- newTeamMember' p1 <$> Util.randomUser
WS.bracketRN c [owner, mem1 ^. userId] $ \[wsOwner, wsMem1] -> do
Util.addTeamMemberInternal tid (mem1 ^. userId) (mem1 ^. permissions) (mem1 ^. invitation)
liftIO . void $ mapConcurrently (checkJoinEvent tid (mem1 ^. userId)) [wsOwner, wsMem1]
assertTeamUpdate "team member join" tid 2 [owner]
void $ Util.getTeamMemberInternal tid (mem1 ^. userId)
testRemoveBindingTeamMember :: Bool -> TestM ()
testRemoveBindingTeamMember ownerHasPassword = do
localDomain <- viewFederationDomain
g <- viewGalley
c <- view tsCannon
Owner who creates the team must have an email , This is why we run all tests with a second
(ownerWithPassword, tid) <- Util.createBindingTeam
ownerMem <-
if ownerHasPassword
then Util.addUserToTeam ownerWithPassword tid
else Util.addUserToTeamWithSSO True tid
assertTeamUpdate "second member join" tid 2 [ownerWithPassword]
refreshIndex
Util.makeOwner ownerWithPassword ownerMem tid
let owner = view userId ownerMem
assertTeamUpdate "second member promoted to owner" tid 2 [ownerWithPassword, owner]
refreshIndex
mext <- Util.randomUser
mem1 <- Util.addUserToTeam owner tid
assertTeamUpdate "team member join" tid 3 [ownerWithPassword, owner]
refreshIndex
Util.connectUsers owner (List1.singleton mext)
cid1 <- Util.createTeamConv owner tid [mem1 ^. userId, mext] (Just "blaa") Nothing Nothing
when ownerHasPassword $ do
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
)
!!! const 400
=== statusCode
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData Nothing)
)
!!! do
const 403 === statusCode
const "access-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData (Just $ PlainTextPassword "wrong passwd"))
)
!!! do
const 403 === statusCode
const "access-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
Mem1 is still part of Wire
Util.ensureDeletedState False owner (mem1 ^. userId)
WS.bracketR2 c owner mext $ \(wsOwner, wsMext) -> do
if ownerHasPassword
then do
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData (Just $ Util.defPassword))
)
!!! const 202
=== statusCode
else do
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem1 ^. userId)]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData Nothing)
)
!!! const 202
=== statusCode
checkTeamMemberLeave tid (mem1 ^. userId) wsOwner
checkConvMemberLeaveEvent (Qualified cid1 localDomain) (Qualified (mem1 ^. userId) localDomain) wsMext
assertTeamUpdate "team member leave" tid 2 [ownerWithPassword, owner]
WS.assertNoEvent timeout [wsMext]
Mem1 is now gone from Wire
Util.ensureDeletedState True owner (mem1 ^. userId)
testRemoveBindingTeamOwner :: TestM ()
testRemoveBindingTeamOwner = do
(ownerA, tid) <- Util.createBindingTeam
refreshIndex
ownerB <-
view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) ownerA tid
assertTeamUpdate "Add owner" tid 2 [ownerA, ownerB]
refreshIndex
ownerWithoutEmail <- do
users must have a ' UserIdentity ' , or @get /i / users@ wo n't find it , so we use
mem <- Util.addUserToTeamWithSSO False tid
refreshIndex
assertTeamUpdate "Add user with SSO" tid 3 [ownerA, ownerB]
Util.makeOwner ownerA mem tid
pure $ view userId mem
assertTeamUpdate "Promote user to owner" tid 3 [ownerA, ownerB, ownerWithoutEmail]
admin <-
view userId <$> Util.addUserToTeamWithRole (Just RoleAdmin) ownerA tid
assertTeamUpdate "Add admin" tid 4 [ownerA, ownerB, ownerWithoutEmail]
refreshIndex
check tid admin ownerWithoutEmail (Just Util.defPassword) (Just "access-denied")
check tid ownerA ownerA (Just Util.defPassword) (Just "access-denied")
check tid ownerWithoutEmail ownerWithoutEmail Nothing (Just "access-denied")
check tid ownerWithoutEmail ownerA Nothing Nothing
Util.waitForMemberDeletion ownerB tid ownerA
assertTeamUpdate "Remove ownerA" tid 3 [ownerB, ownerWithoutEmail]
refreshIndex
check tid ownerB ownerWithoutEmail (Just Util.defPassword) Nothing
Util.waitForMemberDeletion ownerB tid ownerWithoutEmail
assertTeamUpdate "Remove ownerWithoutEmail" tid 2 [ownerB]
where
check :: HasCallStack => TeamId -> UserId -> UserId -> Maybe PlainTextPassword -> Maybe LText -> TestM ()
check tid deleter deletee pass maybeError = do
g <- viewGalley
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' deletee]
. zUser deleter
. zConn "conn"
. json (newTeamMemberDeleteData pass)
)
!!! case maybeError of
Nothing ->
const 202 === statusCode
Just label -> do
const 403 === statusCode
const label === (Error.label . responseJsonUnsafeWithMsg "error label")
testAddTeamConvLegacy :: TestM ()
testAddTeamConvLegacy = do
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
extern <- Util.randomUser
let p = Util.symmPermissions [CreateConversation, DoNotUseDeprecatedAddRemoveConvMember]
mem1 <- newTeamMember' p <$> Util.randomUser
mem2 <- newTeamMember' p <$> Util.randomUser
Util.connectUsers owner (list1 (mem1 ^. userId) [extern, mem2 ^. userId])
allUserIds <- for [owner, extern, mem1 ^. userId, mem2 ^. userId] $
\u -> Qualified u <$> viewFederationDomain
WS.bracketRN c (qUnqualified <$> allUserIds) $ \wss -> do
cid <- Util.createTeamConvLegacy owner tid (qUnqualified <$> allUserIds) (Just "blaa")
mapM_ (checkConvCreateEvent cid) wss
mapM_ (assertConvMemberWithRole roleNameWireAdmin cid) allUserIds
testAddTeamConvWithRole :: TestM ()
testAddTeamConvWithRole = do
c <- view tsCannon
(tid, owner, mem2 : _) <- Util.createBindingTeamWithMembers 2
qOwner <- Qualified owner <$> viewFederationDomain
extern <- Util.randomUser
qExtern <- Qualified extern <$> viewFederationDomain
Util.connectUsers owner (list1 extern [])
Util.connectUsers mem2 (list1 extern [])
WS.bracketRN c [owner, extern, mem2] $ \[wsOwner, wsExtern, wsMem2] -> do
cid2 <- Util.createTeamConvWithRole owner tid [extern] (Just "blaa") Nothing Nothing roleNameWireAdmin
checkConvCreateEvent cid2 wsOwner
checkConvCreateEvent cid2 wsExtern
mapM_ (assertConvMemberWithRole roleNameWireAdmin cid2) [qOwner, qExtern]
cid3 <- Util.createTeamConvWithRole owner tid [extern] (Just "blaa") Nothing Nothing roleNameWireMember
checkConvCreateEvent cid3 wsOwner
checkConvCreateEvent cid3 wsExtern
assertConvMemberWithRole roleNameWireAdmin cid3 qOwner
assertConvMemberWithRole roleNameWireMember cid3 qExtern
mem1 <- Util.addUserToTeam owner tid
checkTeamMemberJoin tid (mem1 ^. userId) wsOwner
checkTeamMemberJoin tid (mem1 ^. userId) wsMem2
Util.assertNotConvMember (mem1 ^. userId) cid2
testCreateTeamMLSConv :: TestM ()
testCreateTeamMLSConv = do
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
lOwner <- flip toLocalUnsafe owner <$> viewFederationDomain
extern <- Util.randomUser
WS.bracketR2 c owner extern $ \(wsOwner, wsExtern) -> do
lConvId <-
Util.createMLSTeamConv
lOwner
(newClientId 0)
tid
mempty
(Just "Team MLS conversation")
Nothing
Nothing
Nothing
Nothing
Right conv <- responseJsonError <$> getConvQualified owner (tUntagged lConvId)
liftIO $ do
assertEqual "protocol mismatch" ProtocolMLSTag (protocolTag (cnvProtocol conv))
checkConvCreateEvent (tUnqualified lConvId) wsOwner
WS.assertNoEvent (2 # Second) [wsExtern]
testAddTeamConvAsExternalPartner :: TestM ()
testAddTeamConvAsExternalPartner = do
(owner, tid) <- Util.createBindingTeam
memMember1 <- Util.addUserToTeamWithRole (Just RoleMember) owner tid
assertTeamUpdate "team member join 2" tid 2 [owner]
refreshIndex
memMember2 <- Util.addUserToTeamWithRole (Just RoleMember) owner tid
assertTeamUpdate "team member join 3" tid 3 [owner]
refreshIndex
memExternalPartner <- Util.addUserToTeamWithRole (Just RoleExternalPartner) owner tid
assertTeamUpdate "team member join 4" tid 4 [owner]
refreshIndex
let acc = Just $ Set.fromList [InviteAccess, CodeAccess]
Util.createTeamConvAccessRaw
(memExternalPartner ^. userId)
tid
[memMember1 ^. userId, memMember2 ^. userId]
(Just "blaa")
acc
(Just (Set.fromList [TeamMemberAccessRole]))
Nothing
Nothing
!!! do
const 403 === statusCode
const "operation-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
testAddTeamMemberToConv :: TestM ()
testAddTeamMemberToConv = do
personalUser <- Util.randomUser
(ownerT1, qOwnerT1) <- Util.randomUserTuple
let p = Util.symmPermissions [DoNotUseDeprecatedAddRemoveConvMember]
mem1T1 <- Util.randomUser
qMem1T1 <- Qualified mem1T1 <$> viewFederationDomain
mem2T1 <- Util.randomUser
qMem2T1 <- Qualified mem2T1 <$> viewFederationDomain
let pEmpty = Util.symmPermissions []
mem3T1 <- Util.randomUser
qMem3T1 <- Qualified mem3T1 <$> viewFederationDomain
mem4T1 <- newTeamMember' pEmpty <$> Util.randomUser
qMem4T1 <- Qualified (mem4T1 ^. userId) <$> viewFederationDomain
(ownerT2, qOwnerT2) <- Util.randomUserTuple
mem1T2 <- newTeamMember' p <$> Util.randomUser
qMem1T2 <- Qualified (mem1T2 ^. userId) <$> viewFederationDomain
Util.connectUsers ownerT1 (list1 mem1T1 [mem2T1, mem3T1, ownerT2, personalUser])
tidT1 <- createBindingTeamInternal "foo" ownerT1
do
Util.addTeamMemberInternal tidT1 mem1T1 p Nothing
Util.addTeamMemberInternal tidT1 mem2T1 p Nothing
Util.addTeamMemberInternal tidT1 mem3T1 pEmpty Nothing
tidT2 <- Util.createBindingTeamInternal "foo" ownerT2
Util.addTeamMemberInternal tidT2 (mem1T2 ^. userId) (mem1T2 ^. permissions) (mem1T2 ^. invitation)
cidT1 <- Util.createTeamConv ownerT1 tidT1 [] (Just "blaa") Nothing Nothing
qcidT1 <- Qualified cidT1 <$> viewFederationDomain
cidT2 <- Util.createTeamConv ownerT2 tidT2 [] (Just "blaa") Nothing Nothing
qcidT2 <- Qualified cidT2 <$> viewFederationDomain
cidPersonal <- decodeConvId <$> Util.postConv personalUser [] (Just "blaa") [] Nothing Nothing
qcidPersonal <- Qualified cidPersonal <$> viewFederationDomain
Util.assertNotConvMember mem1T1 cidT1
Util.postMembers mem1T1 (pure qMem2T1) qcidT1 !!! const 404 === statusCode
Util.assertNotConvMember mem2T1 cidT1
OTOH , mem3T1 _ can _ add another team member despite lacking the required team permission
Util.assertConvMember qOwnerT1 cidT1
Util.postMembers ownerT1 (pure qMem2T1) qcidT1 !!! const 200 === statusCode
Util.assertConvMember qMem2T1 cidT1
Util.postMembers ownerT1 (pure qOwnerT2) qcidT1 !!! const 200 === statusCode
Util.assertConvMember qOwnerT2 cidT1
Util.postMembers ownerT2 (pure qMem1T2) qcidT1 !!! const 200 === statusCode
Util.assertConvMember qMem1T2 cidT1
Util.postMembers ownerT2 (pure qMem4T1) qcidT1 !!! const 403 === statusCode
Util.assertNotConvMember (mem4T1 ^. userId) cidT1
Now let 's look at convs hosted on team2
Util.postMembers ownerT2 (pure qOwnerT1) qcidT2 !!! const 200 === statusCode
Util.assertConvMember qOwnerT1 cidT2
Util.postMembers ownerT2 (qMem1T2 :| [qMem1T1]) qcidT2 !!! const 403 === statusCode
Util.assertNotConvMember mem1T1 cidT2
Util.assertNotConvMember (mem1T2 ^. userId) cidT2
Util.postMembers ownerT2 (pure qMem1T2) qcidT2 !!! const 200 === statusCode
Util.assertConvMember qMem1T2 cidT2
Util.postMembers ownerT2 (pure qMem3T1) qcidT2 !!! const 403 === statusCode
Util.assertNotConvMember mem3T1 cidT2
Util.postMembers personalUser (pure qOwnerT1) qcidPersonal !!! const 200 === statusCode
Util.assertConvMember qOwnerT1 cidPersonal
Util.postMembers personalUser (pure qOwnerT2) qcidPersonal !!! const 403 === statusCode
Util.assertNotConvMember ownerT2 cidPersonal
Users of the same team can add one another
Util.postMembers ownerT1 (pure qMem1T1) qcidPersonal !!! const 200 === statusCode
Util.assertConvMember qMem1T1 cidPersonal
Util.postMembers mem1T1 (pure qOwnerT2) qcidPersonal !!! const 403 === statusCode
Util.assertNotConvMember ownerT2 cidPersonal
Util.postMembers ownerT1 (pure qOwnerT2) qcidPersonal !!! const 200 === statusCode
Util.assertConvMember qOwnerT2 cidPersonal
testUpdateTeamConv ::
Role ->
RoleName ->
TestM ()
testUpdateTeamConv _ convRole = do
(tid, owner, member : _) <- Util.createBindingTeamWithMembers 2
cid <- Util.createTeamConvWithRole owner tid [member] (Just "gossip") Nothing Nothing convRole
resp <- updateTeamConv member cid (ConversationRename "not gossip")
liftIO $ assertEqual "status conv" convRoleCheck (statusCode resp)
where
convRoleCheck = if isActionAllowed ModifyConversationName convRole == Just True then 200 else 403
testDeleteBindingTeamSingleMember :: TestM ()
testDeleteBindingTeamSingleMember = do
g <- viewGalley
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
other <- Util.addUserToTeam owner tid
assertTeamUpdate "team member leave 1" tid 2 [owner]
refreshIndex
extern <- Util.randomUser
delete
( g
. paths ["/i/teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json (newTeamDeleteData (Just $ Util.defPassword))
)
!!! do
const 403 === statusCode
const "not-one-member-team" === (Error.label . responseJsonUnsafeWithMsg "error label when deleting a team")
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (other ^. userId)]
. zUser owner
. zConn "conn"
. json
( newTeamMemberDeleteData (Just Util.defPassword)
)
)
!!! const 202
=== statusCode
assertTeamUpdate "team member leave 1" tid 1 [owner]
void $
retryWhileN
10
(/= Just True)
(getDeletedState extern (other ^. userId))
void . WS.bracketRN c [owner, extern] $ \[wsOwner, wsExtern] -> do
delete
( g
. paths ["/i/teams", toByteString' tid]
. zUser owner
. zConn "conn"
)
!!! const 202
=== statusCode
checkUserDeleteEvent owner wsOwner
WS.assertNoEvent (1 # Second) [wsExtern]
assertTeamDelete 10 "team delete, should be there" tid
Util.ensureDeletedState True extern owner
testDeleteBindingTeamNoMembers :: TestM ()
testDeleteBindingTeamNoMembers = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam
deleteUser owner !!! const 200 === statusCode
refreshIndex
delete (g . paths ["/i/teams", toByteString' tid]) !!! const 202 === statusCode
assertTeamDelete 10 "team delete, should be there" tid
testDeleteBindingTeamMoreThanOneMember :: TestM ()
testDeleteBindingTeamMoreThanOneMember = do
g <- viewGalley
b <- viewBrig
c <- view tsCannon
(alice, tid, members) <- Util.createBindingTeamWithNMembers 10
void . WS.bracketRN c (alice : members) $ \(wsAlice : wsMembers) -> do
deleting a team with more than one member should be forbidden
delete (g . paths ["/i/teams", toByteString' tid]) !!! do
const 403 === statusCode
const "not-one-member-team" === (Error.label . responseJsonUnsafeWithMsg "error label when deleting a team")
delete (g . paths ["/i/teams", toByteString' tid] . queryItem "force" "true") !!! do
const 202 === statusCode
checkUserDeleteEvent alice wsAlice
zipWithM_ checkUserDeleteEvent members wsMembers
assertTeamDelete 10 "team delete, should be there" tid
let ensureDeleted :: UserId -> TestM ()
ensureDeleted uid = do
resp <- get (b . paths ["/i/users", toByteString' uid, "status"]) <!! const 200 === statusCode
let mbStatus = fmap fromAccountStatusResp . responseJsonUnsafe $ resp
liftIO $ mbStatus @?= Just Brig.Deleted
ensureDeleted alice
for_ members ensureDeleted
testDeleteTeamVerificationCodeSuccess :: TestM ()
testDeleteTeamVerificationCodeSuccess = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam'
let Just email = U.userEmail owner
setFeatureLockStatus @Public.SndFactorPasswordChallengeConfig tid Public.LockStatusUnlocked
setTeamSndFactorPasswordChallenge tid Public.FeatureStatusEnabled
generateVerificationCode $ Public.SendVerificationCode Public.DeleteTeam email
code <- getVerificationCode (U.userId owner) Public.DeleteTeam
delete
( g
. paths ["teams", toByteString' tid]
. zUser (U.userId owner)
. zConn "conn"
. json (newTeamDeleteDataWithCode (Just Util.defPassword) (Just code))
)
!!! do
const 202 === statusCode
assertTeamDelete 10 "team delete, should be there" tid
@SF.Channel @TSFI.RESTfulAPI @S2
Test that team can not be deleted with missing second factor email verification code when this feature is enabled
testDeleteTeamVerificationCodeMissingCode :: TestM ()
testDeleteTeamVerificationCodeMissingCode = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam'
setFeatureLockStatus @Public.SndFactorPasswordChallengeConfig tid Public.LockStatusUnlocked
setTeamSndFactorPasswordChallenge tid Public.FeatureStatusEnabled
let Just email = U.userEmail owner
generateVerificationCode $ Public.SendVerificationCode Public.DeleteTeam email
delete
( g
. paths ["teams", toByteString' tid]
. zUser (U.userId owner)
. zConn "conn"
. json (newTeamMemberDeleteData (Just Util.defPassword))
)
!!! do
const 403 === statusCode
const "code-authentication-required" === (Error.label . responseJsonUnsafeWithMsg "error label")
@END
@SF.Channel @TSFI.RESTfulAPI @S2
Test that team can not be deleted with expired second factor email verification code when this feature is enabled
testDeleteTeamVerificationCodeExpiredCode :: TestM ()
testDeleteTeamVerificationCodeExpiredCode = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam'
setFeatureLockStatus @Public.SndFactorPasswordChallengeConfig tid Public.LockStatusUnlocked
setTeamSndFactorPasswordChallenge tid Public.FeatureStatusEnabled
let Just email = U.userEmail owner
generateVerificationCode $ Public.SendVerificationCode Public.DeleteTeam email
code <- getVerificationCode (U.userId owner) Public.DeleteTeam
wait > 5 sec for the code to expire ( assumption : setVerificationTimeout in brig.integration.yaml is set to < = 5 sec )
threadDelay $ (10 * 1000 * 1000) + 600 * 1000
delete
( g
. paths ["teams", toByteString' tid]
. zUser (U.userId owner)
. zConn "conn"
. json (newTeamDeleteDataWithCode (Just Util.defPassword) (Just code))
)
!!! do
const 403 === statusCode
const "code-authentication-failed" === (Error.label . responseJsonUnsafeWithMsg "error label")
@END
@SF.Channel @TSFI.RESTfulAPI @S2
Test that team can not be deleted with wrong second factor email verification code when this feature is enabled
testDeleteTeamVerificationCodeWrongCode :: TestM ()
testDeleteTeamVerificationCodeWrongCode = do
g <- viewGalley
(owner, tid) <- Util.createBindingTeam'
setFeatureLockStatus @Public.SndFactorPasswordChallengeConfig tid Public.LockStatusUnlocked
setTeamSndFactorPasswordChallenge tid Public.FeatureStatusEnabled
let Just email = U.userEmail owner
generateVerificationCode $ Public.SendVerificationCode Public.DeleteTeam email
let wrongCode = Code.Value $ unsafeRange (fromRight undefined (validate "123456"))
delete
( g
. paths ["teams", toByteString' tid]
. zUser (U.userId owner)
. zConn "conn"
. json (newTeamDeleteDataWithCode (Just Util.defPassword) (Just wrongCode))
)
!!! do
const 403 === statusCode
const "code-authentication-failed" === (Error.label . responseJsonUnsafeWithMsg "error label")
@END
setFeatureLockStatus :: forall cfg. (KnownSymbol (Public.FeatureSymbol cfg)) => TeamId -> Public.LockStatus -> TestM ()
setFeatureLockStatus tid status = do
g <- viewGalley
put (g . paths ["i", "teams", toByteString' tid, "features", Public.featureNameBS @cfg, toByteString' status]) !!! const 200 === statusCode
generateVerificationCode :: Public.SendVerificationCode -> TestM ()
generateVerificationCode req = do
brig <- viewBrig
let js = RequestBodyLBS $ encode req
post (brig . paths ["verification-code", "send"] . contentJson . body js) !!! const 200 === statusCode
setTeamSndFactorPasswordChallenge :: TeamId -> Public.FeatureStatus -> TestM ()
setTeamSndFactorPasswordChallenge tid status = do
g <- viewGalley
let js = RequestBodyLBS $ encode $ Public.WithStatusNoLock status Public.SndFactorPasswordChallengeConfig Public.FeatureTTLUnlimited
put (g . paths ["i", "teams", toByteString' tid, "features", Public.featureNameBS @Public.SndFactorPasswordChallengeConfig] . contentJson . body js) !!! const 200 === statusCode
getVerificationCode :: UserId -> Public.VerificationAction -> TestM Code.Value
getVerificationCode uid action = do
brig <- viewBrig
resp <-
get (brig . paths ["i", "users", toByteString' uid, "verification-code", toByteString' action])
<!! const 200
=== statusCode
pure $ responseJsonUnsafe @Code.Value resp
testDeleteBindingTeam :: Bool -> TestM ()
testDeleteBindingTeam ownerHasPassword = do
g <- viewGalley
c <- view tsCannon
(ownerWithPassword, tid) <- Util.createBindingTeam
ownerMem <-
if ownerHasPassword
then Util.addUserToTeam ownerWithPassword tid
else Util.addUserToTeamWithSSO True tid
assertTeamUpdate "team member join 2" tid 2 [ownerWithPassword]
refreshIndex
Util.makeOwner ownerWithPassword ownerMem tid
let owner = view userId ownerMem
assertTeamUpdate "team member promoted" tid 2 [ownerWithPassword, owner]
refreshIndex
mem1 <- Util.addUserToTeam owner tid
assertTeamUpdate "team member join 3" tid 3 [ownerWithPassword, owner]
refreshIndex
mem2 <- Util.addUserToTeam owner tid
assertTeamUpdate "team member join 4" tid 4 [ownerWithPassword, owner]
refreshIndex
mem3 <- Util.addUserToTeam owner tid
assertTeamUpdate "team member join 5" tid 5 [ownerWithPassword, owner]
refreshIndex
extern <- Util.randomUser
delete
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json (newTeamDeleteData (Just $ PlainTextPassword "wrong passwd"))
)
!!! do
const 403 === statusCode
const "access-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' (mem3 ^. userId)]
. zUser owner
. zConn "conn"
. json
( newTeamMemberDeleteData
( if ownerHasPassword
then Just Util.defPassword
else Nothing
)
)
)
!!! const 202
=== statusCode
assertTeamUpdate "team member leave 1" tid 4 [ownerWithPassword, owner]
void . WS.bracketRN c [owner, mem1 ^. userId, mem2 ^. userId, extern] $ \[wsOwner, wsMember1, wsMember2, wsExtern] -> do
delete
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json
( newTeamDeleteData
( if ownerHasPassword
then Just Util.defPassword
else Nothing
)
)
)
!!! const 202
=== statusCode
checkUserDeleteEvent owner wsOwner
checkUserDeleteEvent (mem1 ^. userId) wsMember1
checkUserDeleteEvent (mem2 ^. userId) wsMember2
checkTeamDeleteEvent tid wsOwner
checkTeamDeleteEvent tid wsMember1
checkTeamDeleteEvent tid wsMember2
WS.assertNoEvent (1 # Second) [wsExtern]
assertTeamDelete 10 "team delete, should be there" tid
forM_ [owner, mem1 ^. userId, mem2 ^. userId] $
Util.ensureDeletedState True extern
testDeleteTeamConv :: TestM ()
testDeleteTeamConv = do
localDomain <- viewFederationDomain
c <- view tsCannon
(tid, owner, _) <- Util.createBindingTeamWithMembers 2
qOwner <- Qualified owner <$> viewFederationDomain
let p = Util.symmPermissions [DoNotUseDeprecatedDeleteConversation]
member <- newTeamMember' p <$> Util.randomUser
qMember <- Qualified (member ^. userId) <$> viewFederationDomain
Util.addTeamMemberInternal tid (member ^. userId) (member ^. permissions) Nothing
let members = [qOwner, qMember]
extern <- Util.randomUser
qExtern <- Qualified extern <$> viewFederationDomain
for_ members $ \m -> Util.connectUsers (m & qUnqualified) (list1 extern [])
cid1 <- Util.createTeamConv owner tid [] (Just "blaa") Nothing Nothing
qcid1 <- Qualified cid1 <$> viewFederationDomain
let access = ConversationAccessData (Set.fromList [InviteAccess, CodeAccess]) (Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole])
putQualifiedAccessUpdate owner qcid1 access !!! const 200 === statusCode
code <- decodeConvCodeEvent <$> (postConvCode owner cid1 <!! const 201 === statusCode)
cid2 <- Util.createTeamConv owner tid (qUnqualified <$> members) (Just "blup") Nothing Nothing
Util.postMembers owner (qExtern :| [qMember]) qcid1 !!! const 200 === statusCode
for_ (qExtern : members) $ \u -> Util.assertConvMember u cid1
for_ members $ flip Util.assertConvMember cid2
WS.bracketR3 c owner extern (member ^. userId) $ \(wsOwner, wsExtern, wsMember) -> do
deleteTeamConv tid cid2 (member ^. userId)
!!! const 200
=== statusCode
i.e. , as both a regular " conversation.delete " to all
let qcid2 = Qualified cid2 localDomain
checkConvDeleteEvent qcid2 wsOwner
checkConvDeleteEvent qcid2 wsMember
WS.assertNoEvent timeout [wsOwner, wsMember]
deleteTeamConv tid cid1 (member ^. userId)
!!! const 200
=== statusCode
i.e. , as both a regular " conversation.delete " to all
checkConvDeleteEvent qcid1 wsOwner
checkConvDeleteEvent qcid1 wsMember
checkConvDeleteEvent qcid1 wsExtern
WS.assertNoEvent timeout [wsOwner, wsMember, wsExtern]
for_ [cid1, cid2] $ \x ->
for_ [owner, member ^. userId, extern] $ \u -> do
Util.getConv u x !!! const 404 === statusCode
Util.assertNotConvMember u x
postConvCodeCheck code !!! const 404 === statusCode
testUpdateTeamIconValidation :: TestM ()
testUpdateTeamIconValidation = do
g <- viewGalley
(tid, owner, _) <- Util.createBindingTeamWithMembers 2
let update payload expectedStatusCode =
put
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json payload
)
!!! const expectedStatusCode
=== statusCode
let payloadWithInvalidIcon = object ["name" .= String "name", "icon" .= String "invalid"]
update payloadWithInvalidIcon 400
let payloadWithValidIcon =
object
[ "name" .= String "name",
"icon" .= String "3-1-47de4580-ae51-4650-acbb-d10c028cb0ac"
]
update payloadWithValidIcon 200
let payloadSetIconToDefault = object ["icon" .= String "default"]
update payloadSetIconToDefault 200
testUpdateTeam :: TestM ()
testUpdateTeam = do
g <- viewGalley
c <- view tsCannon
(tid, owner, [member]) <- Util.createBindingTeamWithMembers 2
let doPut :: LByteString -> Int -> TestM ()
doPut payload code =
put
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. contentJson
. body (RequestBodyLBS payload)
)
!!! const code
=== statusCode
let bad = object ["name" .= T.replicate 100 "too large"]
doPut (encode bad) 400
let u =
newTeamUpdateData
& nameUpdate ?~ unsafeRange "bar"
& iconUpdate .~ fromByteString "3-1-47de4580-ae51-4650-acbb-d10c028cb0ac"
& iconKeyUpdate ?~ unsafeRange "yyy"
& splashScreenUpdate .~ fromByteString "3-1-e1c89a56-882e-4694-bab3-c4f57803c57a"
WS.bracketR2 c owner member $ \(wsOwner, wsMember) -> do
doPut (encode u) 200
checkTeamUpdateEvent tid u wsOwner
checkTeamUpdateEvent tid u wsMember
WS.assertNoEvent timeout [wsOwner, wsMember]
t <- Util.getTeam owner tid
liftIO $ assertEqual "teamSplashScreen" (t ^. teamSplashScreen) (fromJust $ fromByteString "3-1-e1c89a56-882e-4694-bab3-c4f57803c57a")
do
doPut "{\"name\": \"new team name\", \"splash_screen\": null}" 200
t' <- Util.getTeam owner tid
liftIO $ assertEqual "teamSplashScreen" (t' ^. teamSplashScreen) (fromJust $ fromByteString "3-1-e1c89a56-882e-4694-bab3-c4f57803c57a")
do
doPut "{\"splash_screen\": \"default\"}" 200
t' <- Util.getTeam owner tid
liftIO $ assertEqual "teamSplashScreen" (t' ^. teamSplashScreen) DefaultIcon
testTeamAddRemoveMemberAboveThresholdNoEvents :: HasCallStack => TestM ()
testTeamAddRemoveMemberAboveThresholdNoEvents = do
localDomain <- viewFederationDomain
o <- view tsGConf
c <- view tsCannon
let fanoutLimit = fromIntegral . fromRange $ Galley.currentFanoutLimit o
(owner, tid) <- Util.createBindingTeam
member1 <- addTeamMemberAndExpectEvent True tid owner
Now last fill the team until truncationSize - 2
replicateM_ (fanoutLimit - 4) $ Util.addUserToTeam owner tid
(extern, qextern) <- Util.randomUserTuple
modifyTeamDataAndExpectEvent True tid owner
member2 <- do
temp <- addTeamMemberAndExpectEvent True tid owner
Util.connectUsers extern (list1 temp [])
removeTeamMemberAndExpectEvent True owner tid temp [extern]
addTeamMemberAndExpectEvent True tid owner
modifyUserProfileAndExpectEvent True owner [member1, member2]
Util.connectUsers extern (list1 owner [member1, member2])
_memLastWithFanout <- addTeamMemberAndExpectEvent True tid owner
Due to the async nature of pushes , waiting even a second might not
WS.bracketR c owner $ \wsOwner -> WS.assertNoEvent (1 # Second) [wsOwner]
_memWithoutFanout <- addTeamMemberAndExpectEvent False tid owner
modifyTeamDataAndExpectEvent False tid owner
modifyUserProfileAndExpectEvent False owner [member1, member2]
Let us remove 1 member that exceeds the limit , verify that team users
removeTeamMemberAndExpectEvent False owner tid member2 [extern]
removeTeamMemberAndExpectEvent True owner tid member1 [extern]
_memLastWithFanout <- addTeamMemberAndExpectEvent True tid owner
Due to the async nature of pushes , waiting even a second might not
WS.bracketR c owner $ \wsOwner -> WS.assertNoEvent (1 # Second) [wsOwner]
_memWithoutFanout <- addTeamMemberAndExpectEvent False tid owner
cid1 <- Util.createTeamConv owner tid [] (Just "blaa") Nothing Nothing
qcid1 <- Qualified cid1 <$> viewFederationDomain
Util.postMembers owner (pure qextern) qcid1 !!! const 200 === statusCode
deleteTeam tid owner [] [Qualified cid1 localDomain] extern
where
modifyUserProfileAndExpectEvent :: HasCallStack => Bool -> UserId -> [UserId] -> TestM ()
modifyUserProfileAndExpectEvent expect target listeners = do
c <- view tsCannon
b <- viewBrig
WS.bracketRN c listeners $ \wsListeners -> do
let u = U.UserUpdate (Just $ U.Name "name") Nothing Nothing Nothing
put
( b
. paths ["self"]
. zUser target
. zConn "conn"
. json u
)
!!! const 200
=== statusCode
if expect
then mapM_ (checkUserUpdateEvent target) wsListeners
else WS.assertNoEvent (1 # Second) wsListeners
modifyTeamDataAndExpectEvent :: HasCallStack => Bool -> TeamId -> UserId -> TestM ()
modifyTeamDataAndExpectEvent expect tid origin = do
c <- view tsCannon
g <- viewGalley
let u = newTeamUpdateData & nameUpdate ?~ unsafeRange "bar"
WS.bracketR c origin $ \wsOrigin -> do
put
( g
. paths ["teams", toByteString' tid]
. zUser origin
. zConn "conn"
. json u
)
!!! const 200
=== statusCode
if expect
then checkTeamUpdateEvent tid u wsOrigin
else WS.assertNoEvent (1 # Second) [wsOrigin]
addTeamMemberAndExpectEvent :: HasCallStack => Bool -> TeamId -> UserId -> TestM UserId
addTeamMemberAndExpectEvent expect tid origin = do
c <- view tsCannon
WS.bracketR c origin $ \wsOrigin -> do
member <- view userId <$> Util.addUserToTeam origin tid
refreshIndex
if expect
then checkTeamMemberJoin tid member wsOrigin
else WS.assertNoEvent (1 # Second) [wsOrigin]
pure member
removeTeamMemberAndExpectEvent :: HasCallStack => Bool -> UserId -> TeamId -> UserId -> [UserId] -> TestM ()
removeTeamMemberAndExpectEvent expect owner tid victim others = do
c <- view tsCannon
g <- viewGalley
WS.bracketRN c (owner : victim : others) $ \(wsOwner : _wsVictim : wsOthers) -> do
delete
( g
. paths ["teams", toByteString' tid, "members", toByteString' victim]
. zUser owner
. zConn "conn"
. json (newTeamMemberDeleteData (Just $ Util.defPassword))
)
!!! const 202
=== statusCode
if expect
then checkTeamMemberLeave tid victim wsOwner
else WS.assertNoEvent (1 # Second) [wsOwner]
mapM_ (checkUserDeleteEvent victim) wsOthers
Util.ensureDeletedState True owner victim
deleteTeam :: HasCallStack => TeamId -> UserId -> [UserId] -> [Qualified ConvId] -> UserId -> TestM ()
deleteTeam tid owner otherRealUsersInTeam teamCidsThatExternBelongsTo extern = do
c <- view tsCannon
g <- viewGalley
void . WS.bracketRN c (owner : extern : otherRealUsersInTeam) $ \(_wsOwner : wsExtern : _wsotherRealUsersInTeam) -> do
delete
( g
. paths ["teams", toByteString' tid]
. zUser owner
. zConn "conn"
. json (newTeamDeleteData (Just Util.defPassword))
)
!!! const 202
=== statusCode
for_ (owner : otherRealUsersInTeam) $ \u -> checkUserDeleteEvent u wsExtern
for_ (owner : otherRealUsersInTeam) $ Util.ensureDeletedState True extern
mapM_ (flip checkConvDeleteEvent wsExtern) teamCidsThatExternBelongsTo
void $
retryWhileN
10
((/= TeamsIntra.Deleted) . TeamsIntra.tdStatus)
(getTeamInternal tid)
testBillingInLargeTeam :: TestM ()
testBillingInLargeTeam = do
(firstOwner, team) <- Util.createBindingTeam
refreshIndex
opts <- view tsGConf
galley <- viewGalley
let fanoutLimit = fromRange $ Galley.currentFanoutLimit opts
allOwnersBeforeFanoutLimit <-
foldM
( \billingMembers n -> do
newBillingMemberId <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
let allBillingMembers = newBillingMemberId : billingMembers
assertTeamUpdate ("add " <> show n <> "th billing member: " <> show newBillingMemberId) team n allBillingMembers
refreshIndex
pure allBillingMembers
)
[firstOwner]
[2 .. (fanoutLimit + 1)]
ownerFanoutPlusTwo <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate ("add fanoutLimit + 2nd billing member: " <> show ownerFanoutPlusTwo) team (fanoutLimit + 2) (ownerFanoutPlusTwo : allOwnersBeforeFanoutLimit)
refreshIndex
ownerFanoutPlusThree <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate ("add fanoutLimit + 3rd billing member: " <> show ownerFanoutPlusThree) team (fanoutLimit + 3) (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusTwo, ownerFanoutPlusThree])
refreshIndex
Util.deleteTeamMember galley team firstOwner ownerFanoutPlusThree
assertTeamUpdate ("delete fanoutLimit + 3rd billing member: " <> show ownerFanoutPlusThree) team (fanoutLimit + 2) (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusTwo])
refreshIndex
testBillingInLargeTeamWithoutIndexedBillingTeamMembers :: TestM ()
testBillingInLargeTeamWithoutIndexedBillingTeamMembers = do
(firstOwner, team) <- Util.createBindingTeam
refreshIndex
opts <- view tsGConf
galley <- viewGalley
let withoutIndexedBillingTeamMembers =
withSettingsOverrides (\o -> o & optSettings . setEnableIndexedBillingTeamMembers ?~ False)
let fanoutLimit = fromRange $ Galley.currentFanoutLimit opts
billingUsers <- mapM (\n -> (n,) <$> randomUser) [2 .. (fanoutLimit + 1)]
allOwnersBeforeFanoutLimit <-
withoutIndexedBillingTeamMembers $
foldM
( \billingMembers (n, newBillingMemberId) -> do
let mem = json $ Member.mkNewTeamMember newBillingMemberId (rolePermissions RoleOwner) Nothing
post (galley . paths ["i", "teams", toByteString' team, "members"] . mem)
!!! const 200
=== statusCode
let allBillingMembers = newBillingMemberId : billingMembers
members from being indexed . Hence the count of team is always 2
assertTeamUpdate ("add " <> show n <> "th billing member: " <> show newBillingMemberId) team 2 allBillingMembers
pure allBillingMembers
)
[firstOwner]
billingUsers
refreshIndex
If we add another owner , one of them wo n't get notified
ownerFanoutPlusTwo <- randomUser
let memFanoutPlusTwo = json $ Member.mkNewTeamMember ownerFanoutPlusTwo (rolePermissions RoleOwner) Nothing
withoutIndexedBillingTeamMembers $ do
g <- viewGalley
post (g . paths ["i", "teams", toByteString' team, "members"] . memFanoutPlusTwo)
!!! const 200
=== statusCode
assertIfWatcher ("add " <> show (fanoutLimit + 2) <> "th billing member: " <> show ownerFanoutPlusTwo) (updateMatcher team) $
\s maybeEvent ->
liftIO $ case maybeEvent of
Nothing -> assertFailure "Expected 1 TeamUpdate, got nothing"
Just event -> do
assertEqual (s <> ": eventType") E.TeamEvent'TEAM_UPDATE (event ^. E.eventType)
assertEqual (s <> ": count") 2 (event ^. E.eventData . E.memberCount)
let reportedBillingUserIds = mapMaybe (UUID.fromByteString . fromStrict) (event ^. E.eventData . E.billingUser)
assertEqual (s <> ": number of billing users") (fromIntegral fanoutLimit + 1) (length reportedBillingUserIds)
refreshIndex
ownerFanoutPlusThree <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate
("add fanoutLimit + 3rd billing member: " <> show ownerFanoutPlusThree)
team
2
(allOwnersBeforeFanoutLimit <> [ownerFanoutPlusTwo, ownerFanoutPlusThree])
refreshIndex
withoutIndexedBillingTeamMembers $ Util.deleteTeamMember galley team firstOwner ownerFanoutPlusTwo
Util.waitForMemberDeletion firstOwner team ownerFanoutPlusTwo
assertTeamUpdate "delete 1 owner" team 1 (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusThree])
ownerFanoutPlusFour <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate
("add billing member to test deletion: " <> show ownerFanoutPlusFour)
team
3
(allOwnersBeforeFanoutLimit <> [ownerFanoutPlusThree, ownerFanoutPlusFour])
refreshIndex
let demoteFanoutPlusThree = Member.mkNewTeamMember ownerFanoutPlusThree (rolePermissions RoleAdmin) Nothing
withoutIndexedBillingTeamMembers $ updateTeamMember galley team firstOwner demoteFanoutPlusThree !!! const 200 === statusCode
assertTeamUpdate "demote 1 user" team 3 (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusFour])
ownerFanoutPlusFive <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate
("add billing member to test demotion: " <> show ownerFanoutPlusFive)
team
4
(allOwnersBeforeFanoutLimit <> [ownerFanoutPlusFour, ownerFanoutPlusFive])
refreshIndex
let promoteFanoutPlusThree = Member.mkNewTeamMember ownerFanoutPlusThree (rolePermissions RoleOwner) Nothing
withoutIndexedBillingTeamMembers $ updateTeamMember galley team firstOwner promoteFanoutPlusThree !!! const 200 === statusCode
assertTeamUpdate "demote 1 user" team 4 (allOwnersBeforeFanoutLimit <> [ownerFanoutPlusThree, ownerFanoutPlusFour, ownerFanoutPlusFive])
ownerFanoutPlusSix <- view userId <$> Util.addUserToTeamWithRole (Just RoleOwner) firstOwner team
assertTeamUpdate
("add billing member to test promotion: " <> show ownerFanoutPlusSix)
team
5
(allOwnersBeforeFanoutLimit <> [ownerFanoutPlusThree, ownerFanoutPlusFour, ownerFanoutPlusFive, ownerFanoutPlusSix])
where
updateTeamMember g tid zusr change =
put
( g
. paths ["teams", toByteString' tid, "members"]
. zUser zusr
. zConn "conn"
. json change
)
| @SF.Management @TSFI.RESTfulAPI @S2
testUpdateTeamMember :: TestM ()
testUpdateTeamMember = do
g <- viewGalley
c <- view tsCannon
(owner, tid) <- Util.createBindingTeam
member <- Util.addUserToTeamWithRole (Just RoleAdmin) owner tid
assertTeamUpdate "add member" tid 2 [owner]
refreshIndex
let demoteOwner = Member.mkNewTeamMember owner (rolePermissions RoleAdmin) Nothing
updateTeamMember g tid (member ^. userId) demoteOwner !!! do
const 403 === statusCode
const "access-denied" === (Error.label . responseJsonUnsafeWithMsg "error label")
let demoteMember = Member.mkNewTeamMember (member ^. userId) noPermissions (member ^. invitation)
WS.bracketR2 c owner (member ^. userId) $ \(wsOwner, wsMember) -> do
updateTeamMember g tid owner demoteMember !!! do
const 200 === statusCode
member' <- Util.getTeamMember owner tid (member ^. userId)
liftIO $ assertEqual "permissions" (member' ^. permissions) (demoteMember ^. nPermissions)
checkTeamMemberUpdateEvent tid (member ^. userId) wsOwner (pure noPermissions)
checkTeamMemberUpdateEvent tid (member ^. userId) wsMember (pure noPermissions)
WS.assertNoEvent timeout [wsOwner, wsMember]
assertTeamUpdate "Member demoted" tid 2 [owner]
let promoteMember = Member.mkNewTeamMember (member ^. userId) fullPermissions (member ^. invitation)
WS.bracketR2 c owner (member ^. userId) $ \(wsOwner, wsMember) -> do
updateTeamMember g tid owner promoteMember !!! do
const 200 === statusCode
member' <- Util.getTeamMember owner tid (member ^. userId)
liftIO $ assertEqual "permissions" (member' ^. permissions) (promoteMember ^. nPermissions)
checkTeamMemberUpdateEvent tid (member ^. userId) wsOwner (pure fullPermissions)
checkTeamMemberUpdateEvent tid (member ^. userId) wsMember (pure fullPermissions)
WS.assertNoEvent timeout [wsOwner, wsMember]
assertTeamUpdate "Member promoted to owner" tid 2 [owner, member ^. userId]
updateTeamMember g tid owner demoteOwner !!! do
const 403 === statusCode
WS.bracketR2 c (member ^. userId) owner $ \(wsMember, wsOwner) -> do
updateTeamMember g tid (member ^. userId) demoteOwner !!! do
const 200 === statusCode
owner' <- Util.getTeamMember (member ^. userId) tid owner
liftIO $ assertEqual "permissions" (owner' ^. permissions) (demoteOwner ^. nPermissions)
owner no longer has GetPermissions , but she can still see the update because it 's about her !
checkTeamMemberUpdateEvent tid owner wsOwner (pure (rolePermissions RoleAdmin))
checkTeamMemberUpdateEvent tid owner wsMember (pure (rolePermissions RoleAdmin))
WS.assertNoEvent timeout [wsOwner, wsMember]
assertTeamUpdate "Owner demoted" tid 2 [member ^. userId]
where
updateTeamMember g tid zusr change =
put
( g
. paths ["teams", toByteString' tid, "members"]
. zUser zusr
. zConn "conn"
. json change
)
checkTeamMemberUpdateEvent tid uid w mPerm = WS.assertMatch_ timeout w $ \notif -> do
ntfTransient notif @?= False
let e = List1.head (WS.unpackPayload notif)
e ^. eventTeam @?= tid
e ^. eventData @?= EdMemberUpdate uid mPerm
@END
testUpdateTeamStatus :: TestM ()
testUpdateTeamStatus = do
g <- viewGalley
(_, tid) <- Util.createBindingTeam
Util.changeTeamStatus tid TeamsIntra.Active
Util.changeTeamStatus tid TeamsIntra.Suspended
assertTeamSuspend "suspend first time" tid
Util.changeTeamStatus tid TeamsIntra.Suspended
Util.changeTeamStatus tid TeamsIntra.Suspended
Util.changeTeamStatus tid TeamsIntra.Active
assertTeamActivate "activate again" tid
void $
put
( g
. paths ["i", "teams", toByteString' tid, "status"]
. json (TeamStatusUpdate TeamsIntra.Deleted Nothing)
)
!!! do
const 403 === statusCode
const "invalid-team-status-update" === (Error.label . responseJsonUnsafeWithMsg "error label")
postCryptoBroadcastMessage :: Broadcast -> TestM ()
postCryptoBroadcastMessage bcast = do
localDomain <- viewFederationDomain
let q :: Id a -> Qualified (Id a)
q = (`Qualified` localDomain)
c <- view tsCannon
Team1 : , . Team2 : . Regular user : . Connect , ,
(alice, tid) <- Util.createBindingTeam
bob <- view userId <$> Util.addUserToTeam alice tid
assertTeamUpdate "add bob" tid 2 [alice]
refreshIndex
(charlie, _) <- Util.createBindingTeam
refreshIndex
ac <- Util.randomClient alice (head someLastPrekeys)
bc <- Util.randomClient bob (someLastPrekeys !! 1)
cc <- Util.randomClient charlie (someLastPrekeys !! 2)
(dan, dc) <- randomUserWithClient (someLastPrekeys !! 3)
connectUsers alice (list1 charlie [dan])
A second client for
ac2 <- randomClient alice (someLastPrekeys !! 4)
Complete : broadcasts a message to , , and herself
let msg =
[ (alice, ac2, toBase64Text "ciphertext0"),
(bob, bc, toBase64Text "ciphertext1"),
(charlie, cc, toBase64Text "ciphertext2"),
(dan, dc, toBase64Text "ciphertext3")
]
WS.bracketRN c [bob, charlie, dan] $ \[wsB, wsC, wsD] ->
's clients 1 and 2 listen to their own messages only
WS.bracketR (c . queryItem "client" (toByteString' ac2)) alice $ \wsA2 ->
WS.bracketR (c . queryItem "client" (toByteString' ac)) alice $ \wsA1 -> do
Util.postBroadcast (q alice) ac bcast {bMessage = msg} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] []
should get the broadcast ( team member of alice )
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext1"))
should get the broadcast ( contact of alice and user of teams feature )
void . liftIO $
WS.assertMatch t wsC (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext2"))
should get the broadcast ( contact of alice and not user of teams feature )
void . liftIO $
WS.assertMatch t wsD (wsAssertOtr (q (selfConv dan)) (q alice) ac dc (toBase64Text "ciphertext3"))
's first client should not get the broadcast
assertNoMsg wsA1 (wsAssertOtr (q (selfConv alice)) (q alice) ac ac (toBase64Text "ciphertext0"))
's second client should get the broadcast
void . liftIO $
WS.assertMatch t wsA2 (wsAssertOtr (q (selfConv alice)) (q alice) ac ac2 (toBase64Text "ciphertext0"))
postCryptoBroadcastMessageFilteredTooLargeTeam :: Broadcast -> TestM ()
postCryptoBroadcastMessageFilteredTooLargeTeam bcast = do
localDomain <- viewFederationDomain
let q :: Id a -> Qualified (Id a)
q = (`Qualified` localDomain)
c <- view tsCannon
Team1 : alice , and 3 unnamed
(alice, tid) <- Util.createBindingTeam
bob <- view userId <$> Util.addUserToTeam alice tid
assertTeamUpdate "add bob" tid 2 [alice]
refreshIndex
forM_ [3 .. 5] $ \count -> do
void $ Util.addUserToTeam alice tid
assertTeamUpdate "add user" tid count [alice]
refreshIndex
Team2 :
(charlie, _) <- Util.createBindingTeam
refreshIndex
ac <- Util.randomClient alice (head someLastPrekeys)
bc <- Util.randomClient bob (someLastPrekeys !! 1)
cc <- Util.randomClient charlie (someLastPrekeys !! 2)
(dan, dc) <- randomUserWithClient (someLastPrekeys !! 3)
connectUsers alice (list1 charlie [dan])
A second client for
ac2 <- randomClient alice (someLastPrekeys !! 4)
Complete : broadcasts a message to , , and herself
let msg =
[ (alice, ac2, toBase64Text "ciphertext0"),
(bob, bc, toBase64Text "ciphertext1"),
(charlie, cc, toBase64Text "ciphertext2"),
(dan, dc, toBase64Text "ciphertext3")
]
WS.bracketRN c [bob, charlie, dan] $ \[wsB, wsC, wsD] ->
's clients 1 and 2 listen to their own messages only
WS.bracketR (c . queryItem "client" (toByteString' ac2)) alice $ \wsA2 ->
WS.bracketR (c . queryItem "client" (toByteString' ac)) alice $ \wsA1 -> do
let newOpts =
((optSettings . setMaxFanoutSize) ?~ unsafeRange 4)
. (optSettings . setMaxConvSize .~ 4)
withSettingsOverrides newOpts $ do
Untargeted , 's team is too large
Util.postBroadcast (q alice) ac bcast {bMessage = msg} !!! do
const 400 === statusCode
const "too-many-users-to-broadcast" === Error.label . responseJsonUnsafeWithMsg "error label"
We target the message to the 4 users , that should be fine
let inbody = Just [alice, bob, charlie, dan]
Util.postBroadcast (q alice) ac bcast {bReport = inbody, bMessage = msg} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] []
should get the broadcast ( team member of alice )
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext1"))
should get the broadcast ( contact of alice and user of teams feature )
void . liftIO $
WS.assertMatch t wsC (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext2"))
should get the broadcast ( contact of alice and not user of teams feature )
void . liftIO $
WS.assertMatch t wsD (wsAssertOtr (q (selfConv dan)) (q alice) ac dc (toBase64Text "ciphertext3"))
's first client should not get the broadcast
assertNoMsg wsA1 (wsAssertOtr (q (selfConv alice)) (q alice) ac ac (toBase64Text "ciphertext0"))
's second client should get the broadcast
void . liftIO $
WS.assertMatch t wsA2 (wsAssertOtr (q (selfConv alice)) (q alice) ac ac2 (toBase64Text "ciphertext0"))
postCryptoBroadcastMessageReportMissingBody :: Broadcast -> TestM ()
postCryptoBroadcastMessageReportMissingBody bcast = do
localDomain <- viewFederationDomain
(alice, tid) <- Util.createBindingTeam
let qalice = Qualified alice localDomain
bob <- view userId <$> Util.addUserToTeam alice tid
assertTeamUpdate "add bob" tid 2 [alice]
refreshIndex
ac <- Util.randomClient alice (head someLastPrekeys)
inquery = case bAPI bcast of
BroadcastLegacyQueryParams -> id
_ -> queryItem "report_missing" (toByteString' alice)
msg = [(alice, ac, "ciphertext0")]
Util.postBroadcast qalice ac bcast {bReport = Just [bob], bMessage = msg, bReq = inquery}
!!! const 412
=== statusCode
postCryptoBroadcastMessage2 :: Broadcast -> TestM ()
postCryptoBroadcastMessage2 bcast = do
localDomain <- viewFederationDomain
let q :: Id a -> Qualified (Id a)
q = (`Qualified` localDomain)
c <- view tsCannon
Team1 : , . Team2 : . Connect ,
(alice, tid) <- Util.createBindingTeam
bob <- view userId <$> Util.addUserToTeam alice tid
assertTeamUpdate "add bob" tid 2 [alice]
refreshIndex
(charlie, _) <- Util.createBindingTeam
refreshIndex
ac <- Util.randomClient alice (head someLastPrekeys)
bc <- Util.randomClient bob (someLastPrekeys !! 1)
cc <- Util.randomClient charlie (someLastPrekeys !! 2)
connectUsers alice (list1 charlie [])
Missing
let m1 = [(bob, bc, toBase64Text "ciphertext1")]
Util.postBroadcast (q alice) ac bcast {bMessage = m1} !!! do
const 412 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [(charlie, Set.singleton cc)] [] []
WS.bracketR2 c bob charlie $ \(wsB, wsE) -> do
let m2 = [(bob, bc, toBase64Text "ciphertext2"), (charlie, cc, toBase64Text "ciphertext2")]
Util.postBroadcast (q alice) ac bcast {bMessage = m2} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] []
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext2"))
void . liftIO $
WS.assertMatch t wsE (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext2"))
WS.bracketR3 c alice bob charlie $ \(wsA, wsB, wsE) -> do
let m3 =
[ (alice, ac, toBase64Text "ciphertext3"),
(bob, bc, toBase64Text "ciphertext3"),
(charlie, cc, toBase64Text "ciphertext3")
]
Util.postBroadcast (q alice) ac bcast {bMessage = m3} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [(alice, Set.singleton ac)] []
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext3"))
void . liftIO $
WS.assertMatch t wsE (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext3"))
should not get it
assertNoMsg wsA (wsAssertOtr (q (selfConv alice)) (q alice) ac ac (toBase64Text "ciphertext3"))
Deleted
WS.bracketR2 c bob charlie $ \(wsB, wsE) -> do
deleteClient charlie cc (Just defPassword) !!! const 200 === statusCode
liftIO $
WS.assertMatch_ (5 # WS.Second) wsE $
wsAssertClientRemoved cc
let m4 = [(bob, bc, toBase64Text "ciphertext4"), (charlie, cc, toBase64Text "ciphertext4")]
Util.postBroadcast (q alice) ac bcast {bMessage = m4} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] [(charlie, Set.singleton cc)]
void . liftIO $
WS.assertMatch t wsB (wsAssertOtr (q (selfConv bob)) (q alice) ac bc (toBase64Text "ciphertext4"))
assertNoMsg wsE (wsAssertOtr (q (selfConv charlie)) (q alice) ac cc (toBase64Text "ciphertext4"))
postCryptoBroadcastMessageNoTeam :: Broadcast -> TestM ()
postCryptoBroadcastMessageNoTeam bcast = do
localDomain <- viewFederationDomain
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
let qalice = Qualified alice localDomain
(bob, bc) <- randomUserWithClient (someLastPrekeys !! 1)
connectUsers alice (list1 bob [])
let msg = [(bob, bc, toBase64Text "ciphertext1")]
Util.postBroadcast qalice ac bcast {bMessage = msg} !!! const 404 === statusCode
postCryptoBroadcastMessage100OrMaxConns :: Broadcast -> TestM ()
postCryptoBroadcastMessage100OrMaxConns bcast = do
localDomain <- viewFederationDomain
c <- view tsCannon
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
let qalice = Qualified alice localDomain
tid <- createBindingTeamInternal "foo" alice
assertTeamActivate "" tid
((bob, bc), others) <- createAndConnectUserWhileLimitNotReached alice (100 :: Int) [] (someLastPrekeys !! 1)
connectUsers alice (list1 bob (fst <$> others))
WS.bracketRN c (bob : (fst <$> others)) $ \ws -> do
let f (u, clt) = (u, clt, toBase64Text "ciphertext")
let msg = (bob, bc, toBase64Text "ciphertext") : (f <$> others)
Util.postBroadcast qalice ac bcast {bMessage = msg} !!! do
const 201 === statusCode
assertBroadcastMismatch localDomain (bAPI bcast) [] [] []
let qbobself = Qualified (selfConv bob) localDomain
void . liftIO $
WS.assertMatch t (Imports.head ws) (wsAssertOtr qbobself qalice ac bc (toBase64Text "ciphertext"))
for_ (zip (tail ws) others) $ \(wsU, (u, clt)) -> do
let qself = Qualified (selfConv u) localDomain
liftIO $ WS.assertMatch t wsU (wsAssertOtr qself qalice ac clt (toBase64Text "ciphertext"))
where
createAndConnectUserWhileLimitNotReached alice remaining acc pk = do
(uid, cid) <- randomUserWithClient pk
(r1, r2) <- List1.head <$> connectUsersUnchecked alice (List1.singleton uid)
case (statusCode r1, statusCode r2, remaining, acc) of
(201, 200, 0, []) -> error "Need to connect with at least 1 user"
(201, 200, 0, x : xs) -> pure (x, xs)
(201, 200, _, _) -> createAndConnectUserWhileLimitNotReached alice (remaining - 1) ((uid, cid) : acc) pk
(403, 403, _, []) -> error "Need to connect with at least 1 user"
(403, 403, _, x : xs) -> pure (x, xs)
(xxx, yyy, _, _) -> error ("Unexpected while connecting users: " ++ show xxx ++ " and " ++ show yyy)
newTeamMember' :: Permissions -> UserId -> TeamMember
newTeamMember' perms uid = Member.mkTeamMember uid perms Nothing LH.defUserLegalHoldStatus
getSSOEnabledInternal :: HasCallStack => TeamId -> TestM ResponseLBS
getSSOEnabledInternal = Util.getTeamFeatureFlagInternal @Public.SSOConfig
putSSOEnabledInternal :: HasCallStack => TeamId -> Public.FeatureStatus -> TestM ()
putSSOEnabledInternal tid statusValue =
void $ Util.putTeamFeatureFlagInternal @Public.SSOConfig expect2xx tid (Public.WithStatusNoLock statusValue Public.SSOConfig Public.FeatureTTLUnlimited)
getSearchVisibility :: HasCallStack => (Request -> Request) -> UserId -> TeamId -> MonadHttp m => m ResponseLBS
getSearchVisibility g uid tid = do
get $
g
. paths ["teams", toByteString' tid, "search-visibility"]
. zUser uid
putSearchVisibility :: HasCallStack => (Request -> Request) -> UserId -> TeamId -> TeamSearchVisibility -> MonadHttp m => m ResponseLBS
putSearchVisibility g uid tid vis = do
put $
g
. paths ["teams", toByteString' tid, "search-visibility"]
. zUser uid
. json (TeamSearchVisibilityView vis)
checkJoinEvent :: (MonadIO m, MonadCatch m) => TeamId -> UserId -> WS.WebSocket -> m ()
checkJoinEvent tid usr w = WS.assertMatch_ timeout w $ \notif -> do
ntfTransient notif @?= False
let e = List1.head (WS.unpackPayload notif)
e ^. eventTeam @?= tid
e ^. eventData @?= EdMemberJoin usr
|
f1820d999b887943898ecadb8f18667c1ba1e6cfa8e0687ea6e524673ec6145a | donut/OCamURL-server | url.ml |
open Lib_common
open Lib_common.Ext_option
module Scheme = struct
type t = HTTP | HTTPS
exception No_matching_string of string
let of_string s = match String.lowercase_ascii s with
| "http" -> HTTP | "https" -> HTTPS
| _ -> raise (No_matching_string s)
let of_string_opt s =
try Some (of_string s) with _ -> None
let to_string = function HTTP -> "http" | HTTPS -> "https"
end
module ID : Convertable.IntType = Convertable.Int
module Username : Convertable.StringType = Convertable.String
module Password : Convertable.StringType = Convertable.String
module Host : Convertable.StringType = Convertable.String
module Port : Convertable.IntType = Convertable.Int
module Path : Convertable.StringType = struct
type t = string
let of_string x = x
let to_string x =
if String.length x > 0 && not (Char.equal (String.get x 0) '/')
then "/" ^ x else x
end
type param = { key: string; value: string option; }
module Params : sig
type t
val of_list : param list -> t
val to_list : t -> param list
val of_string : string -> t
val to_string : t -> string
end = struct
type t = param list
let of_list x = x
let to_list x = x
let of_string x =
let dec = Uri.pct_decode in
String.split_on_char '&' x
|> List.map (String.split_on_char '=')
|> List.map (function
| [] -> { key = ""; value = None }
| [key] -> { key = dec key; value = None }
| [key; value] -> { key = dec key; value = Some (dec value) }
| key :: value -> {
key = dec key;
value = Some (String.concat "=" value |> dec)
}
)
let to_string x =
let pair_up = List.map (fun { key; value; } ->
let enc = Uri.pct_encode in
let k = enc ~component:`Query_key key in
let v = match value with
| None -> ""
| Some v ->
"=" ^ enc ~component:`Query_value (value =?: lazy "") in
k ^ v
) in
String.concat "&" @@ pair_up x
end
module Fragment : Convertable.StringType = Convertable.String
type t = {
id: ID.t option;
scheme: Scheme.t;
user: Username.t option;
password: Password.t option;
host: Host.t;
port: Port.t option;
path: Path.t;
params: Params.t option;
fragment: Fragment.t option;
}
let set_id t id' =
{ t with id = Some (ID.of_int id') }
let id t = Core.Option.map t.id ID.to_int
type or_id = URL of t | ID of ID.t
let of_ref = function
| `ID id -> ID id
| `Int id -> ID (ID.of_int id)
| `Rec r -> URL r
| `Ref ref -> ref
let id_of_ref = function
| ID id
| URL { id = Some id } -> Some id
| _ -> None
let to_string url =
let opt_to_str maybe prefix to_string =
(maybe, (^) prefix <% to_string) =!?: lazy "" in
let scheme = Scheme.to_string url.scheme in
let user = opt_to_str url.user "" Username.to_string in
let password = opt_to_str url.password ":" Password.to_string in
let auth = match (url.user, url.password) with
| (None, None) -> ""
| _ -> user ^ password ^ "@" in
let host = Host.to_string url.host in
let path = Path.to_string url.path in
let port = opt_to_str url.port ":" (Port.to_int %> string_of_int) in
let params = opt_to_str url.params "?" Params.to_string in
let fragment = opt_to_str url.fragment "#" Fragment.to_string in
scheme ^ "://" ^ auth ^ host ^ port ^ path ^ params ^ fragment
let of_string url =
let module Opt = Core.Option in
let uri = Uri.of_string url in
let scheme = Scheme.of_string_opt (Uri.scheme uri =?: lazy "https")
=?: lazy Scheme.HTTPS in
{
id = None;
scheme;
user = map (Uri.user uri) (Username.of_string);
password = map (Uri.password uri) (Password.of_string);
host = Host.of_string @@ Uri.host_with_default ~default:"" uri;
port = map (Uri.port uri) (Port.of_int);
path = Path.of_string @@ Uri.path uri;
params = map (Uri.verbatim_query uri) (Params.of_string);
fragment = map (Uri.fragment uri) (Fragment.of_string);
} | null | https://raw.githubusercontent.com/donut/OCamURL-server/87738c1a0bbfc2c848f9f4e2052cacc81a176489/lib/model/url.ml | ocaml |
open Lib_common
open Lib_common.Ext_option
module Scheme = struct
type t = HTTP | HTTPS
exception No_matching_string of string
let of_string s = match String.lowercase_ascii s with
| "http" -> HTTP | "https" -> HTTPS
| _ -> raise (No_matching_string s)
let of_string_opt s =
try Some (of_string s) with _ -> None
let to_string = function HTTP -> "http" | HTTPS -> "https"
end
module ID : Convertable.IntType = Convertable.Int
module Username : Convertable.StringType = Convertable.String
module Password : Convertable.StringType = Convertable.String
module Host : Convertable.StringType = Convertable.String
module Port : Convertable.IntType = Convertable.Int
module Path : Convertable.StringType = struct
type t = string
let of_string x = x
let to_string x =
if String.length x > 0 && not (Char.equal (String.get x 0) '/')
then "/" ^ x else x
end
type param = { key: string; value: string option; }
module Params : sig
type t
val of_list : param list -> t
val to_list : t -> param list
val of_string : string -> t
val to_string : t -> string
end = struct
type t = param list
let of_list x = x
let to_list x = x
let of_string x =
let dec = Uri.pct_decode in
String.split_on_char '&' x
|> List.map (String.split_on_char '=')
|> List.map (function
| [] -> { key = ""; value = None }
| [key] -> { key = dec key; value = None }
| [key; value] -> { key = dec key; value = Some (dec value) }
| key :: value -> {
key = dec key;
value = Some (String.concat "=" value |> dec)
}
)
let to_string x =
let pair_up = List.map (fun { key; value; } ->
let enc = Uri.pct_encode in
let k = enc ~component:`Query_key key in
let v = match value with
| None -> ""
| Some v ->
"=" ^ enc ~component:`Query_value (value =?: lazy "") in
k ^ v
) in
String.concat "&" @@ pair_up x
end
module Fragment : Convertable.StringType = Convertable.String
type t = {
id: ID.t option;
scheme: Scheme.t;
user: Username.t option;
password: Password.t option;
host: Host.t;
port: Port.t option;
path: Path.t;
params: Params.t option;
fragment: Fragment.t option;
}
let set_id t id' =
{ t with id = Some (ID.of_int id') }
let id t = Core.Option.map t.id ID.to_int
type or_id = URL of t | ID of ID.t
let of_ref = function
| `ID id -> ID id
| `Int id -> ID (ID.of_int id)
| `Rec r -> URL r
| `Ref ref -> ref
let id_of_ref = function
| ID id
| URL { id = Some id } -> Some id
| _ -> None
let to_string url =
let opt_to_str maybe prefix to_string =
(maybe, (^) prefix <% to_string) =!?: lazy "" in
let scheme = Scheme.to_string url.scheme in
let user = opt_to_str url.user "" Username.to_string in
let password = opt_to_str url.password ":" Password.to_string in
let auth = match (url.user, url.password) with
| (None, None) -> ""
| _ -> user ^ password ^ "@" in
let host = Host.to_string url.host in
let path = Path.to_string url.path in
let port = opt_to_str url.port ":" (Port.to_int %> string_of_int) in
let params = opt_to_str url.params "?" Params.to_string in
let fragment = opt_to_str url.fragment "#" Fragment.to_string in
scheme ^ "://" ^ auth ^ host ^ port ^ path ^ params ^ fragment
let of_string url =
let module Opt = Core.Option in
let uri = Uri.of_string url in
let scheme = Scheme.of_string_opt (Uri.scheme uri =?: lazy "https")
=?: lazy Scheme.HTTPS in
{
id = None;
scheme;
user = map (Uri.user uri) (Username.of_string);
password = map (Uri.password uri) (Password.of_string);
host = Host.of_string @@ Uri.host_with_default ~default:"" uri;
port = map (Uri.port uri) (Port.of_int);
path = Path.of_string @@ Uri.path uri;
params = map (Uri.verbatim_query uri) (Params.of_string);
fragment = map (Uri.fragment uri) (Fragment.of_string);
} |
|
79daf870dc0db72f4e740534487501d112f4b26ee8c00926ef86420d46e22f1d | jfeser/castor | layout_to_depjoin.ml | open Core
open Ast
module V = Visitors
module S = Schema
module A = Constructors.Annot
let list l = { d_lhs = l.l_keys; d_rhs = l.l_values }
let dedup_names =
List.stable_dedup_staged ~compare:(fun n n' ->
[%compare: String.t] (Name.name n) (Name.name n'))
|> Staged.unstage
let hash_idx h =
let rk_schema = S.schema h.hi_keys |> S.zero
and rv_schema = S.schema h.hi_values in
let key_pred =
List.map2_exn rk_schema h.hi_lookup ~f:(fun p1 p2 ->
`Binop (Binop.Eq, `Name p1, p2))
|> Pred.conjoin
and slist = rk_schema @ rv_schema |> dedup_names |> Select_list.of_names in
{
d_lhs = strip_meta h.hi_keys;
d_rhs = A.select slist (A.filter key_pred h.hi_values);
}
let ordered_idx { oi_keys = rk; oi_values = rv; oi_lookup; _ } =
let rk = strip_meta rk and rv = strip_meta rv in
let rk_schema = S.schema rk and rv_schema = S.schema rv in
let key_pred =
List.zip_exn rk_schema oi_lookup
|> List.concat_map ~f:(fun (n, (lb, ub)) ->
let p1 =
Option.map lb ~f:(fun (p, b) ->
match b with
| `Closed -> [ `Binop (Binop.Ge, `Name n, p) ]
| `Open -> [ `Binop (Gt, `Name n, p) ])
|> Option.value ~default:[]
in
let p2 =
Option.map ub ~f:(fun (p, b) ->
match b with
| `Closed -> [ `Binop (Binop.Le, `Name n, p) ]
| `Open -> [ `Binop (Lt, `Name n, p) ])
|> Option.value ~default:[]
in
p1 @ p2)
|> Pred.conjoin
and slist = rk_schema @ rv_schema |> dedup_names |> Select_list.of_names in
{ d_lhs = rk; d_rhs = A.select slist (A.filter key_pred rv) }
let cross_tuple ts =
let scalars, others =
List.partition_map ts ~f:(fun r ->
match r.node with
| AScalar p -> First (p.s_pred, p.s_name)
| _ -> Second r)
in
let base_relation, base_schema =
match List.reduce others ~f:(A.join (`Bool true)) with
| Some r -> (r, S.schema r)
| None -> (A.scalar (`Int 0) (Fresh.name Global.fresh "x%d"), [])
in
let select_list = scalars @ S.to_select_list base_schema in
Select (select_list, base_relation)
let rec annot r = { r with node = query r.node }
and query = function
| AOrderedIdx o -> DepJoin (ordered_idx (V.Map.ordered_idx annot pred o))
| AHashIdx h -> DepJoin (hash_idx (V.Map.hash_idx annot pred h))
| AList l -> DepJoin (list @@ V.Map.list annot l)
| ATuple (ts, Cross) -> cross_tuple (List.map ~f:annot ts)
| q -> V.Map.query annot pred q
and pred p = V.Map.pred annot pred p
| null | https://raw.githubusercontent.com/jfeser/castor/e9f394e9c0984300f71dc77b5a457ae4e4faa226/lib/layout_to_depjoin.ml | ocaml | open Core
open Ast
module V = Visitors
module S = Schema
module A = Constructors.Annot
let list l = { d_lhs = l.l_keys; d_rhs = l.l_values }
let dedup_names =
List.stable_dedup_staged ~compare:(fun n n' ->
[%compare: String.t] (Name.name n) (Name.name n'))
|> Staged.unstage
let hash_idx h =
let rk_schema = S.schema h.hi_keys |> S.zero
and rv_schema = S.schema h.hi_values in
let key_pred =
List.map2_exn rk_schema h.hi_lookup ~f:(fun p1 p2 ->
`Binop (Binop.Eq, `Name p1, p2))
|> Pred.conjoin
and slist = rk_schema @ rv_schema |> dedup_names |> Select_list.of_names in
{
d_lhs = strip_meta h.hi_keys;
d_rhs = A.select slist (A.filter key_pred h.hi_values);
}
let ordered_idx { oi_keys = rk; oi_values = rv; oi_lookup; _ } =
let rk = strip_meta rk and rv = strip_meta rv in
let rk_schema = S.schema rk and rv_schema = S.schema rv in
let key_pred =
List.zip_exn rk_schema oi_lookup
|> List.concat_map ~f:(fun (n, (lb, ub)) ->
let p1 =
Option.map lb ~f:(fun (p, b) ->
match b with
| `Closed -> [ `Binop (Binop.Ge, `Name n, p) ]
| `Open -> [ `Binop (Gt, `Name n, p) ])
|> Option.value ~default:[]
in
let p2 =
Option.map ub ~f:(fun (p, b) ->
match b with
| `Closed -> [ `Binop (Binop.Le, `Name n, p) ]
| `Open -> [ `Binop (Lt, `Name n, p) ])
|> Option.value ~default:[]
in
p1 @ p2)
|> Pred.conjoin
and slist = rk_schema @ rv_schema |> dedup_names |> Select_list.of_names in
{ d_lhs = rk; d_rhs = A.select slist (A.filter key_pred rv) }
let cross_tuple ts =
let scalars, others =
List.partition_map ts ~f:(fun r ->
match r.node with
| AScalar p -> First (p.s_pred, p.s_name)
| _ -> Second r)
in
let base_relation, base_schema =
match List.reduce others ~f:(A.join (`Bool true)) with
| Some r -> (r, S.schema r)
| None -> (A.scalar (`Int 0) (Fresh.name Global.fresh "x%d"), [])
in
let select_list = scalars @ S.to_select_list base_schema in
Select (select_list, base_relation)
let rec annot r = { r with node = query r.node }
and query = function
| AOrderedIdx o -> DepJoin (ordered_idx (V.Map.ordered_idx annot pred o))
| AHashIdx h -> DepJoin (hash_idx (V.Map.hash_idx annot pred h))
| AList l -> DepJoin (list @@ V.Map.list annot l)
| ATuple (ts, Cross) -> cross_tuple (List.map ~f:annot ts)
| q -> V.Map.query annot pred q
and pred p = V.Map.pred annot pred p
|
|
6792f7b13521c2b0de6011af52e9186cd5a1701b7bb549574f1d220ac4e3b5cb | coq/coq | tac2interp.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
open Util
open Pp
open CErrors
open Names
open Proofview.Notations
open Tac2expr
open Tac2ffi
exception LtacError = Tac2ffi.LtacError
let backtrace : backtrace Evd.Store.field = Evd.Store.field ()
let print_ltac2_backtrace = ref false
let get_backtrace =
Proofview.tclEVARMAP >>= fun sigma ->
match Evd.Store.get (Evd.get_extra_data sigma) backtrace with
| None -> Proofview.tclUNIT []
| Some bt -> Proofview.tclUNIT bt
let set_backtrace bt =
Proofview.tclEVARMAP >>= fun sigma ->
let store = Evd.get_extra_data sigma in
let store = Evd.Store.set store backtrace bt in
let sigma = Evd.set_extra_data store sigma in
Proofview.Unsafe.tclEVARS sigma
let with_frame frame tac =
if !print_ltac2_backtrace then
get_backtrace >>= fun bt ->
set_backtrace (frame :: bt) >>= fun () ->
tac >>= fun ans ->
set_backtrace bt >>= fun () ->
Proofview.tclUNIT ans
else tac
type environment = Tac2env.environment = {
env_ist : valexpr Id.Map.t;
}
let empty_environment = {
env_ist = Id.Map.empty;
}
type closure = {
mutable clos_env : valexpr Id.Map.t;
(** Mutable so that we can implement recursive functions imperatively *)
clos_var : Name.t list;
(** Bound variables *)
clos_exp : glb_tacexpr;
(** Body *)
clos_ref : ltac_constant option;
(** Global constant from which the closure originates *)
}
let push_name ist id v = match id with
| Anonymous -> ist
| Name id -> { env_ist = Id.Map.add id v ist.env_ist }
let get_var ist id =
try Id.Map.find id ist.env_ist with Not_found ->
anomaly (str "Unbound variable " ++ Id.print id)
let get_ref ist kn =
try
let data = Tac2env.interp_global kn in
data.Tac2env.gdata_expr
with Not_found ->
anomaly (str "Unbound reference" ++ KerName.print kn)
let return = Proofview.tclUNIT
exception NoMatch
let match_ctor_against ctor v =
match ctor, v with
| { cindx = Open ctor }, ValOpn (ctor', vs) ->
if KerName.equal ctor ctor' then vs
else raise NoMatch
| { cindx = Open _ }, _ -> assert false
| { cnargs = 0; cindx = Closed i }, ValInt i' ->
if Int.equal i i' then [| |]
else raise NoMatch
| { cnargs = 0; cindx = Closed _ }, ValBlk _ -> raise NoMatch
| _, ValInt _ -> raise NoMatch
| { cindx = Closed i }, ValBlk (i', vs) ->
if Int.equal i i' then vs
else raise NoMatch
| { cindx = Closed _ }, ValOpn _ -> assert false
| _, (ValStr _ | ValCls _ | ValExt _ | ValUint63 _ | ValFloat _) -> assert false
let check_atom_against atm v =
match atm, v with
| AtmInt n, ValInt n' -> if not (Int.equal n n') then raise NoMatch
| AtmStr s, ValStr s' -> if not (String.equal s (Bytes.unsafe_to_string s')) then raise NoMatch
| (AtmInt _ | AtmStr _), _ -> assert false
let rec match_pattern_against ist pat v =
match pat with
| GPatVar x -> push_name ist x v
| GPatAtm atm -> check_atom_against atm v; ist
| GPatAs (p,x) -> match_pattern_against (push_name ist (Name x) v) p v
| GPatRef (ctor,pats) ->
let vs = match_ctor_against ctor v in
List.fold_left_i (fun i ist pat -> match_pattern_against ist pat vs.(i)) 0 ist pats
| GPatOr pats -> match_pattern_against_or ist pats v
and match_pattern_against_or ist pats v =
match pats with
| [] -> raise NoMatch
| pat :: pats ->
try match_pattern_against ist pat v
with NoMatch -> match_pattern_against_or ist pats v
let rec interp (ist : environment) = function
| GTacAtm (AtmInt n) -> return (Tac2ffi.of_int n)
| GTacAtm (AtmStr s) -> return (Tac2ffi.of_string s)
| GTacVar id -> return (get_var ist id)
| GTacRef kn ->
let data = get_ref ist kn in
return (eval_pure Id.Map.empty (Some kn) data)
| GTacFun (ids, e) ->
let cls = { clos_ref = None; clos_env = ist.env_ist; clos_var = ids; clos_exp = e } in
let f = interp_closure cls in
return f
| GTacApp (f, args) ->
interp ist f >>= fun f ->
Proofview.Monad.List.map (fun e -> interp ist e) args >>= fun args ->
Tac2ffi.apply (Tac2ffi.to_closure f) args
| GTacLet (false, el, e) ->
let fold accu (na, e) =
interp ist e >>= fun e ->
return (push_name accu na e)
in
Proofview.Monad.List.fold_left fold ist el >>= fun ist ->
interp ist e
| GTacLet (true, el, e) ->
let map (na, e) = match e with
| GTacFun (ids, e) ->
let cls = { clos_ref = None; clos_env = ist.env_ist; clos_var = ids; clos_exp = e } in
let f = interp_closure cls in
na, cls, f
| _ -> anomaly (str "Ill-formed recursive function")
in
let fixs = List.map map el in
let fold accu (na, _, cls) = match na with
| Anonymous -> accu
| Name id -> { env_ist = Id.Map.add id cls accu.env_ist }
in
let ist = List.fold_left fold ist fixs in
(* Hack to make a cycle imperatively in the environment *)
let iter (_, e, _) = e.clos_env <- ist.env_ist in
let () = List.iter iter fixs in
interp ist e
| GTacCst (_, n, []) -> return (Valexpr.make_int n)
| GTacCst (_, n, el) ->
Proofview.Monad.List.map (fun e -> interp ist e) el >>= fun el ->
return (Valexpr.make_block n (Array.of_list el))
| GTacCse (e, _, cse0, cse1) ->
interp ist e >>= fun e -> interp_case ist e cse0 cse1
| GTacWth { opn_match = e; opn_branch = cse; opn_default = def } ->
interp ist e >>= fun e -> interp_with ist e cse def
| GTacFullMatch (e,brs) ->
interp ist e >>= fun e -> interp_full_match ist e brs
| GTacPrj (_, e, p) ->
interp ist e >>= fun e -> interp_proj ist e p
| GTacSet (_, e, p, r) ->
interp ist e >>= fun e ->
interp ist r >>= fun r ->
interp_set ist e p r
| GTacOpn (kn, el) ->
Proofview.Monad.List.map (fun e -> interp ist e) el >>= fun el ->
return (Tac2ffi.of_open (kn, Array.of_list el))
| GTacPrm (ml, el) ->
Proofview.Monad.List.map (fun e -> interp ist e) el >>= fun el ->
with_frame (FrPrim ml) (Tac2ffi.apply (Tac2env.interp_primitive ml) el)
| GTacExt (tag, e) ->
let tpe = Tac2env.interp_ml_object tag in
with_frame (FrExtn (tag, e)) (tpe.Tac2env.ml_interp ist e)
and interp_closure f =
let ans = fun args ->
let { clos_env = ist; clos_var = ids; clos_exp = e; clos_ref = kn } = f in
let frame = match kn with
| None -> FrAnon e
| Some kn -> FrLtac kn
in
let ist = { env_ist = ist } in
let ist = List.fold_left2 push_name ist ids args in
with_frame frame (interp ist e)
in
Tac2ffi.(of_closure (abstract (List.length f.clos_var) ans))
and interp_case ist e cse0 cse1 =
if Valexpr.is_int e then
interp ist cse0.(Tac2ffi.to_int e)
else
let (n, args) = Tac2ffi.to_block e in
let (ids, e) = cse1.(n) in
let ist = CArray.fold_left2 push_name ist ids args in
interp ist e
and interp_with ist e cse def =
let (kn, args) = Tac2ffi.to_open e in
let br = try Some (KNmap.find kn cse) with Not_found -> None in
begin match br with
| None ->
let (self, def) = def in
let ist = push_name ist self e in
interp ist def
| Some (self, ids, p) ->
let ist = push_name ist self e in
let ist = CArray.fold_left2 push_name ist ids args in
interp ist p
end
and interp_full_match ist e = function
| [] -> CErrors.anomaly Pp.(str "ltac2 match not exhaustive")
| (pat,br) :: rest ->
begin match match_pattern_against ist pat e with
| exception NoMatch -> interp_full_match ist e rest
| ist -> interp ist br
end
and interp_proj ist e p =
return (Valexpr.field e p)
and interp_set ist e p r =
let () = Valexpr.set_field e p r in
return (Valexpr.make_int 0)
and eval_pure bnd kn = function
| GTacVar id -> Id.Map.get id bnd
| GTacAtm (AtmInt n) -> Valexpr.make_int n
| GTacRef kn ->
let { Tac2env.gdata_expr = e } =
try Tac2env.interp_global kn
with Not_found -> assert false
in
eval_pure bnd (Some kn) e
| GTacFun (na, e) ->
let cls = { clos_ref = kn; clos_env = bnd; clos_var = na; clos_exp = e } in
interp_closure cls
| GTacCst (_, n, []) -> Valexpr.make_int n
| GTacCst (_, n, el) -> Valexpr.make_block n (eval_pure_args bnd el)
| GTacOpn (kn, el) -> Tac2ffi.of_open (kn, eval_pure_args bnd el)
| GTacLet (isrec, vals, body) ->
let () = assert (not isrec) in
let fold accu (na, e) = match na with
| Anonymous ->
(* No need to evaluate, we know this is a value *)
accu
| Name id ->
let v = eval_pure bnd None e in
Id.Map.add id v accu
in
let bnd = List.fold_left fold bnd vals in
eval_pure bnd kn body
| GTacAtm (AtmStr _) | GTacSet _
| GTacApp _ | GTacCse _ | GTacPrj _
| GTacPrm _ | GTacExt _ | GTacWth _
| GTacFullMatch _ ->
anomaly (Pp.str "Term is not a syntactical value")
and eval_pure_args bnd args =
let map e = eval_pure bnd None e in
Array.map_of_list map args
let interp_value ist tac =
eval_pure ist.env_ist None tac
(** Cross-boundary hacks. *)
open Geninterp
let val_env : environment Val.typ = Val.create "ltac2:env"
let env_ref = Id.of_string_soft "@@ltac2_env@@"
let extract_env (Val.Dyn (tag, v)) : environment =
match Val.eq tag val_env with
| None -> assert false
| Some Refl -> v
let get_env ist =
try extract_env (Id.Map.find env_ref ist)
with Not_found -> empty_environment
let set_env env ist =
Id.Map.add env_ref (Val.Dyn (val_env, env)) ist
| null | https://raw.githubusercontent.com/coq/coq/be037486c27f29dc0bcfbfd742c0303af295e23f/plugins/ltac2/tac2interp.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
* Mutable so that we can implement recursive functions imperatively
* Bound variables
* Body
* Global constant from which the closure originates
Hack to make a cycle imperatively in the environment
No need to evaluate, we know this is a value
* Cross-boundary hacks. | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
open Util
open Pp
open CErrors
open Names
open Proofview.Notations
open Tac2expr
open Tac2ffi
exception LtacError = Tac2ffi.LtacError
let backtrace : backtrace Evd.Store.field = Evd.Store.field ()
let print_ltac2_backtrace = ref false
let get_backtrace =
Proofview.tclEVARMAP >>= fun sigma ->
match Evd.Store.get (Evd.get_extra_data sigma) backtrace with
| None -> Proofview.tclUNIT []
| Some bt -> Proofview.tclUNIT bt
let set_backtrace bt =
Proofview.tclEVARMAP >>= fun sigma ->
let store = Evd.get_extra_data sigma in
let store = Evd.Store.set store backtrace bt in
let sigma = Evd.set_extra_data store sigma in
Proofview.Unsafe.tclEVARS sigma
let with_frame frame tac =
if !print_ltac2_backtrace then
get_backtrace >>= fun bt ->
set_backtrace (frame :: bt) >>= fun () ->
tac >>= fun ans ->
set_backtrace bt >>= fun () ->
Proofview.tclUNIT ans
else tac
type environment = Tac2env.environment = {
env_ist : valexpr Id.Map.t;
}
let empty_environment = {
env_ist = Id.Map.empty;
}
type closure = {
mutable clos_env : valexpr Id.Map.t;
clos_var : Name.t list;
clos_exp : glb_tacexpr;
clos_ref : ltac_constant option;
}
let push_name ist id v = match id with
| Anonymous -> ist
| Name id -> { env_ist = Id.Map.add id v ist.env_ist }
let get_var ist id =
try Id.Map.find id ist.env_ist with Not_found ->
anomaly (str "Unbound variable " ++ Id.print id)
let get_ref ist kn =
try
let data = Tac2env.interp_global kn in
data.Tac2env.gdata_expr
with Not_found ->
anomaly (str "Unbound reference" ++ KerName.print kn)
let return = Proofview.tclUNIT
exception NoMatch
let match_ctor_against ctor v =
match ctor, v with
| { cindx = Open ctor }, ValOpn (ctor', vs) ->
if KerName.equal ctor ctor' then vs
else raise NoMatch
| { cindx = Open _ }, _ -> assert false
| { cnargs = 0; cindx = Closed i }, ValInt i' ->
if Int.equal i i' then [| |]
else raise NoMatch
| { cnargs = 0; cindx = Closed _ }, ValBlk _ -> raise NoMatch
| _, ValInt _ -> raise NoMatch
| { cindx = Closed i }, ValBlk (i', vs) ->
if Int.equal i i' then vs
else raise NoMatch
| { cindx = Closed _ }, ValOpn _ -> assert false
| _, (ValStr _ | ValCls _ | ValExt _ | ValUint63 _ | ValFloat _) -> assert false
let check_atom_against atm v =
match atm, v with
| AtmInt n, ValInt n' -> if not (Int.equal n n') then raise NoMatch
| AtmStr s, ValStr s' -> if not (String.equal s (Bytes.unsafe_to_string s')) then raise NoMatch
| (AtmInt _ | AtmStr _), _ -> assert false
let rec match_pattern_against ist pat v =
match pat with
| GPatVar x -> push_name ist x v
| GPatAtm atm -> check_atom_against atm v; ist
| GPatAs (p,x) -> match_pattern_against (push_name ist (Name x) v) p v
| GPatRef (ctor,pats) ->
let vs = match_ctor_against ctor v in
List.fold_left_i (fun i ist pat -> match_pattern_against ist pat vs.(i)) 0 ist pats
| GPatOr pats -> match_pattern_against_or ist pats v
and match_pattern_against_or ist pats v =
match pats with
| [] -> raise NoMatch
| pat :: pats ->
try match_pattern_against ist pat v
with NoMatch -> match_pattern_against_or ist pats v
let rec interp (ist : environment) = function
| GTacAtm (AtmInt n) -> return (Tac2ffi.of_int n)
| GTacAtm (AtmStr s) -> return (Tac2ffi.of_string s)
| GTacVar id -> return (get_var ist id)
| GTacRef kn ->
let data = get_ref ist kn in
return (eval_pure Id.Map.empty (Some kn) data)
| GTacFun (ids, e) ->
let cls = { clos_ref = None; clos_env = ist.env_ist; clos_var = ids; clos_exp = e } in
let f = interp_closure cls in
return f
| GTacApp (f, args) ->
interp ist f >>= fun f ->
Proofview.Monad.List.map (fun e -> interp ist e) args >>= fun args ->
Tac2ffi.apply (Tac2ffi.to_closure f) args
| GTacLet (false, el, e) ->
let fold accu (na, e) =
interp ist e >>= fun e ->
return (push_name accu na e)
in
Proofview.Monad.List.fold_left fold ist el >>= fun ist ->
interp ist e
| GTacLet (true, el, e) ->
let map (na, e) = match e with
| GTacFun (ids, e) ->
let cls = { clos_ref = None; clos_env = ist.env_ist; clos_var = ids; clos_exp = e } in
let f = interp_closure cls in
na, cls, f
| _ -> anomaly (str "Ill-formed recursive function")
in
let fixs = List.map map el in
let fold accu (na, _, cls) = match na with
| Anonymous -> accu
| Name id -> { env_ist = Id.Map.add id cls accu.env_ist }
in
let ist = List.fold_left fold ist fixs in
let iter (_, e, _) = e.clos_env <- ist.env_ist in
let () = List.iter iter fixs in
interp ist e
| GTacCst (_, n, []) -> return (Valexpr.make_int n)
| GTacCst (_, n, el) ->
Proofview.Monad.List.map (fun e -> interp ist e) el >>= fun el ->
return (Valexpr.make_block n (Array.of_list el))
| GTacCse (e, _, cse0, cse1) ->
interp ist e >>= fun e -> interp_case ist e cse0 cse1
| GTacWth { opn_match = e; opn_branch = cse; opn_default = def } ->
interp ist e >>= fun e -> interp_with ist e cse def
| GTacFullMatch (e,brs) ->
interp ist e >>= fun e -> interp_full_match ist e brs
| GTacPrj (_, e, p) ->
interp ist e >>= fun e -> interp_proj ist e p
| GTacSet (_, e, p, r) ->
interp ist e >>= fun e ->
interp ist r >>= fun r ->
interp_set ist e p r
| GTacOpn (kn, el) ->
Proofview.Monad.List.map (fun e -> interp ist e) el >>= fun el ->
return (Tac2ffi.of_open (kn, Array.of_list el))
| GTacPrm (ml, el) ->
Proofview.Monad.List.map (fun e -> interp ist e) el >>= fun el ->
with_frame (FrPrim ml) (Tac2ffi.apply (Tac2env.interp_primitive ml) el)
| GTacExt (tag, e) ->
let tpe = Tac2env.interp_ml_object tag in
with_frame (FrExtn (tag, e)) (tpe.Tac2env.ml_interp ist e)
and interp_closure f =
let ans = fun args ->
let { clos_env = ist; clos_var = ids; clos_exp = e; clos_ref = kn } = f in
let frame = match kn with
| None -> FrAnon e
| Some kn -> FrLtac kn
in
let ist = { env_ist = ist } in
let ist = List.fold_left2 push_name ist ids args in
with_frame frame (interp ist e)
in
Tac2ffi.(of_closure (abstract (List.length f.clos_var) ans))
and interp_case ist e cse0 cse1 =
if Valexpr.is_int e then
interp ist cse0.(Tac2ffi.to_int e)
else
let (n, args) = Tac2ffi.to_block e in
let (ids, e) = cse1.(n) in
let ist = CArray.fold_left2 push_name ist ids args in
interp ist e
and interp_with ist e cse def =
let (kn, args) = Tac2ffi.to_open e in
let br = try Some (KNmap.find kn cse) with Not_found -> None in
begin match br with
| None ->
let (self, def) = def in
let ist = push_name ist self e in
interp ist def
| Some (self, ids, p) ->
let ist = push_name ist self e in
let ist = CArray.fold_left2 push_name ist ids args in
interp ist p
end
and interp_full_match ist e = function
| [] -> CErrors.anomaly Pp.(str "ltac2 match not exhaustive")
| (pat,br) :: rest ->
begin match match_pattern_against ist pat e with
| exception NoMatch -> interp_full_match ist e rest
| ist -> interp ist br
end
and interp_proj ist e p =
return (Valexpr.field e p)
and interp_set ist e p r =
let () = Valexpr.set_field e p r in
return (Valexpr.make_int 0)
and eval_pure bnd kn = function
| GTacVar id -> Id.Map.get id bnd
| GTacAtm (AtmInt n) -> Valexpr.make_int n
| GTacRef kn ->
let { Tac2env.gdata_expr = e } =
try Tac2env.interp_global kn
with Not_found -> assert false
in
eval_pure bnd (Some kn) e
| GTacFun (na, e) ->
let cls = { clos_ref = kn; clos_env = bnd; clos_var = na; clos_exp = e } in
interp_closure cls
| GTacCst (_, n, []) -> Valexpr.make_int n
| GTacCst (_, n, el) -> Valexpr.make_block n (eval_pure_args bnd el)
| GTacOpn (kn, el) -> Tac2ffi.of_open (kn, eval_pure_args bnd el)
| GTacLet (isrec, vals, body) ->
let () = assert (not isrec) in
let fold accu (na, e) = match na with
| Anonymous ->
accu
| Name id ->
let v = eval_pure bnd None e in
Id.Map.add id v accu
in
let bnd = List.fold_left fold bnd vals in
eval_pure bnd kn body
| GTacAtm (AtmStr _) | GTacSet _
| GTacApp _ | GTacCse _ | GTacPrj _
| GTacPrm _ | GTacExt _ | GTacWth _
| GTacFullMatch _ ->
anomaly (Pp.str "Term is not a syntactical value")
and eval_pure_args bnd args =
let map e = eval_pure bnd None e in
Array.map_of_list map args
let interp_value ist tac =
eval_pure ist.env_ist None tac
open Geninterp
let val_env : environment Val.typ = Val.create "ltac2:env"
let env_ref = Id.of_string_soft "@@ltac2_env@@"
let extract_env (Val.Dyn (tag, v)) : environment =
match Val.eq tag val_env with
| None -> assert false
| Some Refl -> v
let get_env ist =
try extract_env (Id.Map.find env_ref ist)
with Not_found -> empty_environment
let set_env env ist =
Id.Map.add env_ref (Val.Dyn (val_env, env)) ist
|
6889869a0765d0446a83c8748d71a00ada4318dfa6d8c71d14d02224b568686a | ocaml-flambda/ocaml-jst | toploop.ml | # 2 "toplevel/toploop.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 Format
include Topcommon
include Topeval
type input =
| Stdin
| File of string
| String of string
let use_print_results = ref true
let filename_of_input = function
| File name -> name
| Stdin | String _ -> ""
let use_lexbuf ppf ~wrap_in_module lb name filename =
Warnings.reset_fatal ();
Location.init lb filename;
(* Skip initial #! line if any *)
Lexer.skip_hash_bang lb;
Misc.protect_refs
[ R (Location.input_name, filename);
R (Location.input_lexbuf, Some lb); ]
(fun () ->
try
List.iter
(fun ph ->
let ph = preprocess_phrase ppf ph in
if not (execute_phrase !use_print_results ppf ph) then raise Exit)
(if wrap_in_module then
parse_mod_use_file name lb
else
!parse_use_file lb);
true
with
| Exit -> false
| Sys.Break -> fprintf ppf "Interrupted.@."; false
| x -> Location.report_exception ppf x; false)
let use_output ppf command =
let fn = Filename.temp_file "ocaml" "_toploop.ml" in
Misc.try_finally ~always:(fun () ->
try Sys.remove fn with Sys_error _ -> ())
(fun () ->
match
Printf.ksprintf Sys.command "%s > %s"
command
(Filename.quote fn)
with
| 0 ->
let ic = open_in_bin fn in
Misc.try_finally ~always:(fun () -> close_in ic)
(fun () ->
let lexbuf = (Lexing.from_channel ic) in
use_lexbuf ppf ~wrap_in_module:false lexbuf "" "(command-output)")
| n ->
fprintf ppf "Command exited with code %d.@." n;
false)
let use_input ppf ~wrap_in_module input =
match input with
| Stdin ->
let lexbuf = Lexing.from_channel stdin in
use_lexbuf ppf ~wrap_in_module lexbuf "" "(stdin)"
| String value ->
let lexbuf = Lexing.from_string value in
use_lexbuf ppf ~wrap_in_module lexbuf "" "(command-line input)"
| File name ->
match Load_path.find name with
| filename ->
let ic = open_in_bin filename in
Misc.try_finally ~always:(fun () -> close_in ic)
(fun () ->
let lexbuf = Lexing.from_channel ic in
use_lexbuf ppf ~wrap_in_module lexbuf name filename)
| exception Not_found ->
fprintf ppf "Cannot find file %s.@." name;
false
let mod_use_input ppf name =
use_input ppf ~wrap_in_module:true name
let use_input ppf name =
use_input ppf ~wrap_in_module:false name
let use_file ppf name =
use_input ppf (File name)
let use_silently ppf name =
Misc.protect_refs
[ R (use_print_results, false) ]
(fun () -> use_input ppf name)
let load_file = load_file false
Execute a script . If [ name ] is " " , read the script from stdin .
let run_script ppf name args =
override_sys_argv args;
let filename = filename_of_input name in
Compmisc.init_path ~dir:(Filename.dirname filename) ();
(* Note: would use [Filename.abspath] here, if we had it. *)
begin
try toplevel_env := Compmisc.initial_env()
with Env.Error _ | Typetexp.Error _ as exn ->
Location.report_exception ppf exn; raise (Compenv.Exit_with_status 2)
end;
Sys.interactive := false;
run_hooks After_setup;
let explicit_name =
match name with
| File name as filename -> (
(* Prevent use_silently from searching in the path. *)
if name <> "" && Filename.is_implicit name
then File (Filename.concat Filename.current_dir_name name)
else filename)
| (Stdin | String _) as x -> x
in
use_silently ppf explicit_name
Toplevel initialization . Performed here instead of at the
beginning of loop ( ) so that user code linked in with ocamlmktop
can call directives from Topdirs .
beginning of loop() so that user code linked in with ocamlmktop
can call directives from Topdirs. *)
let _ =
if !Sys.interactive then (* PR#6108 *)
invalid_arg "The ocamltoplevel.cma library from compiler-libs \
cannot be loaded inside the OCaml toplevel";
Sys.interactive := true;
Topeval.init ()
let find_ocamlinit () =
let ocamlinit = ".ocamlinit" in
if Sys.file_exists ocamlinit then Some ocamlinit else
let getenv var = match Sys.getenv var with
| exception Not_found -> None | "" -> None | v -> Some v
in
let exists_in_dir dir file = match dir with
| None -> None
| Some dir ->
let file = Filename.concat dir file in
if Sys.file_exists file then Some file else None
in
let home_dir () = getenv "HOME" in
let config_dir () =
if Sys.win32 then None else
match getenv "XDG_CONFIG_HOME" with
| Some _ as v -> v
| None ->
match home_dir () with
| None -> None
| Some dir -> Some (Filename.concat dir ".config")
in
let init_ml = Filename.concat "ocaml" "init.ml" in
match exists_in_dir (config_dir ()) init_ml with
| Some _ as v -> v
| None -> exists_in_dir (home_dir ()) ocamlinit
let load_ocamlinit ppf =
if !Clflags.noinit then ()
else match !Clflags.init_file with
| Some f ->
if Sys.file_exists f then ignore (use_silently ppf (File f) )
else fprintf ppf "Init file not found: \"%s\".@." f
| None ->
match find_ocamlinit () with
| None -> ()
| Some file -> ignore (use_silently ppf (File file))
(* The interactive loop *)
exception PPerror
let loop ppf =
Clflags.debug := true;
Location.formatter_for_warnings := ppf;
if not !Clflags.noversion then
fprintf ppf "OCaml version %s%s%[email protected] #help;; for help.@.@."
Config.version
(if Topeval.implementation_label = "" then "" else " - ")
Topeval.implementation_label;
begin
try initialize_toplevel_env ()
with Env.Error _ | Typetexp.Error _ as exn ->
Location.report_exception ppf exn; raise (Compenv.Exit_with_status 2)
end;
let lb = Lexing.from_function refill_lexbuf in
Location.init lb "//toplevel//";
Location.input_name := "//toplevel//";
Location.input_lexbuf := Some lb;
Location.input_phrase_buffer := Some phrase_buffer;
Sys.catch_break true;
run_hooks After_setup;
load_ocamlinit ppf;
while true do
let snap = Btype.snapshot () in
try
Lexing.flush_input lb;
(* Reset the phrase buffer when we flush the lexing buffer. *)
Buffer.reset phrase_buffer;
Location.reset();
Warnings.reset_fatal ();
first_line := true;
let phr = try !parse_toplevel_phrase lb with Exit -> raise PPerror in
let phr = preprocess_phrase ppf phr in
Env.reset_cache_toplevel ();
ignore(execute_phrase true ppf phr)
with
| End_of_file -> raise (Compenv.Exit_with_status 0)
| Sys.Break -> fprintf ppf "Interrupted.@."; Btype.backtrack snap
| PPerror -> ()
| x -> Location.report_exception ppf x; Btype.backtrack snap
done
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/1bb6c797df7c63ddae1fc2e6f403a0ee9896cc8e/toplevel/toploop.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.
************************************************************************
Skip initial #! line if any
Note: would use [Filename.abspath] here, if we had it.
Prevent use_silently from searching in the path.
PR#6108
The interactive loop
Reset the phrase buffer when we flush the lexing buffer. | # 2 "toplevel/toploop.ml"
, 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 Format
include Topcommon
include Topeval
type input =
| Stdin
| File of string
| String of string
let use_print_results = ref true
let filename_of_input = function
| File name -> name
| Stdin | String _ -> ""
let use_lexbuf ppf ~wrap_in_module lb name filename =
Warnings.reset_fatal ();
Location.init lb filename;
Lexer.skip_hash_bang lb;
Misc.protect_refs
[ R (Location.input_name, filename);
R (Location.input_lexbuf, Some lb); ]
(fun () ->
try
List.iter
(fun ph ->
let ph = preprocess_phrase ppf ph in
if not (execute_phrase !use_print_results ppf ph) then raise Exit)
(if wrap_in_module then
parse_mod_use_file name lb
else
!parse_use_file lb);
true
with
| Exit -> false
| Sys.Break -> fprintf ppf "Interrupted.@."; false
| x -> Location.report_exception ppf x; false)
let use_output ppf command =
let fn = Filename.temp_file "ocaml" "_toploop.ml" in
Misc.try_finally ~always:(fun () ->
try Sys.remove fn with Sys_error _ -> ())
(fun () ->
match
Printf.ksprintf Sys.command "%s > %s"
command
(Filename.quote fn)
with
| 0 ->
let ic = open_in_bin fn in
Misc.try_finally ~always:(fun () -> close_in ic)
(fun () ->
let lexbuf = (Lexing.from_channel ic) in
use_lexbuf ppf ~wrap_in_module:false lexbuf "" "(command-output)")
| n ->
fprintf ppf "Command exited with code %d.@." n;
false)
let use_input ppf ~wrap_in_module input =
match input with
| Stdin ->
let lexbuf = Lexing.from_channel stdin in
use_lexbuf ppf ~wrap_in_module lexbuf "" "(stdin)"
| String value ->
let lexbuf = Lexing.from_string value in
use_lexbuf ppf ~wrap_in_module lexbuf "" "(command-line input)"
| File name ->
match Load_path.find name with
| filename ->
let ic = open_in_bin filename in
Misc.try_finally ~always:(fun () -> close_in ic)
(fun () ->
let lexbuf = Lexing.from_channel ic in
use_lexbuf ppf ~wrap_in_module lexbuf name filename)
| exception Not_found ->
fprintf ppf "Cannot find file %s.@." name;
false
let mod_use_input ppf name =
use_input ppf ~wrap_in_module:true name
let use_input ppf name =
use_input ppf ~wrap_in_module:false name
let use_file ppf name =
use_input ppf (File name)
let use_silently ppf name =
Misc.protect_refs
[ R (use_print_results, false) ]
(fun () -> use_input ppf name)
let load_file = load_file false
Execute a script . If [ name ] is " " , read the script from stdin .
let run_script ppf name args =
override_sys_argv args;
let filename = filename_of_input name in
Compmisc.init_path ~dir:(Filename.dirname filename) ();
begin
try toplevel_env := Compmisc.initial_env()
with Env.Error _ | Typetexp.Error _ as exn ->
Location.report_exception ppf exn; raise (Compenv.Exit_with_status 2)
end;
Sys.interactive := false;
run_hooks After_setup;
let explicit_name =
match name with
| File name as filename -> (
if name <> "" && Filename.is_implicit name
then File (Filename.concat Filename.current_dir_name name)
else filename)
| (Stdin | String _) as x -> x
in
use_silently ppf explicit_name
Toplevel initialization . Performed here instead of at the
beginning of loop ( ) so that user code linked in with ocamlmktop
can call directives from Topdirs .
beginning of loop() so that user code linked in with ocamlmktop
can call directives from Topdirs. *)
let _ =
invalid_arg "The ocamltoplevel.cma library from compiler-libs \
cannot be loaded inside the OCaml toplevel";
Sys.interactive := true;
Topeval.init ()
let find_ocamlinit () =
let ocamlinit = ".ocamlinit" in
if Sys.file_exists ocamlinit then Some ocamlinit else
let getenv var = match Sys.getenv var with
| exception Not_found -> None | "" -> None | v -> Some v
in
let exists_in_dir dir file = match dir with
| None -> None
| Some dir ->
let file = Filename.concat dir file in
if Sys.file_exists file then Some file else None
in
let home_dir () = getenv "HOME" in
let config_dir () =
if Sys.win32 then None else
match getenv "XDG_CONFIG_HOME" with
| Some _ as v -> v
| None ->
match home_dir () with
| None -> None
| Some dir -> Some (Filename.concat dir ".config")
in
let init_ml = Filename.concat "ocaml" "init.ml" in
match exists_in_dir (config_dir ()) init_ml with
| Some _ as v -> v
| None -> exists_in_dir (home_dir ()) ocamlinit
let load_ocamlinit ppf =
if !Clflags.noinit then ()
else match !Clflags.init_file with
| Some f ->
if Sys.file_exists f then ignore (use_silently ppf (File f) )
else fprintf ppf "Init file not found: \"%s\".@." f
| None ->
match find_ocamlinit () with
| None -> ()
| Some file -> ignore (use_silently ppf (File file))
exception PPerror
let loop ppf =
Clflags.debug := true;
Location.formatter_for_warnings := ppf;
if not !Clflags.noversion then
fprintf ppf "OCaml version %s%s%[email protected] #help;; for help.@.@."
Config.version
(if Topeval.implementation_label = "" then "" else " - ")
Topeval.implementation_label;
begin
try initialize_toplevel_env ()
with Env.Error _ | Typetexp.Error _ as exn ->
Location.report_exception ppf exn; raise (Compenv.Exit_with_status 2)
end;
let lb = Lexing.from_function refill_lexbuf in
Location.init lb "//toplevel//";
Location.input_name := "//toplevel//";
Location.input_lexbuf := Some lb;
Location.input_phrase_buffer := Some phrase_buffer;
Sys.catch_break true;
run_hooks After_setup;
load_ocamlinit ppf;
while true do
let snap = Btype.snapshot () in
try
Lexing.flush_input lb;
Buffer.reset phrase_buffer;
Location.reset();
Warnings.reset_fatal ();
first_line := true;
let phr = try !parse_toplevel_phrase lb with Exit -> raise PPerror in
let phr = preprocess_phrase ppf phr in
Env.reset_cache_toplevel ();
ignore(execute_phrase true ppf phr)
with
| End_of_file -> raise (Compenv.Exit_with_status 0)
| Sys.Break -> fprintf ppf "Interrupted.@."; Btype.backtrack snap
| PPerror -> ()
| x -> Location.report_exception ppf x; Btype.backtrack snap
done
|
8483354dc0df22462c4e12114904b3aa58194c2b3a2b8d102b06b91ce68e15b0 | jarohen/phoenix | project.clj | (defproject jarohen/phoenix.build "0.0.1"
:description "The build protocols for the Phoenix runtime, so that Components don't have to depend on Phoenix core."
:url "-henderson/phoenix"
:license {:name "Eclipse Public License"
:url "-v10.html"})
| null | https://raw.githubusercontent.com/jarohen/phoenix/f828bf144154f110f0a73f54645f5696e2c8bdab/build/project.clj | clojure | (defproject jarohen/phoenix.build "0.0.1"
:description "The build protocols for the Phoenix runtime, so that Components don't have to depend on Phoenix core."
:url "-henderson/phoenix"
:license {:name "Eclipse Public License"
:url "-v10.html"})
|
|
1834a48974599c255967b621bb9242fbc5fea8e236d1c5372c51f0eae1ac44e2 | dawidovsky/IIUWr | Wykład.rkt | #lang racket
(define (leaf? x)
(eq? x 'leaf))
(define leaf 'leaf)
(define (node? x)
(and (list? x)
(= (length x) 4)
(eq? (car x) 'node)))
(define (node-val x)
(cadr x))
(define (node-left x)
(caddr x))
(define (node-right x)
(cadddr x))
(define (make-node v l r)
(list 'node v l r))
(define (tree? t)
(or (leaf? t)
(and (node? t)
(tree? (node-left t))
(tree? (node-right t)))))
wyszukiwanie i wstawianie w drzewach przeszukiwań binarnych
(define (bst-find x t)
(cond [(leaf? t) false]
[(= x (node-val t)) true]
[(< x (node-val t)) (bst-find x (node-left t))]
[(> x (node-val t)) (bst-find x (node-right t))]))
(define (bst-insert x t)
(cond [(leaf? t)
(make-node x leaf leaf)]
[(< x (node-val t))
(make-node (node-val t)
(bst-insert x (node-left t))
(node-right t))]
[else
(make-node (node-val t)
(node-left t)
(bst-insert x (node-right t)))]))
kodowanie Huffmana
(define (concat-map f cs)
(apply append (map f cs)))
;; pairs with priority
(define (ord key priority)
(cons key priority))
(define (ord? val)
(and (pair? val)
(integer? (cdr val))))
(define (ord-priority val)
(cdr val))
(define (ord-key val)
(car val))
;; priority queues, aka heaps
;; trivial implementation using ordered lists
(define empty-heap null)
(define (heap-empty? h)
(null? h))
(define (heap-insert elt h)
(if [or (null? h)
(< (ord-priority elt)
(ord-priority (car h)))]
(cons elt h)
(cons (car h) (heap-insert elt (cdr h)))))
(define (heap-min h)
(car h))
(define (heap-pop h)
(cdr h))
reprezentacja drzewa kodowego
(define (htleaf c)
(list 'htleaf c))
(define (htleaf-sym t)
(cadr t))
(define (htleaf? t)
(and (list? t)
(= (length t) 2)
(eq? (car t) 'htleaf)))
(define (htnode t1 t2)
(list 'htnode t1 t2))
(define (htnode-left t)
(cadr t))
(define (htnode-right t)
(caddr t))
(define (htnode? t)
(and (list? t)
(= 3 (length t))
(eq? (car t) 'htnode)))
(define plist '((a . 10) (b . 1) (c . 6) (d . 5) (e . 3) (f . 6)))
lista par
(define empty-dict null)
(define (dict-insert k v d)
(cons (cons k v) d))
(define (dict-find k d)
(cond [(null? d) false]
[(eq? (caar d) k) (car d)]
[else (dict-find k (cdr d))]))
tworzenie drzewa kodowego
xs -- lista par znak - częstość występowania
(define (make-code-tree xs)
(define (convert-list xs h)
(if (null? xs)
h
(let ((s (caar xs))
(f (cdar xs)))
(convert-list (cdr xs)
(heap-insert (ord (htleaf s) f) h)))))
(define (merge-elems e1 e2)
(let ((tr (htnode (ord-key e1) (ord-key e2)))
(fr (+ (ord-priority e1) (ord-priority e2))))
(ord tr fr)))
(define (handle-pqueue h)
(let ((e1 (heap-min h))
(h1 (heap-pop h)))
(if (heap-empty? h1)
(ord-key e1)
(let* ((e2 (heap-min h1))
(h2 (heap-pop h1))
(hr (heap-insert (merge-elems e1 e2) h2)))
(handle-pqueue hr)))))
(handle-pqueue (convert-list xs empty-heap)))
słownik z drzewa kodowego Huffmana
(define (code-tree->dict t)
(define (aux t rcpref d)
(if (htleaf? t)
(dict-insert (htleaf-sym t) (reverse rcpref) d)
(aux (htnode-right t)
(cons 1 rcpref)
(aux (htnode-left t)
(cons 0 rcpref)
d))))
(aux t null empty-dict))
kodowanie listy symboli
(define (encode symlist dict)
(let ((code-sym
(lambda (s)
(let ((kv (dict-find s dict)))
(if kv
(cdr kv)
(error "Unknown symbol" s))))))
(concat-map code-sym symlist)))
;; dekodowanie
(define (decode bitlist tree)
(define (dec-sym bitlist tree)
(cond [(htleaf? tree)
(cons (htleaf-sym tree) bitlist)]
[(null? bitlist)
(error "Stream terminated prematurely")]
[(= 0 (car bitlist))
(dec-sym (cdr bitlist) (htnode-left tree))]
[(= 1 (car bitlist))
(dec-sym (cdr bitlist) (htnode-right tree))]))
(define (aux bitlist)
(if (null? bitlist)
null
(let ((sb (dec-sym bitlist tree)))
(cons (car sb) (aux (cdr sb))))))
(aux bitlist))
| null | https://raw.githubusercontent.com/dawidovsky/IIUWr/73f0f65fb141f82a05dac2573f39f6fa48a81409/MP/Pracownia4/Wyk%C5%82ad.rkt | racket | pairs with priority
priority queues, aka heaps
trivial implementation using ordered lists
dekodowanie | #lang racket
(define (leaf? x)
(eq? x 'leaf))
(define leaf 'leaf)
(define (node? x)
(and (list? x)
(= (length x) 4)
(eq? (car x) 'node)))
(define (node-val x)
(cadr x))
(define (node-left x)
(caddr x))
(define (node-right x)
(cadddr x))
(define (make-node v l r)
(list 'node v l r))
(define (tree? t)
(or (leaf? t)
(and (node? t)
(tree? (node-left t))
(tree? (node-right t)))))
wyszukiwanie i wstawianie w drzewach przeszukiwań binarnych
(define (bst-find x t)
(cond [(leaf? t) false]
[(= x (node-val t)) true]
[(< x (node-val t)) (bst-find x (node-left t))]
[(> x (node-val t)) (bst-find x (node-right t))]))
(define (bst-insert x t)
(cond [(leaf? t)
(make-node x leaf leaf)]
[(< x (node-val t))
(make-node (node-val t)
(bst-insert x (node-left t))
(node-right t))]
[else
(make-node (node-val t)
(node-left t)
(bst-insert x (node-right t)))]))
kodowanie Huffmana
(define (concat-map f cs)
(apply append (map f cs)))
(define (ord key priority)
(cons key priority))
(define (ord? val)
(and (pair? val)
(integer? (cdr val))))
(define (ord-priority val)
(cdr val))
(define (ord-key val)
(car val))
(define empty-heap null)
(define (heap-empty? h)
(null? h))
(define (heap-insert elt h)
(if [or (null? h)
(< (ord-priority elt)
(ord-priority (car h)))]
(cons elt h)
(cons (car h) (heap-insert elt (cdr h)))))
(define (heap-min h)
(car h))
(define (heap-pop h)
(cdr h))
reprezentacja drzewa kodowego
(define (htleaf c)
(list 'htleaf c))
(define (htleaf-sym t)
(cadr t))
(define (htleaf? t)
(and (list? t)
(= (length t) 2)
(eq? (car t) 'htleaf)))
(define (htnode t1 t2)
(list 'htnode t1 t2))
(define (htnode-left t)
(cadr t))
(define (htnode-right t)
(caddr t))
(define (htnode? t)
(and (list? t)
(= 3 (length t))
(eq? (car t) 'htnode)))
(define plist '((a . 10) (b . 1) (c . 6) (d . 5) (e . 3) (f . 6)))
lista par
(define empty-dict null)
(define (dict-insert k v d)
(cons (cons k v) d))
(define (dict-find k d)
(cond [(null? d) false]
[(eq? (caar d) k) (car d)]
[else (dict-find k (cdr d))]))
tworzenie drzewa kodowego
xs -- lista par znak - częstość występowania
(define (make-code-tree xs)
(define (convert-list xs h)
(if (null? xs)
h
(let ((s (caar xs))
(f (cdar xs)))
(convert-list (cdr xs)
(heap-insert (ord (htleaf s) f) h)))))
(define (merge-elems e1 e2)
(let ((tr (htnode (ord-key e1) (ord-key e2)))
(fr (+ (ord-priority e1) (ord-priority e2))))
(ord tr fr)))
(define (handle-pqueue h)
(let ((e1 (heap-min h))
(h1 (heap-pop h)))
(if (heap-empty? h1)
(ord-key e1)
(let* ((e2 (heap-min h1))
(h2 (heap-pop h1))
(hr (heap-insert (merge-elems e1 e2) h2)))
(handle-pqueue hr)))))
(handle-pqueue (convert-list xs empty-heap)))
słownik z drzewa kodowego Huffmana
(define (code-tree->dict t)
(define (aux t rcpref d)
(if (htleaf? t)
(dict-insert (htleaf-sym t) (reverse rcpref) d)
(aux (htnode-right t)
(cons 1 rcpref)
(aux (htnode-left t)
(cons 0 rcpref)
d))))
(aux t null empty-dict))
kodowanie listy symboli
(define (encode symlist dict)
(let ((code-sym
(lambda (s)
(let ((kv (dict-find s dict)))
(if kv
(cdr kv)
(error "Unknown symbol" s))))))
(concat-map code-sym symlist)))
(define (decode bitlist tree)
(define (dec-sym bitlist tree)
(cond [(htleaf? tree)
(cons (htleaf-sym tree) bitlist)]
[(null? bitlist)
(error "Stream terminated prematurely")]
[(= 0 (car bitlist))
(dec-sym (cdr bitlist) (htnode-left tree))]
[(= 1 (car bitlist))
(dec-sym (cdr bitlist) (htnode-right tree))]))
(define (aux bitlist)
(if (null? bitlist)
null
(let ((sb (dec-sym bitlist tree)))
(cons (car sb) (aux (cdr sb))))))
(aux bitlist))
|
8b08a4f62a394c4c8c13fcf4be7bed1d386e587a0c313c895f61f1b4f3ab76f7 | ruricolist/core-lisp | core-lisp-boot.lisp | (in-package :core-lisp)
(cl:defmacro with-unique-names (names &body body)
`(let ,(loop for name in names
collect `(,name (cl:gensym ,(symbol-name name))))
,@body))
(cl:defmacro rebinding (vars &body body)
(loop for var in vars
for name = (cl:gensym (symbol-name var))
collect `(,name ,var) into renames
collect ``(,,var ,,name) into temps
finally (return `(let ,renames
(with-unique-names ,vars
`(let (,,@temps) ,,@body))))))
(cl:defmacro eval-when (situations &body body)
`(cl:eval-when ,situations
,@body))
(defvar *core-lisp-global-package*
(find-package "CORE-LISP-GLOBAL-DEFINITIONS"))
(cl:defgeneric global (name)
(:method ((symbol cl:symbol))
(intern (cl:format cl:nil "~A::~A"
(package-name (symbol-package symbol))
(symbol-name symbol))
*core-lisp-global-package*))
(:method ((name cl:cons))
`(cl:setf ,(global (cl:cadr name)))))
(cl:setf (find-class '<object>) (find-class 'cl:t)
(find-class '<basic-array>) (find-class 'array)
(find-class '<basic-vector>) (find-class 'cl:vector)
(find-class '<general-vector>) (find-class 'cl:vector)
(find-class '<string>) (find-class 'string)
(find-class '<built-in-class>) (find-class 'built-in-class)
(find-class '<character>) (find-class 'character)
(find-class '<function>) (find-class 'cl:function)
(find-class '<generic-function>) (find-class 'generic-function)
(find-class '<standard-generic-function>) (find-class 'standard-generic-function)
(find-class '<list>) (find-class 'cl:list)
(find-class '<cons>) (find-class 'cl:cons)
(find-class '<null>) (find-class 'cl:null)
(find-class '<symbol>) (find-class 'symbol)
(find-class '<number>) (find-class 'number)
(find-class '<float>) (find-class 'cl:float)
(find-class '<integer>) (find-class 'integer)
(find-class '<serious-condition>) (find-class 'serious-condition)
(find-class '<error>) (find-class 'cl:error)
(find-class '<arithmetic-error>) (find-class 'arithmetic-error)
(find-class '<division-by-zero>) (find-class 'division-by-zero)
(find-class '<floating-point-overflow>) (find-class 'floating-point-overflow)
(find-class '<floating-point-underflow>) (find-class 'floating-point-underflow)
(find-class '<control-error>) (find-class 'control-error)
(find-class '<parse-error>) (find-class 'parse-error)
(find-class '<program-error>) (find-class 'program-error)
(find-class '<domain-error>) (find-class 'type-error)
(find-class '<undefined-entity>) (find-class 'cell-error)
(find-class '<unbound-variable>) (find-class 'unbound-variable)
(find-class '<undefined-function>) (find-class 'undefined-function)
(find-class '<simple-error>) (find-class 'simple-error)
(find-class '<stream-error>) (find-class 'stream-error)
(find-class '<end-of-stream>) (find-class 'end-of-file)
(find-class '<storage-exhausted>) (find-class 'storage-condition)
(find-class '<standard-class>) (find-class 'standard-class)
(find-class '<standard-object>) (find-class 'standard-object)
(find-class '<stream>) (find-class 'stream))
(defvar *core-lisp-lambda-list-keywords*
'(&body &environment &rest &whole))
(defvar *lambda-list-keyword-map*
(loop for keyword in *core-lisp-lambda-list-keywords*
collect (cl:cons (intern (cl:subseq (symbol-name keyword) 1) :keyword) keyword)))
(defvar *error-ll*)
(cl:defun ll-keywordp (symbol)
(cl:let ((symbol-name (symbol-name symbol)))
(cl:eql (when (cl:> (cl:length symbol-name) 0)
(cl:aref symbol-name 0))
#\&)))
(cl:defun ll-element-err (element)
(cl:error "Unexpected element ~S in lambda list ~S." element *error-ll*))
(cl:defun ll-end-err (&optional tail)
(cl:if tail
(cl:error "Unexpected tail ~S in lambda-list ~S." tail *error-ll*)
(cl:error "Unexpected NIL / end in lambda list ~S." *error-ll*)))
(cl:defun ll-duplicate-err (var)
(cl:error "Duplicate variable ~S in lambda list ~S." var *error-ll*))
(cl:defun ll-keyword (keyword)
(cl:if (cl:and (cl:symbolp keyword) (keywordp keyword))
(cl:let ((ll-keyword (cl:cdr (cl:assoc keyword *lambda-list-keyword-map*))))
(cl:if ll-keyword ll-keyword (ll-element-err keyword)))
keyword))
(cl:defun symbol-not-null (element)
(cl:if (cl:and element (cl:symbolp element)) element
(ll-element-err element)))
(cl:defun var-symbol (element)
(cl:if element
(cl:if (cl:and (cl:symbolp element)
(cl:not (keywordp element))
(cl:not (ll-keywordp element)))
element (ll-element-err element))
(ll-end-err)))
(cl:defun gf-name (name)
(cl:if (cl:consp name)
(cl:cond ((cl:eq (cl:car name) 'cl:setf) name)
((cl:eq (cl:car name) 'setf) `(cl:setf ,(cl:cadr name)))
(cl:t (cl:error "Illegal function name ~S." name)))
name))
(cl:defun check-specializer (element)
(cl:if (cl:and (cl:car element)
(cl:symbolp (cl:car element))
(cl:not (keywordp (cl:car element)))
(cl:not (ll-keywordp (cl:car element)))
(cl:null (cl:cddr element)))
element (ll-element-err element)))
(cl:defun check-duplicate (var aliases)
(when (cl:member var aliases :key #'cl:car)
(ll-duplicate-err var)))
(cl:defun parse-element (rest)
(unless (cl:listp rest) (ll-end-err rest))
(cl:if (cl:null rest) '()
(cl:let ((element (cl:car rest)))
(cl:if (cl:consp element)
(cl:list 'specializer
(check-specializer element)
(cl:cdr rest))
(cl:let ((element (symbol-not-null element)))
(cl:if (cl:or (keywordp element) (ll-keywordp element))
(cl:list element
(var-symbol (cl:cadr rest))
(cl:cddr rest))
(cl:list 'var element (cl:cdr rest))))))))
(cl:defun parse-lambda-list (ll &key ((:error-ll *error-ll*) ll) (specializers cl:nil) (rest-keys '(&rest)))
(loop for (kind var-spec rest) = (parse-element ll) then (parse-element rest)
for var = (cl:if (cl:eq kind 'specializer)
(cl:if specializers (cl:car var-spec)
(ll-element-err var))
var-spec)
for alias = (when kind (copy-symbol var))
while kind do (check-duplicate var aliases)
unless (cl:member kind '(var specializer)) collect (ll-keyword kind) into new-lambda-list end
if (cl:eq kind 'specializer)
collect (cl:cons alias (cl:cdr var-spec)) into new-lambda-list
and collect (cl:list var alias) into aliases
else
collect alias into new-lambda-list
and collect (cl:list var alias) into aliases
while (cl:member kind '(var specializer))
finally
(when kind
(unless (cl:member (ll-keyword kind) rest-keys)
(ll-element-err kind))
(when rest (ll-end-err rest)))
(return (values new-lambda-list aliases))))
(cl:defun parse-macro-lambda-list (ll &aux (*error-ll* ll))
(cl:let ((rest-ll ll)
(element (parse-element ll))
whole-var whole-alias env-var env-alias)
(when element
(destructuring-bind (kind var rest) element
(when (cl:member kind '(:whole &whole))
(cl:setq rest-ll rest
whole-var var
whole-alias (copy-symbol var)
element (parse-element rest))))
(when element
(destructuring-bind (kind var rest) element
(when (cl:member kind '(:environment &environment))
(cl:setq rest-ll rest
env-var var
env-alias (copy-symbol var)
element (parse-element rest))))
(when (cl:and (cl:or whole-var env-var) (cl:eq whole-var env-var))
(ll-duplicate-err whole-var))
(multiple-value-bind
(new-lambda-list aliases)
(parse-lambda-list rest-ll :error-ll ll :rest-keys '(&rest &body))
(check-duplicate env-var aliases)
(check-duplicate whole-var aliases)
(values
(nconc (when whole-var (cl:list '&whole whole-alias))
(when env-var (cl:list '&environment env-alias))
new-lambda-list)
(nconc (when whole-var (cl:list (cl:list whole-var whole-alias)))
(when env-var (cl:list (cl:list env-var env-alias)))
aliases)))))))
(cl:defun err-illegal-slot-spec (slot-spec w)
(cl:error "Invalid slot spec ~S in ~S." slot-spec w))
(cl:defun parse-slot-spec (w slot-spec)
(cl:cond ((cl:null slot-spec) (err-illegal-slot-spec slot-spec w))
((cl:symbolp slot-spec) (cl:list slot-spec '() '()))
((cl:consp slot-spec)
(unless (cl:and (cl:car slot-spec) (cl:symbolp (cl:car slot-spec)))
(err-illegal-slot-spec slot-spec w))
(loop for (key value) on (cl:cdr slot-spec) by #'cl:cddr
nconc (cl:if (cl:member key '(:accessor :reader :writer))
`(,key ,(global value))
`(,key ,value)) into new-slot-spec
when (cl:member key '(:accessor :reader))
collect value into readers
when (cl:member key '(:accessor :writer))
collect (cl:if (cl:eq key :accessor)
`(cl:setf ,value) (gf-name value)) into writers
finally (return (cl:list `(,(cl:car slot-spec) ,@new-slot-spec) readers writers))))
(cl:t (err-illegal-slot-spec slot-spec w))))
(cl:defmacro -import-variable- (name alias)
`(cl:progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-symbol-macro ,name ,alias)
(cl:setf (get ',name '%aliases%) ',alias)
',name)))
(cl:defmacro -import-symbol-macro- (name alias)
`(cl:progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-symbol-macro ,name ,alias)
(cl:setf (get ',name '%aliases%) ',alias)
',name)))
(cl:defmacro -import-function- (fname falias &optional (lambda-list '() lambda-list-p))
(assert (cl:or (cl:and (cl:symbolp fname) (cl:symbolp falias))
(cl:and (cl:consp fname) (cl:consp falias))))
(cl:let ((name (cl:if (cl:symbolp fname) fname (cl:cadr fname)))
(alias (cl:if (cl:symbolp falias) falias (cl:cadr falias))))
`(cl:progn
,(cl:if lambda-list-p
(loop for (element . rest) on lambda-list
for restp = (cl:member element '(:rest &rest))
until restp
collect element into required-vars
finally (return
(cl:if restp
(cl:let ((rest-var (cl:car rest)))
(cl:if (cl:symbolp fname)
`(cl:defmacro ,fname (,@required-vars &rest ,rest-var)
`(,',falias ,,@required-vars ,@,rest-var))
`(defsetf ,name (,@(cl:cdr required-vars) &rest ,rest-var)
(,(cl:car required-vars))
`(cl:setf (,',alias ,,@(cl:cdr required-vars) ,@,rest-var)
,,(cl:car required-vars)))))
(cl:if (cl:symbolp fname)
`(cl:defmacro ,fname (,@lambda-list)
`(,',falias ,,@lambda-list))
`(defsetf ,name (,@(cl:cdr lambda-list)) (,(cl:car lambda-list))
`(cl:setf (,',alias ,,@(cl:cdr lambda-list))
,,(cl:car lambda-list)))))))
(cl:let ((rest-var (cl:gensym)))
(cl:if (cl:symbolp fname)
`(cl:defmacro ,fname (&rest ,rest-var)
`(,',falias ,@,rest-var))
(cl:let ((store-var (cl:gensym)))
`(defsetf ,fname (&rest ,rest-var) (,store-var)
`(cl:setf (,',alias ,@,rest-var) ,,store-var))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:setf (get ',name '%function-aliases%) ',alias))
',fname)))
(cl:defmacro -import-generic-function- (fname falias &optional (lambda-list '() lambda-list-p))
(assert (cl:or (cl:and (cl:symbolp fname) (cl:symbolp falias))
(cl:and (cl:consp fname) (cl:consp falias))))
(cl:let ((name (cl:if (cl:symbolp fname) fname (cl:cadr fname)))
(alias (cl:if (cl:symbolp falias) falias (cl:cadr falias))))
`(cl:progn
,(cl:if lambda-list-p
`(defgeneric ,fname (,@lambda-list))
`(defgeneric ,fname (&rest ,(cl:gensym))))
(cl:setf (cl:fdefinition ',(global fname)) (cl:fdefinition ',falias))
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:setf (get ',name '%function-aliases%) ',alias))
',fname)))
(cl:defmacro -import-macro- (fname falias &optional (lambda-list '() lambda-list-p))
(cl:if lambda-list-p
(loop with whole-var
with env-var
with body-var
with rest-var
for (elm1 elm2) on lambda-list
for element = (ll-keyword elm1)
if (cl:eq element '&whole) do (cl:setq whole-var elm2)
else if (cl:eq element '&environment) do (cl:setq env-var elm2)
else if (cl:eq element '&body) do (cl:setq body-var elm2)
else if (cl:eq element '&rest) do (cl:setq rest-var elm2)
else unless (cl:member element (cl:list whole-var env-var body-var rest-var))
collect element into required-vars
finally
(cl:let ((new-whole-var (cl:if whole-var whole-var 'whole-form))
(new-env-var (cl:if env-var env-var 'environment)))
(return
`(cl:progn
(cl:defmacro ,fname (&whole ,new-whole-var &environment ,new-env-var
,@required-vars
,@(when body-var `(&body ,body-var))
,@(when rest-var `(&rest ,rest-var)))
(declare (ignore ,@required-vars
,@(when body-var (cl:list body-var))
,@(when rest-var (cl:list rest-var))))
(cl:funcall (cl:macro-function ',falias ,new-env-var) ,new-whole-var ,new-env-var))
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:setf (get ',fname '%function-aliases%) ',falias))
',fname))))
(cl:let ((whole-var (cl:gensym)) (env-var (cl:gensym)) (body-var (cl:gensym)))
`(cl:progn
(cl:defmacro ,fname (&whole ,whole-var &environment ,env-var &body ,body-var)
(declare (ignore ,body-var))
(cl:funcall (cl:macro-function ',falias ,env-var) ,whole-var ,env-var))
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:setf (get ',fname '%function-aliases%) ',falias)
',fname)))))
(cl:defmacro -with-imported-variables- ((&rest bindings) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%aliases% env)))
`(locally (declare #+sbcl (sb-ext:disable-package-locks %aliases%))
(symbol-macrolet ((%aliases% ,(revappend bindings old-aliases)))
(declare (ignorable %aliases%))
(symbol-macrolet ,bindings ,@body)))))
(cl:defmacro -with-imported-symbol-macros- ((&rest bindings) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%aliases% env)))
`(locally (declare #+sbcl (sb-ext:disable-package-locks %aliases%))
(symbol-macrolet ((%aliases% ,(revappend bindings old-aliases)))
(declare (ignorable %aliases%))
(symbol-macrolet ,bindings ,@body)))))
(cl:defmacro -with-imported-functions- ((&rest bindings) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%function-aliases% env)))
`(locally (declare #+sbcl (sb-ext:disable-package-locks %function-aliases%))
(symbol-macrolet ((%function-aliases% ,(revappend bindings old-aliases)))
(declare (ignorable %function-aliases%))
(cl:macrolet ,(loop for (fun alias) in bindings
collect `(,fun (&rest args) `(,',alias ,@args)))
,@body)))))
(cl:defvar -arguments-for-local-macros-)
(cl:defmacro expand-local-macro (name &environment env)
`',(macroexpand `(,name ,@-arguments-for-local-macros-) env))
(cl:defmacro -with-imported-macros- ((&rest bindings) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%function-aliases% env)))
`(locally (declare #+sbcl (sb-ext:disable-package-locks %function-aliases%))
(symbol-macrolet ((%function-aliases% ,(revappend bindings old-aliases)))
(declare (ignorable %function-aliases%))
(cl:macrolet ,(loop for (macro alias) in bindings
collect `(,macro (&rest -arguments-for-local-macros-) (expand-local-macro ,alias)))
,@body)))))
(cl:defmacro -with-imported-block- ((block-name block-alias) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%block-aliases% env)))
`(cl:block ,block-name
(locally (declare #+sbcl (sb-ext:disable-package-locks %block-aliases%))
(symbol-macrolet ((%block-aliases% ,(cl:cons `(,block-name ,block-alias) old-aliases)))
,@body)))))
(cl:defmacro -defmacro- (macro-name lambda-list &body body)
(cl:let ((macro-alias (global macro-name)))
(multiple-value-bind
(new-lambda-list new-aliases)
(parse-macro-lambda-list lambda-list)
`(cl:progn
(cl:defmacro ,macro-alias ,new-lambda-list
(-with-imported-variables- ,new-aliases ,@body))
(-import-macro- ,macro-name ,macro-alias ,lambda-list)))))
(cl:defun expand-body (new-aliases old-aliases body)
`(locally (declare #+sbcl (sb-ext:disable-package-locks %aliases%))
(symbol-macrolet ((%aliases% ,(revappend new-aliases old-aliases)))
(declare (ignorable %aliases%))
(symbol-macrolet ,new-aliases ,@body))))
(cl:defun process-lambda (env lambda-list body)
(cl:let ((old-aliases (macroexpand '%aliases% env)))
(multiple-value-bind
(new-lambda-list new-aliases)
(parse-lambda-list lambda-list)
(values new-lambda-list (expand-body new-aliases old-aliases body)))))
(cl:defun expand-method-body (qualifiers new-aliases old-aliases body)
(cl:let ((form (expand-body new-aliases old-aliases body)))
(cl:if (cl:or (cl:null qualifiers) (cl:member :around qualifiers))
`(-with-imported-functions- ((call-next-method cl:call-next-method)
(next-method-p cl:next-method-p))
,form)
form)))
(cl:defun expand-defclass (w class-name superclasses options &optional (conditionp cl:nil))
;; TODO Actually implement abstract classes.
(when (cl:find :abstractp options :key #'cl:car)
(setf options (cl:remove :abstractp options :key #'cl:car)))
(unless (cl:and (cl:symbolp class-name)
(cl:listp superclasses)
(every #'cl:symbolp superclasses)
options
(cl:listp (cl:car options))
(cl:listp (cl:cdr options))
(loop for option in (cl:cdr options)
always (cl:and (cl:consp option)
(cl:car option)
(cl:symbolp (cl:car option)))))
(cl:error "Malformed definition: ~S." w))
(loop for slot-spec in (cl:car options)
for (new-slot-spec readers writers) = (parse-slot-spec w slot-spec)
collect new-slot-spec into new-slot-specs
nconc readers into reader-gfs
nconc writers into writer-gfs
finally (return `(cl:progn
,@(loop for gf in reader-gfs
collect `(defgeneric ,gf (object)))
,@(loop for gf in writer-gfs
collect `(defgeneric ,gf (new-value object)))
(,(cl:if conditionp 'cl:define-condition 'cl:defclass)
,class-name ,superclasses ,new-slot-specs ,@(cl:cdr options))))))
| null | https://raw.githubusercontent.com/ruricolist/core-lisp/1ea73b65a7de8abb608c253134b1b8e617018063/core-lisp-boot.lisp | lisp | TODO Actually implement abstract classes. | (in-package :core-lisp)
(cl:defmacro with-unique-names (names &body body)
`(let ,(loop for name in names
collect `(,name (cl:gensym ,(symbol-name name))))
,@body))
(cl:defmacro rebinding (vars &body body)
(loop for var in vars
for name = (cl:gensym (symbol-name var))
collect `(,name ,var) into renames
collect ``(,,var ,,name) into temps
finally (return `(let ,renames
(with-unique-names ,vars
`(let (,,@temps) ,,@body))))))
(cl:defmacro eval-when (situations &body body)
`(cl:eval-when ,situations
,@body))
(defvar *core-lisp-global-package*
(find-package "CORE-LISP-GLOBAL-DEFINITIONS"))
(cl:defgeneric global (name)
(:method ((symbol cl:symbol))
(intern (cl:format cl:nil "~A::~A"
(package-name (symbol-package symbol))
(symbol-name symbol))
*core-lisp-global-package*))
(:method ((name cl:cons))
`(cl:setf ,(global (cl:cadr name)))))
(cl:setf (find-class '<object>) (find-class 'cl:t)
(find-class '<basic-array>) (find-class 'array)
(find-class '<basic-vector>) (find-class 'cl:vector)
(find-class '<general-vector>) (find-class 'cl:vector)
(find-class '<string>) (find-class 'string)
(find-class '<built-in-class>) (find-class 'built-in-class)
(find-class '<character>) (find-class 'character)
(find-class '<function>) (find-class 'cl:function)
(find-class '<generic-function>) (find-class 'generic-function)
(find-class '<standard-generic-function>) (find-class 'standard-generic-function)
(find-class '<list>) (find-class 'cl:list)
(find-class '<cons>) (find-class 'cl:cons)
(find-class '<null>) (find-class 'cl:null)
(find-class '<symbol>) (find-class 'symbol)
(find-class '<number>) (find-class 'number)
(find-class '<float>) (find-class 'cl:float)
(find-class '<integer>) (find-class 'integer)
(find-class '<serious-condition>) (find-class 'serious-condition)
(find-class '<error>) (find-class 'cl:error)
(find-class '<arithmetic-error>) (find-class 'arithmetic-error)
(find-class '<division-by-zero>) (find-class 'division-by-zero)
(find-class '<floating-point-overflow>) (find-class 'floating-point-overflow)
(find-class '<floating-point-underflow>) (find-class 'floating-point-underflow)
(find-class '<control-error>) (find-class 'control-error)
(find-class '<parse-error>) (find-class 'parse-error)
(find-class '<program-error>) (find-class 'program-error)
(find-class '<domain-error>) (find-class 'type-error)
(find-class '<undefined-entity>) (find-class 'cell-error)
(find-class '<unbound-variable>) (find-class 'unbound-variable)
(find-class '<undefined-function>) (find-class 'undefined-function)
(find-class '<simple-error>) (find-class 'simple-error)
(find-class '<stream-error>) (find-class 'stream-error)
(find-class '<end-of-stream>) (find-class 'end-of-file)
(find-class '<storage-exhausted>) (find-class 'storage-condition)
(find-class '<standard-class>) (find-class 'standard-class)
(find-class '<standard-object>) (find-class 'standard-object)
(find-class '<stream>) (find-class 'stream))
(defvar *core-lisp-lambda-list-keywords*
'(&body &environment &rest &whole))
(defvar *lambda-list-keyword-map*
(loop for keyword in *core-lisp-lambda-list-keywords*
collect (cl:cons (intern (cl:subseq (symbol-name keyword) 1) :keyword) keyword)))
(defvar *error-ll*)
(cl:defun ll-keywordp (symbol)
(cl:let ((symbol-name (symbol-name symbol)))
(cl:eql (when (cl:> (cl:length symbol-name) 0)
(cl:aref symbol-name 0))
#\&)))
(cl:defun ll-element-err (element)
(cl:error "Unexpected element ~S in lambda list ~S." element *error-ll*))
(cl:defun ll-end-err (&optional tail)
(cl:if tail
(cl:error "Unexpected tail ~S in lambda-list ~S." tail *error-ll*)
(cl:error "Unexpected NIL / end in lambda list ~S." *error-ll*)))
(cl:defun ll-duplicate-err (var)
(cl:error "Duplicate variable ~S in lambda list ~S." var *error-ll*))
(cl:defun ll-keyword (keyword)
(cl:if (cl:and (cl:symbolp keyword) (keywordp keyword))
(cl:let ((ll-keyword (cl:cdr (cl:assoc keyword *lambda-list-keyword-map*))))
(cl:if ll-keyword ll-keyword (ll-element-err keyword)))
keyword))
(cl:defun symbol-not-null (element)
(cl:if (cl:and element (cl:symbolp element)) element
(ll-element-err element)))
(cl:defun var-symbol (element)
(cl:if element
(cl:if (cl:and (cl:symbolp element)
(cl:not (keywordp element))
(cl:not (ll-keywordp element)))
element (ll-element-err element))
(ll-end-err)))
(cl:defun gf-name (name)
(cl:if (cl:consp name)
(cl:cond ((cl:eq (cl:car name) 'cl:setf) name)
((cl:eq (cl:car name) 'setf) `(cl:setf ,(cl:cadr name)))
(cl:t (cl:error "Illegal function name ~S." name)))
name))
(cl:defun check-specializer (element)
(cl:if (cl:and (cl:car element)
(cl:symbolp (cl:car element))
(cl:not (keywordp (cl:car element)))
(cl:not (ll-keywordp (cl:car element)))
(cl:null (cl:cddr element)))
element (ll-element-err element)))
(cl:defun check-duplicate (var aliases)
(when (cl:member var aliases :key #'cl:car)
(ll-duplicate-err var)))
(cl:defun parse-element (rest)
(unless (cl:listp rest) (ll-end-err rest))
(cl:if (cl:null rest) '()
(cl:let ((element (cl:car rest)))
(cl:if (cl:consp element)
(cl:list 'specializer
(check-specializer element)
(cl:cdr rest))
(cl:let ((element (symbol-not-null element)))
(cl:if (cl:or (keywordp element) (ll-keywordp element))
(cl:list element
(var-symbol (cl:cadr rest))
(cl:cddr rest))
(cl:list 'var element (cl:cdr rest))))))))
(cl:defun parse-lambda-list (ll &key ((:error-ll *error-ll*) ll) (specializers cl:nil) (rest-keys '(&rest)))
(loop for (kind var-spec rest) = (parse-element ll) then (parse-element rest)
for var = (cl:if (cl:eq kind 'specializer)
(cl:if specializers (cl:car var-spec)
(ll-element-err var))
var-spec)
for alias = (when kind (copy-symbol var))
while kind do (check-duplicate var aliases)
unless (cl:member kind '(var specializer)) collect (ll-keyword kind) into new-lambda-list end
if (cl:eq kind 'specializer)
collect (cl:cons alias (cl:cdr var-spec)) into new-lambda-list
and collect (cl:list var alias) into aliases
else
collect alias into new-lambda-list
and collect (cl:list var alias) into aliases
while (cl:member kind '(var specializer))
finally
(when kind
(unless (cl:member (ll-keyword kind) rest-keys)
(ll-element-err kind))
(when rest (ll-end-err rest)))
(return (values new-lambda-list aliases))))
(cl:defun parse-macro-lambda-list (ll &aux (*error-ll* ll))
(cl:let ((rest-ll ll)
(element (parse-element ll))
whole-var whole-alias env-var env-alias)
(when element
(destructuring-bind (kind var rest) element
(when (cl:member kind '(:whole &whole))
(cl:setq rest-ll rest
whole-var var
whole-alias (copy-symbol var)
element (parse-element rest))))
(when element
(destructuring-bind (kind var rest) element
(when (cl:member kind '(:environment &environment))
(cl:setq rest-ll rest
env-var var
env-alias (copy-symbol var)
element (parse-element rest))))
(when (cl:and (cl:or whole-var env-var) (cl:eq whole-var env-var))
(ll-duplicate-err whole-var))
(multiple-value-bind
(new-lambda-list aliases)
(parse-lambda-list rest-ll :error-ll ll :rest-keys '(&rest &body))
(check-duplicate env-var aliases)
(check-duplicate whole-var aliases)
(values
(nconc (when whole-var (cl:list '&whole whole-alias))
(when env-var (cl:list '&environment env-alias))
new-lambda-list)
(nconc (when whole-var (cl:list (cl:list whole-var whole-alias)))
(when env-var (cl:list (cl:list env-var env-alias)))
aliases)))))))
(cl:defun err-illegal-slot-spec (slot-spec w)
(cl:error "Invalid slot spec ~S in ~S." slot-spec w))
(cl:defun parse-slot-spec (w slot-spec)
(cl:cond ((cl:null slot-spec) (err-illegal-slot-spec slot-spec w))
((cl:symbolp slot-spec) (cl:list slot-spec '() '()))
((cl:consp slot-spec)
(unless (cl:and (cl:car slot-spec) (cl:symbolp (cl:car slot-spec)))
(err-illegal-slot-spec slot-spec w))
(loop for (key value) on (cl:cdr slot-spec) by #'cl:cddr
nconc (cl:if (cl:member key '(:accessor :reader :writer))
`(,key ,(global value))
`(,key ,value)) into new-slot-spec
when (cl:member key '(:accessor :reader))
collect value into readers
when (cl:member key '(:accessor :writer))
collect (cl:if (cl:eq key :accessor)
`(cl:setf ,value) (gf-name value)) into writers
finally (return (cl:list `(,(cl:car slot-spec) ,@new-slot-spec) readers writers))))
(cl:t (err-illegal-slot-spec slot-spec w))))
(cl:defmacro -import-variable- (name alias)
`(cl:progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-symbol-macro ,name ,alias)
(cl:setf (get ',name '%aliases%) ',alias)
',name)))
(cl:defmacro -import-symbol-macro- (name alias)
`(cl:progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-symbol-macro ,name ,alias)
(cl:setf (get ',name '%aliases%) ',alias)
',name)))
(cl:defmacro -import-function- (fname falias &optional (lambda-list '() lambda-list-p))
(assert (cl:or (cl:and (cl:symbolp fname) (cl:symbolp falias))
(cl:and (cl:consp fname) (cl:consp falias))))
(cl:let ((name (cl:if (cl:symbolp fname) fname (cl:cadr fname)))
(alias (cl:if (cl:symbolp falias) falias (cl:cadr falias))))
`(cl:progn
,(cl:if lambda-list-p
(loop for (element . rest) on lambda-list
for restp = (cl:member element '(:rest &rest))
until restp
collect element into required-vars
finally (return
(cl:if restp
(cl:let ((rest-var (cl:car rest)))
(cl:if (cl:symbolp fname)
`(cl:defmacro ,fname (,@required-vars &rest ,rest-var)
`(,',falias ,,@required-vars ,@,rest-var))
`(defsetf ,name (,@(cl:cdr required-vars) &rest ,rest-var)
(,(cl:car required-vars))
`(cl:setf (,',alias ,,@(cl:cdr required-vars) ,@,rest-var)
,,(cl:car required-vars)))))
(cl:if (cl:symbolp fname)
`(cl:defmacro ,fname (,@lambda-list)
`(,',falias ,,@lambda-list))
`(defsetf ,name (,@(cl:cdr lambda-list)) (,(cl:car lambda-list))
`(cl:setf (,',alias ,,@(cl:cdr lambda-list))
,,(cl:car lambda-list)))))))
(cl:let ((rest-var (cl:gensym)))
(cl:if (cl:symbolp fname)
`(cl:defmacro ,fname (&rest ,rest-var)
`(,',falias ,@,rest-var))
(cl:let ((store-var (cl:gensym)))
`(defsetf ,fname (&rest ,rest-var) (,store-var)
`(cl:setf (,',alias ,@,rest-var) ,,store-var))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:setf (get ',name '%function-aliases%) ',alias))
',fname)))
(cl:defmacro -import-generic-function- (fname falias &optional (lambda-list '() lambda-list-p))
(assert (cl:or (cl:and (cl:symbolp fname) (cl:symbolp falias))
(cl:and (cl:consp fname) (cl:consp falias))))
(cl:let ((name (cl:if (cl:symbolp fname) fname (cl:cadr fname)))
(alias (cl:if (cl:symbolp falias) falias (cl:cadr falias))))
`(cl:progn
,(cl:if lambda-list-p
`(defgeneric ,fname (,@lambda-list))
`(defgeneric ,fname (&rest ,(cl:gensym))))
(cl:setf (cl:fdefinition ',(global fname)) (cl:fdefinition ',falias))
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:setf (get ',name '%function-aliases%) ',alias))
',fname)))
(cl:defmacro -import-macro- (fname falias &optional (lambda-list '() lambda-list-p))
(cl:if lambda-list-p
(loop with whole-var
with env-var
with body-var
with rest-var
for (elm1 elm2) on lambda-list
for element = (ll-keyword elm1)
if (cl:eq element '&whole) do (cl:setq whole-var elm2)
else if (cl:eq element '&environment) do (cl:setq env-var elm2)
else if (cl:eq element '&body) do (cl:setq body-var elm2)
else if (cl:eq element '&rest) do (cl:setq rest-var elm2)
else unless (cl:member element (cl:list whole-var env-var body-var rest-var))
collect element into required-vars
finally
(cl:let ((new-whole-var (cl:if whole-var whole-var 'whole-form))
(new-env-var (cl:if env-var env-var 'environment)))
(return
`(cl:progn
(cl:defmacro ,fname (&whole ,new-whole-var &environment ,new-env-var
,@required-vars
,@(when body-var `(&body ,body-var))
,@(when rest-var `(&rest ,rest-var)))
(declare (ignore ,@required-vars
,@(when body-var (cl:list body-var))
,@(when rest-var (cl:list rest-var))))
(cl:funcall (cl:macro-function ',falias ,new-env-var) ,new-whole-var ,new-env-var))
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:setf (get ',fname '%function-aliases%) ',falias))
',fname))))
(cl:let ((whole-var (cl:gensym)) (env-var (cl:gensym)) (body-var (cl:gensym)))
`(cl:progn
(cl:defmacro ,fname (&whole ,whole-var &environment ,env-var &body ,body-var)
(declare (ignore ,body-var))
(cl:funcall (cl:macro-function ',falias ,env-var) ,whole-var ,env-var))
(eval-when (:compile-toplevel :load-toplevel :execute)
(cl:setf (get ',fname '%function-aliases%) ',falias)
',fname)))))
(cl:defmacro -with-imported-variables- ((&rest bindings) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%aliases% env)))
`(locally (declare #+sbcl (sb-ext:disable-package-locks %aliases%))
(symbol-macrolet ((%aliases% ,(revappend bindings old-aliases)))
(declare (ignorable %aliases%))
(symbol-macrolet ,bindings ,@body)))))
(cl:defmacro -with-imported-symbol-macros- ((&rest bindings) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%aliases% env)))
`(locally (declare #+sbcl (sb-ext:disable-package-locks %aliases%))
(symbol-macrolet ((%aliases% ,(revappend bindings old-aliases)))
(declare (ignorable %aliases%))
(symbol-macrolet ,bindings ,@body)))))
(cl:defmacro -with-imported-functions- ((&rest bindings) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%function-aliases% env)))
`(locally (declare #+sbcl (sb-ext:disable-package-locks %function-aliases%))
(symbol-macrolet ((%function-aliases% ,(revappend bindings old-aliases)))
(declare (ignorable %function-aliases%))
(cl:macrolet ,(loop for (fun alias) in bindings
collect `(,fun (&rest args) `(,',alias ,@args)))
,@body)))))
(cl:defvar -arguments-for-local-macros-)
(cl:defmacro expand-local-macro (name &environment env)
`',(macroexpand `(,name ,@-arguments-for-local-macros-) env))
(cl:defmacro -with-imported-macros- ((&rest bindings) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%function-aliases% env)))
`(locally (declare #+sbcl (sb-ext:disable-package-locks %function-aliases%))
(symbol-macrolet ((%function-aliases% ,(revappend bindings old-aliases)))
(declare (ignorable %function-aliases%))
(cl:macrolet ,(loop for (macro alias) in bindings
collect `(,macro (&rest -arguments-for-local-macros-) (expand-local-macro ,alias)))
,@body)))))
(cl:defmacro -with-imported-block- ((block-name block-alias) &body body &environment env)
(cl:let ((old-aliases (macroexpand '%block-aliases% env)))
`(cl:block ,block-name
(locally (declare #+sbcl (sb-ext:disable-package-locks %block-aliases%))
(symbol-macrolet ((%block-aliases% ,(cl:cons `(,block-name ,block-alias) old-aliases)))
,@body)))))
(cl:defmacro -defmacro- (macro-name lambda-list &body body)
(cl:let ((macro-alias (global macro-name)))
(multiple-value-bind
(new-lambda-list new-aliases)
(parse-macro-lambda-list lambda-list)
`(cl:progn
(cl:defmacro ,macro-alias ,new-lambda-list
(-with-imported-variables- ,new-aliases ,@body))
(-import-macro- ,macro-name ,macro-alias ,lambda-list)))))
(cl:defun expand-body (new-aliases old-aliases body)
`(locally (declare #+sbcl (sb-ext:disable-package-locks %aliases%))
(symbol-macrolet ((%aliases% ,(revappend new-aliases old-aliases)))
(declare (ignorable %aliases%))
(symbol-macrolet ,new-aliases ,@body))))
(cl:defun process-lambda (env lambda-list body)
(cl:let ((old-aliases (macroexpand '%aliases% env)))
(multiple-value-bind
(new-lambda-list new-aliases)
(parse-lambda-list lambda-list)
(values new-lambda-list (expand-body new-aliases old-aliases body)))))
(cl:defun expand-method-body (qualifiers new-aliases old-aliases body)
(cl:let ((form (expand-body new-aliases old-aliases body)))
(cl:if (cl:or (cl:null qualifiers) (cl:member :around qualifiers))
`(-with-imported-functions- ((call-next-method cl:call-next-method)
(next-method-p cl:next-method-p))
,form)
form)))
(cl:defun expand-defclass (w class-name superclasses options &optional (conditionp cl:nil))
(when (cl:find :abstractp options :key #'cl:car)
(setf options (cl:remove :abstractp options :key #'cl:car)))
(unless (cl:and (cl:symbolp class-name)
(cl:listp superclasses)
(every #'cl:symbolp superclasses)
options
(cl:listp (cl:car options))
(cl:listp (cl:cdr options))
(loop for option in (cl:cdr options)
always (cl:and (cl:consp option)
(cl:car option)
(cl:symbolp (cl:car option)))))
(cl:error "Malformed definition: ~S." w))
(loop for slot-spec in (cl:car options)
for (new-slot-spec readers writers) = (parse-slot-spec w slot-spec)
collect new-slot-spec into new-slot-specs
nconc readers into reader-gfs
nconc writers into writer-gfs
finally (return `(cl:progn
,@(loop for gf in reader-gfs
collect `(defgeneric ,gf (object)))
,@(loop for gf in writer-gfs
collect `(defgeneric ,gf (new-value object)))
(,(cl:if conditionp 'cl:define-condition 'cl:defclass)
,class-name ,superclasses ,new-slot-specs ,@(cl:cdr options))))))
|
8f030de9e0af79a163de1b834ecfb8b7b40aa7ff2964f1558996df4c44016627 | monadius/ocaml_simple_interval | t_interval1.ml | open Test
open Interval1
module T = Test_interval
(* let () = Random.self_init () *)
let samples =
try int_of_string (Sys.getenv "TEST_SAMPLES")
with Not_found -> 1000
let () = Format.printf "samples = %d@." samples
let intervals_of_pair =
let intervals (a, b) =
if is_nan a || is_nan b || (a = infinity && b = neg_infinity) ||
(a = infinity && b = infinity) || (a = neg_infinity && b = neg_infinity) then
empty_interval, T.empty_interval
else if a <= b then
{low = a; high = b}, T.mk_i a b
else
{low = b; high = a}, T.mk_i b a in
fun (a, b) ->
let v, tv = intervals (a, b) in
assert (T.is_valid tv);
v, tv
let test_eq_intervals v tv =
compare v.low tv.T.lo = 0 && compare v.high tv.T.hi = 0
let test_subset v tv =
if T.is_empty tv then is_empty v
else
v.low <= tv.T.lo && tv.T.hi <= v.high
let test_subset_1ulp tv v =
if T.is_empty tv then is_empty v
else
let a = T.prev_float tv.T.lo and
b = T.next_float tv.T.hi in
a <= v.low && v.high <= b
let test_subset_2ulp tv v =
if T.is_empty tv then is_empty v
else
let a = T.prev_float (T.prev_float tv.T.lo) and
b = T.next_float (T.next_float tv.T.hi) in
a <= v.low && v.high <= b
let cmp_intervals v w =
let a = compare v.low w.low in
if a = 0 then compare v.high w.high
else a
let is_pos v = v.low >= 0.0
let is_neg v = v.high <= 0.0
let in_special_range =
let lo = ldexp 1.0 (-1022) and
hi = ldexp 1.0 (-1020) in
fun x -> let t = abs_float x in
lo <= t && t <= hi
(* fsucc tests *)
let test_fsucc x =
let y = fsucc x in
let z = T.next_float x in
if in_special_range x then
fact ("special_range", z <= y && y <= T.next_float z)
else
fact ("eq", compare y z = 0);
true
let () =
run_eq_f "fsucc (eq)" fsucc [
-.0.0, eta_float;
0.0, eta_float;
min_float, min_float +. 2.0 *. eta_float;
min_float -. eta_float, min_float;
-.min_float, -.(min_float -. 2.0 *. eta_float);
eta_float, 2.0 *. eta_float;
-.eta_float, 0.0;
1.0, 1.0 +. epsilon_float;
1.0 -. epsilon_float *. 0.5, 1.0;
-1.0, -.(1.0 -. epsilon_float *. 0.5);
max_float, infinity;
infinity, infinity;
nan, nan;
neg_infinity, nan;
]
let () =
run_test (test_f "fsucc (special)" test_fsucc)
(special_data_f ());
run_test (test_f "fsucc" test_fsucc)
(standard_data_f ~n:samples ~sign:0)
(* fpred tests *)
let test_fpred x =
let y = fpred x in
let z = T.prev_float x in
if in_special_range x then
fact ("special_range", T.prev_float z <= y && y <= z)
else
fact ("eq", compare y z = 0);
true
let () =
run_eq_f "fpred (eq)" fpred [
-.0.0, -.eta_float;
0.0, -.eta_float;
min_float, min_float -. 2.0 *. eta_float;
min_float +. eta_float, min_float -. eta_float;
-.min_float, -.(min_float +. 2.0 *. eta_float);
eta_float, 0.0;
-.eta_float, -2.0 *. eta_float;
1.0, 1.0 -. 0.5 *. epsilon_float;
1.0 -. epsilon_float *. 0.5, 1.0 -. epsilon_float;
-1.0, -.(1.0 +. epsilon_float);
-.max_float, neg_infinity;
infinity, nan;
nan, nan;
neg_infinity, neg_infinity;
]
let () =
run_test (test_f "fpred (special)" test_fpred)
(special_data_f ());
run_test (test_f "fpred" test_fpred)
(standard_data_f ~n:samples ~sign:0)
(* mid tests *)
let test_mid_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let m = mid_i v in
if is_empty v then fact ("empty", is_nan m)
else
begin
fact ("in", v.low <= m && m <= v.high);
fact ("finite", neg_infinity < m && m < infinity);
if v.low = -.v.high then fact ("sym", m = 0.);
end;
true
let () =
let f = fun (a, b) -> mid_i (make_interval a b) in
run_eq_f2 "mid_i (eq)" f [
(-0., 0.), 0.;
(infinity, neg_infinity), nan;
(neg_infinity, infinity), 0.;
(0., infinity), max_float;
(neg_infinity, 0.), -.max_float;
(-1., infinity), max_float;
(neg_infinity, 2.), -.max_float;
(-3., 3.), 0.;
(max_float *. 0.5, max_float), max_float *. 0.75;
(4., 100.), 52.;
(-3., 5.), 1.;
(0., eta_float), 0.;
(eta_float, 2. *. eta_float), 2. *. eta_float;
(eta_float, eta_float), eta_float;
(max_float, max_float), max_float;
]
let () =
let f = test_mid_i in
run_test (test_f2 "mid_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "mid_i" f)
(standard_data_f2 ~n:samples ~sign:0)
(* neg tests *)
let test_neg_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = neg_i v and
tr = T.neg_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("eq", test_eq_intervals r tr);
end;
true
let () =
let f = fun (a, b) -> neg_i (make_interval a b) in
run_eq_f2 "neg_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), make_interval 0. 0.;
(infinity, neg_infinity), empty_interval;
(neg_infinity, infinity), entire_interval;
(1., infinity), make_interval neg_infinity (-1.);
(neg_infinity, -3.), make_interval 3. infinity;
(-3., 2.), make_interval (-2.) 3.;
]
let () =
let f = test_neg_i in
run_test (test_f2 "neg_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "neg_i" f)
(standard_data_f2 ~n:samples ~sign:0)
(* abs tests *)
let test_abs_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = abs_i v and
tr = T.abs_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("eq", test_eq_intervals r tr);
end;
true
let () =
let f = fun (a, b) -> abs_i (make_interval a b) in
run_eq_f2 "abs_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), zero_interval;
(infinity, neg_infinity), empty_interval;
(neg_infinity, infinity), make_interval 0. infinity;
(1., infinity), make_interval 1. infinity;
(neg_infinity, -3.), make_interval 3. infinity;
(neg_infinity, 3.), make_interval 0. infinity;
(-3., 2.), make_interval 0. 3.;
(-3., -2.), make_interval 2. 3.;
]
let () =
let f = test_abs_i in
run_test (test_f2 "abs_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "abs_i" f)
(standard_data_f2 ~n:samples ~sign:0)
(* min/max tests *)
let test_min_max_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r1 = min_ii v w and
r2 = max_ii v w and
tr1 = T.min_ii tv tw and
tr2 = T.max_ii tv tw in
begin
fact ("valid", is_valid r1 && is_valid r2 && T.is_valid tr1 && T.is_valid tr2);
fact ("eq_min", test_eq_intervals r1 tr1);
fact ("eq_max", test_eq_intervals r2 tr2);
end;
true
let () =
let f = test_min_max_ii in
run_test (test_f2f2 "min(max)_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "min(max)_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
(* add tests *)
let test_add_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r = add_ii v w and
tr = T.add_ii tv tw in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if is_pos v && is_pos w then fact ("pos", is_pos r);
if is_neg v && is_neg w then fact ("neg", is_neg r);
end;
true
let test_add_id_di ((a, b) as p) (c, _) =
let v, tv = intervals_of_pair p in
let x = if is_nan c || c = infinity || c = neg_infinity then 0. else c in
let r = add_id v x and
r' = add_di x v and
tr = T.add_id tv x in
begin
fact ("id = di", cmp_intervals r r' = 0);
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if is_pos v && x >= 0. then fact ("pos", is_pos r);
if is_neg v && x <= 0. then fact ("neg", is_neg r);
end;
true
let () =
let f = fun (a, b) (c, d) -> add_ii (make_interval a b) (make_interval c d) in
run_eq_f2f2 "add_ii (eq)" ~cmp:cmp_intervals f [
(0., 0.), (0., 0.), zero_interval;
(infinity, neg_infinity), (1., 2.), empty_interval;
(-3., -5.), (infinity, neg_infinity), empty_interval;
(infinity, neg_infinity), (0., infinity), empty_interval;
(neg_infinity, infinity), (0., 1.), entire_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(3., 5.), (-3., 0.), make_interval 0. (fsucc 5.);
(neg_infinity, -1.), (0.1, infinity), entire_interval;
]
let () =
let f = test_add_ii in
run_test (test_f2f2 "add_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "add_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let () =
let f = test_add_id_di in
run_test (test_f2f2 "add_id(di) (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "add_id(di)" f)
(standard_data_f2f2 ~n:samples ~sign:0)
(* sub tests *)
let test_sub_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r = sub_ii v w and
tr = T.sub_ii tv tw in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if is_pos v && is_neg w then fact ("pos", is_pos r);
if is_neg v && is_pos w then fact ("neg", is_neg r);
end;
true
let test_sub_id_di ((a, b) as p) (c, _) =
let v, tv = intervals_of_pair p in
let x = if is_nan c || c = infinity || c = neg_infinity then 0. else c in
let r = sub_id v x and
r' = sub_di x v and
tr = T.sub_id tv x and
tr' = T.sub_di x tv in
begin
fact ("valid", is_valid r && is_valid r' && T.is_valid tr && T.is_valid tr');
fact ("subset", test_subset r tr && test_subset r' tr');
fact ("2ulp", test_subset_2ulp tr r && test_subset_2ulp tr' r');
if is_pos v && x <= 0. then begin
fact ("pos(id)", is_pos r);
fact ("neg(di)", is_neg r');
end;
if is_neg v && x >= 0. then begin
fact ("neg(id)", is_neg r);
fact ("pos(di)", is_pos r');
end;
end;
true
let () =
let f = fun (a, b) (c, d) -> sub_ii (make_interval a b) (make_interval c d) in
run_eq_f2f2 "sub_ii (eq)" ~cmp:cmp_intervals f [
(0., 0.), (0., 0.), zero_interval;
(infinity, neg_infinity), (1., 2.), empty_interval;
(-3., -5.), (infinity, neg_infinity), empty_interval;
(infinity, neg_infinity), (0., infinity), empty_interval;
(neg_infinity, infinity), (0., 1.), entire_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(3., 5.), (0., 3.), make_interval 0. (fsucc 5.);
(neg_infinity, -1.), (neg_infinity, 0.1), entire_interval;
]
let () =
let f = test_sub_ii in
run_test (test_f2f2 "sub_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "sub_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let () =
let f = test_sub_id_di in
run_test (test_f2f2 "sub_id(di) (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "sub_id(di)" f)
(standard_data_f2f2 ~n:samples ~sign:0)
(* mul tests *)
let test_mul_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r = mul_ii v w and
tr = T.mul_ii tv tw in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if (is_pos v && is_pos w) || (is_neg v && is_neg w) then fact ("pos", is_pos r);
if (is_pos v && is_neg w) || (is_neg v && is_pos w) then fact ("neg", is_neg r);
end;
true
let test_mul_id_di ((a, b) as p) (c, _) =
let v, tv = intervals_of_pair p in
let x = if is_nan c || c = infinity || c = neg_infinity then 0. else c in
let r = mul_id v x and
r' = mul_di x v and
tr = T.mul_id tv x in
begin
fact ("id = di", cmp_intervals r r' = 0);
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if (is_pos v && x >= 0.) || (is_neg v && x <= 0.) then fact ("pos", is_pos r);
if (is_pos v && x <= 0.) || (is_neg v && x >= 0.) then fact ("neg", is_neg r);
end;
true
let () =
let f = fun (a, b) (c, d) -> mul_ii (make_interval a b) (make_interval c d) in
run_eq_f2f2 "mul_ii (eq)" ~cmp:cmp_intervals f [
(0., 0.), (0., 0.), zero_interval;
(infinity, neg_infinity), (1., 2.), empty_interval;
(-3., -5.), (infinity, neg_infinity), empty_interval;
(infinity, neg_infinity), (0., infinity), empty_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(neg_infinity, infinity), (0., 1.), entire_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(neg_infinity, infinity), (0., 0.), zero_interval;
(neg_infinity, -1.), (0., infinity), make_interval neg_infinity 0.;
(neg_infinity, -1.), (neg_infinity, 0.), make_interval 0. infinity;
]
let () =
let f = test_mul_ii in
run_test (test_f2f2 "mul_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "mul_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let () =
let f = test_mul_id_di in
run_test (test_f2f2 "mul_id(di) (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "mul_id(di)" f)
(standard_data_f2f2 ~n:samples ~sign:0)
(* div tests *)
let test_div_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r = div_ii v w and
tr = T.div_ii tv tw in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if (is_pos v && is_pos w) || (is_neg v && is_neg w) then fact ("pos", is_pos r);
if (is_pos v && is_neg w) || (is_neg v && is_pos w) then fact ("neg", is_neg r);
end;
true
let test_div_id_di ((a, b) as p) (c, _) =
let v, tv = intervals_of_pair p in
let x = if is_nan c || c = infinity || c = neg_infinity then 0. else c in
let r = div_id v x and
r' = div_di x v and
tr = T.div_id tv x and
tr' = T.div_di x tv in
begin
fact ("valid", is_valid r && is_valid r' && T.is_valid tr && T.is_valid tr');
fact ("subset", test_subset r tr && test_subset r' tr');
fact ("2ulp", test_subset_2ulp tr r && test_subset_2ulp tr' r');
if (is_pos v && x >= 0.) || (is_neg v && x <= 0.) then begin
fact ("pos(id)", is_pos r);
fact ("pos(di)", is_pos r');
end;
if (is_pos v && x <= 0.) || (is_neg v && x >= 0.) then begin
fact ("neg(id)", is_neg r);
fact ("neg(di)", is_neg r');
end;
end;
true
let () =
let f = fun (a, b) (c, d) -> div_ii (make_interval a b) (make_interval c d) in
run_eq_f2f2 "div_ii (eq)" ~cmp:cmp_intervals f [
(0., 0.), (0., 0.), empty_interval;
(infinity, neg_infinity), (1., 2.), empty_interval;
(-3., -5.), (infinity, neg_infinity), empty_interval;
(infinity, neg_infinity), (0., infinity), empty_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(neg_infinity, infinity), (0., 1.), entire_interval;
(neg_infinity, infinity), (0., 0.), empty_interval;
(0., 0.), (neg_infinity, infinity), zero_interval;
(neg_infinity, 0.), (0., infinity), make_interval neg_infinity 0.;
(neg_infinity, 1.), (0., infinity), entire_interval;
(neg_infinity, -100.), (0., infinity), make_interval neg_infinity 0.;
(2., infinity), (0., infinity), make_interval 0. infinity;
(neg_infinity, 0.), (neg_infinity, 0.), make_interval 0. infinity;
(0., infinity), (0., infinity), make_interval 0. infinity;
(-1., 1.), (0., 1.), entire_interval;
]
let () =
let f = test_div_ii in
run_test (test_f2f2 "div_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "div_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let () =
let f = test_div_id_di in
run_test (test_f2f2 "div_id(di) (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "div_id(di)" f)
(standard_data_f2f2 ~n:samples ~sign:0)
(* inv tests *)
let test_inv_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = inv_i v and
tr = T.inv_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if is_pos v then fact ("pos", is_pos r);
if is_neg v then fact ("neg", is_neg r);
end;
true
let () =
let f = fun (a, b) -> inv_i (make_interval a b) in
run_eq_f2 "inv_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), empty_interval;
(infinity, neg_infinity), empty_interval;
(neg_infinity, infinity), entire_interval;
(0., infinity), make_interval 0. infinity;
(neg_infinity, 0.), make_interval neg_infinity 0.;
(neg_infinity, 3.), entire_interval;
(-1., infinity), entire_interval;
]
let () =
let f = test_inv_i in
run_test (test_f2 "inv_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "inv_i" f)
(standard_data_f2 ~n:samples ~sign:0)
(* sqrt tests *)
let test_sqrt_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = sqrt_i v and
tr = T.sqrt_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
fact ("pos", is_pos r);
if v.high < 0. then fact ("empty", is_empty r);
end;
true
let () =
let f = fun (a, b) -> sqrt_i (make_interval a b) in
run_eq_f2 "sqrt_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), zero_interval;
(infinity, neg_infinity), empty_interval;
(-3., -2.), empty_interval;
(neg_infinity, infinity), make_interval 0. infinity;
(0., infinity), make_interval 0. infinity;
(-5., 0.), zero_interval;
(neg_infinity, 0.), zero_interval;
(-1., infinity), make_interval 0. infinity;
]
let () =
let f = test_sqrt_i in
run_test (test_f2 "sqrt_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "sqrt_i" f)
(standard_data_f2 ~n:samples ~sign:0)
sqr tests
let test_sqr_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = sqr_i v and
tr = T.sqr_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
fact ("pos", is_pos r);
end;
true
let () =
let f = fun (a, b) -> sqr_i (make_interval a b) in
run_eq_f2 "sqr_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), zero_interval;
(infinity, neg_infinity), empty_interval;
(neg_infinity, infinity), make_interval 0. infinity;
(0., infinity), make_interval 0. infinity;
(neg_infinity, 0.), make_interval 0. infinity;
(-1., infinity), make_interval 0. infinity;
(neg_infinity, 2.), make_interval 0. infinity;
]
let () =
let f = test_sqr_i in
run_test (test_f2 "sqr_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "sqr_i" f)
(standard_data_f2 ~n:samples ~sign:0)
(* pown tests *)
let test_pown_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r0 = pown_i v 0 and
r1 = pown_i v 1 and
r3 = pown_i v 3 and
r8 = pown_i v 8 and
rn1 = pown_i v (-1) and
rn2 = pown_i v (-2) and
rn3 = pown_i v (-3) and
tr3 = T.pown_i tv 3 and
tr8 = T.pown_i tv 8 and
trn1 = T.pown_i tv (-1) and
trn2 = T.pown_i tv (-2) and
trn3 = T.pown_i tv (-3) in
begin
fact ("valid", is_valid r0 && is_valid r1 && is_valid r3 && is_valid r8 &&
is_valid rn1 && is_valid rn2 && is_valid rn3 &&
T.is_valid tr3 && T.is_valid tr8 && T.is_valid trn1 &&
T.is_valid trn2 && T.is_valid trn3);
if is_empty v then fact ("empty0", is_empty r0)
else fact ("eq0", cmp_intervals r0 one_interval = 0);
if T.is_empty tr3 then fact ("empty3", is_empty r3);
if T.is_empty tr8 then fact ("empty8", is_empty r8);
if T.is_empty trn1 then fact ("empty(-1)", is_empty rn1);
if T.is_empty trn2 then fact ("empty(-2)", is_empty rn2);
if T.is_empty trn3 then fact ("empty(-3)", is_empty rn3);
fact ("eq1", cmp_intervals r1 v = 0);
fact ("subset_pos", test_subset r3 tr3 && test_subset r8 tr8);
fact ("subset_neg", test_subset rn1 trn1 && test_subset rn2 trn2 && test_subset rn3 trn3);
fact ("2ulp(-1)", test_subset_2ulp trn1 rn1);
if is_pos v then fact ("pos", is_pos r3 && is_pos r8 &&
is_pos rn1 && is_pos rn2 && is_pos rn3);
if is_neg v then fact ("neg(odd)", is_neg r3 && is_neg rn1 && is_neg rn3);
if is_neg v then fact ("pos(even)", is_pos r8 && is_pos rn2);
end;
true
let () =
let f = fun (a, b) e -> pown_i (make_interval a b) (int_of_float e) in
run_eq_f2f "pown_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), 3., zero_interval;
(0., 0.), 8., zero_interval;
(0., 0.), -2., empty_interval;
(0., 0.), -3., empty_interval;
(0., 0.), -8., empty_interval;
(infinity, neg_infinity), -3., empty_interval;
(neg_infinity, infinity), 3., entire_interval;
(neg_infinity, infinity), 8., make_interval 0. infinity;
(neg_infinity, infinity), -2., make_interval 0. infinity;
(neg_infinity, infinity), -3., entire_interval;
(neg_infinity, infinity), -8., make_interval 0. infinity;
(0., infinity), 3., make_interval 0. infinity;
(0., infinity), 8., make_interval 0. infinity;
(0., infinity), -2., make_interval 0. infinity;
(0., infinity), -3., make_interval 0. infinity;
(0., infinity), -8., make_interval 0. infinity;
(neg_infinity, 0.), 3., make_interval neg_infinity 0.;
(neg_infinity, 0.), 8., make_interval 0. infinity;
(neg_infinity, 0.), -2., make_interval 0. infinity;
(neg_infinity, 0.), -3., make_interval neg_infinity 0.;
(neg_infinity, 0.), -8., make_interval 0. infinity;
(-1., infinity), 8., make_interval 0. infinity;
(-1., infinity), -2., make_interval 0. infinity;
(-1., infinity), -3., entire_interval;
(-1., infinity), -8., make_interval 0. infinity;
(neg_infinity, 2.), 8., make_interval 0. infinity;
(neg_infinity, 2.), -2., make_interval 0. infinity;
(neg_infinity, 2.), -3., entire_interval;
(neg_infinity, 2.), -8., make_interval 0. infinity;
]
let () =
let f = test_pown_i in
run_test (test_f2 "pown_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "pown_i" f)
(standard_data_f2 ~n:samples ~sign:0)
let () =
let errs = errors () in
if errs > 0 then
Format.printf "FAILED: %d@." errs
else
Format.printf "ALL PASSED@.";
exit (if errs > 0 then 1 else 0)
| null | https://raw.githubusercontent.com/monadius/ocaml_simple_interval/d1081e969e7f4907bc60c1e7d2af95fdf1f34310/tests/t_interval1.ml | ocaml | let () = Random.self_init ()
fsucc tests
fpred tests
mid tests
neg tests
abs tests
min/max tests
add tests
sub tests
mul tests
div tests
inv tests
sqrt tests
pown tests | open Test
open Interval1
module T = Test_interval
let samples =
try int_of_string (Sys.getenv "TEST_SAMPLES")
with Not_found -> 1000
let () = Format.printf "samples = %d@." samples
let intervals_of_pair =
let intervals (a, b) =
if is_nan a || is_nan b || (a = infinity && b = neg_infinity) ||
(a = infinity && b = infinity) || (a = neg_infinity && b = neg_infinity) then
empty_interval, T.empty_interval
else if a <= b then
{low = a; high = b}, T.mk_i a b
else
{low = b; high = a}, T.mk_i b a in
fun (a, b) ->
let v, tv = intervals (a, b) in
assert (T.is_valid tv);
v, tv
let test_eq_intervals v tv =
compare v.low tv.T.lo = 0 && compare v.high tv.T.hi = 0
let test_subset v tv =
if T.is_empty tv then is_empty v
else
v.low <= tv.T.lo && tv.T.hi <= v.high
let test_subset_1ulp tv v =
if T.is_empty tv then is_empty v
else
let a = T.prev_float tv.T.lo and
b = T.next_float tv.T.hi in
a <= v.low && v.high <= b
let test_subset_2ulp tv v =
if T.is_empty tv then is_empty v
else
let a = T.prev_float (T.prev_float tv.T.lo) and
b = T.next_float (T.next_float tv.T.hi) in
a <= v.low && v.high <= b
let cmp_intervals v w =
let a = compare v.low w.low in
if a = 0 then compare v.high w.high
else a
let is_pos v = v.low >= 0.0
let is_neg v = v.high <= 0.0
let in_special_range =
let lo = ldexp 1.0 (-1022) and
hi = ldexp 1.0 (-1020) in
fun x -> let t = abs_float x in
lo <= t && t <= hi
let test_fsucc x =
let y = fsucc x in
let z = T.next_float x in
if in_special_range x then
fact ("special_range", z <= y && y <= T.next_float z)
else
fact ("eq", compare y z = 0);
true
let () =
run_eq_f "fsucc (eq)" fsucc [
-.0.0, eta_float;
0.0, eta_float;
min_float, min_float +. 2.0 *. eta_float;
min_float -. eta_float, min_float;
-.min_float, -.(min_float -. 2.0 *. eta_float);
eta_float, 2.0 *. eta_float;
-.eta_float, 0.0;
1.0, 1.0 +. epsilon_float;
1.0 -. epsilon_float *. 0.5, 1.0;
-1.0, -.(1.0 -. epsilon_float *. 0.5);
max_float, infinity;
infinity, infinity;
nan, nan;
neg_infinity, nan;
]
let () =
run_test (test_f "fsucc (special)" test_fsucc)
(special_data_f ());
run_test (test_f "fsucc" test_fsucc)
(standard_data_f ~n:samples ~sign:0)
let test_fpred x =
let y = fpred x in
let z = T.prev_float x in
if in_special_range x then
fact ("special_range", T.prev_float z <= y && y <= z)
else
fact ("eq", compare y z = 0);
true
let () =
run_eq_f "fpred (eq)" fpred [
-.0.0, -.eta_float;
0.0, -.eta_float;
min_float, min_float -. 2.0 *. eta_float;
min_float +. eta_float, min_float -. eta_float;
-.min_float, -.(min_float +. 2.0 *. eta_float);
eta_float, 0.0;
-.eta_float, -2.0 *. eta_float;
1.0, 1.0 -. 0.5 *. epsilon_float;
1.0 -. epsilon_float *. 0.5, 1.0 -. epsilon_float;
-1.0, -.(1.0 +. epsilon_float);
-.max_float, neg_infinity;
infinity, nan;
nan, nan;
neg_infinity, neg_infinity;
]
let () =
run_test (test_f "fpred (special)" test_fpred)
(special_data_f ());
run_test (test_f "fpred" test_fpred)
(standard_data_f ~n:samples ~sign:0)
let test_mid_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let m = mid_i v in
if is_empty v then fact ("empty", is_nan m)
else
begin
fact ("in", v.low <= m && m <= v.high);
fact ("finite", neg_infinity < m && m < infinity);
if v.low = -.v.high then fact ("sym", m = 0.);
end;
true
let () =
let f = fun (a, b) -> mid_i (make_interval a b) in
run_eq_f2 "mid_i (eq)" f [
(-0., 0.), 0.;
(infinity, neg_infinity), nan;
(neg_infinity, infinity), 0.;
(0., infinity), max_float;
(neg_infinity, 0.), -.max_float;
(-1., infinity), max_float;
(neg_infinity, 2.), -.max_float;
(-3., 3.), 0.;
(max_float *. 0.5, max_float), max_float *. 0.75;
(4., 100.), 52.;
(-3., 5.), 1.;
(0., eta_float), 0.;
(eta_float, 2. *. eta_float), 2. *. eta_float;
(eta_float, eta_float), eta_float;
(max_float, max_float), max_float;
]
let () =
let f = test_mid_i in
run_test (test_f2 "mid_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "mid_i" f)
(standard_data_f2 ~n:samples ~sign:0)
let test_neg_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = neg_i v and
tr = T.neg_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("eq", test_eq_intervals r tr);
end;
true
let () =
let f = fun (a, b) -> neg_i (make_interval a b) in
run_eq_f2 "neg_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), make_interval 0. 0.;
(infinity, neg_infinity), empty_interval;
(neg_infinity, infinity), entire_interval;
(1., infinity), make_interval neg_infinity (-1.);
(neg_infinity, -3.), make_interval 3. infinity;
(-3., 2.), make_interval (-2.) 3.;
]
let () =
let f = test_neg_i in
run_test (test_f2 "neg_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "neg_i" f)
(standard_data_f2 ~n:samples ~sign:0)
let test_abs_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = abs_i v and
tr = T.abs_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("eq", test_eq_intervals r tr);
end;
true
let () =
let f = fun (a, b) -> abs_i (make_interval a b) in
run_eq_f2 "abs_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), zero_interval;
(infinity, neg_infinity), empty_interval;
(neg_infinity, infinity), make_interval 0. infinity;
(1., infinity), make_interval 1. infinity;
(neg_infinity, -3.), make_interval 3. infinity;
(neg_infinity, 3.), make_interval 0. infinity;
(-3., 2.), make_interval 0. 3.;
(-3., -2.), make_interval 2. 3.;
]
let () =
let f = test_abs_i in
run_test (test_f2 "abs_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "abs_i" f)
(standard_data_f2 ~n:samples ~sign:0)
let test_min_max_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r1 = min_ii v w and
r2 = max_ii v w and
tr1 = T.min_ii tv tw and
tr2 = T.max_ii tv tw in
begin
fact ("valid", is_valid r1 && is_valid r2 && T.is_valid tr1 && T.is_valid tr2);
fact ("eq_min", test_eq_intervals r1 tr1);
fact ("eq_max", test_eq_intervals r2 tr2);
end;
true
let () =
let f = test_min_max_ii in
run_test (test_f2f2 "min(max)_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "min(max)_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let test_add_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r = add_ii v w and
tr = T.add_ii tv tw in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if is_pos v && is_pos w then fact ("pos", is_pos r);
if is_neg v && is_neg w then fact ("neg", is_neg r);
end;
true
let test_add_id_di ((a, b) as p) (c, _) =
let v, tv = intervals_of_pair p in
let x = if is_nan c || c = infinity || c = neg_infinity then 0. else c in
let r = add_id v x and
r' = add_di x v and
tr = T.add_id tv x in
begin
fact ("id = di", cmp_intervals r r' = 0);
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if is_pos v && x >= 0. then fact ("pos", is_pos r);
if is_neg v && x <= 0. then fact ("neg", is_neg r);
end;
true
let () =
let f = fun (a, b) (c, d) -> add_ii (make_interval a b) (make_interval c d) in
run_eq_f2f2 "add_ii (eq)" ~cmp:cmp_intervals f [
(0., 0.), (0., 0.), zero_interval;
(infinity, neg_infinity), (1., 2.), empty_interval;
(-3., -5.), (infinity, neg_infinity), empty_interval;
(infinity, neg_infinity), (0., infinity), empty_interval;
(neg_infinity, infinity), (0., 1.), entire_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(3., 5.), (-3., 0.), make_interval 0. (fsucc 5.);
(neg_infinity, -1.), (0.1, infinity), entire_interval;
]
let () =
let f = test_add_ii in
run_test (test_f2f2 "add_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "add_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let () =
let f = test_add_id_di in
run_test (test_f2f2 "add_id(di) (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "add_id(di)" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let test_sub_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r = sub_ii v w and
tr = T.sub_ii tv tw in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if is_pos v && is_neg w then fact ("pos", is_pos r);
if is_neg v && is_pos w then fact ("neg", is_neg r);
end;
true
let test_sub_id_di ((a, b) as p) (c, _) =
let v, tv = intervals_of_pair p in
let x = if is_nan c || c = infinity || c = neg_infinity then 0. else c in
let r = sub_id v x and
r' = sub_di x v and
tr = T.sub_id tv x and
tr' = T.sub_di x tv in
begin
fact ("valid", is_valid r && is_valid r' && T.is_valid tr && T.is_valid tr');
fact ("subset", test_subset r tr && test_subset r' tr');
fact ("2ulp", test_subset_2ulp tr r && test_subset_2ulp tr' r');
if is_pos v && x <= 0. then begin
fact ("pos(id)", is_pos r);
fact ("neg(di)", is_neg r');
end;
if is_neg v && x >= 0. then begin
fact ("neg(id)", is_neg r);
fact ("pos(di)", is_pos r');
end;
end;
true
let () =
let f = fun (a, b) (c, d) -> sub_ii (make_interval a b) (make_interval c d) in
run_eq_f2f2 "sub_ii (eq)" ~cmp:cmp_intervals f [
(0., 0.), (0., 0.), zero_interval;
(infinity, neg_infinity), (1., 2.), empty_interval;
(-3., -5.), (infinity, neg_infinity), empty_interval;
(infinity, neg_infinity), (0., infinity), empty_interval;
(neg_infinity, infinity), (0., 1.), entire_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(3., 5.), (0., 3.), make_interval 0. (fsucc 5.);
(neg_infinity, -1.), (neg_infinity, 0.1), entire_interval;
]
let () =
let f = test_sub_ii in
run_test (test_f2f2 "sub_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "sub_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let () =
let f = test_sub_id_di in
run_test (test_f2f2 "sub_id(di) (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "sub_id(di)" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let test_mul_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r = mul_ii v w and
tr = T.mul_ii tv tw in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if (is_pos v && is_pos w) || (is_neg v && is_neg w) then fact ("pos", is_pos r);
if (is_pos v && is_neg w) || (is_neg v && is_pos w) then fact ("neg", is_neg r);
end;
true
let test_mul_id_di ((a, b) as p) (c, _) =
let v, tv = intervals_of_pair p in
let x = if is_nan c || c = infinity || c = neg_infinity then 0. else c in
let r = mul_id v x and
r' = mul_di x v and
tr = T.mul_id tv x in
begin
fact ("id = di", cmp_intervals r r' = 0);
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if (is_pos v && x >= 0.) || (is_neg v && x <= 0.) then fact ("pos", is_pos r);
if (is_pos v && x <= 0.) || (is_neg v && x >= 0.) then fact ("neg", is_neg r);
end;
true
let () =
let f = fun (a, b) (c, d) -> mul_ii (make_interval a b) (make_interval c d) in
run_eq_f2f2 "mul_ii (eq)" ~cmp:cmp_intervals f [
(0., 0.), (0., 0.), zero_interval;
(infinity, neg_infinity), (1., 2.), empty_interval;
(-3., -5.), (infinity, neg_infinity), empty_interval;
(infinity, neg_infinity), (0., infinity), empty_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(neg_infinity, infinity), (0., 1.), entire_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(neg_infinity, infinity), (0., 0.), zero_interval;
(neg_infinity, -1.), (0., infinity), make_interval neg_infinity 0.;
(neg_infinity, -1.), (neg_infinity, 0.), make_interval 0. infinity;
]
let () =
let f = test_mul_ii in
run_test (test_f2f2 "mul_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "mul_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let () =
let f = test_mul_id_di in
run_test (test_f2f2 "mul_id(di) (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "mul_id(di)" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let test_div_ii ((a, b) as p1) ((c, d) as p2) =
let v, tv = intervals_of_pair p1 and
w, tw = intervals_of_pair p2 in
let r = div_ii v w and
tr = T.div_ii tv tw in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if (is_pos v && is_pos w) || (is_neg v && is_neg w) then fact ("pos", is_pos r);
if (is_pos v && is_neg w) || (is_neg v && is_pos w) then fact ("neg", is_neg r);
end;
true
let test_div_id_di ((a, b) as p) (c, _) =
let v, tv = intervals_of_pair p in
let x = if is_nan c || c = infinity || c = neg_infinity then 0. else c in
let r = div_id v x and
r' = div_di x v and
tr = T.div_id tv x and
tr' = T.div_di x tv in
begin
fact ("valid", is_valid r && is_valid r' && T.is_valid tr && T.is_valid tr');
fact ("subset", test_subset r tr && test_subset r' tr');
fact ("2ulp", test_subset_2ulp tr r && test_subset_2ulp tr' r');
if (is_pos v && x >= 0.) || (is_neg v && x <= 0.) then begin
fact ("pos(id)", is_pos r);
fact ("pos(di)", is_pos r');
end;
if (is_pos v && x <= 0.) || (is_neg v && x >= 0.) then begin
fact ("neg(id)", is_neg r);
fact ("neg(di)", is_neg r');
end;
end;
true
let () =
let f = fun (a, b) (c, d) -> div_ii (make_interval a b) (make_interval c d) in
run_eq_f2f2 "div_ii (eq)" ~cmp:cmp_intervals f [
(0., 0.), (0., 0.), empty_interval;
(infinity, neg_infinity), (1., 2.), empty_interval;
(-3., -5.), (infinity, neg_infinity), empty_interval;
(infinity, neg_infinity), (0., infinity), empty_interval;
(neg_infinity, infinity), (neg_infinity, infinity), entire_interval;
(neg_infinity, infinity), (0., 1.), entire_interval;
(neg_infinity, infinity), (0., 0.), empty_interval;
(0., 0.), (neg_infinity, infinity), zero_interval;
(neg_infinity, 0.), (0., infinity), make_interval neg_infinity 0.;
(neg_infinity, 1.), (0., infinity), entire_interval;
(neg_infinity, -100.), (0., infinity), make_interval neg_infinity 0.;
(2., infinity), (0., infinity), make_interval 0. infinity;
(neg_infinity, 0.), (neg_infinity, 0.), make_interval 0. infinity;
(0., infinity), (0., infinity), make_interval 0. infinity;
(-1., 1.), (0., 1.), entire_interval;
]
let () =
let f = test_div_ii in
run_test (test_f2f2 "div_ii (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "div_ii" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let () =
let f = test_div_id_di in
run_test (test_f2f2 "div_id(di) (special)" f)
(special_data_f2f2 ());
run_test (test_f2f2 "div_id(di)" f)
(standard_data_f2f2 ~n:samples ~sign:0)
let test_inv_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = inv_i v and
tr = T.inv_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
if is_pos v then fact ("pos", is_pos r);
if is_neg v then fact ("neg", is_neg r);
end;
true
let () =
let f = fun (a, b) -> inv_i (make_interval a b) in
run_eq_f2 "inv_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), empty_interval;
(infinity, neg_infinity), empty_interval;
(neg_infinity, infinity), entire_interval;
(0., infinity), make_interval 0. infinity;
(neg_infinity, 0.), make_interval neg_infinity 0.;
(neg_infinity, 3.), entire_interval;
(-1., infinity), entire_interval;
]
let () =
let f = test_inv_i in
run_test (test_f2 "inv_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "inv_i" f)
(standard_data_f2 ~n:samples ~sign:0)
let test_sqrt_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = sqrt_i v and
tr = T.sqrt_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
fact ("pos", is_pos r);
if v.high < 0. then fact ("empty", is_empty r);
end;
true
let () =
let f = fun (a, b) -> sqrt_i (make_interval a b) in
run_eq_f2 "sqrt_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), zero_interval;
(infinity, neg_infinity), empty_interval;
(-3., -2.), empty_interval;
(neg_infinity, infinity), make_interval 0. infinity;
(0., infinity), make_interval 0. infinity;
(-5., 0.), zero_interval;
(neg_infinity, 0.), zero_interval;
(-1., infinity), make_interval 0. infinity;
]
let () =
let f = test_sqrt_i in
run_test (test_f2 "sqrt_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "sqrt_i" f)
(standard_data_f2 ~n:samples ~sign:0)
sqr tests
let test_sqr_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r = sqr_i v and
tr = T.sqr_i tv in
begin
fact ("valid", is_valid r && T.is_valid tr);
fact ("subset", test_subset r tr);
fact ("2ulp", test_subset_2ulp tr r);
fact ("pos", is_pos r);
end;
true
let () =
let f = fun (a, b) -> sqr_i (make_interval a b) in
run_eq_f2 "sqr_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), zero_interval;
(infinity, neg_infinity), empty_interval;
(neg_infinity, infinity), make_interval 0. infinity;
(0., infinity), make_interval 0. infinity;
(neg_infinity, 0.), make_interval 0. infinity;
(-1., infinity), make_interval 0. infinity;
(neg_infinity, 2.), make_interval 0. infinity;
]
let () =
let f = test_sqr_i in
run_test (test_f2 "sqr_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "sqr_i" f)
(standard_data_f2 ~n:samples ~sign:0)
let test_pown_i ((a, b) as p) =
let v, tv = intervals_of_pair p in
let r0 = pown_i v 0 and
r1 = pown_i v 1 and
r3 = pown_i v 3 and
r8 = pown_i v 8 and
rn1 = pown_i v (-1) and
rn2 = pown_i v (-2) and
rn3 = pown_i v (-3) and
tr3 = T.pown_i tv 3 and
tr8 = T.pown_i tv 8 and
trn1 = T.pown_i tv (-1) and
trn2 = T.pown_i tv (-2) and
trn3 = T.pown_i tv (-3) in
begin
fact ("valid", is_valid r0 && is_valid r1 && is_valid r3 && is_valid r8 &&
is_valid rn1 && is_valid rn2 && is_valid rn3 &&
T.is_valid tr3 && T.is_valid tr8 && T.is_valid trn1 &&
T.is_valid trn2 && T.is_valid trn3);
if is_empty v then fact ("empty0", is_empty r0)
else fact ("eq0", cmp_intervals r0 one_interval = 0);
if T.is_empty tr3 then fact ("empty3", is_empty r3);
if T.is_empty tr8 then fact ("empty8", is_empty r8);
if T.is_empty trn1 then fact ("empty(-1)", is_empty rn1);
if T.is_empty trn2 then fact ("empty(-2)", is_empty rn2);
if T.is_empty trn3 then fact ("empty(-3)", is_empty rn3);
fact ("eq1", cmp_intervals r1 v = 0);
fact ("subset_pos", test_subset r3 tr3 && test_subset r8 tr8);
fact ("subset_neg", test_subset rn1 trn1 && test_subset rn2 trn2 && test_subset rn3 trn3);
fact ("2ulp(-1)", test_subset_2ulp trn1 rn1);
if is_pos v then fact ("pos", is_pos r3 && is_pos r8 &&
is_pos rn1 && is_pos rn2 && is_pos rn3);
if is_neg v then fact ("neg(odd)", is_neg r3 && is_neg rn1 && is_neg rn3);
if is_neg v then fact ("pos(even)", is_pos r8 && is_pos rn2);
end;
true
let () =
let f = fun (a, b) e -> pown_i (make_interval a b) (int_of_float e) in
run_eq_f2f "pown_i (eq)" ~cmp:cmp_intervals f [
(-0., 0.), 3., zero_interval;
(0., 0.), 8., zero_interval;
(0., 0.), -2., empty_interval;
(0., 0.), -3., empty_interval;
(0., 0.), -8., empty_interval;
(infinity, neg_infinity), -3., empty_interval;
(neg_infinity, infinity), 3., entire_interval;
(neg_infinity, infinity), 8., make_interval 0. infinity;
(neg_infinity, infinity), -2., make_interval 0. infinity;
(neg_infinity, infinity), -3., entire_interval;
(neg_infinity, infinity), -8., make_interval 0. infinity;
(0., infinity), 3., make_interval 0. infinity;
(0., infinity), 8., make_interval 0. infinity;
(0., infinity), -2., make_interval 0. infinity;
(0., infinity), -3., make_interval 0. infinity;
(0., infinity), -8., make_interval 0. infinity;
(neg_infinity, 0.), 3., make_interval neg_infinity 0.;
(neg_infinity, 0.), 8., make_interval 0. infinity;
(neg_infinity, 0.), -2., make_interval 0. infinity;
(neg_infinity, 0.), -3., make_interval neg_infinity 0.;
(neg_infinity, 0.), -8., make_interval 0. infinity;
(-1., infinity), 8., make_interval 0. infinity;
(-1., infinity), -2., make_interval 0. infinity;
(-1., infinity), -3., entire_interval;
(-1., infinity), -8., make_interval 0. infinity;
(neg_infinity, 2.), 8., make_interval 0. infinity;
(neg_infinity, 2.), -2., make_interval 0. infinity;
(neg_infinity, 2.), -3., entire_interval;
(neg_infinity, 2.), -8., make_interval 0. infinity;
]
let () =
let f = test_pown_i in
run_test (test_f2 "pown_i (special)" f)
(special_data_f2 ());
run_test (test_f2 "pown_i" f)
(standard_data_f2 ~n:samples ~sign:0)
let () =
let errs = errors () in
if errs > 0 then
Format.printf "FAILED: %d@." errs
else
Format.printf "ALL PASSED@.";
exit (if errs > 0 then 1 else 0)
|
353e3f1691cee549ab8091bba3b6b304725e75ea50faeebbeb3e9de44877cb83 | eugeneia/athens | tests.lisp | (defpackage :simple-date-tests
(:use :common-lisp :fiveam :simple-date))
(in-package :simple-date-tests)
;; After loading the file, run the tests with (fiveam:run! :simple-date)
(def-suite :simple-date)
(in-suite :simple-date)
(test days-in-month
Note : internal date numbers , so 0 is March
(is (= 31 (simple-date::days-in-month 0 2000)))
(is (= 30 (simple-date::days-in-month 1 2000)))
(is (= 31 (simple-date::days-in-month 2 2000)))
(is (= 30 (simple-date::days-in-month 3 2000)))
(is (= 31 (simple-date::days-in-month 4 2000)))
(is (= 31 (simple-date::days-in-month 5 2000)))
(is (= 30 (simple-date::days-in-month 6 2000)))
(is (= 31 (simple-date::days-in-month 7 2000)))
(is (= 30 (simple-date::days-in-month 8 2000)))
(is (= 31 (simple-date::days-in-month 9 2000)))
(is (= 31 (simple-date::days-in-month 10 2000)))
(is (= 29 (simple-date::days-in-month 11 2000)))
(is (= 28 (simple-date::days-in-month 11 2001))))
(defmacro with-random-dates (amount &body body)
(let ((i (gensym)))
`(dotimes (,i ,amount)
(let ((year (+ 1900 (random 300)))
(month (1+ (random 12)))
(day (1+ (random 28)))
(hour (random 24))
(min (random 60))
(sec (random 60))
(millisec (random 1000)))
,@body))))
(test encode-date
(with-random-dates 100
(declare (ignore hour min sec millisec))
(multiple-value-bind (year* month* day*) (decode-date (encode-date year month day))
(is (and (= year* year)
(= month* month)
(= day* day))))))
(test leap-year
(flet ((test-date (y m d)
(multiple-value-bind (y2 m2 d2) (decode-date (encode-date y m d))
(and (= y y2) (= m m2) (= d d2)))))
(is (test-date 2000 2 29))
(is (test-date 2004 2 29))
(is (test-date 2108 2 29))
(is (test-date 1992 2 29))))
(test encode-timestamp
(with-random-dates 100
(multiple-value-bind (year* month* day* hour* min* sec* millisec*)
(decode-timestamp (encode-timestamp year month day hour min sec millisec))
(is (and (= year* year)
(= month* month)
(= day* day)
(= hour* hour)
(= min* min)
(= sec* sec)
(= millisec* millisec))))))
(test timestamp-universal-times
(with-random-dates 100
(declare (ignore millisec))
(let ((stamp (encode-timestamp year month day hour min sec 0))
(utime (encode-universal-time sec min hour day month year 0)))
(is (= (timestamp-to-universal-time stamp) utime))
(is (time= (universal-time-to-timestamp utime) stamp)))))
(test add-month
(with-random-dates 100
(multiple-value-bind (year* month* day* hour* min* sec* millisec*)
(decode-timestamp (time-add (encode-timestamp year month day hour min sec millisec)
(encode-interval :month 1)))
(is (and (or (and (= year* year) (= month* (1+ month)))
(and (= year* (1+ year)) (= month* 1)))
(= day* day)
(= hour* hour)
(= min* min)
(= sec* sec)
(= millisec* millisec))))))
(test subtract-month
(with-random-dates 100
(multiple-value-bind (year* month* day* hour* min* sec* millisec*)
(decode-timestamp (time-add (encode-timestamp year month day hour min sec millisec)
(encode-interval :month -1)))
(is (and (or (and (= year* year) (= month* (1- month)))
(and (= year* (1- year)) (= month* 12)))
(= day* day)
(= hour* hour)
(= min* min)
(= sec* sec)
(= millisec* millisec))))))
(test add-hour
(with-random-dates 100
(declare (ignore millisec))
(is (= (- (timestamp-to-universal-time (time-add (encode-timestamp year month day hour min sec 0)
(encode-interval :hour 1)))
(encode-universal-time sec min hour day month year 0))
3600))))
(test time<
(with-random-dates 100
(is (time< (encode-date year month day)
(encode-date (1+ year) month day)))
(is (time< (encode-timestamp year month day hour min sec millisec)
(encode-timestamp year month day hour min (1+ sec) millisec)))
(is (time< (encode-interval :month month :hour hour)
(encode-interval :month month :hour hour :minute 30)))))
| null | https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/postmodern-20180711-git/simple-date/tests.lisp | lisp | After loading the file, run the tests with (fiveam:run! :simple-date) | (defpackage :simple-date-tests
(:use :common-lisp :fiveam :simple-date))
(in-package :simple-date-tests)
(def-suite :simple-date)
(in-suite :simple-date)
(test days-in-month
Note : internal date numbers , so 0 is March
(is (= 31 (simple-date::days-in-month 0 2000)))
(is (= 30 (simple-date::days-in-month 1 2000)))
(is (= 31 (simple-date::days-in-month 2 2000)))
(is (= 30 (simple-date::days-in-month 3 2000)))
(is (= 31 (simple-date::days-in-month 4 2000)))
(is (= 31 (simple-date::days-in-month 5 2000)))
(is (= 30 (simple-date::days-in-month 6 2000)))
(is (= 31 (simple-date::days-in-month 7 2000)))
(is (= 30 (simple-date::days-in-month 8 2000)))
(is (= 31 (simple-date::days-in-month 9 2000)))
(is (= 31 (simple-date::days-in-month 10 2000)))
(is (= 29 (simple-date::days-in-month 11 2000)))
(is (= 28 (simple-date::days-in-month 11 2001))))
(defmacro with-random-dates (amount &body body)
(let ((i (gensym)))
`(dotimes (,i ,amount)
(let ((year (+ 1900 (random 300)))
(month (1+ (random 12)))
(day (1+ (random 28)))
(hour (random 24))
(min (random 60))
(sec (random 60))
(millisec (random 1000)))
,@body))))
(test encode-date
(with-random-dates 100
(declare (ignore hour min sec millisec))
(multiple-value-bind (year* month* day*) (decode-date (encode-date year month day))
(is (and (= year* year)
(= month* month)
(= day* day))))))
(test leap-year
(flet ((test-date (y m d)
(multiple-value-bind (y2 m2 d2) (decode-date (encode-date y m d))
(and (= y y2) (= m m2) (= d d2)))))
(is (test-date 2000 2 29))
(is (test-date 2004 2 29))
(is (test-date 2108 2 29))
(is (test-date 1992 2 29))))
(test encode-timestamp
(with-random-dates 100
(multiple-value-bind (year* month* day* hour* min* sec* millisec*)
(decode-timestamp (encode-timestamp year month day hour min sec millisec))
(is (and (= year* year)
(= month* month)
(= day* day)
(= hour* hour)
(= min* min)
(= sec* sec)
(= millisec* millisec))))))
(test timestamp-universal-times
(with-random-dates 100
(declare (ignore millisec))
(let ((stamp (encode-timestamp year month day hour min sec 0))
(utime (encode-universal-time sec min hour day month year 0)))
(is (= (timestamp-to-universal-time stamp) utime))
(is (time= (universal-time-to-timestamp utime) stamp)))))
(test add-month
(with-random-dates 100
(multiple-value-bind (year* month* day* hour* min* sec* millisec*)
(decode-timestamp (time-add (encode-timestamp year month day hour min sec millisec)
(encode-interval :month 1)))
(is (and (or (and (= year* year) (= month* (1+ month)))
(and (= year* (1+ year)) (= month* 1)))
(= day* day)
(= hour* hour)
(= min* min)
(= sec* sec)
(= millisec* millisec))))))
(test subtract-month
(with-random-dates 100
(multiple-value-bind (year* month* day* hour* min* sec* millisec*)
(decode-timestamp (time-add (encode-timestamp year month day hour min sec millisec)
(encode-interval :month -1)))
(is (and (or (and (= year* year) (= month* (1- month)))
(and (= year* (1- year)) (= month* 12)))
(= day* day)
(= hour* hour)
(= min* min)
(= sec* sec)
(= millisec* millisec))))))
(test add-hour
(with-random-dates 100
(declare (ignore millisec))
(is (= (- (timestamp-to-universal-time (time-add (encode-timestamp year month day hour min sec 0)
(encode-interval :hour 1)))
(encode-universal-time sec min hour day month year 0))
3600))))
(test time<
(with-random-dates 100
(is (time< (encode-date year month day)
(encode-date (1+ year) month day)))
(is (time< (encode-timestamp year month day hour min sec millisec)
(encode-timestamp year month day hour min (1+ sec) millisec)))
(is (time< (encode-interval :month month :hour hour)
(encode-interval :month month :hour hour :minute 30)))))
|
10a39840a876420e731cd4240008c3782eb2ca21c02ec6fb9e0c282ae0ba52ab | Janiczek/clj-markov | project.clj | (defproject janiczek/markov "0.3.1"
:description "Markov chains in Clojure"
:url ""
:license {:name "Eclipse Public License - v1.0"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]])
| null | https://raw.githubusercontent.com/Janiczek/clj-markov/e1da8e1653e029fbc3f38056d7019946013465f4/project.clj | clojure | (defproject janiczek/markov "0.3.1"
:description "Markov chains in Clojure"
:url ""
:license {:name "Eclipse Public License - v1.0"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]])
|
|
85a9b9435db3434f9c5873dabf29dfdc1bf64feb1236bfa1de32326ac7e5d186 | Apress/practical-webdev-haskell | Fixture.hs | module Fixture where
import ClassyPrelude
unimplemented :: a
unimplemented = error "unimplemented"
dispatch :: (MonadIO m, MonadReader r m)
=> (r -> a -> IO b)
-> (a -> m b)
dispatch getter param = do
func <- asks getter
liftIO $ func param
dispatch2 :: (MonadIO m, MonadReader r m)
=> (r -> a -> b -> IO c)
-> (a -> b -> m c)
dispatch2 getter param1 param2 = do
func <- asks getter
liftIO $ func param1 param2
| null | https://raw.githubusercontent.com/Apress/practical-webdev-haskell/17b90c06030def254bb0497b9e357f5d3b96d0cf/12/test/Fixture.hs | haskell | module Fixture where
import ClassyPrelude
unimplemented :: a
unimplemented = error "unimplemented"
dispatch :: (MonadIO m, MonadReader r m)
=> (r -> a -> IO b)
-> (a -> m b)
dispatch getter param = do
func <- asks getter
liftIO $ func param
dispatch2 :: (MonadIO m, MonadReader r m)
=> (r -> a -> b -> IO c)
-> (a -> b -> m c)
dispatch2 getter param1 param2 = do
func <- asks getter
liftIO $ func param1 param2
|
|
cf81ea2217bcfd857840b51b299a27a65f26833e232c5d8cfd6cef60e28e16cb | samoht/camloo | io.scm | ;; Le module
(module
__caml_io
(import
__caml_arg
__caml_baltree
__caml_char
__caml_eq
__caml_exc
__caml_fchar
__caml_filename
__caml_float
__caml_fstring
__caml_fvect
__caml_genlex
__caml_hashtbl
__caml_int
__caml_lexing
__caml_list
__caml_map
__caml_pair
__caml_parsing
__caml_printexc
__caml_printf
__caml_queue
__caml_random
__caml_set
__caml_sort
__caml_stack
__caml_stream
__caml_string
__caml_vect
__caml_constr
__caml_bfloat
__caml_bint
__caml_bio
__caml_bmisc
__caml_bstring
__caml_sys
__caml_handle
__caml_intext
__caml_tag)
(export
std_in_43@io
std_out_112@io
std_err_241@io
stdin_193@io
stdout_127@io
stderr_46@io
(exit_246@io x1)
(open_in_gen_187@io x1)
(3-49-open_in_gen_187@io x1 x2 x3)
open_in_150@io
open_in_bin_161@io
(input_26@io x1)
(4-66-input_26@io x1 x2 x3 x4)
(fast_really_input_45@io x1)
(4-208-fast_really_input_45@io x1 x2 x3 x4)
(really_input_190@io x1)
(4-14-really_input_190@io x1 x2 x3 x4)
(read_line_228@io x1)
(read_int_41@io x1)
(read_float_120@io x1)
(open_out_gen_252@io x1)
(3-76-open_out_gen_252@io x1 x2 x3)
open_out_142@io
open_out_bin_83@io
(output_249@io x1)
(4-119-output_249@io x1 x2 x3 x4)
(output_string_156@io x1)
(2-235-output_string_156@io x1 x2)
print_char_82@io
print_string_98@io
(print_int_72@io x1)
(print_float_250@io x1)
(print_endline_197@io x1)
(print_newline_91@io x1)
prerr_char_240@io
prerr_string_235@io
(prerr_int_158@io x1)
(prerr_float_62@io x1)
(prerr_endline_232@io x1)))
L'initialisation du module
(init_camloo!)
;; Les variables globales
;; Les expressions globales
(begin
(define std_in_43@io (open_descriptor 0))
(begin
(define std_out_112@io (open_descriptor 1))
(define std_err_241@io (open_descriptor 2))))
(begin
(define stdin_193@io std_in_43@io)
(begin
(define stdout_127@io std_out_112@io)
(define stderr_46@io std_err_241@io)))
(define (exit_246@io x1)
(begin
(flush std_out_112@io)
(begin (flush std_err_241@io) (sys_exit x1))))
(begin
(define (open_in_gen_187@io x1)
(lambda (x2)
(lambda (x3) (3-49-open_in_gen_187@io x1 x2 x3))))
(define (3-49-open_in_gen_187@io x1 x2 x3)
(open_descriptor (sys_open x3 x1 x2)))
)
(begin
(define open_in_150@io
((open_in_gen_187@io '(#f #<0009>)) 0))
(define open_in_bin_161@io
((open_in_gen_187@io '(#f #<0008>)) 0))
)
(begin
(define (input_26@io x1)
(lambda (x2)
(lambda (x3)
(lambda (x4) (4-66-input_26@io x1 x2 x3 x4)))))
(define (4-66-input_26@io x1 x2 x3 x4)
(if (or (<fx x4 0)
(or (<fx x3 0)
(>fx (+fx x3 x4) (string-length x2))))
(invalid_arg_209@exc "input")
(input x1 x2 x3 x4)))
)
(begin
(define (fast_really_input_45@io x1)
(lambda (x2)
(lambda (x3)
(lambda (x4)
(4-208-fast_really_input_45@io x1 x2 x3 x4)))))
(define (4-208-fast_really_input_45@io x1 x2 x3 x4)
(if (<=fx x4 0)
#f
(let ((x5 (input x1 x2 x3 x4)))
(labels
((staticfail1001
()
(4-208-fast_really_input_45@io
x1
x2
(+fx x3 x5)
(-fx x4 x5))))
(let ((g1002 x5))
(cond ((=fx g1002 0) (caml-raise 'End_of_file_1@io))
(else (staticfail1001))))))))
)
(begin
(define (really_input_190@io x1)
(lambda (x2)
(lambda (x3)
(lambda (x4)
(4-14-really_input_190@io x1 x2 x3 x4)))))
(define (4-14-really_input_190@io x1 x2 x3 x4)
(if (or (<fx x4 0)
(or (<fx x3 0)
(>fx (+fx x3 x4) (string-length x2))))
(invalid_arg_209@exc "really_input")
(4-208-fast_really_input_45@io x1 x2 x3 x4)))
)
(define (read_line_228@io x1)
(begin
(flush std_out_112@io)
(input_line std_in_43@io)))
(define (read_int_41@io x1)
(int_of_string (read_line_228@io #f)))
(define (read_float_120@io x1)
(float_of_string (read_line_228@io #f)))
(begin
(define (open_out_gen_252@io x1)
(lambda (x2)
(lambda (x3) (3-76-open_out_gen_252@io x1 x2 x3))))
(define (3-76-open_out_gen_252@io x1 x2 x3)
(open_descriptor (sys_open x3 x1 x2)))
)
(begin
(define open_out_142@io
((open_out_gen_252@io '(#t #<0006> #a000 #<0009>))
(+fx s_irall_56@sys s_iwall_219@sys)))
(define open_out_bin_83@io
((open_out_gen_252@io '(#t #<0006> #a000 #<0008>))
(+fx s_irall_56@sys s_iwall_219@sys)))
)
(begin
(define (output_249@io x1)
(lambda (x2)
(lambda (x3)
(lambda (x4) (4-119-output_249@io x1 x2 x3 x4)))))
(define (4-119-output_249@io x1 x2 x3 x4)
(if (or (<fx x4 0)
(or (<fx x3 0)
(>fx (+fx x3 x4) (string-length x2))))
(invalid_arg_209@exc "output")
(output x1 x2 x3 x4)))
)
(begin
(define (output_string_156@io x1)
(lambda (x2) (2-235-output_string_156@io x1 x2)))
(define (2-235-output_string_156@io x1 x2)
(output x1 x2 0 (string-length x2)))
)
(define print_char_82@io
((lambda (x1) (lambda (x2) (output_char x1 x2)))
std_out_112@io))
(define print_string_98@io
(output_string_156@io std_out_112@io))
(define (print_int_72@io x1)
(print_string_98@io (string_of_int_188@int x1)))
(define (print_float_250@io x1)
(print_string_98@io
(string_of_float_111@float x1)))
(define (print_endline_197@io x1)
(begin
(print_string_98@io x1)
(print_char_82@io #\newline)))
(define (print_newline_91@io x1)
(begin
(print_char_82@io #\newline)
(flush std_out_112@io)))
(define prerr_char_240@io
((lambda (x1) (lambda (x2) (output_char x1 x2)))
std_err_241@io))
(define prerr_string_235@io
(output_string_156@io std_err_241@io))
(define (prerr_int_158@io x1)
(prerr_string_235@io (string_of_int_188@int x1)))
(define (prerr_float_62@io x1)
(prerr_string_235@io
(string_of_float_111@float x1)))
(define (prerr_endline_232@io x1)
(begin
(prerr_string_235@io x1)
(begin
(prerr_char_240@io #\newline)
(flush std_err_241@io))))
| null | https://raw.githubusercontent.com/samoht/camloo/29a578a152fa23a3125a2a5b23e325b6d45d3abd/src/runtime/Llib.bootstrap/io.scm | scheme | Le module
Les variables globales
Les expressions globales | (module
__caml_io
(import
__caml_arg
__caml_baltree
__caml_char
__caml_eq
__caml_exc
__caml_fchar
__caml_filename
__caml_float
__caml_fstring
__caml_fvect
__caml_genlex
__caml_hashtbl
__caml_int
__caml_lexing
__caml_list
__caml_map
__caml_pair
__caml_parsing
__caml_printexc
__caml_printf
__caml_queue
__caml_random
__caml_set
__caml_sort
__caml_stack
__caml_stream
__caml_string
__caml_vect
__caml_constr
__caml_bfloat
__caml_bint
__caml_bio
__caml_bmisc
__caml_bstring
__caml_sys
__caml_handle
__caml_intext
__caml_tag)
(export
std_in_43@io
std_out_112@io
std_err_241@io
stdin_193@io
stdout_127@io
stderr_46@io
(exit_246@io x1)
(open_in_gen_187@io x1)
(3-49-open_in_gen_187@io x1 x2 x3)
open_in_150@io
open_in_bin_161@io
(input_26@io x1)
(4-66-input_26@io x1 x2 x3 x4)
(fast_really_input_45@io x1)
(4-208-fast_really_input_45@io x1 x2 x3 x4)
(really_input_190@io x1)
(4-14-really_input_190@io x1 x2 x3 x4)
(read_line_228@io x1)
(read_int_41@io x1)
(read_float_120@io x1)
(open_out_gen_252@io x1)
(3-76-open_out_gen_252@io x1 x2 x3)
open_out_142@io
open_out_bin_83@io
(output_249@io x1)
(4-119-output_249@io x1 x2 x3 x4)
(output_string_156@io x1)
(2-235-output_string_156@io x1 x2)
print_char_82@io
print_string_98@io
(print_int_72@io x1)
(print_float_250@io x1)
(print_endline_197@io x1)
(print_newline_91@io x1)
prerr_char_240@io
prerr_string_235@io
(prerr_int_158@io x1)
(prerr_float_62@io x1)
(prerr_endline_232@io x1)))
L'initialisation du module
(init_camloo!)
(begin
(define std_in_43@io (open_descriptor 0))
(begin
(define std_out_112@io (open_descriptor 1))
(define std_err_241@io (open_descriptor 2))))
(begin
(define stdin_193@io std_in_43@io)
(begin
(define stdout_127@io std_out_112@io)
(define stderr_46@io std_err_241@io)))
(define (exit_246@io x1)
(begin
(flush std_out_112@io)
(begin (flush std_err_241@io) (sys_exit x1))))
(begin
(define (open_in_gen_187@io x1)
(lambda (x2)
(lambda (x3) (3-49-open_in_gen_187@io x1 x2 x3))))
(define (3-49-open_in_gen_187@io x1 x2 x3)
(open_descriptor (sys_open x3 x1 x2)))
)
(begin
(define open_in_150@io
((open_in_gen_187@io '(#f #<0009>)) 0))
(define open_in_bin_161@io
((open_in_gen_187@io '(#f #<0008>)) 0))
)
(begin
(define (input_26@io x1)
(lambda (x2)
(lambda (x3)
(lambda (x4) (4-66-input_26@io x1 x2 x3 x4)))))
(define (4-66-input_26@io x1 x2 x3 x4)
(if (or (<fx x4 0)
(or (<fx x3 0)
(>fx (+fx x3 x4) (string-length x2))))
(invalid_arg_209@exc "input")
(input x1 x2 x3 x4)))
)
(begin
(define (fast_really_input_45@io x1)
(lambda (x2)
(lambda (x3)
(lambda (x4)
(4-208-fast_really_input_45@io x1 x2 x3 x4)))))
(define (4-208-fast_really_input_45@io x1 x2 x3 x4)
(if (<=fx x4 0)
#f
(let ((x5 (input x1 x2 x3 x4)))
(labels
((staticfail1001
()
(4-208-fast_really_input_45@io
x1
x2
(+fx x3 x5)
(-fx x4 x5))))
(let ((g1002 x5))
(cond ((=fx g1002 0) (caml-raise 'End_of_file_1@io))
(else (staticfail1001))))))))
)
(begin
(define (really_input_190@io x1)
(lambda (x2)
(lambda (x3)
(lambda (x4)
(4-14-really_input_190@io x1 x2 x3 x4)))))
(define (4-14-really_input_190@io x1 x2 x3 x4)
(if (or (<fx x4 0)
(or (<fx x3 0)
(>fx (+fx x3 x4) (string-length x2))))
(invalid_arg_209@exc "really_input")
(4-208-fast_really_input_45@io x1 x2 x3 x4)))
)
(define (read_line_228@io x1)
(begin
(flush std_out_112@io)
(input_line std_in_43@io)))
(define (read_int_41@io x1)
(int_of_string (read_line_228@io #f)))
(define (read_float_120@io x1)
(float_of_string (read_line_228@io #f)))
(begin
(define (open_out_gen_252@io x1)
(lambda (x2)
(lambda (x3) (3-76-open_out_gen_252@io x1 x2 x3))))
(define (3-76-open_out_gen_252@io x1 x2 x3)
(open_descriptor (sys_open x3 x1 x2)))
)
(begin
(define open_out_142@io
((open_out_gen_252@io '(#t #<0006> #a000 #<0009>))
(+fx s_irall_56@sys s_iwall_219@sys)))
(define open_out_bin_83@io
((open_out_gen_252@io '(#t #<0006> #a000 #<0008>))
(+fx s_irall_56@sys s_iwall_219@sys)))
)
(begin
(define (output_249@io x1)
(lambda (x2)
(lambda (x3)
(lambda (x4) (4-119-output_249@io x1 x2 x3 x4)))))
(define (4-119-output_249@io x1 x2 x3 x4)
(if (or (<fx x4 0)
(or (<fx x3 0)
(>fx (+fx x3 x4) (string-length x2))))
(invalid_arg_209@exc "output")
(output x1 x2 x3 x4)))
)
(begin
(define (output_string_156@io x1)
(lambda (x2) (2-235-output_string_156@io x1 x2)))
(define (2-235-output_string_156@io x1 x2)
(output x1 x2 0 (string-length x2)))
)
(define print_char_82@io
((lambda (x1) (lambda (x2) (output_char x1 x2)))
std_out_112@io))
(define print_string_98@io
(output_string_156@io std_out_112@io))
(define (print_int_72@io x1)
(print_string_98@io (string_of_int_188@int x1)))
(define (print_float_250@io x1)
(print_string_98@io
(string_of_float_111@float x1)))
(define (print_endline_197@io x1)
(begin
(print_string_98@io x1)
(print_char_82@io #\newline)))
(define (print_newline_91@io x1)
(begin
(print_char_82@io #\newline)
(flush std_out_112@io)))
(define prerr_char_240@io
((lambda (x1) (lambda (x2) (output_char x1 x2)))
std_err_241@io))
(define prerr_string_235@io
(output_string_156@io std_err_241@io))
(define (prerr_int_158@io x1)
(prerr_string_235@io (string_of_int_188@int x1)))
(define (prerr_float_62@io x1)
(prerr_string_235@io
(string_of_float_111@float x1)))
(define (prerr_endline_232@io x1)
(begin
(prerr_string_235@io x1)
(begin
(prerr_char_240@io #\newline)
(flush std_err_241@io))))
|
d793593f8bb8c2703015685c94d4f13b5646247ad5e595452ee093cd993027d3 | racket/racket7 | get-linklet.rkt | #lang racket/base
(require "../common/set.rkt"
"../common/phase.rkt"
"../run/status.rkt"
"../host/linklet.rkt"
"../compile/module-use.rkt"
"../syntax/binding.rkt"
"../namespace/provided.rkt"
"link.rkt"
"linklet-info.rkt"
"linklet.rkt"
"module.rkt")
(provide get-linklets!)
(define (get-linklets! lnk
#:cache cache
#:compiled-modules compiled-modules
#:seen seen
#:linklets linklets
#:linklets-in-order linklets-in-order
#:side-effect-free-modules side-effect-free-modules)
(let get-linklets! ([lnk lnk] [first? #t])
(define name (link-name lnk))
(define phase (link-phase lnk))
(define root-name (if (pair? name) (car name) name)) ; strip away submodule path
(unless (or (symbol? root-name) ; skip pre-defined modules
(hash-ref seen lnk #f))
Seeing this module+phase combination for the first time
(log-status "Getting ~s at ~s" name phase)
(define comp-mod (get-compiled-module name root-name
#:compiled-modules compiled-modules
#:cache cache))
Extract the relevant ( i.e. , at a given phase )
;; from the compiled module
(define h (compiled-module-phase-to-linklet comp-mod))
(define linklet
(hash-ref h phase #f))
;; Extract other metadata at the module level:
(define reqs (instance-variable-value (compiled-module-declaration comp-mod) 'requires))
(define provs (instance-variable-value (compiled-module-declaration comp-mod) 'provides))
;; Extract phase-specific (i.e., linklet-specific) info on variables:
(define vars (if linklet
(list->set (linklet-export-variables linklet))
null))
;; Extract phase-specific info on imports (for reporting bootstrap issues):
(define in-vars (if linklet
(skip-abi-imports (linklet-import-variables linklet))
null))
;; Extract phase-specific info on side effects:
(define side-effects? (and (not (hash-ref side-effect-free-modules name #f))
(member phase (hash-ref h 'side-effects '()))
#t))
;; Extract phase-specific mapping of the linklet arguments to modules
(define uses
(hash-ref (instance-variable-value (compiled-module-declaration comp-mod) 'phase-to-link-modules)
phase
null))
(define dependencies
(for*/list ([phase+reqs (in-list reqs)]
[req (in-list (cdr phase+reqs))])
;; we want whatever required module will have at this module's `phase`
(define at-phase (phase- phase (car phase+reqs)))
(link (module-path-index->module-name req name)
at-phase)))
Get linklets implied by the module 's ` require ` ( although some
;; of those may turn out to be dead code)
(for ([dependency (in-list dependencies)])
(get-linklets! dependency #f))
;; Imports are the subset of the transitive closure of `require`
;; that are used by this linklet's implementation
(define imports
(for/list ([mu (in-list uses)])
(link (module-path-index->module-name (module-use-module mu) name)
(module-use-phase mu))))
(when (and (pair? imports)
(not linklet))
(error "no implementation, but uses arguments?" name phase))
;; Re-exports are the subset of the transitive closure of
;; `require` that have variables that are re-exported from this
;; linklet; relevant only for the starting point
(define re-exports
(and first?
(set->list
(for*/set ([(sym binding/p) (in-hash (hash-ref provs phase #hasheq()))]
[(binding) (in-value (provided-as-binding binding/p))]
[l (in-value
(link (module-path-index->module-name (module-binding-module binding) name)
(module-binding-phase binding)))]
[re-li (in-value (hash-ref linklets l #f))]
#:when (and re-li
(set-member? (linklet-info-variables re-li) (module-binding-sym binding))))
l))))
(define li (linklet-info linklet imports re-exports vars in-vars side-effects?))
(hash-set! seen lnk li)
(when linklet
(hash-set! linklets lnk li)
(set-box! linklets-in-order (cons lnk (unbox linklets-in-order)))))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/expander/extract/get-linklet.rkt | racket | strip away submodule path
skip pre-defined modules
from the compiled module
Extract other metadata at the module level:
Extract phase-specific (i.e., linklet-specific) info on variables:
Extract phase-specific info on imports (for reporting bootstrap issues):
Extract phase-specific info on side effects:
Extract phase-specific mapping of the linklet arguments to modules
we want whatever required module will have at this module's `phase`
of those may turn out to be dead code)
Imports are the subset of the transitive closure of `require`
that are used by this linklet's implementation
Re-exports are the subset of the transitive closure of
`require` that have variables that are re-exported from this
linklet; relevant only for the starting point | #lang racket/base
(require "../common/set.rkt"
"../common/phase.rkt"
"../run/status.rkt"
"../host/linklet.rkt"
"../compile/module-use.rkt"
"../syntax/binding.rkt"
"../namespace/provided.rkt"
"link.rkt"
"linklet-info.rkt"
"linklet.rkt"
"module.rkt")
(provide get-linklets!)
(define (get-linklets! lnk
#:cache cache
#:compiled-modules compiled-modules
#:seen seen
#:linklets linklets
#:linklets-in-order linklets-in-order
#:side-effect-free-modules side-effect-free-modules)
(let get-linklets! ([lnk lnk] [first? #t])
(define name (link-name lnk))
(define phase (link-phase lnk))
(hash-ref seen lnk #f))
Seeing this module+phase combination for the first time
(log-status "Getting ~s at ~s" name phase)
(define comp-mod (get-compiled-module name root-name
#:compiled-modules compiled-modules
#:cache cache))
Extract the relevant ( i.e. , at a given phase )
(define h (compiled-module-phase-to-linklet comp-mod))
(define linklet
(hash-ref h phase #f))
(define reqs (instance-variable-value (compiled-module-declaration comp-mod) 'requires))
(define provs (instance-variable-value (compiled-module-declaration comp-mod) 'provides))
(define vars (if linklet
(list->set (linklet-export-variables linklet))
null))
(define in-vars (if linklet
(skip-abi-imports (linklet-import-variables linklet))
null))
(define side-effects? (and (not (hash-ref side-effect-free-modules name #f))
(member phase (hash-ref h 'side-effects '()))
#t))
(define uses
(hash-ref (instance-variable-value (compiled-module-declaration comp-mod) 'phase-to-link-modules)
phase
null))
(define dependencies
(for*/list ([phase+reqs (in-list reqs)]
[req (in-list (cdr phase+reqs))])
(define at-phase (phase- phase (car phase+reqs)))
(link (module-path-index->module-name req name)
at-phase)))
Get linklets implied by the module 's ` require ` ( although some
(for ([dependency (in-list dependencies)])
(get-linklets! dependency #f))
(define imports
(for/list ([mu (in-list uses)])
(link (module-path-index->module-name (module-use-module mu) name)
(module-use-phase mu))))
(when (and (pair? imports)
(not linklet))
(error "no implementation, but uses arguments?" name phase))
(define re-exports
(and first?
(set->list
(for*/set ([(sym binding/p) (in-hash (hash-ref provs phase #hasheq()))]
[(binding) (in-value (provided-as-binding binding/p))]
[l (in-value
(link (module-path-index->module-name (module-binding-module binding) name)
(module-binding-phase binding)))]
[re-li (in-value (hash-ref linklets l #f))]
#:when (and re-li
(set-member? (linklet-info-variables re-li) (module-binding-sym binding))))
l))))
(define li (linklet-info linklet imports re-exports vars in-vars side-effects?))
(hash-set! seen lnk li)
(when linklet
(hash-set! linklets lnk li)
(set-box! linklets-in-order (cons lnk (unbox linklets-in-order)))))))
|
adeb3e23d16680bc618b292b72c97084121df793000f35a4c43da923e639ca4f | marigold-dev/mankavar | a_test.expected.ml | module My_int_container :
sig
type nonrec ints
val of_ints : ints -> int list
val to_ints : int list -> ints
end =
struct type nonrec ints = int list
let of_ints x = x
let to_ints x = x end
| null | https://raw.githubusercontent.com/marigold-dev/mankavar/2a384efc359799b6cf37504fc6f2e6019a5feabc/vendors/ppx-abstract/test/positive/a_test.expected.ml | ocaml | module My_int_container :
sig
type nonrec ints
val of_ints : ints -> int list
val to_ints : int list -> ints
end =
struct type nonrec ints = int list
let of_ints x = x
let to_ints x = x end
|
|
2d80946d21defe97f9b58219fc42f249df316497f6b0773728c1016164df9e18 | janestreet/merlin-jst | pprintast.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, OCamlPro
(* Fabrice Le Fessant, INRIA Saclay *)
, University of Pennsylvania
(* *)
Copyright 2007 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. *)
(* *)
(**************************************************************************)
Original Code from Ber - metaocaml , modified for 3.12.0 and fixed
(* Printing code expressions *)
Authors : ,
Extensive Rewrite : : University of Pennsylvania
TODO more fine - grained precedence pretty - printing
open Asttypes
open Format
open Location
open Longident
open Parsetree
open Ast_helper
let prefix_symbols = [ '!'; '?'; '~' ] ;;
let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/';
'$'; '%'; '#' ]
(* type fixity = Infix| Prefix *)
let special_infix_strings =
["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "::" ]
let letop s =
String.length s > 3
&& s.[0] = 'l'
&& s.[1] = 'e'
&& s.[2] = 't'
&& List.mem s.[3] infix_symbols
let andop s =
String.length s > 3
&& s.[0] = 'a'
&& s.[1] = 'n'
&& s.[2] = 'd'
&& List.mem s.[3] infix_symbols
determines if the string is an infix string .
checks backwards , first allowing a renaming postfix ( " _ 102 " ) which
may have resulted from - > Texp - > translation , then checking
if all the characters in the beginning of the string are valid infix
characters .
checks backwards, first allowing a renaming postfix ("_102") which
may have resulted from Pexp -> Texp -> Pexp translation, then checking
if all the characters in the beginning of the string are valid infix
characters. *)
let fixity_of_string = function
| "" -> `Normal
| s when List.mem s special_infix_strings -> `Infix s
| s when List.mem s.[0] infix_symbols -> `Infix s
| s when List.mem s.[0] prefix_symbols -> `Prefix s
| s when s.[0] = '.' -> `Mixfix s
| s when letop s -> `Letop s
| s when andop s -> `Andop s
| _ -> `Normal
let view_fixity_of_exp = function
| {pexp_desc = Pexp_ident {txt=Lident l;_}; pexp_attributes = []} ->
fixity_of_string l
| _ -> `Normal
let is_infix = function `Infix _ -> true | _ -> false
let is_mixfix = function `Mixfix _ -> true | _ -> false
let is_kwdop = function `Letop _ | `Andop _ -> true | _ -> false
let first_is c str =
str <> "" && str.[0] = c
let last_is c str =
str <> "" && str.[String.length str - 1] = c
let first_is_in cs str =
str <> "" && List.mem str.[0] cs
(* which identifiers are in fact operators needing parentheses *)
let needs_parens txt =
let fix = fixity_of_string txt in
is_infix fix
|| is_mixfix fix
|| is_kwdop fix
|| first_is_in prefix_symbols txt
(* some infixes need spaces around parens to avoid clashes with comment
syntax *)
let needs_spaces txt =
first_is '*' txt || last_is '*' txt
let string_loc ppf x = fprintf ppf "%s" x.txt
(* add parentheses to binders when they are in fact infix or prefix operators *)
let protect_ident ppf txt =
let format : (_, _, _) format =
if not (needs_parens txt) then "%s"
else if needs_spaces txt then "(@;%s@;)"
else "(%s)"
in fprintf ppf format txt
let protect_longident ppf print_longident longprefix txt =
let format : (_, _, _) format =
if not (needs_parens txt) then "%a.%s"
else if needs_spaces txt then "%a.(@;%s@;)"
else "%a.(%s)" in
fprintf ppf format print_longident longprefix txt
type space_formatter = (unit, Format.formatter, unit) format
let override = function
| Override -> "!"
| Fresh -> ""
(* variance encoding: need to sync up with the [parser.mly] *)
let type_variance = function
| NoVariance -> ""
| Covariant -> "+"
| Contravariant -> "-"
let type_injectivity = function
| NoInjectivity -> ""
| Injective -> "!"
type construct =
[ `cons of expression list
| `list of expression list
| `nil
| `normal
| `simple of Longident.t
| `tuple ]
let view_expr x =
match x.pexp_desc with
| Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple
| Pexp_construct ( {txt= Lident "[]";_},_) -> `nil
| Pexp_construct ( {txt= Lident"::";_},Some _) ->
let rec loop exp acc = match exp with
| {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_);
pexp_attributes = []} ->
(List.rev acc,true)
| {pexp_desc=
Pexp_construct ({txt=Lident "::";_},
Some ({pexp_desc= Pexp_tuple([e1;e2]);
pexp_attributes = []}));
pexp_attributes = []}
->
loop e2 (e1::acc)
| e -> (List.rev (e::acc),false) in
let (ls,b) = loop x [] in
if b then
`list ls
else `cons ls
| Pexp_construct (x,None) -> `simple (x.txt)
| _ -> `normal
let is_simple_construct :construct -> bool = function
| `nil | `tuple | `list _ | `simple _ -> true
| `cons _ | `normal -> false
let pp = fprintf
type ctxt = {
pipe : bool;
semi : bool;
ifthenelse : bool;
}
let reset_ctxt = { pipe=false; semi=false; ifthenelse=false }
let under_pipe ctxt = { ctxt with pipe=true }
let under_semi ctxt = { ctxt with semi=true }
let under_ifthenelse ctxt = { ctxt with ifthenelse=true }
let reset_semi = with semi = false }
let reset_ifthenelse = with ifthenelse = false }
let = with pipe = false }
let reset_semi ctxt = { ctxt with semi=false }
let reset_ifthenelse ctxt = { ctxt with ifthenelse=false }
let reset_pipe ctxt = { ctxt with pipe=false }
*)
let list : 'a . ?sep:space_formatter -> ?first:space_formatter ->
?last:space_formatter -> (Format.formatter -> 'a -> unit) ->
Format.formatter -> 'a list -> unit
= fun ?sep ?first ?last fu f xs ->
let first = match first with Some x -> x |None -> ("": _ format6)
and last = match last with Some x -> x |None -> ("": _ format6)
and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in
let aux f = function
| [] -> ()
| [x] -> fu f x
| xs ->
let rec loop f = function
| [x] -> fu f x
| x::xs -> fu f x; pp f sep; loop f xs;
| _ -> assert false in begin
pp f first; loop f xs; pp f last;
end in
aux f xs
let option : 'a. ?first:space_formatter -> ?last:space_formatter ->
(Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit
= fun ?first ?last fu f a ->
let first = match first with Some x -> x | None -> ("": _ format6)
and last = match last with Some x -> x | None -> ("": _ format6) in
match a with
| None -> ()
| Some x -> pp f first; fu f x; pp f last
let paren: 'a . ?first:space_formatter -> ?last:space_formatter ->
bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit
= fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x ->
if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")")
else fu f x
let rec longident f = function
| Lident s -> protect_ident f s
| Ldot(y,s) -> protect_longident f longident y s
| Lapply (y,s) ->
pp f "%a(%a)" longident y longident s
let longident_loc f x = pp f "%a" longident x.txt
let constant f = function
| Pconst_char i ->
pp f "%C" i
| Pconst_string (i, _, None) ->
pp f "%S" i
| Pconst_string (i, _, Some delim) ->
pp f "{%s|%s|%s}" delim i delim
| Pconst_integer (i, None) ->
paren (first_is '-' i) (fun f -> pp f "%s") f i
| Pconst_integer (i, Some m) ->
paren (first_is '-' i) (fun f (i, m) -> pp f "%s%c" i m) f (i,m)
| Pconst_float (i, None) ->
paren (first_is '-' i) (fun f -> pp f "%s") f i
| Pconst_float (i, Some m) ->
paren (first_is '-' i) (fun f (i,m) -> pp f "%s%c" i m) f (i,m)
(* trailing space*)
let mutable_flag f = function
| Immutable -> ()
| Mutable -> pp f "mutable@;"
let virtual_flag f = function
| Concrete -> ()
| Virtual -> pp f "virtual@;"
(* trailing space added *)
let rec_flag f rf =
match rf with
| Nonrecursive -> ()
| Recursive -> pp f "rec "
let nonrec_flag f rf =
match rf with
| Nonrecursive -> pp f "nonrec "
| Recursive -> ()
let direction_flag f = function
| Upto -> pp f "to@ "
| Downto -> pp f "downto@ "
let private_flag f = function
| Public -> ()
| Private -> pp f "private@ "
let iter_loc f ctxt {txt; loc = _} = f ctxt txt
let constant_string f s = pp f "%S" s
let tyvar ppf s =
if String.length s >= 2 && s.[1] = '\'' then
(* without the space, this would be parsed as
a character literal *)
Format.fprintf ppf "' %s" s
else
Format.fprintf ppf "'%s" s
let tyvar_loc f str = tyvar f str.txt
let string_quot f x = pp f "`%s" x
(* c ['a,'b] *)
let rec class_params_def ctxt f = function
| [] -> ()
| l ->
pp f "[%a] " (* space *)
(list (type_param ctxt) ~sep:",") l
and type_with_label ctxt f (label, c) =
match label with
| Nolabel -> core_type1 ctxt f c (* otherwise parenthesize *)
| Labelled s -> pp f "%s:%a" s (core_type1 ctxt) c
| Optional s -> pp f "?%s:%a" s (core_type1 ctxt) c
and core_type ctxt f x =
if x.ptyp_attributes <> [] then begin
pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]}
(attributes ctxt) x.ptyp_attributes
end
else match x.ptyp_desc with
| Ptyp_arrow (l, ct1, ct2) ->
FIXME remove parens later
(type_with_label ctxt) (l,ct1) (core_type ctxt) ct2
| Ptyp_alias (ct, s) ->
pp f "@[<2>%a@;as@;%a@]" (core_type1 ctxt) ct tyvar s
| Ptyp_poly ([], ct) ->
core_type ctxt f ct
| Ptyp_poly (sl, ct) ->
pp f "@[<2>%a%a@]"
(fun f l ->
pp f "%a"
(fun f l -> match l with
| [] -> ()
| _ ->
pp f "%a@;.@;"
(list tyvar_loc ~sep:"@;") l)
l)
sl (core_type ctxt) ct
| _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x
and core_type1 ctxt f x =
if x.ptyp_attributes <> [] then core_type ctxt f x
else match x.ptyp_desc with
| Ptyp_any -> pp f "_";
| Ptyp_var s -> tyvar f s;
| Ptyp_tuple l -> pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l
| Ptyp_constr (li, l) ->
pp f (* "%a%a@;" *) "%a%a"
(fun f l -> match l with
|[] -> ()
|[x]-> pp f "%a@;" (core_type1 ctxt) x
| _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l)
l longident_loc li
| Ptyp_variant (l, closed, low) ->
let first_is_inherit = match l with
| {Parsetree.prf_desc = Rinherit _}::_ -> true
| _ -> false in
let type_variant_helper f x =
match x.prf_desc with
| Rtag (l, _, ctl) ->
pp f "@[<2>%a%a@;%a@]" (iter_loc string_quot) l
(fun f l -> match l with
|[] -> ()
| _ -> pp f "@;of@;%a"
(list (core_type ctxt) ~sep:"&") ctl) ctl
(attributes ctxt) x.prf_attributes
| Rinherit ct -> core_type ctxt f ct in
pp f "@[<2>[%a%a]@]"
(fun f l ->
match l, closed with
| [], Closed -> ()
| [], Open -> pp f ">" (* Cf #7200: print [>] correctly *)
| _ ->
pp f "%s@;%a"
(match (closed,low) with
| (Closed,None) -> if first_is_inherit then " |" else ""
| (Closed,Some _) -> "<" (* FIXME desugar the syntax sugar*)
| (Open,_) -> ">")
(list type_variant_helper ~sep:"@;<1 -2>| ") l) l
(fun f low -> match low with
|Some [] |None -> ()
|Some xs ->
pp f ">@ %a"
(list string_quot) xs) low
| Ptyp_object (l, o) ->
let core_field_type f x = match x.pof_desc with
| Otag (l, ct) ->
Cf # 7200
pp f "@[<hov2>%s: %a@ %a@ @]" l.txt
(core_type ctxt) ct (attributes ctxt) x.pof_attributes
| Oinherit ct ->
pp f "@[<hov2>%a@ @]" (core_type ctxt) ct
in
let field_var f = function
| Asttypes.Closed -> ()
| Asttypes.Open ->
match l with
| [] -> pp f ".."
| _ -> pp f " ;.."
in
pp f "@[<hov2><@ %a%a@ > @]"
(list core_field_type ~sep:";") l
Cf # 7200
FIXME
pp f "@[<hov2>%a#%a@]"
(list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l
longident_loc li
| Ptyp_package (lid, cstrs) ->
let aux f (s, ct) =
pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in
(match cstrs with
|[] -> pp f "@[<hov2>(module@ %a)@]" longident_loc lid
|_ ->
pp f "@[<hov2>(module@ %a@ with@ %a)@]" longident_loc lid
(list aux ~sep:"@ and@ ") cstrs)
| Ptyp_extension e -> extension ctxt f e
| _ -> paren true (core_type ctxt) f x
(********************pattern********************)
be cautious when use [ pattern ] , [ ] is preferred
and pattern ctxt f x =
if x.ppat_attributes <> [] then begin
pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]}
(attributes ctxt) x.ppat_attributes
end
else match x.ppat_desc with
| Ppat_alias (p, s) ->
pp f "@[<2>%a@;as@;%a@]" (pattern ctxt) p protect_ident s.txt
| _ -> pattern_or ctxt f x
and pattern_or ctxt f x =
let rec left_associative x acc = match x with
| {ppat_desc=Ppat_or (p1,p2); ppat_attributes = []} ->
left_associative p1 (p2 :: acc)
| x -> x :: acc
in
match left_associative x [] with
| [] -> assert false
| [x] -> pattern1 ctxt f x
| orpats ->
pp f "@[<hov0>%a@]" (list ~sep:"@ | " (pattern1 ctxt)) orpats
and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit =
let rec pattern_list_helper f = function
| {ppat_desc =
Ppat_construct
({ txt = Lident("::") ;_},
Some ([], {ppat_desc = Ppat_tuple([pat1; pat2]);_}));
ppat_attributes = []}
->
pp f "%a::%a" (simple_pattern ctxt) pat1 pattern_list_helper pat2 (*RA*)
| p -> pattern1 ctxt f p
in
if x.ppat_attributes <> [] then pattern ctxt f x
else match x.ppat_desc with
| Ppat_variant (l, Some p) ->
pp f "@[<2>`%s@;%a@]" l (simple_pattern ctxt) p
| Ppat_construct (({txt=Lident("()"|"[]");_}), _) ->
simple_pattern ctxt f x
| Ppat_construct (({txt;_} as li), po) ->
FIXME The third field always false
if txt = Lident "::" then
pp f "%a" pattern_list_helper x
else
(match po with
| Some ([], x) ->
pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x
| Some (vl, x) ->
pp f "%a@ (type %a)@;%a" longident_loc li
(list ~sep:"@ " string_loc) vl
(simple_pattern ctxt) x
| None -> pp f "%a" longident_loc li)
| _ -> simple_pattern ctxt f x
and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit =
if x.ppat_attributes <> [] then pattern ctxt f x
else match x.ppat_desc with
| Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), None) ->
pp f "%s" x
| Ppat_any -> pp f "_";
| Ppat_var ({txt = txt;_}) -> protect_ident f txt
| Ppat_array l ->
pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l
| Ppat_unpack { txt = None } ->
pp f "(module@ _)@ "
| Ppat_unpack { txt = Some s } ->
pp f "(module@ %s)@ " s
| Ppat_type li ->
pp f "#%a" longident_loc li
| Ppat_record (l, closed) ->
let longident_x_pattern f (li, p) =
match (li,p) with
| ({txt=Lident s;_ },
{ppat_desc=Ppat_var {txt;_};
ppat_attributes=[]; _})
when s = txt ->
pp f "@[<2>%a@]" longident_loc li
| _ ->
pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p
in
begin match closed with
| Closed ->
pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l
| _ ->
pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l
end
| Ppat_tuple l ->
| Ppat_constant (c) -> pp f "%a" constant c
| Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2
| Ppat_variant (l,None) -> pp f "`%s" l
| Ppat_constraint (p, ct) ->
pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct
| Ppat_lazy p ->
pp f "@[<2>(lazy@;%a)@]" (simple_pattern ctxt) p
| Ppat_exception p ->
pp f "@[<2>exception@;%a@]" (pattern1 ctxt) p
| Ppat_extension e -> extension ctxt f e
| Ppat_open (lid, p) ->
let with_paren =
match p.ppat_desc with
| Ppat_array _ | Ppat_record _
| Ppat_construct (({txt=Lident ("()"|"[]");_}), None) -> false
| _ -> true in
pp f "@[<2>%a.%a @]" longident_loc lid
(paren with_paren @@ pattern1 ctxt) p
| _ -> paren true (pattern ctxt) f x
and label_exp ctxt f (l,opt,p) =
match l with
| Nolabel ->
(* single case pattern parens needed here *)
pp f "%a@ " (simple_pattern ctxt) p
| Optional rest ->
begin match p with
| {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []}
when txt = rest ->
(match opt with
| Some o -> pp f "?(%s=@;%a)@;" rest (expression ctxt) o
| None -> pp f "?%s@ " rest)
| _ ->
(match opt with
| Some o ->
pp f "?%s:(%a=@;%a)@;"
rest (pattern1 ctxt) p (expression ctxt) o
| None -> pp f "?%s:%a@;" rest (simple_pattern ctxt) p)
end
| Labelled l -> match p with
| {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []}
when txt = l ->
pp f "~%s@;" l
| _ -> pp f "~%s:%a@;" l (simple_pattern ctxt) p
and sugar_expr ctxt f e =
if e.pexp_attributes <> [] then false
else match e.pexp_desc with
| Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _};
pexp_attributes=[]; _}, args)
when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin
let print_indexop a path_prefix assign left sep right print_index indices
rem_args =
let print_path ppf = function
| None -> ()
| Some m -> pp ppf ".%a" longident m in
match assign, rem_args with
| false, [] ->
pp f "@[%a%a%s%a%s@]"
(simple_expr ctxt) a print_path path_prefix
left (list ~sep print_index) indices right; true
| true, [v] ->
pp f "@[%a%a%s%a%s@ <-@;<1 2>%a@]"
(simple_expr ctxt) a print_path path_prefix
left (list ~sep print_index) indices right
(simple_expr ctxt) v; true
| _ -> false in
match id, List.map snd args with
| Lident "!", [e] ->
pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true
| Ldot (path, ("get"|"set" as func)), a :: other_args -> begin
let assign = func = "set" in
let print = print_indexop a None assign in
match path, other_args with
| Lident "Array", i :: rest ->
print ".(" "" ")" (expression ctxt) [i] rest
| Lident "String", i :: rest ->
print ".[" "" "]" (expression ctxt) [i] rest
| Ldot (Lident "Bigarray", "Array1"), i1 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1] rest
| Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1; i2] rest
| Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1; i2; i3] rest
| Ldot (Lident "Bigarray", "Genarray"),
{pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest ->
print ".{" "," "}" (simple_expr ctxt) indexes rest
| _ -> false
end
| (Lident s | Ldot(_,s)) , a :: i :: rest
when first_is '.' s ->
(* extract operator:
assignment operators end with [right_bracket ^ "<-"],
access operators end with [right_bracket] directly
*)
let multi_indices = String.contains s ';' in
let i =
match i.pexp_desc with
| Pexp_array l when multi_indices -> l
| _ -> [ i ] in
let assign = last_is '-' s in
let kind =
(* extract the right end bracket *)
let n = String.length s in
if assign then s.[n - 3] else s.[n - 1] in
let left, right = match kind with
| ')' -> '(', ")"
| ']' -> '[', "]"
| '}' -> '{', "}"
| _ -> assert false in
let path_prefix = match id with
| Ldot(m,_) -> Some m
| _ -> None in
let left = String.sub s 0 (1+String.index s left) in
print_indexop a path_prefix assign left ";" right
(if multi_indices then expression ctxt else simple_expr ctxt)
i rest
| _ -> false
end
| _ -> false
and expression ctxt f x =
if x.pexp_attributes <> [] then
pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]}
(attributes ctxt) x.pexp_attributes
else match x.pexp_desc with
| Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _
| Pexp_newtype _
when ctxt.pipe || ctxt.semi ->
paren true (expression reset_ctxt) f x
| Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse ->
paren true (expression reset_ctxt) f x
| Pexp_let _ | Pexp_letmodule _ | Pexp_open _
| Pexp_letexception _ | Pexp_letop _
when ctxt.semi ->
paren true (expression reset_ctxt) f x
| Pexp_fun (l, e0, p, e) ->
pp f "@[<2>fun@;%a->@;%a@]"
(label_exp ctxt) (l, e0, p)
(expression ctxt) e
| Pexp_newtype (lid, e) ->
pp f "@[<2>fun@;(type@;%s)@;->@;%a@]" lid.txt
(expression ctxt) e
| Pexp_function l ->
pp f "@[<hv>function%a@]" (case_list ctxt) l
| Pexp_match (e, l) ->
pp f "@[<hv0>@[<hv0>@[<2>match %a@]@ with@]%a@]"
(expression reset_ctxt) e (case_list ctxt) l
| Pexp_try (e, l) ->
pp f "@[<0>@[<hv2>try@ %a@]@ @[<0>with%a@]@]"
(* "try@;@[<2>%a@]@\nwith@\n%a"*)
(expression reset_ctxt) e (case_list ctxt) l
| Pexp_let (rf, l, e) ->
(* pp f "@[<2>let %a%a in@;<1 -2>%a@]"
(*no indentation here, a new line*) *)
rec_flag rf
pp f "@[<2>%a in@;<1 -2>%a@]"
(bindings reset_ctxt) (rf,l)
(expression ctxt) e
| Pexp_apply (e, l) ->
begin if not (sugar_expr ctxt f x) then
match view_fixity_of_exp e with
| `Infix s ->
begin match l with
| [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] ->
FIXME associativity label_x_expression_param
pp f "@[<2>%a@;%s@;%a@]"
(label_x_expression_param reset_ctxt) arg1 s
(label_x_expression_param ctxt) arg2
| _ ->
pp f "@[<2>%a %a@]"
(simple_expr ctxt) e
(list (label_x_expression_param ctxt)) l
end
| `Prefix s ->
let s =
if List.mem s ["~+";"~-";"~+.";"~-."] &&
(match l with
(* See #7200: avoid turning (~- 1) into (- 1) which is
parsed as an int literal *)
|[(_,{pexp_desc=Pexp_constant _})] -> false
| _ -> true)
then String.sub s 1 (String.length s -1)
else s in
begin match l with
| [(Nolabel, x)] ->
pp f "@[<2>%s@;%a@]" s (simple_expr ctxt) x
| _ ->
pp f "@[<2>%a %a@]" (simple_expr ctxt) e
(list (label_x_expression_param ctxt)) l
end
| _ ->
pp f "@[<hov2>%a@]" begin fun f (e,l) ->
pp f "%a@ %a" (expression2 ctxt) e
(list (label_x_expression_param reset_ctxt)) l
(* reset here only because [function,match,try,sequence]
are lower priority *)
end (e,l)
end
| Pexp_construct (li, Some eo)
when not (is_simple_construct (view_expr x))-> (* Not efficient FIXME*)
(match view_expr x with
| `cons ls -> list (simple_expr ctxt) f ls ~sep:"@;::@;"
| `normal ->
pp f "@[<2>%a@;%a@]" longident_loc li
(simple_expr ctxt) eo
| _ -> assert false)
| Pexp_setfield (e1, li, e2) ->
pp f "@[<2>%a.%a@ <-@ %a@]"
(simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2
| Pexp_ifthenelse (e1, e2, eo) ->
(* @;@[<2>else@ %a@]@] *)
let fmt:(_,_,_)format ="@[<hv0>@[<2>if@ %a@]@;@[<2>then@ %a@]%a@]" in
let expression_under_ifthenelse = expression (under_ifthenelse ctxt) in
pp f fmt expression_under_ifthenelse e1 expression_under_ifthenelse e2
(fun f eo -> match eo with
| Some x ->
pp f "@;@[<2>else@;%a@]" (expression (under_semi ctxt)) x
| None -> () (* pp f "()" *)) eo
| Pexp_sequence _ ->
let rec sequence_helper acc = function
| {pexp_desc=Pexp_sequence(e1,e2); pexp_attributes = []} ->
sequence_helper (e1::acc) e2
| v -> List.rev (v::acc) in
let lst = sequence_helper [] x in
pp f "@[<hv>%a@]"
(list (expression (under_semi ctxt)) ~sep:";@;") lst
| Pexp_new (li) ->
pp f "@[<hov2>new@ %a@]" longident_loc li;
| Pexp_setinstvar (s, e) ->
pp f "@[<hov2>%s@ <-@ %a@]" s.txt (expression ctxt) e
FIXME
let string_x_expression f (s, e) =
pp f "@[<hov2>%s@ =@ %a@]" s.txt (expression ctxt) e in
pp f "@[<hov2>{<%a>}@]"
(list string_x_expression ~sep:";" ) l;
| Pexp_letmodule (s, me, e) ->
pp f "@[<hov2>let@ module@ %s@ =@ %a@ in@ %a@]"
(Option.value s.txt ~default:"_")
(module_expr reset_ctxt) me (expression ctxt) e
| Pexp_letexception (cd, e) ->
pp f "@[<hov2>let@ exception@ %a@ in@ %a@]"
(extension_constructor ctxt) cd
(expression ctxt) e
| Pexp_assert e ->
pp f "@[<hov2>assert@ %a@]" (simple_expr ctxt) e
| Pexp_lazy (e) ->
pp f "@[<hov2>lazy@ %a@]" (simple_expr ctxt) e
(* Pexp_poly: impossible but we should print it anyway, rather than
assert false *)
| Pexp_poly (e, None) ->
pp f "@[<hov2>!poly!@ %a@]" (simple_expr ctxt) e
| Pexp_poly (e, Some ct) ->
pp f "@[<hov2>(!poly!@ %a@ : %a)@]"
(simple_expr ctxt) e (core_type ctxt) ct
| Pexp_open (o, e) ->
pp f "@[<2>let open%s %a in@;%a@]"
(override o.popen_override) (module_expr ctxt) o.popen_expr
(expression ctxt) e
| Pexp_variant (l,Some eo) ->
pp f "@[<2>`%s@;%a@]" l (simple_expr ctxt) eo
| Pexp_letop {let_; ands; body} ->
pp f "@[<2>@[<v>%a@,%a@] in@;<1 -2>%a@]"
(binding_op ctxt) let_
(list ~sep:"@," (binding_op ctxt)) ands
(expression ctxt) body
| Pexp_extension e -> extension ctxt f e
| Pexp_unreachable -> pp f "."
| _ -> expression1 ctxt f x
and expression1 ctxt f x =
if x.pexp_attributes <> [] then expression ctxt f x
else match x.pexp_desc with
| Pexp_object cs -> pp f "%a" (class_structure ctxt) cs
| _ -> expression2 ctxt f x
(* used in [Pexp_apply] *)
and expression2 ctxt f x =
if x.pexp_attributes <> [] then expression ctxt f x
else match x.pexp_desc with
| Pexp_field (e, li) ->
pp f "@[<hov2>%a.%a@]" (simple_expr ctxt) e longident_loc li
| Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" (simple_expr ctxt) e s.txt
| _ -> simple_expr ctxt f x
and simple_expr ctxt f x =
if x.pexp_attributes <> [] then expression ctxt f x
else match x.pexp_desc with
| Pexp_construct _ when is_simple_construct (view_expr x) ->
(match view_expr x with
| `nil -> pp f "[]"
| `tuple -> pp f "()"
| `list xs ->
pp f "@[<hv0>[%a]@]"
(list (expression (under_semi ctxt)) ~sep:";@;") xs
| `simple x -> longident f x
| _ -> assert false)
| Pexp_ident li ->
longident_loc f li
(* (match view_fixity_of_exp x with *)
(* |`Normal -> longident_loc f li *)
(* | `Prefix _ | `Infix _ -> pp f "( %a )" longident_loc li) *)
| Pexp_constant c -> constant f c;
| Pexp_pack me ->
pp f "(module@;%a)" (module_expr ctxt) me
| Pexp_tuple l ->
pp f "@[<hov2>(%a)@]" (list (simple_expr ctxt) ~sep:",@;") l
| Pexp_constraint (e, ct) ->
pp f "(%a : %a)" (expression ctxt) e (core_type ctxt) ct
| Pexp_coerce (e, cto1, ct) ->
pp f "(%a%a :> %a)" (expression ctxt) e
(option (core_type ctxt) ~first:" : " ~last:" ") cto1 (* no sep hint*)
(core_type ctxt) ct
| Pexp_variant (l, None) -> pp f "`%s" l
| Pexp_record (l, eo) ->
let longident_x_expression f ( li, e) =
match e with
| {pexp_desc=Pexp_ident {txt;_};
pexp_attributes=[]; _} when li.txt = txt ->
pp f "@[<hov2>%a@]" longident_loc li
| _ ->
pp f "@[<hov2>%a@;=@;%a@]" longident_loc li (simple_expr ctxt) e
in
pp f "@[<hv0>@[<hv2>{@;%a%a@]@;}@]"(* "@[<hov2>{%a%a}@]" *)
(option ~last:" with@;" (simple_expr ctxt)) eo
(list longident_x_expression ~sep:";@;") l
| Pexp_array (l) ->
pp f "@[<0>@[<2>[|%a|]@]@]"
(list (simple_expr (under_semi ctxt)) ~sep:";") l
| Pexp_while (e1, e2) ->
let fmt : (_,_,_) format = "@[<2>while@;%a@;do@;%a@;done@]" in
pp f fmt (expression ctxt) e1 (expression ctxt) e2
| Pexp_for (s, e1, e2, df, e3) ->
let fmt:(_,_,_)format =
"@[<hv0>@[<hv2>@[<2>for %a =@;%a@;%a%a@;do@]@;%a@]@;done@]" in
let expression = expression ctxt in
pp f fmt (pattern ctxt) s expression e1 direction_flag
df expression e2 expression e3
| _ -> paren true (expression ctxt) f x
and attributes ctxt f l =
List.iter (attribute ctxt f) l
and item_attributes ctxt f l =
List.iter (item_attribute ctxt f) l
and attribute ctxt f a =
pp f "@[<2>[@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload
and item_attribute ctxt f a =
pp f "@[<2>[@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload
and floating_attribute ctxt f a =
pp f "@[<2>[@@@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload
and value_description ctxt f x =
(* note: value_description has an attribute field,
but they're already printed by the callers this method *)
pp f "@[<hov2>%a%a@]" (core_type ctxt) x.pval_type
(fun f x ->
if x.pval_prim <> []
then pp f "@ =@ %a" (list constant_string) x.pval_prim
) x
and extension ctxt f (s, e) =
pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e
and item_extension ctxt f (s, e) =
pp f "@[<2>[%%%%%s@ %a]@]" s.txt (payload ctxt) e
and exception_declaration ctxt f x =
pp f "@[<hov2>exception@ %a@]%a"
(extension_constructor ctxt) x.ptyexn_constructor
(item_attributes ctxt) x.ptyexn_attributes
and class_type_field ctxt f x =
match x.pctf_desc with
| Pctf_inherit (ct) ->
pp f "@[<2>inherit@ %a@]%a" (class_type ctxt) ct
(item_attributes ctxt) x.pctf_attributes
| Pctf_val (s, mf, vf, ct) ->
pp f "@[<2>val @ %a%a%s@ :@ %a@]%a"
mutable_flag mf virtual_flag vf s.txt (core_type ctxt) ct
(item_attributes ctxt) x.pctf_attributes
| Pctf_method (s, pf, vf, ct) ->
pp f "@[<2>method %a %a%s :@;%a@]%a"
private_flag pf virtual_flag vf s.txt (core_type ctxt) ct
(item_attributes ctxt) x.pctf_attributes
| Pctf_constraint (ct1, ct2) ->
pp f "@[<2>constraint@ %a@ =@ %a@]%a"
(core_type ctxt) ct1 (core_type ctxt) ct2
(item_attributes ctxt) x.pctf_attributes
| Pctf_attribute a -> floating_attribute ctxt f a
| Pctf_extension e ->
item_extension ctxt f e;
item_attributes ctxt f x.pctf_attributes
and class_signature ctxt f { pcsig_self = ct; pcsig_fields = l ;_} =
pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]"
(fun f -> function
{ptyp_desc=Ptyp_any; ptyp_attributes=[]; _} -> ()
| ct -> pp f " (%a)" (core_type ctxt) ct) ct
(list (class_type_field ctxt) ~sep:"@;") l
(* call [class_signature] called by [class_signature] *)
and class_type ctxt f x =
match x.pcty_desc with
| Pcty_signature cs ->
class_signature ctxt f cs;
attributes ctxt f x.pcty_attributes
| Pcty_constr (li, l) ->
pp f "%a%a%a"
(fun f l -> match l with
| [] -> ()
| _ -> pp f "[%a]@ " (list (core_type ctxt) ~sep:"," ) l) l
longident_loc li
(attributes ctxt) x.pcty_attributes
| Pcty_arrow (l, co, cl) ->
FIXME remove parens later
(type_with_label ctxt) (l,co)
(class_type ctxt) cl
| Pcty_extension e ->
extension ctxt f e;
attributes ctxt f x.pcty_attributes
| Pcty_open (o, e) ->
pp f "@[<2>let open%s %a in@;%a@]"
(override o.popen_override) longident_loc o.popen_expr
(class_type ctxt) e
(* [class type a = object end] *)
and class_type_declaration_list ctxt f l =
let class_type_declaration kwd f x =
let { pci_params=ls; pci_name={ txt; _ }; _ } = x in
pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd
virtual_flag x.pci_virt
(class_params_def ctxt) ls txt
(class_type ctxt) x.pci_expr
(item_attributes ctxt) x.pci_attributes
in
match l with
| [] -> ()
| [x] -> class_type_declaration "class type" f x
| x :: xs ->
pp f "@[<v>%a@,%a@]"
(class_type_declaration "class type") x
(list ~sep:"@," (class_type_declaration "and")) xs
and class_field ctxt f x =
match x.pcf_desc with
| Pcf_inherit (ovf, ce, so) ->
pp f "@[<2>inherit@ %s@ %a%a@]%a" (override ovf)
(class_expr ctxt) ce
(fun f so -> match so with
| None -> ();
| Some (s) -> pp f "@ as %s" s.txt ) so
(item_attributes ctxt) x.pcf_attributes
| Pcf_val (s, mf, Cfk_concrete (ovf, e)) ->
pp f "@[<2>val%s %a%s =@;%a@]%a" (override ovf)
mutable_flag mf s.txt
(expression ctxt) e
(item_attributes ctxt) x.pcf_attributes
| Pcf_method (s, pf, Cfk_virtual ct) ->
pp f "@[<2>method virtual %a %s :@;%a@]%a"
private_flag pf s.txt
(core_type ctxt) ct
(item_attributes ctxt) x.pcf_attributes
| Pcf_val (s, mf, Cfk_virtual ct) ->
pp f "@[<2>val virtual %a%s :@ %a@]%a"
mutable_flag mf s.txt
(core_type ctxt) ct
(item_attributes ctxt) x.pcf_attributes
| Pcf_method (s, pf, Cfk_concrete (ovf, e)) ->
let bind e =
binding ctxt f
{pvb_pat=
{ppat_desc=Ppat_var s;
ppat_loc=Location.none;
ppat_loc_stack=[];
ppat_attributes=[]};
pvb_expr=e;
pvb_attributes=[];
pvb_loc=Location.none;
}
in
pp f "@[<2>method%s %a%a@]%a"
(override ovf)
private_flag pf
(fun f -> function
| {pexp_desc=Pexp_poly (e, Some ct); pexp_attributes=[]; _} ->
pp f "%s :@;%a=@;%a"
s.txt (core_type ctxt) ct (expression ctxt) e
| {pexp_desc=Pexp_poly (e, None); pexp_attributes=[]; _} ->
bind e
| _ -> bind e) e
(item_attributes ctxt) x.pcf_attributes
| Pcf_constraint (ct1, ct2) ->
pp f "@[<2>constraint %a =@;%a@]%a"
(core_type ctxt) ct1
(core_type ctxt) ct2
(item_attributes ctxt) x.pcf_attributes
| Pcf_initializer (e) ->
pp f "@[<2>initializer@ %a@]%a"
(expression ctxt) e
(item_attributes ctxt) x.pcf_attributes
| Pcf_attribute a -> floating_attribute ctxt f a
| Pcf_extension e ->
item_extension ctxt f e;
item_attributes ctxt f x.pcf_attributes
and class_structure ctxt f { pcstr_self = p; pcstr_fields = l } =
pp f "@[<hv0>@[<hv2>object%a@;%a@]@;end@]"
(fun f p -> match p.ppat_desc with
| Ppat_any -> ()
| Ppat_constraint _ -> pp f " %a" (pattern ctxt) p
| _ -> pp f " (%a)" (pattern ctxt) p) p
(list (class_field ctxt)) l
and class_expr ctxt f x =
if x.pcl_attributes <> [] then begin
pp f "((%a)%a)" (class_expr ctxt) {x with pcl_attributes=[]}
(attributes ctxt) x.pcl_attributes
end else
match x.pcl_desc with
| Pcl_structure (cs) -> class_structure ctxt f cs
| Pcl_fun (l, eo, p, e) ->
pp f "fun@ %a@ ->@ %a"
(label_exp ctxt) (l,eo,p)
(class_expr ctxt) e
| Pcl_let (rf, l, ce) ->
pp f "%a@ in@ %a"
(bindings ctxt) (rf,l)
(class_expr ctxt) ce
| Pcl_apply (ce, l) ->
Cf : # 7200
(class_expr ctxt) ce
(list (label_x_expression_param ctxt)) l
| Pcl_constr (li, l) ->
pp f "%a%a"
(fun f l-> if l <>[] then
pp f "[%a]@ "
(list (core_type ctxt) ~sep:",") l) l
longident_loc li
| Pcl_constraint (ce, ct) ->
pp f "(%a@ :@ %a)"
(class_expr ctxt) ce
(class_type ctxt) ct
| Pcl_extension e -> extension ctxt f e
| Pcl_open (o, e) ->
pp f "@[<2>let open%s %a in@;%a@]"
(override o.popen_override) longident_loc o.popen_expr
(class_expr ctxt) e
and module_type ctxt f x =
if x.pmty_attributes <> [] then begin
pp f "((%a)%a)" (module_type ctxt) {x with pmty_attributes=[]}
(attributes ctxt) x.pmty_attributes
end else
match x.pmty_desc with
| Pmty_functor (Unit, mt2) ->
pp f "@[<hov2>functor () ->@ %a@]" (module_type ctxt) mt2
| Pmty_functor (Named (s, mt1), mt2) ->
begin match s.txt with
| None ->
pp f "@[<hov2>%a@ ->@ %a@]"
(module_type1 ctxt) mt1 (module_type ctxt) mt2
| Some name ->
pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" name
(module_type ctxt) mt1 (module_type ctxt) mt2
end
| Pmty_with (mt, []) -> module_type ctxt f mt
| Pmty_with (mt, l) ->
pp f "@[<hov2>%a@ with@ %a@]"
(module_type1 ctxt) mt
(list (with_constraint ctxt) ~sep:"@ and@ ") l
| _ -> module_type1 ctxt f x
and with_constraint ctxt f = function
| Pwith_type (li, ({ptype_params= ls ;_} as td)) ->
let ls = List.map fst ls in
pp f "type@ %a %a =@ %a"
(list (core_type ctxt) ~sep:"," ~first:"(" ~last:")")
ls longident_loc li (type_declaration ctxt) td
| Pwith_module (li, li2) ->
pp f "module %a =@ %a" longident_loc li longident_loc li2;
| Pwith_modtype (li, mty) ->
pp f "module type %a =@ %a" longident_loc li (module_type ctxt) mty;
| Pwith_typesubst (li, ({ptype_params=ls;_} as td)) ->
let ls = List.map fst ls in
pp f "type@ %a %a :=@ %a"
(list (core_type ctxt) ~sep:"," ~first:"(" ~last:")")
ls longident_loc li
(type_declaration ctxt) td
| Pwith_modsubst (li, li2) ->
pp f "module %a :=@ %a" longident_loc li longident_loc li2
| Pwith_modtypesubst (li, mty) ->
pp f "module type %a :=@ %a" longident_loc li (module_type ctxt) mty;
and module_type1 ctxt f x =
if x.pmty_attributes <> [] then module_type ctxt f x
else match x.pmty_desc with
| Pmty_ident li ->
pp f "%a" longident_loc li;
| Pmty_alias li ->
pp f "(module %a)" longident_loc li;
| Pmty_signature (s) ->
pp f "@[<hv0>@[<hv2>sig@ %a@]@ end@]" (* "@[<hov>sig@ %a@ end@]" *)
(list (signature_item ctxt)) s (* FIXME wrong indentation*)
| Pmty_typeof me ->
pp f "@[<hov2>module@ type@ of@ %a@]" (module_expr ctxt) me
| Pmty_extension e -> extension ctxt f e
| _ -> paren true (module_type ctxt) f x
and signature ctxt f x = list ~sep:"@\n" (signature_item ctxt) f x
and signature_item ctxt f x : unit =
match x.psig_desc with
| Psig_type (rf, l) ->
type_def_list ctxt f (rf, true, l)
| Psig_typesubst l ->
(* Psig_typesubst is never recursive, but we specify [Recursive] here to
avoid printing a [nonrec] flag, which would be rejected by the parser.
*)
type_def_list ctxt f (Recursive, false, l)
| Psig_value vd ->
let intro = if vd.pval_prim = [] then "val" else "external" in
pp f "@[<2>%s@ %a@ :@ %a@]%a" intro
protect_ident vd.pval_name.txt
(value_description ctxt) vd
(item_attributes ctxt) vd.pval_attributes
| Psig_typext te ->
type_extension ctxt f te
| Psig_exception ed ->
exception_declaration ctxt f ed
| Psig_class l ->
let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) =
pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd
virtual_flag x.pci_virt
(class_params_def ctxt) ls txt
(class_type ctxt) x.pci_expr
(item_attributes ctxt) x.pci_attributes
in begin
match l with
| [] -> ()
| [x] -> class_description "class" f x
| x :: xs ->
pp f "@[<v>%a@,%a@]"
(class_description "class") x
(list ~sep:"@," (class_description "and")) xs
end
| Psig_module ({pmd_type={pmty_desc=Pmty_alias alias;
pmty_attributes=[]; _};_} as pmd) ->
pp f "@[<hov>module@ %s@ =@ %a@]%a"
(Option.value pmd.pmd_name.txt ~default:"_")
longident_loc alias
(item_attributes ctxt) pmd.pmd_attributes
| Psig_module pmd ->
pp f "@[<hov>module@ %s@ :@ %a@]%a"
(Option.value pmd.pmd_name.txt ~default:"_")
(module_type ctxt) pmd.pmd_type
(item_attributes ctxt) pmd.pmd_attributes
| Psig_modsubst pms ->
pp f "@[<hov>module@ %s@ :=@ %a@]%a" pms.pms_name.txt
longident_loc pms.pms_manifest
(item_attributes ctxt) pms.pms_attributes
| Psig_open od ->
pp f "@[<hov2>open%s@ %a@]%a"
(override od.popen_override)
longident_loc od.popen_expr
(item_attributes ctxt) od.popen_attributes
| Psig_include incl ->
pp f "@[<hov2>include@ %a@]%a"
(module_type ctxt) incl.pincl_mod
(item_attributes ctxt) incl.pincl_attributes
| Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} ->
pp f "@[<hov2>module@ type@ %s%a@]%a"
s.txt
(fun f md -> match md with
| None -> ()
| Some mt ->
pp_print_space f () ;
pp f "@ =@ %a" (module_type ctxt) mt
) md
(item_attributes ctxt) attrs
| Psig_modtypesubst {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} ->
let md = match md with
| None -> assert false (* ast invariant *)
| Some mt -> mt in
pp f "@[<hov2>module@ type@ %s@ :=@ %a@]%a"
s.txt (module_type ctxt) md
(item_attributes ctxt) attrs
| Psig_class_type (l) -> class_type_declaration_list ctxt f l
| Psig_recmodule decls ->
let rec string_x_module_type_list f ?(first=true) l =
match l with
| [] -> () ;
| pmd :: tl ->
if not first then
pp f "@ @[<hov2>and@ %s:@ %a@]%a"
(Option.value pmd.pmd_name.txt ~default:"_")
(module_type1 ctxt) pmd.pmd_type
(item_attributes ctxt) pmd.pmd_attributes
else
pp f "@[<hov2>module@ rec@ %s:@ %a@]%a"
(Option.value pmd.pmd_name.txt ~default:"_")
(module_type1 ctxt) pmd.pmd_type
(item_attributes ctxt) pmd.pmd_attributes;
string_x_module_type_list f ~first:false tl
in
string_x_module_type_list f decls
| Psig_attribute a -> floating_attribute ctxt f a
| Psig_extension(e, a) ->
item_extension ctxt f e;
item_attributes ctxt f a
and module_expr ctxt f x =
if x.pmod_attributes <> [] then
pp f "((%a)%a)" (module_expr ctxt) {x with pmod_attributes=[]}
(attributes ctxt) x.pmod_attributes
else match x.pmod_desc with
| Pmod_structure (s) ->
pp f "@[<hv2>struct@;@[<0>%a@]@;<1 -2>end@]"
(list (structure_item ctxt) ~sep:"@\n") s;
| Pmod_constraint (me, mt) ->
pp f "@[<hov2>(%a@ :@ %a)@]"
(module_expr ctxt) me
(module_type ctxt) mt
| Pmod_ident (li) ->
pp f "%a" longident_loc li;
| Pmod_functor (Unit, me) ->
pp f "functor ()@;->@;%a" (module_expr ctxt) me
| Pmod_functor (Named (s, mt), me) ->
pp f "functor@ (%s@ :@ %a)@;->@;%a"
(Option.value s.txt ~default:"_")
(module_type ctxt) mt (module_expr ctxt) me
| Pmod_apply (me1, me2) ->
pp f "(%a)(%a)" (module_expr ctxt) me1 (module_expr ctxt) me2
Cf : # 7200
| Pmod_unpack e ->
pp f "(val@ %a)" (expression ctxt) e
| Pmod_extension e -> extension ctxt f e
and structure ctxt f x = list ~sep:"@\n" (structure_item ctxt) f x
and payload ctxt f = function
| PStr [{pstr_desc = Pstr_eval (e, attrs)}] ->
pp f "@[<2>%a@]%a"
(expression ctxt) e
(item_attributes ctxt) attrs
| PStr x -> structure ctxt f x
| PTyp x -> pp f ":@ "; core_type ctxt f x
| PSig x -> pp f ":@ "; signature ctxt f x
| PPat (x, None) -> pp f "?@ "; pattern ctxt f x
| PPat (x, Some e) ->
pp f "?@ "; pattern ctxt f x;
pp f " when "; expression ctxt f e
(* transform [f = fun g h -> ..] to [f g h = ... ] could be improved *)
and binding ctxt f {pvb_pat=p; pvb_expr=x; _} =
(* .pvb_attributes have already been printed by the caller, #bindings *)
let rec pp_print_pexp_function f x =
if x.pexp_attributes <> [] then pp f "=@;%a" (expression ctxt) x
else match x.pexp_desc with
| Pexp_fun (label, eo, p, e) ->
if label=Nolabel then
pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function e
else
pp f "%a@ %a"
(label_exp ctxt) (label,eo,p) pp_print_pexp_function e
| Pexp_newtype (str,e) ->
pp f "(type@ %s)@ %a" str.txt pp_print_pexp_function e
| _ -> pp f "=@;%a" (expression ctxt) x
in
let tyvars_str tyvars = List.map (fun v -> v.txt) tyvars in
let is_desugared_gadt p e =
let gadt_pattern =
match p with
| {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _} as pat,
{ptyp_desc=Ptyp_poly (args_tyvars, rt)});
ppat_attributes=[]}->
Some (pat, args_tyvars, rt)
| _ -> None in
let rec gadt_exp tyvars e =
match e with
| {pexp_desc=Pexp_newtype (tyvar, e); pexp_attributes=[]} ->
gadt_exp (tyvar :: tyvars) e
| {pexp_desc=Pexp_constraint (e, ct); pexp_attributes=[]} ->
Some (List.rev tyvars, e, ct)
| _ -> None in
let gadt_exp = gadt_exp [] e in
match gadt_pattern, gadt_exp with
| Some (p, pt_tyvars, pt_ct), Some (e_tyvars, e, e_ct)
when tyvars_str pt_tyvars = tyvars_str e_tyvars ->
let ety = Typ.varify_constructors e_tyvars e_ct in
if ety = pt_ct then
Some (p, pt_tyvars, e_ct, e) else None
| _ -> None in
if x.pexp_attributes <> []
then
match p with
| {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _; _} as pat,
({ptyp_desc=Ptyp_poly _; _} as typ));
ppat_attributes=[]; _} ->
pp f "%a@;: %a@;=@;%a"
(simple_pattern ctxt) pat (core_type ctxt) typ (expression ctxt) x
| _ ->
pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x
else
match is_desugared_gadt p x with
| Some (p, [], ct, e) ->
pp f "%a@;: %a@;=@;%a"
(simple_pattern ctxt) p (core_type ctxt) ct (expression ctxt) e
| Some (p, tyvars, ct, e) -> begin
pp f "%a@;: type@;%a.@;%a@;=@;%a"
(simple_pattern ctxt) p (list pp_print_string ~sep:"@;")
(tyvars_str tyvars) (core_type ctxt) ct (expression ctxt) e
end
| None -> begin
match p with
| {ppat_desc=Ppat_constraint(p ,ty);
special case for the first
begin match ty with
| {ptyp_desc=Ptyp_poly _; ptyp_attributes=[]} ->
pp f "%a@;:@;%a@;=@;%a" (simple_pattern ctxt) p
(core_type ctxt) ty (expression ctxt) x
| _ ->
pp f "(%a@;:@;%a)@;=@;%a" (simple_pattern ctxt) p
(core_type ctxt) ty (expression ctxt) x
end
| {ppat_desc=Ppat_var _; ppat_attributes=[]} ->
pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x
| _ ->
pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x
end
(* [in] is not printed *)
and bindings ctxt f (rf,l) =
let binding kwd rf f x =
pp f "@[<2>%s %a%a@]%a" kwd rec_flag rf
(binding ctxt) x (item_attributes ctxt) x.pvb_attributes
in
match l with
| [] -> ()
| [x] -> binding "let" rf f x
| x::xs ->
pp f "@[<v>%a@,%a@]"
(binding "let" rf) x
(list ~sep:"@," (binding "and" Nonrecursive)) xs
and binding_op ctxt f x =
match x.pbop_pat, x.pbop_exp with
| {ppat_desc = Ppat_var { txt=pvar; _ }; ppat_attributes = []; _},
{pexp_desc = Pexp_ident { txt=Lident evar; _}; pexp_attributes = []; _}
when pvar = evar ->
pp f "@[<2>%s %s@]" x.pbop_op.txt evar
| pat, exp ->
pp f "@[<2>%s %a@;=@;%a@]"
x.pbop_op.txt (pattern ctxt) pat (expression ctxt) exp
and structure_item ctxt f x =
match x.pstr_desc with
| Pstr_eval (e, attrs) ->
pp f "@[<hov2>;;%a@]%a"
(expression ctxt) e
(item_attributes ctxt) attrs
| Pstr_type (_, []) -> assert false
| Pstr_type (rf, l) -> type_def_list ctxt f (rf, true, l)
| Pstr_value (rf, l) ->
pp f " @[<hov2 > let % a%a@ ] " rec_flag rf bindings l
pp f "@[<2>%a@]" (bindings ctxt) (rf,l)
| Pstr_typext te -> type_extension ctxt f te
| Pstr_exception ed -> exception_declaration ctxt f ed
| Pstr_module x ->
let rec module_helper = function
| {pmod_desc=Pmod_functor(arg_opt,me'); pmod_attributes = []} ->
begin match arg_opt with
| Unit -> pp f "()"
| Named (s, mt) ->
pp f "(%s:%a)" (Option.value s.txt ~default:"_")
(module_type ctxt) mt
end;
module_helper me'
| me -> me
in
pp f "@[<hov2>module %s%a@]%a"
(Option.value x.pmb_name.txt ~default:"_")
(fun f me ->
let me = module_helper me in
match me with
| {pmod_desc=
Pmod_constraint
(me',
({pmty_desc=(Pmty_ident (_)
| Pmty_signature (_));_} as mt));
pmod_attributes = []} ->
pp f " :@;%a@;=@;%a@;"
(module_type ctxt) mt (module_expr ctxt) me'
| _ -> pp f " =@ %a" (module_expr ctxt) me
) x.pmb_expr
(item_attributes ctxt) x.pmb_attributes
| Pstr_open od ->
pp f "@[<2>open%s@;%a@]%a"
(override od.popen_override)
(module_expr ctxt) od.popen_expr
(item_attributes ctxt) od.popen_attributes
| Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} ->
pp f "@[<hov2>module@ type@ %s%a@]%a"
s.txt
(fun f md -> match md with
| None -> ()
| Some mt ->
pp_print_space f () ;
pp f "@ =@ %a" (module_type ctxt) mt
) md
(item_attributes ctxt) attrs
| Pstr_class l ->
let extract_class_args cl =
let rec loop acc = function
| {pcl_desc=Pcl_fun (l, eo, p, cl'); pcl_attributes = []} ->
loop ((l,eo,p) :: acc) cl'
| cl -> List.rev acc, cl
in
let args, cl = loop [] cl in
let constr, cl =
match cl with
| {pcl_desc=Pcl_constraint (cl', ct); pcl_attributes = []} ->
Some ct, cl'
| _ -> None, cl
in
args, constr, cl
in
let class_constraint f ct = pp f ": @[%a@] " (class_type ctxt) ct in
let class_declaration kwd f
({pci_params=ls; pci_name={txt;_}; _} as x) =
let args, constr, cl = extract_class_args x.pci_expr in
pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd
virtual_flag x.pci_virt
(class_params_def ctxt) ls txt
(list (label_exp ctxt)) args
(option class_constraint) constr
(class_expr ctxt) cl
(item_attributes ctxt) x.pci_attributes
in begin
match l with
| [] -> ()
| [x] -> class_declaration "class" f x
| x :: xs ->
pp f "@[<v>%a@,%a@]"
(class_declaration "class") x
(list ~sep:"@," (class_declaration "and")) xs
end
| Pstr_class_type l -> class_type_declaration_list ctxt f l
| Pstr_primitive vd ->
pp f "@[<hov2>external@ %a@ :@ %a@]%a"
protect_ident vd.pval_name.txt
(value_description ctxt) vd
(item_attributes ctxt) vd.pval_attributes
| Pstr_include incl ->
pp f "@[<hov2>include@ %a@]%a"
(module_expr ctxt) incl.pincl_mod
(item_attributes ctxt) incl.pincl_attributes
3.07
let aux f = function
| ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) ->
pp f "@[<hov2>@ and@ %s:%a@ =@ %a@]%a"
(Option.value pmb.pmb_name.txt ~default:"_")
(module_type ctxt) typ
(module_expr ctxt) expr
(item_attributes ctxt) pmb.pmb_attributes
| pmb ->
pp f "@[<hov2>@ and@ %s@ =@ %a@]%a"
(Option.value pmb.pmb_name.txt ~default:"_")
(module_expr ctxt) pmb.pmb_expr
(item_attributes ctxt) pmb.pmb_attributes
in
begin match decls with
| ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 ->
pp f "@[<hv>@[<hov2>module@ rec@ %s:%a@ =@ %a@]%a@ %a@]"
(Option.value pmb.pmb_name.txt ~default:"_")
(module_type ctxt) typ
(module_expr ctxt) expr
(item_attributes ctxt) pmb.pmb_attributes
(fun f l2 -> List.iter (aux f) l2) l2
| pmb :: l2 ->
pp f "@[<hv>@[<hov2>module@ rec@ %s@ =@ %a@]%a@ %a@]"
(Option.value pmb.pmb_name.txt ~default:"_")
(module_expr ctxt) pmb.pmb_expr
(item_attributes ctxt) pmb.pmb_attributes
(fun f l2 -> List.iter (aux f) l2) l2
| _ -> assert false
end
| Pstr_attribute a -> floating_attribute ctxt f a
| Pstr_extension(e, a) ->
item_extension ctxt f e;
item_attributes ctxt f a
and type_param ctxt f (ct, (a,b)) =
pp f "%s%s%a" (type_variance a) (type_injectivity b) (core_type ctxt) ct
and type_params ctxt f = function
| [] -> ()
| l -> pp f "%a " (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",@;") l
and type_def_list ctxt f (rf, exported, l) =
let type_decl kwd rf f x =
let eq =
if (x.ptype_kind = Ptype_abstract)
&& (x.ptype_manifest = None) then ""
else if exported then " ="
else " :="
in
pp f "@[<2>%s %a%a%s%s%a@]%a" kwd
nonrec_flag rf
(type_params ctxt) x.ptype_params
x.ptype_name.txt eq
(type_declaration ctxt) x
(item_attributes ctxt) x.ptype_attributes
in
match l with
| [] -> assert false
| [x] -> type_decl "type" rf f x
| x :: xs -> pp f "@[<v>%a@,%a@]"
(type_decl "type" rf) x
(list ~sep:"@," (type_decl "and" Recursive)) xs
and record_declaration ctxt f lbls =
let type_record_field f pld =
pp f "@[<2>%a%s:@;%a@;%a@]"
mutable_flag pld.pld_mutable
pld.pld_name.txt
(core_type ctxt) pld.pld_type
(attributes ctxt) pld.pld_attributes
in
pp f "{@\n%a}"
(list type_record_field ~sep:";@\n" ) lbls
and type_declaration ctxt f x =
(* type_declaration has an attribute field,
but it's been printed by the caller of this method *)
let priv f =
match x.ptype_private with
| Public -> ()
| Private -> pp f "@;private"
in
let manifest f =
match x.ptype_manifest with
| None -> ()
| Some y ->
if x.ptype_kind = Ptype_abstract then
pp f "%t@;%a" priv (core_type ctxt) y
else
pp f "@;%a" (core_type ctxt) y
in
let constructor_declaration f pcd =
pp f "|@;";
constructor_declaration ctxt f
(pcd.pcd_name.txt, pcd.pcd_vars,
pcd.pcd_args, pcd.pcd_res, pcd.pcd_attributes)
in
let repr f =
let intro f =
if x.ptype_manifest = None then ()
else pp f "@;="
in
match x.ptype_kind with
| Ptype_variant xs ->
let variants fmt xs =
if xs = [] then pp fmt " |" else
pp fmt "@\n%a" (list ~sep:"@\n" constructor_declaration) xs
in pp f "%t%t%a" intro priv variants xs
| Ptype_abstract -> ()
| Ptype_record l ->
pp f "%t%t@;%a" intro priv (record_declaration ctxt) l
| Ptype_open -> pp f "%t%t@;.." intro priv
in
let constraints f =
List.iter
(fun (ct1,ct2,_) ->
pp f "@[<hov2>@ constraint@ %a@ =@ %a@]"
(core_type ctxt) ct1 (core_type ctxt) ct2)
x.ptype_cstrs
in
pp f "%t%t%t" manifest repr constraints
and type_extension ctxt f x =
let extension_constructor f x =
pp f "@\n|@;%a" (extension_constructor ctxt) x
in
pp f "@[<2>type %a%a += %a@ %a@]%a"
(fun f -> function
| [] -> ()
| l ->
pp f "%a@;" (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l)
x.ptyext_params
longident_loc x.ptyext_path
Cf : # 7200
(list ~sep:"" extension_constructor)
x.ptyext_constructors
(item_attributes ctxt) x.ptyext_attributes
and constructor_declaration ctxt f (name, vars, args, res, attrs) =
let name =
match name with
| "::" -> "(::)"
| s -> s in
let pp_vars f vs =
match vs with
| [] -> ()
| vs -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") vs in
match res with
| None ->
pp f "%s%a@;%a" name
(fun f -> function
| Pcstr_tuple [] -> ()
| Pcstr_tuple l ->
pp f "@;of@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l
| Pcstr_record l -> pp f "@;of@;%a" (record_declaration ctxt) l
) args
(attributes ctxt) attrs
| Some r ->
pp f "%s:@;%a%a@;%a" name
pp_vars vars
(fun f -> function
| Pcstr_tuple [] -> core_type1 ctxt f r
| Pcstr_tuple l -> pp f "%a@;->@;%a"
(list (core_type1 ctxt) ~sep:"@;*@;") l
(core_type1 ctxt) r
| Pcstr_record l ->
pp f "%a@;->@;%a" (record_declaration ctxt) l (core_type1 ctxt) r
)
args
(attributes ctxt) attrs
and extension_constructor ctxt f x =
Cf : # 7200
match x.pext_kind with
| Pext_decl(v, l, r) ->
constructor_declaration ctxt f
(x.pext_name.txt, v, l, r, x.pext_attributes)
| Pext_rebind li ->
pp f "%s@;=@;%a%a" x.pext_name.txt
longident_loc li
(attributes ctxt) x.pext_attributes
and case_list ctxt f l : unit =
let aux f {pc_lhs; pc_guard; pc_rhs} =
pp f "@;| @[<2>%a%a@;->@;%a@]"
(pattern ctxt) pc_lhs (option (expression ctxt) ~first:"@;when@;")
pc_guard (expression (under_pipe ctxt)) pc_rhs
in
list aux f l ~sep:""
and label_x_expression_param ctxt f (l,e) =
let simple_name = match e with
| {pexp_desc=Pexp_ident {txt=Lident l;_};
pexp_attributes=[]} -> Some l
| _ -> None
in match l with
level 2
| Optional str ->
if Some str = simple_name then
pp f "?%s" str
else
pp f "?%s:%a" str (simple_expr ctxt) e
| Labelled lbl ->
if Some lbl = simple_name then
pp f "~%s" lbl
else
pp f "~%s:%a" lbl (simple_expr ctxt) e
and directive_argument f x =
match x.pdira_desc with
| Pdir_string (s) -> pp f "@ %S" s
| Pdir_int (n, None) -> pp f "@ %s" n
| Pdir_int (n, Some m) -> pp f "@ %s%c" n m
| Pdir_ident (li) -> pp f "@ %a" longident li
| Pdir_bool (b) -> pp f "@ %s" (string_of_bool b)
let toplevel_phrase f x =
match x with
| Ptop_def (s) ->pp f "@[<hov0>%a@]" (list (structure_item reset_ctxt)) s
(* pp_open_hvbox f 0; *)
(* pp_print_list structure_item f s ; *)
pp_close_box f ( ) ;
| Ptop_dir {pdir_name; pdir_arg = None; _} ->
pp f "@[<hov2>#%s@]" pdir_name.txt
| Ptop_dir {pdir_name; pdir_arg = Some pdir_arg; _} ->
pp f "@[<hov2>#%s@ %a@]" pdir_name.txt directive_argument pdir_arg
let expression f x =
pp f "@[%a@]" (expression reset_ctxt) x
let string_of_expression x =
ignore (flush_str_formatter ()) ;
let f = str_formatter in
expression f x;
flush_str_formatter ()
let string_of_structure x =
ignore (flush_str_formatter ());
let f = str_formatter in
structure reset_ctxt f x;
flush_str_formatter ()
let top_phrase f x =
pp_print_newline f ();
toplevel_phrase f x;
pp f ";;";
pp_print_newline f ()
let core_type = core_type reset_ctxt
let pattern = pattern reset_ctxt
let signature = signature reset_ctxt
let structure = structure reset_ctxt
let module_expr = module_expr reset_ctxt
let module_type = module_type reset_ctxt
let class_field = class_field reset_ctxt
let class_type_field = class_type_field reset_ctxt
let class_expr = class_expr reset_ctxt
let class_type = class_type reset_ctxt
let structure_item = structure_item reset_ctxt
let signature_item = signature_item reset_ctxt
let binding = binding reset_ctxt
let payload = payload reset_ctxt
| null | https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/upstream/ocaml_414/parsing/pprintast.ml | ocaml | ************************************************************************
OCaml
Fabrice Le Fessant, INRIA Saclay
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Printing code expressions
type fixity = Infix| Prefix
which identifiers are in fact operators needing parentheses
some infixes need spaces around parens to avoid clashes with comment
syntax
add parentheses to binders when they are in fact infix or prefix operators
variance encoding: need to sync up with the [parser.mly]
trailing space
trailing space added
without the space, this would be parsed as
a character literal
c ['a,'b]
space
otherwise parenthesize
"%a%a@;"
Cf #7200: print [>] correctly
FIXME desugar the syntax sugar
*******************pattern*******************
RA
single case pattern parens needed here
extract operator:
assignment operators end with [right_bracket ^ "<-"],
access operators end with [right_bracket] directly
extract the right end bracket
"try@;@[<2>%a@]@\nwith@\n%a"
pp f "@[<2>let %a%a in@;<1 -2>%a@]"
(*no indentation here, a new line
See #7200: avoid turning (~- 1) into (- 1) which is
parsed as an int literal
reset here only because [function,match,try,sequence]
are lower priority
Not efficient FIXME
@;@[<2>else@ %a@]@]
pp f "()"
Pexp_poly: impossible but we should print it anyway, rather than
assert false
used in [Pexp_apply]
(match view_fixity_of_exp x with
|`Normal -> longident_loc f li
| `Prefix _ | `Infix _ -> pp f "( %a )" longident_loc li)
no sep hint
"@[<hov2>{%a%a}@]"
note: value_description has an attribute field,
but they're already printed by the callers this method
call [class_signature] called by [class_signature]
[class type a = object end]
"@[<hov>sig@ %a@ end@]"
FIXME wrong indentation
Psig_typesubst is never recursive, but we specify [Recursive] here to
avoid printing a [nonrec] flag, which would be rejected by the parser.
ast invariant
transform [f = fun g h -> ..] to [f g h = ... ] could be improved
.pvb_attributes have already been printed by the caller, #bindings
[in] is not printed
type_declaration has an attribute field,
but it's been printed by the caller of this method
pp_open_hvbox f 0;
pp_print_list structure_item f s ; | , OCamlPro
, University of Pennsylvania
Copyright 2007 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
Original Code from Ber - metaocaml , modified for 3.12.0 and fixed
Authors : ,
Extensive Rewrite : : University of Pennsylvania
TODO more fine - grained precedence pretty - printing
open Asttypes
open Format
open Location
open Longident
open Parsetree
open Ast_helper
let prefix_symbols = [ '!'; '?'; '~' ] ;;
let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/';
'$'; '%'; '#' ]
let special_infix_strings =
["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "::" ]
let letop s =
String.length s > 3
&& s.[0] = 'l'
&& s.[1] = 'e'
&& s.[2] = 't'
&& List.mem s.[3] infix_symbols
let andop s =
String.length s > 3
&& s.[0] = 'a'
&& s.[1] = 'n'
&& s.[2] = 'd'
&& List.mem s.[3] infix_symbols
determines if the string is an infix string .
checks backwards , first allowing a renaming postfix ( " _ 102 " ) which
may have resulted from - > Texp - > translation , then checking
if all the characters in the beginning of the string are valid infix
characters .
checks backwards, first allowing a renaming postfix ("_102") which
may have resulted from Pexp -> Texp -> Pexp translation, then checking
if all the characters in the beginning of the string are valid infix
characters. *)
let fixity_of_string = function
| "" -> `Normal
| s when List.mem s special_infix_strings -> `Infix s
| s when List.mem s.[0] infix_symbols -> `Infix s
| s when List.mem s.[0] prefix_symbols -> `Prefix s
| s when s.[0] = '.' -> `Mixfix s
| s when letop s -> `Letop s
| s when andop s -> `Andop s
| _ -> `Normal
let view_fixity_of_exp = function
| {pexp_desc = Pexp_ident {txt=Lident l;_}; pexp_attributes = []} ->
fixity_of_string l
| _ -> `Normal
let is_infix = function `Infix _ -> true | _ -> false
let is_mixfix = function `Mixfix _ -> true | _ -> false
let is_kwdop = function `Letop _ | `Andop _ -> true | _ -> false
let first_is c str =
str <> "" && str.[0] = c
let last_is c str =
str <> "" && str.[String.length str - 1] = c
let first_is_in cs str =
str <> "" && List.mem str.[0] cs
let needs_parens txt =
let fix = fixity_of_string txt in
is_infix fix
|| is_mixfix fix
|| is_kwdop fix
|| first_is_in prefix_symbols txt
let needs_spaces txt =
first_is '*' txt || last_is '*' txt
let string_loc ppf x = fprintf ppf "%s" x.txt
let protect_ident ppf txt =
let format : (_, _, _) format =
if not (needs_parens txt) then "%s"
else if needs_spaces txt then "(@;%s@;)"
else "(%s)"
in fprintf ppf format txt
let protect_longident ppf print_longident longprefix txt =
let format : (_, _, _) format =
if not (needs_parens txt) then "%a.%s"
else if needs_spaces txt then "%a.(@;%s@;)"
else "%a.(%s)" in
fprintf ppf format print_longident longprefix txt
type space_formatter = (unit, Format.formatter, unit) format
let override = function
| Override -> "!"
| Fresh -> ""
let type_variance = function
| NoVariance -> ""
| Covariant -> "+"
| Contravariant -> "-"
let type_injectivity = function
| NoInjectivity -> ""
| Injective -> "!"
type construct =
[ `cons of expression list
| `list of expression list
| `nil
| `normal
| `simple of Longident.t
| `tuple ]
let view_expr x =
match x.pexp_desc with
| Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple
| Pexp_construct ( {txt= Lident "[]";_},_) -> `nil
| Pexp_construct ( {txt= Lident"::";_},Some _) ->
let rec loop exp acc = match exp with
| {pexp_desc=Pexp_construct ({txt=Lident "[]";_},_);
pexp_attributes = []} ->
(List.rev acc,true)
| {pexp_desc=
Pexp_construct ({txt=Lident "::";_},
Some ({pexp_desc= Pexp_tuple([e1;e2]);
pexp_attributes = []}));
pexp_attributes = []}
->
loop e2 (e1::acc)
| e -> (List.rev (e::acc),false) in
let (ls,b) = loop x [] in
if b then
`list ls
else `cons ls
| Pexp_construct (x,None) -> `simple (x.txt)
| _ -> `normal
let is_simple_construct :construct -> bool = function
| `nil | `tuple | `list _ | `simple _ -> true
| `cons _ | `normal -> false
let pp = fprintf
type ctxt = {
pipe : bool;
semi : bool;
ifthenelse : bool;
}
let reset_ctxt = { pipe=false; semi=false; ifthenelse=false }
let under_pipe ctxt = { ctxt with pipe=true }
let under_semi ctxt = { ctxt with semi=true }
let under_ifthenelse ctxt = { ctxt with ifthenelse=true }
let reset_semi = with semi = false }
let reset_ifthenelse = with ifthenelse = false }
let = with pipe = false }
let reset_semi ctxt = { ctxt with semi=false }
let reset_ifthenelse ctxt = { ctxt with ifthenelse=false }
let reset_pipe ctxt = { ctxt with pipe=false }
*)
let list : 'a . ?sep:space_formatter -> ?first:space_formatter ->
?last:space_formatter -> (Format.formatter -> 'a -> unit) ->
Format.formatter -> 'a list -> unit
= fun ?sep ?first ?last fu f xs ->
let first = match first with Some x -> x |None -> ("": _ format6)
and last = match last with Some x -> x |None -> ("": _ format6)
and sep = match sep with Some x -> x |None -> ("@ ": _ format6) in
let aux f = function
| [] -> ()
| [x] -> fu f x
| xs ->
let rec loop f = function
| [x] -> fu f x
| x::xs -> fu f x; pp f sep; loop f xs;
| _ -> assert false in begin
pp f first; loop f xs; pp f last;
end in
aux f xs
let option : 'a. ?first:space_formatter -> ?last:space_formatter ->
(Format.formatter -> 'a -> unit) -> Format.formatter -> 'a option -> unit
= fun ?first ?last fu f a ->
let first = match first with Some x -> x | None -> ("": _ format6)
and last = match last with Some x -> x | None -> ("": _ format6) in
match a with
| None -> ()
| Some x -> pp f first; fu f x; pp f last
let paren: 'a . ?first:space_formatter -> ?last:space_formatter ->
bool -> (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a -> unit
= fun ?(first=("": _ format6)) ?(last=("": _ format6)) b fu f x ->
if b then (pp f "("; pp f first; fu f x; pp f last; pp f ")")
else fu f x
let rec longident f = function
| Lident s -> protect_ident f s
| Ldot(y,s) -> protect_longident f longident y s
| Lapply (y,s) ->
pp f "%a(%a)" longident y longident s
let longident_loc f x = pp f "%a" longident x.txt
let constant f = function
| Pconst_char i ->
pp f "%C" i
| Pconst_string (i, _, None) ->
pp f "%S" i
| Pconst_string (i, _, Some delim) ->
pp f "{%s|%s|%s}" delim i delim
| Pconst_integer (i, None) ->
paren (first_is '-' i) (fun f -> pp f "%s") f i
| Pconst_integer (i, Some m) ->
paren (first_is '-' i) (fun f (i, m) -> pp f "%s%c" i m) f (i,m)
| Pconst_float (i, None) ->
paren (first_is '-' i) (fun f -> pp f "%s") f i
| Pconst_float (i, Some m) ->
paren (first_is '-' i) (fun f (i,m) -> pp f "%s%c" i m) f (i,m)
let mutable_flag f = function
| Immutable -> ()
| Mutable -> pp f "mutable@;"
let virtual_flag f = function
| Concrete -> ()
| Virtual -> pp f "virtual@;"
let rec_flag f rf =
match rf with
| Nonrecursive -> ()
| Recursive -> pp f "rec "
let nonrec_flag f rf =
match rf with
| Nonrecursive -> pp f "nonrec "
| Recursive -> ()
let direction_flag f = function
| Upto -> pp f "to@ "
| Downto -> pp f "downto@ "
let private_flag f = function
| Public -> ()
| Private -> pp f "private@ "
let iter_loc f ctxt {txt; loc = _} = f ctxt txt
let constant_string f s = pp f "%S" s
let tyvar ppf s =
if String.length s >= 2 && s.[1] = '\'' then
Format.fprintf ppf "' %s" s
else
Format.fprintf ppf "'%s" s
let tyvar_loc f str = tyvar f str.txt
let string_quot f x = pp f "`%s" x
let rec class_params_def ctxt f = function
| [] -> ()
| l ->
(list (type_param ctxt) ~sep:",") l
and type_with_label ctxt f (label, c) =
match label with
| Labelled s -> pp f "%s:%a" s (core_type1 ctxt) c
| Optional s -> pp f "?%s:%a" s (core_type1 ctxt) c
and core_type ctxt f x =
if x.ptyp_attributes <> [] then begin
pp f "((%a)%a)" (core_type ctxt) {x with ptyp_attributes=[]}
(attributes ctxt) x.ptyp_attributes
end
else match x.ptyp_desc with
| Ptyp_arrow (l, ct1, ct2) ->
FIXME remove parens later
(type_with_label ctxt) (l,ct1) (core_type ctxt) ct2
| Ptyp_alias (ct, s) ->
pp f "@[<2>%a@;as@;%a@]" (core_type1 ctxt) ct tyvar s
| Ptyp_poly ([], ct) ->
core_type ctxt f ct
| Ptyp_poly (sl, ct) ->
pp f "@[<2>%a%a@]"
(fun f l ->
pp f "%a"
(fun f l -> match l with
| [] -> ()
| _ ->
pp f "%a@;.@;"
(list tyvar_loc ~sep:"@;") l)
l)
sl (core_type ctxt) ct
| _ -> pp f "@[<2>%a@]" (core_type1 ctxt) x
and core_type1 ctxt f x =
if x.ptyp_attributes <> [] then core_type ctxt f x
else match x.ptyp_desc with
| Ptyp_any -> pp f "_";
| Ptyp_var s -> tyvar f s;
| Ptyp_tuple l -> pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l
| Ptyp_constr (li, l) ->
(fun f l -> match l with
|[] -> ()
|[x]-> pp f "%a@;" (core_type1 ctxt) x
| _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l)
l longident_loc li
| Ptyp_variant (l, closed, low) ->
let first_is_inherit = match l with
| {Parsetree.prf_desc = Rinherit _}::_ -> true
| _ -> false in
let type_variant_helper f x =
match x.prf_desc with
| Rtag (l, _, ctl) ->
pp f "@[<2>%a%a@;%a@]" (iter_loc string_quot) l
(fun f l -> match l with
|[] -> ()
| _ -> pp f "@;of@;%a"
(list (core_type ctxt) ~sep:"&") ctl) ctl
(attributes ctxt) x.prf_attributes
| Rinherit ct -> core_type ctxt f ct in
pp f "@[<2>[%a%a]@]"
(fun f l ->
match l, closed with
| [], Closed -> ()
| _ ->
pp f "%s@;%a"
(match (closed,low) with
| (Closed,None) -> if first_is_inherit then " |" else ""
| (Open,_) -> ">")
(list type_variant_helper ~sep:"@;<1 -2>| ") l) l
(fun f low -> match low with
|Some [] |None -> ()
|Some xs ->
pp f ">@ %a"
(list string_quot) xs) low
| Ptyp_object (l, o) ->
let core_field_type f x = match x.pof_desc with
| Otag (l, ct) ->
Cf # 7200
pp f "@[<hov2>%s: %a@ %a@ @]" l.txt
(core_type ctxt) ct (attributes ctxt) x.pof_attributes
| Oinherit ct ->
pp f "@[<hov2>%a@ @]" (core_type ctxt) ct
in
let field_var f = function
| Asttypes.Closed -> ()
| Asttypes.Open ->
match l with
| [] -> pp f ".."
| _ -> pp f " ;.."
in
pp f "@[<hov2><@ %a%a@ > @]"
(list core_field_type ~sep:";") l
Cf # 7200
FIXME
pp f "@[<hov2>%a#%a@]"
(list (core_type ctxt) ~sep:"," ~first:"(" ~last:")") l
longident_loc li
| Ptyp_package (lid, cstrs) ->
let aux f (s, ct) =
pp f "type %a@ =@ %a" longident_loc s (core_type ctxt) ct in
(match cstrs with
|[] -> pp f "@[<hov2>(module@ %a)@]" longident_loc lid
|_ ->
pp f "@[<hov2>(module@ %a@ with@ %a)@]" longident_loc lid
(list aux ~sep:"@ and@ ") cstrs)
| Ptyp_extension e -> extension ctxt f e
| _ -> paren true (core_type ctxt) f x
be cautious when use [ pattern ] , [ ] is preferred
and pattern ctxt f x =
if x.ppat_attributes <> [] then begin
pp f "((%a)%a)" (pattern ctxt) {x with ppat_attributes=[]}
(attributes ctxt) x.ppat_attributes
end
else match x.ppat_desc with
| Ppat_alias (p, s) ->
pp f "@[<2>%a@;as@;%a@]" (pattern ctxt) p protect_ident s.txt
| _ -> pattern_or ctxt f x
and pattern_or ctxt f x =
let rec left_associative x acc = match x with
| {ppat_desc=Ppat_or (p1,p2); ppat_attributes = []} ->
left_associative p1 (p2 :: acc)
| x -> x :: acc
in
match left_associative x [] with
| [] -> assert false
| [x] -> pattern1 ctxt f x
| orpats ->
pp f "@[<hov0>%a@]" (list ~sep:"@ | " (pattern1 ctxt)) orpats
and pattern1 ctxt (f:Format.formatter) (x:pattern) : unit =
let rec pattern_list_helper f = function
| {ppat_desc =
Ppat_construct
({ txt = Lident("::") ;_},
Some ([], {ppat_desc = Ppat_tuple([pat1; pat2]);_}));
ppat_attributes = []}
->
| p -> pattern1 ctxt f p
in
if x.ppat_attributes <> [] then pattern ctxt f x
else match x.ppat_desc with
| Ppat_variant (l, Some p) ->
pp f "@[<2>`%s@;%a@]" l (simple_pattern ctxt) p
| Ppat_construct (({txt=Lident("()"|"[]");_}), _) ->
simple_pattern ctxt f x
| Ppat_construct (({txt;_} as li), po) ->
FIXME The third field always false
if txt = Lident "::" then
pp f "%a" pattern_list_helper x
else
(match po with
| Some ([], x) ->
pp f "%a@;%a" longident_loc li (simple_pattern ctxt) x
| Some (vl, x) ->
pp f "%a@ (type %a)@;%a" longident_loc li
(list ~sep:"@ " string_loc) vl
(simple_pattern ctxt) x
| None -> pp f "%a" longident_loc li)
| _ -> simple_pattern ctxt f x
and simple_pattern ctxt (f:Format.formatter) (x:pattern) : unit =
if x.ppat_attributes <> [] then pattern ctxt f x
else match x.ppat_desc with
| Ppat_construct (({txt=Lident ("()"|"[]" as x);_}), None) ->
pp f "%s" x
| Ppat_any -> pp f "_";
| Ppat_var ({txt = txt;_}) -> protect_ident f txt
| Ppat_array l ->
pp f "@[<2>[|%a|]@]" (list (pattern1 ctxt) ~sep:";") l
| Ppat_unpack { txt = None } ->
pp f "(module@ _)@ "
| Ppat_unpack { txt = Some s } ->
pp f "(module@ %s)@ " s
| Ppat_type li ->
pp f "#%a" longident_loc li
| Ppat_record (l, closed) ->
let longident_x_pattern f (li, p) =
match (li,p) with
| ({txt=Lident s;_ },
{ppat_desc=Ppat_var {txt;_};
ppat_attributes=[]; _})
when s = txt ->
pp f "@[<2>%a@]" longident_loc li
| _ ->
pp f "@[<2>%a@;=@;%a@]" longident_loc li (pattern1 ctxt) p
in
begin match closed with
| Closed ->
pp f "@[<2>{@;%a@;}@]" (list longident_x_pattern ~sep:";@;") l
| _ ->
pp f "@[<2>{@;%a;_}@]" (list longident_x_pattern ~sep:";@;") l
end
| Ppat_tuple l ->
| Ppat_constant (c) -> pp f "%a" constant c
| Ppat_interval (c1, c2) -> pp f "%a..%a" constant c1 constant c2
| Ppat_variant (l,None) -> pp f "`%s" l
| Ppat_constraint (p, ct) ->
pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct
| Ppat_lazy p ->
pp f "@[<2>(lazy@;%a)@]" (simple_pattern ctxt) p
| Ppat_exception p ->
pp f "@[<2>exception@;%a@]" (pattern1 ctxt) p
| Ppat_extension e -> extension ctxt f e
| Ppat_open (lid, p) ->
let with_paren =
match p.ppat_desc with
| Ppat_array _ | Ppat_record _
| Ppat_construct (({txt=Lident ("()"|"[]");_}), None) -> false
| _ -> true in
pp f "@[<2>%a.%a @]" longident_loc lid
(paren with_paren @@ pattern1 ctxt) p
| _ -> paren true (pattern ctxt) f x
and label_exp ctxt f (l,opt,p) =
match l with
| Nolabel ->
pp f "%a@ " (simple_pattern ctxt) p
| Optional rest ->
begin match p with
| {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []}
when txt = rest ->
(match opt with
| Some o -> pp f "?(%s=@;%a)@;" rest (expression ctxt) o
| None -> pp f "?%s@ " rest)
| _ ->
(match opt with
| Some o ->
pp f "?%s:(%a=@;%a)@;"
rest (pattern1 ctxt) p (expression ctxt) o
| None -> pp f "?%s:%a@;" rest (simple_pattern ctxt) p)
end
| Labelled l -> match p with
| {ppat_desc = Ppat_var {txt;_}; ppat_attributes = []}
when txt = l ->
pp f "~%s@;" l
| _ -> pp f "~%s:%a@;" l (simple_pattern ctxt) p
and sugar_expr ctxt f e =
if e.pexp_attributes <> [] then false
else match e.pexp_desc with
| Pexp_apply ({ pexp_desc = Pexp_ident {txt = id; _};
pexp_attributes=[]; _}, args)
when List.for_all (fun (lab, _) -> lab = Nolabel) args -> begin
let print_indexop a path_prefix assign left sep right print_index indices
rem_args =
let print_path ppf = function
| None -> ()
| Some m -> pp ppf ".%a" longident m in
match assign, rem_args with
| false, [] ->
pp f "@[%a%a%s%a%s@]"
(simple_expr ctxt) a print_path path_prefix
left (list ~sep print_index) indices right; true
| true, [v] ->
pp f "@[%a%a%s%a%s@ <-@;<1 2>%a@]"
(simple_expr ctxt) a print_path path_prefix
left (list ~sep print_index) indices right
(simple_expr ctxt) v; true
| _ -> false in
match id, List.map snd args with
| Lident "!", [e] ->
pp f "@[<hov>!%a@]" (simple_expr ctxt) e; true
| Ldot (path, ("get"|"set" as func)), a :: other_args -> begin
let assign = func = "set" in
let print = print_indexop a None assign in
match path, other_args with
| Lident "Array", i :: rest ->
print ".(" "" ")" (expression ctxt) [i] rest
| Lident "String", i :: rest ->
print ".[" "" "]" (expression ctxt) [i] rest
| Ldot (Lident "Bigarray", "Array1"), i1 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1] rest
| Ldot (Lident "Bigarray", "Array2"), i1 :: i2 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1; i2] rest
| Ldot (Lident "Bigarray", "Array3"), i1 :: i2 :: i3 :: rest ->
print ".{" "," "}" (simple_expr ctxt) [i1; i2; i3] rest
| Ldot (Lident "Bigarray", "Genarray"),
{pexp_desc = Pexp_array indexes; pexp_attributes = []} :: rest ->
print ".{" "," "}" (simple_expr ctxt) indexes rest
| _ -> false
end
| (Lident s | Ldot(_,s)) , a :: i :: rest
when first_is '.' s ->
let multi_indices = String.contains s ';' in
let i =
match i.pexp_desc with
| Pexp_array l when multi_indices -> l
| _ -> [ i ] in
let assign = last_is '-' s in
let kind =
let n = String.length s in
if assign then s.[n - 3] else s.[n - 1] in
let left, right = match kind with
| ')' -> '(', ")"
| ']' -> '[', "]"
| '}' -> '{', "}"
| _ -> assert false in
let path_prefix = match id with
| Ldot(m,_) -> Some m
| _ -> None in
let left = String.sub s 0 (1+String.index s left) in
print_indexop a path_prefix assign left ";" right
(if multi_indices then expression ctxt else simple_expr ctxt)
i rest
| _ -> false
end
| _ -> false
and expression ctxt f x =
if x.pexp_attributes <> [] then
pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]}
(attributes ctxt) x.pexp_attributes
else match x.pexp_desc with
| Pexp_function _ | Pexp_fun _ | Pexp_match _ | Pexp_try _ | Pexp_sequence _
| Pexp_newtype _
when ctxt.pipe || ctxt.semi ->
paren true (expression reset_ctxt) f x
| Pexp_ifthenelse _ | Pexp_sequence _ when ctxt.ifthenelse ->
paren true (expression reset_ctxt) f x
| Pexp_let _ | Pexp_letmodule _ | Pexp_open _
| Pexp_letexception _ | Pexp_letop _
when ctxt.semi ->
paren true (expression reset_ctxt) f x
| Pexp_fun (l, e0, p, e) ->
pp f "@[<2>fun@;%a->@;%a@]"
(label_exp ctxt) (l, e0, p)
(expression ctxt) e
| Pexp_newtype (lid, e) ->
pp f "@[<2>fun@;(type@;%s)@;->@;%a@]" lid.txt
(expression ctxt) e
| Pexp_function l ->
pp f "@[<hv>function%a@]" (case_list ctxt) l
| Pexp_match (e, l) ->
pp f "@[<hv0>@[<hv0>@[<2>match %a@]@ with@]%a@]"
(expression reset_ctxt) e (case_list ctxt) l
| Pexp_try (e, l) ->
pp f "@[<0>@[<hv2>try@ %a@]@ @[<0>with%a@]@]"
(expression reset_ctxt) e (case_list ctxt) l
| Pexp_let (rf, l, e) ->
rec_flag rf
pp f "@[<2>%a in@;<1 -2>%a@]"
(bindings reset_ctxt) (rf,l)
(expression ctxt) e
| Pexp_apply (e, l) ->
begin if not (sugar_expr ctxt f x) then
match view_fixity_of_exp e with
| `Infix s ->
begin match l with
| [ (Nolabel, _) as arg1; (Nolabel, _) as arg2 ] ->
FIXME associativity label_x_expression_param
pp f "@[<2>%a@;%s@;%a@]"
(label_x_expression_param reset_ctxt) arg1 s
(label_x_expression_param ctxt) arg2
| _ ->
pp f "@[<2>%a %a@]"
(simple_expr ctxt) e
(list (label_x_expression_param ctxt)) l
end
| `Prefix s ->
let s =
if List.mem s ["~+";"~-";"~+.";"~-."] &&
(match l with
|[(_,{pexp_desc=Pexp_constant _})] -> false
| _ -> true)
then String.sub s 1 (String.length s -1)
else s in
begin match l with
| [(Nolabel, x)] ->
pp f "@[<2>%s@;%a@]" s (simple_expr ctxt) x
| _ ->
pp f "@[<2>%a %a@]" (simple_expr ctxt) e
(list (label_x_expression_param ctxt)) l
end
| _ ->
pp f "@[<hov2>%a@]" begin fun f (e,l) ->
pp f "%a@ %a" (expression2 ctxt) e
(list (label_x_expression_param reset_ctxt)) l
end (e,l)
end
| Pexp_construct (li, Some eo)
(match view_expr x with
| `cons ls -> list (simple_expr ctxt) f ls ~sep:"@;::@;"
| `normal ->
pp f "@[<2>%a@;%a@]" longident_loc li
(simple_expr ctxt) eo
| _ -> assert false)
| Pexp_setfield (e1, li, e2) ->
pp f "@[<2>%a.%a@ <-@ %a@]"
(simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2
| Pexp_ifthenelse (e1, e2, eo) ->
let fmt:(_,_,_)format ="@[<hv0>@[<2>if@ %a@]@;@[<2>then@ %a@]%a@]" in
let expression_under_ifthenelse = expression (under_ifthenelse ctxt) in
pp f fmt expression_under_ifthenelse e1 expression_under_ifthenelse e2
(fun f eo -> match eo with
| Some x ->
pp f "@;@[<2>else@;%a@]" (expression (under_semi ctxt)) x
| Pexp_sequence _ ->
let rec sequence_helper acc = function
| {pexp_desc=Pexp_sequence(e1,e2); pexp_attributes = []} ->
sequence_helper (e1::acc) e2
| v -> List.rev (v::acc) in
let lst = sequence_helper [] x in
pp f "@[<hv>%a@]"
(list (expression (under_semi ctxt)) ~sep:";@;") lst
| Pexp_new (li) ->
pp f "@[<hov2>new@ %a@]" longident_loc li;
| Pexp_setinstvar (s, e) ->
pp f "@[<hov2>%s@ <-@ %a@]" s.txt (expression ctxt) e
FIXME
let string_x_expression f (s, e) =
pp f "@[<hov2>%s@ =@ %a@]" s.txt (expression ctxt) e in
pp f "@[<hov2>{<%a>}@]"
(list string_x_expression ~sep:";" ) l;
| Pexp_letmodule (s, me, e) ->
pp f "@[<hov2>let@ module@ %s@ =@ %a@ in@ %a@]"
(Option.value s.txt ~default:"_")
(module_expr reset_ctxt) me (expression ctxt) e
| Pexp_letexception (cd, e) ->
pp f "@[<hov2>let@ exception@ %a@ in@ %a@]"
(extension_constructor ctxt) cd
(expression ctxt) e
| Pexp_assert e ->
pp f "@[<hov2>assert@ %a@]" (simple_expr ctxt) e
| Pexp_lazy (e) ->
pp f "@[<hov2>lazy@ %a@]" (simple_expr ctxt) e
| Pexp_poly (e, None) ->
pp f "@[<hov2>!poly!@ %a@]" (simple_expr ctxt) e
| Pexp_poly (e, Some ct) ->
pp f "@[<hov2>(!poly!@ %a@ : %a)@]"
(simple_expr ctxt) e (core_type ctxt) ct
| Pexp_open (o, e) ->
pp f "@[<2>let open%s %a in@;%a@]"
(override o.popen_override) (module_expr ctxt) o.popen_expr
(expression ctxt) e
| Pexp_variant (l,Some eo) ->
pp f "@[<2>`%s@;%a@]" l (simple_expr ctxt) eo
| Pexp_letop {let_; ands; body} ->
pp f "@[<2>@[<v>%a@,%a@] in@;<1 -2>%a@]"
(binding_op ctxt) let_
(list ~sep:"@," (binding_op ctxt)) ands
(expression ctxt) body
| Pexp_extension e -> extension ctxt f e
| Pexp_unreachable -> pp f "."
| _ -> expression1 ctxt f x
and expression1 ctxt f x =
if x.pexp_attributes <> [] then expression ctxt f x
else match x.pexp_desc with
| Pexp_object cs -> pp f "%a" (class_structure ctxt) cs
| _ -> expression2 ctxt f x
and expression2 ctxt f x =
if x.pexp_attributes <> [] then expression ctxt f x
else match x.pexp_desc with
| Pexp_field (e, li) ->
pp f "@[<hov2>%a.%a@]" (simple_expr ctxt) e longident_loc li
| Pexp_send (e, s) -> pp f "@[<hov2>%a#%s@]" (simple_expr ctxt) e s.txt
| _ -> simple_expr ctxt f x
and simple_expr ctxt f x =
if x.pexp_attributes <> [] then expression ctxt f x
else match x.pexp_desc with
| Pexp_construct _ when is_simple_construct (view_expr x) ->
(match view_expr x with
| `nil -> pp f "[]"
| `tuple -> pp f "()"
| `list xs ->
pp f "@[<hv0>[%a]@]"
(list (expression (under_semi ctxt)) ~sep:";@;") xs
| `simple x -> longident f x
| _ -> assert false)
| Pexp_ident li ->
longident_loc f li
| Pexp_constant c -> constant f c;
| Pexp_pack me ->
pp f "(module@;%a)" (module_expr ctxt) me
| Pexp_tuple l ->
pp f "@[<hov2>(%a)@]" (list (simple_expr ctxt) ~sep:",@;") l
| Pexp_constraint (e, ct) ->
pp f "(%a : %a)" (expression ctxt) e (core_type ctxt) ct
| Pexp_coerce (e, cto1, ct) ->
pp f "(%a%a :> %a)" (expression ctxt) e
(core_type ctxt) ct
| Pexp_variant (l, None) -> pp f "`%s" l
| Pexp_record (l, eo) ->
let longident_x_expression f ( li, e) =
match e with
| {pexp_desc=Pexp_ident {txt;_};
pexp_attributes=[]; _} when li.txt = txt ->
pp f "@[<hov2>%a@]" longident_loc li
| _ ->
pp f "@[<hov2>%a@;=@;%a@]" longident_loc li (simple_expr ctxt) e
in
(option ~last:" with@;" (simple_expr ctxt)) eo
(list longident_x_expression ~sep:";@;") l
| Pexp_array (l) ->
pp f "@[<0>@[<2>[|%a|]@]@]"
(list (simple_expr (under_semi ctxt)) ~sep:";") l
| Pexp_while (e1, e2) ->
let fmt : (_,_,_) format = "@[<2>while@;%a@;do@;%a@;done@]" in
pp f fmt (expression ctxt) e1 (expression ctxt) e2
| Pexp_for (s, e1, e2, df, e3) ->
let fmt:(_,_,_)format =
"@[<hv0>@[<hv2>@[<2>for %a =@;%a@;%a%a@;do@]@;%a@]@;done@]" in
let expression = expression ctxt in
pp f fmt (pattern ctxt) s expression e1 direction_flag
df expression e2 expression e3
| _ -> paren true (expression ctxt) f x
and attributes ctxt f l =
List.iter (attribute ctxt f) l
and item_attributes ctxt f l =
List.iter (item_attribute ctxt f) l
and attribute ctxt f a =
pp f "@[<2>[@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload
and item_attribute ctxt f a =
pp f "@[<2>[@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload
and floating_attribute ctxt f a =
pp f "@[<2>[@@@@@@%s@ %a]@]" a.attr_name.txt (payload ctxt) a.attr_payload
and value_description ctxt f x =
pp f "@[<hov2>%a%a@]" (core_type ctxt) x.pval_type
(fun f x ->
if x.pval_prim <> []
then pp f "@ =@ %a" (list constant_string) x.pval_prim
) x
and extension ctxt f (s, e) =
pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e
and item_extension ctxt f (s, e) =
pp f "@[<2>[%%%%%s@ %a]@]" s.txt (payload ctxt) e
and exception_declaration ctxt f x =
pp f "@[<hov2>exception@ %a@]%a"
(extension_constructor ctxt) x.ptyexn_constructor
(item_attributes ctxt) x.ptyexn_attributes
and class_type_field ctxt f x =
match x.pctf_desc with
| Pctf_inherit (ct) ->
pp f "@[<2>inherit@ %a@]%a" (class_type ctxt) ct
(item_attributes ctxt) x.pctf_attributes
| Pctf_val (s, mf, vf, ct) ->
pp f "@[<2>val @ %a%a%s@ :@ %a@]%a"
mutable_flag mf virtual_flag vf s.txt (core_type ctxt) ct
(item_attributes ctxt) x.pctf_attributes
| Pctf_method (s, pf, vf, ct) ->
pp f "@[<2>method %a %a%s :@;%a@]%a"
private_flag pf virtual_flag vf s.txt (core_type ctxt) ct
(item_attributes ctxt) x.pctf_attributes
| Pctf_constraint (ct1, ct2) ->
pp f "@[<2>constraint@ %a@ =@ %a@]%a"
(core_type ctxt) ct1 (core_type ctxt) ct2
(item_attributes ctxt) x.pctf_attributes
| Pctf_attribute a -> floating_attribute ctxt f a
| Pctf_extension e ->
item_extension ctxt f e;
item_attributes ctxt f x.pctf_attributes
and class_signature ctxt f { pcsig_self = ct; pcsig_fields = l ;_} =
pp f "@[<hv0>@[<hv2>object@[<1>%a@]@ %a@]@ end@]"
(fun f -> function
{ptyp_desc=Ptyp_any; ptyp_attributes=[]; _} -> ()
| ct -> pp f " (%a)" (core_type ctxt) ct) ct
(list (class_type_field ctxt) ~sep:"@;") l
and class_type ctxt f x =
match x.pcty_desc with
| Pcty_signature cs ->
class_signature ctxt f cs;
attributes ctxt f x.pcty_attributes
| Pcty_constr (li, l) ->
pp f "%a%a%a"
(fun f l -> match l with
| [] -> ()
| _ -> pp f "[%a]@ " (list (core_type ctxt) ~sep:"," ) l) l
longident_loc li
(attributes ctxt) x.pcty_attributes
| Pcty_arrow (l, co, cl) ->
FIXME remove parens later
(type_with_label ctxt) (l,co)
(class_type ctxt) cl
| Pcty_extension e ->
extension ctxt f e;
attributes ctxt f x.pcty_attributes
| Pcty_open (o, e) ->
pp f "@[<2>let open%s %a in@;%a@]"
(override o.popen_override) longident_loc o.popen_expr
(class_type ctxt) e
and class_type_declaration_list ctxt f l =
let class_type_declaration kwd f x =
let { pci_params=ls; pci_name={ txt; _ }; _ } = x in
pp f "@[<2>%s %a%a%s@ =@ %a@]%a" kwd
virtual_flag x.pci_virt
(class_params_def ctxt) ls txt
(class_type ctxt) x.pci_expr
(item_attributes ctxt) x.pci_attributes
in
match l with
| [] -> ()
| [x] -> class_type_declaration "class type" f x
| x :: xs ->
pp f "@[<v>%a@,%a@]"
(class_type_declaration "class type") x
(list ~sep:"@," (class_type_declaration "and")) xs
and class_field ctxt f x =
match x.pcf_desc with
| Pcf_inherit (ovf, ce, so) ->
pp f "@[<2>inherit@ %s@ %a%a@]%a" (override ovf)
(class_expr ctxt) ce
(fun f so -> match so with
| None -> ();
| Some (s) -> pp f "@ as %s" s.txt ) so
(item_attributes ctxt) x.pcf_attributes
| Pcf_val (s, mf, Cfk_concrete (ovf, e)) ->
pp f "@[<2>val%s %a%s =@;%a@]%a" (override ovf)
mutable_flag mf s.txt
(expression ctxt) e
(item_attributes ctxt) x.pcf_attributes
| Pcf_method (s, pf, Cfk_virtual ct) ->
pp f "@[<2>method virtual %a %s :@;%a@]%a"
private_flag pf s.txt
(core_type ctxt) ct
(item_attributes ctxt) x.pcf_attributes
| Pcf_val (s, mf, Cfk_virtual ct) ->
pp f "@[<2>val virtual %a%s :@ %a@]%a"
mutable_flag mf s.txt
(core_type ctxt) ct
(item_attributes ctxt) x.pcf_attributes
| Pcf_method (s, pf, Cfk_concrete (ovf, e)) ->
let bind e =
binding ctxt f
{pvb_pat=
{ppat_desc=Ppat_var s;
ppat_loc=Location.none;
ppat_loc_stack=[];
ppat_attributes=[]};
pvb_expr=e;
pvb_attributes=[];
pvb_loc=Location.none;
}
in
pp f "@[<2>method%s %a%a@]%a"
(override ovf)
private_flag pf
(fun f -> function
| {pexp_desc=Pexp_poly (e, Some ct); pexp_attributes=[]; _} ->
pp f "%s :@;%a=@;%a"
s.txt (core_type ctxt) ct (expression ctxt) e
| {pexp_desc=Pexp_poly (e, None); pexp_attributes=[]; _} ->
bind e
| _ -> bind e) e
(item_attributes ctxt) x.pcf_attributes
| Pcf_constraint (ct1, ct2) ->
pp f "@[<2>constraint %a =@;%a@]%a"
(core_type ctxt) ct1
(core_type ctxt) ct2
(item_attributes ctxt) x.pcf_attributes
| Pcf_initializer (e) ->
pp f "@[<2>initializer@ %a@]%a"
(expression ctxt) e
(item_attributes ctxt) x.pcf_attributes
| Pcf_attribute a -> floating_attribute ctxt f a
| Pcf_extension e ->
item_extension ctxt f e;
item_attributes ctxt f x.pcf_attributes
and class_structure ctxt f { pcstr_self = p; pcstr_fields = l } =
pp f "@[<hv0>@[<hv2>object%a@;%a@]@;end@]"
(fun f p -> match p.ppat_desc with
| Ppat_any -> ()
| Ppat_constraint _ -> pp f " %a" (pattern ctxt) p
| _ -> pp f " (%a)" (pattern ctxt) p) p
(list (class_field ctxt)) l
and class_expr ctxt f x =
if x.pcl_attributes <> [] then begin
pp f "((%a)%a)" (class_expr ctxt) {x with pcl_attributes=[]}
(attributes ctxt) x.pcl_attributes
end else
match x.pcl_desc with
| Pcl_structure (cs) -> class_structure ctxt f cs
| Pcl_fun (l, eo, p, e) ->
pp f "fun@ %a@ ->@ %a"
(label_exp ctxt) (l,eo,p)
(class_expr ctxt) e
| Pcl_let (rf, l, ce) ->
pp f "%a@ in@ %a"
(bindings ctxt) (rf,l)
(class_expr ctxt) ce
| Pcl_apply (ce, l) ->
Cf : # 7200
(class_expr ctxt) ce
(list (label_x_expression_param ctxt)) l
| Pcl_constr (li, l) ->
pp f "%a%a"
(fun f l-> if l <>[] then
pp f "[%a]@ "
(list (core_type ctxt) ~sep:",") l) l
longident_loc li
| Pcl_constraint (ce, ct) ->
pp f "(%a@ :@ %a)"
(class_expr ctxt) ce
(class_type ctxt) ct
| Pcl_extension e -> extension ctxt f e
| Pcl_open (o, e) ->
pp f "@[<2>let open%s %a in@;%a@]"
(override o.popen_override) longident_loc o.popen_expr
(class_expr ctxt) e
and module_type ctxt f x =
if x.pmty_attributes <> [] then begin
pp f "((%a)%a)" (module_type ctxt) {x with pmty_attributes=[]}
(attributes ctxt) x.pmty_attributes
end else
match x.pmty_desc with
| Pmty_functor (Unit, mt2) ->
pp f "@[<hov2>functor () ->@ %a@]" (module_type ctxt) mt2
| Pmty_functor (Named (s, mt1), mt2) ->
begin match s.txt with
| None ->
pp f "@[<hov2>%a@ ->@ %a@]"
(module_type1 ctxt) mt1 (module_type ctxt) mt2
| Some name ->
pp f "@[<hov2>functor@ (%s@ :@ %a)@ ->@ %a@]" name
(module_type ctxt) mt1 (module_type ctxt) mt2
end
| Pmty_with (mt, []) -> module_type ctxt f mt
| Pmty_with (mt, l) ->
pp f "@[<hov2>%a@ with@ %a@]"
(module_type1 ctxt) mt
(list (with_constraint ctxt) ~sep:"@ and@ ") l
| _ -> module_type1 ctxt f x
and with_constraint ctxt f = function
| Pwith_type (li, ({ptype_params= ls ;_} as td)) ->
let ls = List.map fst ls in
pp f "type@ %a %a =@ %a"
(list (core_type ctxt) ~sep:"," ~first:"(" ~last:")")
ls longident_loc li (type_declaration ctxt) td
| Pwith_module (li, li2) ->
pp f "module %a =@ %a" longident_loc li longident_loc li2;
| Pwith_modtype (li, mty) ->
pp f "module type %a =@ %a" longident_loc li (module_type ctxt) mty;
| Pwith_typesubst (li, ({ptype_params=ls;_} as td)) ->
let ls = List.map fst ls in
pp f "type@ %a %a :=@ %a"
(list (core_type ctxt) ~sep:"," ~first:"(" ~last:")")
ls longident_loc li
(type_declaration ctxt) td
| Pwith_modsubst (li, li2) ->
pp f "module %a :=@ %a" longident_loc li longident_loc li2
| Pwith_modtypesubst (li, mty) ->
pp f "module type %a :=@ %a" longident_loc li (module_type ctxt) mty;
and module_type1 ctxt f x =
if x.pmty_attributes <> [] then module_type ctxt f x
else match x.pmty_desc with
| Pmty_ident li ->
pp f "%a" longident_loc li;
| Pmty_alias li ->
pp f "(module %a)" longident_loc li;
| Pmty_signature (s) ->
| Pmty_typeof me ->
pp f "@[<hov2>module@ type@ of@ %a@]" (module_expr ctxt) me
| Pmty_extension e -> extension ctxt f e
| _ -> paren true (module_type ctxt) f x
and signature ctxt f x = list ~sep:"@\n" (signature_item ctxt) f x
and signature_item ctxt f x : unit =
match x.psig_desc with
| Psig_type (rf, l) ->
type_def_list ctxt f (rf, true, l)
| Psig_typesubst l ->
type_def_list ctxt f (Recursive, false, l)
| Psig_value vd ->
let intro = if vd.pval_prim = [] then "val" else "external" in
pp f "@[<2>%s@ %a@ :@ %a@]%a" intro
protect_ident vd.pval_name.txt
(value_description ctxt) vd
(item_attributes ctxt) vd.pval_attributes
| Psig_typext te ->
type_extension ctxt f te
| Psig_exception ed ->
exception_declaration ctxt f ed
| Psig_class l ->
let class_description kwd f ({pci_params=ls;pci_name={txt;_};_} as x) =
pp f "@[<2>%s %a%a%s@;:@;%a@]%a" kwd
virtual_flag x.pci_virt
(class_params_def ctxt) ls txt
(class_type ctxt) x.pci_expr
(item_attributes ctxt) x.pci_attributes
in begin
match l with
| [] -> ()
| [x] -> class_description "class" f x
| x :: xs ->
pp f "@[<v>%a@,%a@]"
(class_description "class") x
(list ~sep:"@," (class_description "and")) xs
end
| Psig_module ({pmd_type={pmty_desc=Pmty_alias alias;
pmty_attributes=[]; _};_} as pmd) ->
pp f "@[<hov>module@ %s@ =@ %a@]%a"
(Option.value pmd.pmd_name.txt ~default:"_")
longident_loc alias
(item_attributes ctxt) pmd.pmd_attributes
| Psig_module pmd ->
pp f "@[<hov>module@ %s@ :@ %a@]%a"
(Option.value pmd.pmd_name.txt ~default:"_")
(module_type ctxt) pmd.pmd_type
(item_attributes ctxt) pmd.pmd_attributes
| Psig_modsubst pms ->
pp f "@[<hov>module@ %s@ :=@ %a@]%a" pms.pms_name.txt
longident_loc pms.pms_manifest
(item_attributes ctxt) pms.pms_attributes
| Psig_open od ->
pp f "@[<hov2>open%s@ %a@]%a"
(override od.popen_override)
longident_loc od.popen_expr
(item_attributes ctxt) od.popen_attributes
| Psig_include incl ->
pp f "@[<hov2>include@ %a@]%a"
(module_type ctxt) incl.pincl_mod
(item_attributes ctxt) incl.pincl_attributes
| Psig_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} ->
pp f "@[<hov2>module@ type@ %s%a@]%a"
s.txt
(fun f md -> match md with
| None -> ()
| Some mt ->
pp_print_space f () ;
pp f "@ =@ %a" (module_type ctxt) mt
) md
(item_attributes ctxt) attrs
| Psig_modtypesubst {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} ->
let md = match md with
| Some mt -> mt in
pp f "@[<hov2>module@ type@ %s@ :=@ %a@]%a"
s.txt (module_type ctxt) md
(item_attributes ctxt) attrs
| Psig_class_type (l) -> class_type_declaration_list ctxt f l
| Psig_recmodule decls ->
let rec string_x_module_type_list f ?(first=true) l =
match l with
| [] -> () ;
| pmd :: tl ->
if not first then
pp f "@ @[<hov2>and@ %s:@ %a@]%a"
(Option.value pmd.pmd_name.txt ~default:"_")
(module_type1 ctxt) pmd.pmd_type
(item_attributes ctxt) pmd.pmd_attributes
else
pp f "@[<hov2>module@ rec@ %s:@ %a@]%a"
(Option.value pmd.pmd_name.txt ~default:"_")
(module_type1 ctxt) pmd.pmd_type
(item_attributes ctxt) pmd.pmd_attributes;
string_x_module_type_list f ~first:false tl
in
string_x_module_type_list f decls
| Psig_attribute a -> floating_attribute ctxt f a
| Psig_extension(e, a) ->
item_extension ctxt f e;
item_attributes ctxt f a
and module_expr ctxt f x =
if x.pmod_attributes <> [] then
pp f "((%a)%a)" (module_expr ctxt) {x with pmod_attributes=[]}
(attributes ctxt) x.pmod_attributes
else match x.pmod_desc with
| Pmod_structure (s) ->
pp f "@[<hv2>struct@;@[<0>%a@]@;<1 -2>end@]"
(list (structure_item ctxt) ~sep:"@\n") s;
| Pmod_constraint (me, mt) ->
pp f "@[<hov2>(%a@ :@ %a)@]"
(module_expr ctxt) me
(module_type ctxt) mt
| Pmod_ident (li) ->
pp f "%a" longident_loc li;
| Pmod_functor (Unit, me) ->
pp f "functor ()@;->@;%a" (module_expr ctxt) me
| Pmod_functor (Named (s, mt), me) ->
pp f "functor@ (%s@ :@ %a)@;->@;%a"
(Option.value s.txt ~default:"_")
(module_type ctxt) mt (module_expr ctxt) me
| Pmod_apply (me1, me2) ->
pp f "(%a)(%a)" (module_expr ctxt) me1 (module_expr ctxt) me2
Cf : # 7200
| Pmod_unpack e ->
pp f "(val@ %a)" (expression ctxt) e
| Pmod_extension e -> extension ctxt f e
and structure ctxt f x = list ~sep:"@\n" (structure_item ctxt) f x
and payload ctxt f = function
| PStr [{pstr_desc = Pstr_eval (e, attrs)}] ->
pp f "@[<2>%a@]%a"
(expression ctxt) e
(item_attributes ctxt) attrs
| PStr x -> structure ctxt f x
| PTyp x -> pp f ":@ "; core_type ctxt f x
| PSig x -> pp f ":@ "; signature ctxt f x
| PPat (x, None) -> pp f "?@ "; pattern ctxt f x
| PPat (x, Some e) ->
pp f "?@ "; pattern ctxt f x;
pp f " when "; expression ctxt f e
and binding ctxt f {pvb_pat=p; pvb_expr=x; _} =
let rec pp_print_pexp_function f x =
if x.pexp_attributes <> [] then pp f "=@;%a" (expression ctxt) x
else match x.pexp_desc with
| Pexp_fun (label, eo, p, e) ->
if label=Nolabel then
pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function e
else
pp f "%a@ %a"
(label_exp ctxt) (label,eo,p) pp_print_pexp_function e
| Pexp_newtype (str,e) ->
pp f "(type@ %s)@ %a" str.txt pp_print_pexp_function e
| _ -> pp f "=@;%a" (expression ctxt) x
in
let tyvars_str tyvars = List.map (fun v -> v.txt) tyvars in
let is_desugared_gadt p e =
let gadt_pattern =
match p with
| {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _} as pat,
{ptyp_desc=Ptyp_poly (args_tyvars, rt)});
ppat_attributes=[]}->
Some (pat, args_tyvars, rt)
| _ -> None in
let rec gadt_exp tyvars e =
match e with
| {pexp_desc=Pexp_newtype (tyvar, e); pexp_attributes=[]} ->
gadt_exp (tyvar :: tyvars) e
| {pexp_desc=Pexp_constraint (e, ct); pexp_attributes=[]} ->
Some (List.rev tyvars, e, ct)
| _ -> None in
let gadt_exp = gadt_exp [] e in
match gadt_pattern, gadt_exp with
| Some (p, pt_tyvars, pt_ct), Some (e_tyvars, e, e_ct)
when tyvars_str pt_tyvars = tyvars_str e_tyvars ->
let ety = Typ.varify_constructors e_tyvars e_ct in
if ety = pt_ct then
Some (p, pt_tyvars, e_ct, e) else None
| _ -> None in
if x.pexp_attributes <> []
then
match p with
| {ppat_desc=Ppat_constraint({ppat_desc=Ppat_var _; _} as pat,
({ptyp_desc=Ptyp_poly _; _} as typ));
ppat_attributes=[]; _} ->
pp f "%a@;: %a@;=@;%a"
(simple_pattern ctxt) pat (core_type ctxt) typ (expression ctxt) x
| _ ->
pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x
else
match is_desugared_gadt p x with
| Some (p, [], ct, e) ->
pp f "%a@;: %a@;=@;%a"
(simple_pattern ctxt) p (core_type ctxt) ct (expression ctxt) e
| Some (p, tyvars, ct, e) -> begin
pp f "%a@;: type@;%a.@;%a@;=@;%a"
(simple_pattern ctxt) p (list pp_print_string ~sep:"@;")
(tyvars_str tyvars) (core_type ctxt) ct (expression ctxt) e
end
| None -> begin
match p with
| {ppat_desc=Ppat_constraint(p ,ty);
special case for the first
begin match ty with
| {ptyp_desc=Ptyp_poly _; ptyp_attributes=[]} ->
pp f "%a@;:@;%a@;=@;%a" (simple_pattern ctxt) p
(core_type ctxt) ty (expression ctxt) x
| _ ->
pp f "(%a@;:@;%a)@;=@;%a" (simple_pattern ctxt) p
(core_type ctxt) ty (expression ctxt) x
end
| {ppat_desc=Ppat_var _; ppat_attributes=[]} ->
pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x
| _ ->
pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x
end
and bindings ctxt f (rf,l) =
let binding kwd rf f x =
pp f "@[<2>%s %a%a@]%a" kwd rec_flag rf
(binding ctxt) x (item_attributes ctxt) x.pvb_attributes
in
match l with
| [] -> ()
| [x] -> binding "let" rf f x
| x::xs ->
pp f "@[<v>%a@,%a@]"
(binding "let" rf) x
(list ~sep:"@," (binding "and" Nonrecursive)) xs
and binding_op ctxt f x =
match x.pbop_pat, x.pbop_exp with
| {ppat_desc = Ppat_var { txt=pvar; _ }; ppat_attributes = []; _},
{pexp_desc = Pexp_ident { txt=Lident evar; _}; pexp_attributes = []; _}
when pvar = evar ->
pp f "@[<2>%s %s@]" x.pbop_op.txt evar
| pat, exp ->
pp f "@[<2>%s %a@;=@;%a@]"
x.pbop_op.txt (pattern ctxt) pat (expression ctxt) exp
and structure_item ctxt f x =
match x.pstr_desc with
| Pstr_eval (e, attrs) ->
pp f "@[<hov2>;;%a@]%a"
(expression ctxt) e
(item_attributes ctxt) attrs
| Pstr_type (_, []) -> assert false
| Pstr_type (rf, l) -> type_def_list ctxt f (rf, true, l)
| Pstr_value (rf, l) ->
pp f " @[<hov2 > let % a%a@ ] " rec_flag rf bindings l
pp f "@[<2>%a@]" (bindings ctxt) (rf,l)
| Pstr_typext te -> type_extension ctxt f te
| Pstr_exception ed -> exception_declaration ctxt f ed
| Pstr_module x ->
let rec module_helper = function
| {pmod_desc=Pmod_functor(arg_opt,me'); pmod_attributes = []} ->
begin match arg_opt with
| Unit -> pp f "()"
| Named (s, mt) ->
pp f "(%s:%a)" (Option.value s.txt ~default:"_")
(module_type ctxt) mt
end;
module_helper me'
| me -> me
in
pp f "@[<hov2>module %s%a@]%a"
(Option.value x.pmb_name.txt ~default:"_")
(fun f me ->
let me = module_helper me in
match me with
| {pmod_desc=
Pmod_constraint
(me',
({pmty_desc=(Pmty_ident (_)
| Pmty_signature (_));_} as mt));
pmod_attributes = []} ->
pp f " :@;%a@;=@;%a@;"
(module_type ctxt) mt (module_expr ctxt) me'
| _ -> pp f " =@ %a" (module_expr ctxt) me
) x.pmb_expr
(item_attributes ctxt) x.pmb_attributes
| Pstr_open od ->
pp f "@[<2>open%s@;%a@]%a"
(override od.popen_override)
(module_expr ctxt) od.popen_expr
(item_attributes ctxt) od.popen_attributes
| Pstr_modtype {pmtd_name=s; pmtd_type=md; pmtd_attributes=attrs} ->
pp f "@[<hov2>module@ type@ %s%a@]%a"
s.txt
(fun f md -> match md with
| None -> ()
| Some mt ->
pp_print_space f () ;
pp f "@ =@ %a" (module_type ctxt) mt
) md
(item_attributes ctxt) attrs
| Pstr_class l ->
let extract_class_args cl =
let rec loop acc = function
| {pcl_desc=Pcl_fun (l, eo, p, cl'); pcl_attributes = []} ->
loop ((l,eo,p) :: acc) cl'
| cl -> List.rev acc, cl
in
let args, cl = loop [] cl in
let constr, cl =
match cl with
| {pcl_desc=Pcl_constraint (cl', ct); pcl_attributes = []} ->
Some ct, cl'
| _ -> None, cl
in
args, constr, cl
in
let class_constraint f ct = pp f ": @[%a@] " (class_type ctxt) ct in
let class_declaration kwd f
({pci_params=ls; pci_name={txt;_}; _} as x) =
let args, constr, cl = extract_class_args x.pci_expr in
pp f "@[<2>%s %a%a%s %a%a=@;%a@]%a" kwd
virtual_flag x.pci_virt
(class_params_def ctxt) ls txt
(list (label_exp ctxt)) args
(option class_constraint) constr
(class_expr ctxt) cl
(item_attributes ctxt) x.pci_attributes
in begin
match l with
| [] -> ()
| [x] -> class_declaration "class" f x
| x :: xs ->
pp f "@[<v>%a@,%a@]"
(class_declaration "class") x
(list ~sep:"@," (class_declaration "and")) xs
end
| Pstr_class_type l -> class_type_declaration_list ctxt f l
| Pstr_primitive vd ->
pp f "@[<hov2>external@ %a@ :@ %a@]%a"
protect_ident vd.pval_name.txt
(value_description ctxt) vd
(item_attributes ctxt) vd.pval_attributes
| Pstr_include incl ->
pp f "@[<hov2>include@ %a@]%a"
(module_expr ctxt) incl.pincl_mod
(item_attributes ctxt) incl.pincl_attributes
3.07
let aux f = function
| ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) ->
pp f "@[<hov2>@ and@ %s:%a@ =@ %a@]%a"
(Option.value pmb.pmb_name.txt ~default:"_")
(module_type ctxt) typ
(module_expr ctxt) expr
(item_attributes ctxt) pmb.pmb_attributes
| pmb ->
pp f "@[<hov2>@ and@ %s@ =@ %a@]%a"
(Option.value pmb.pmb_name.txt ~default:"_")
(module_expr ctxt) pmb.pmb_expr
(item_attributes ctxt) pmb.pmb_attributes
in
begin match decls with
| ({pmb_expr={pmod_desc=Pmod_constraint (expr, typ)}} as pmb) :: l2 ->
pp f "@[<hv>@[<hov2>module@ rec@ %s:%a@ =@ %a@]%a@ %a@]"
(Option.value pmb.pmb_name.txt ~default:"_")
(module_type ctxt) typ
(module_expr ctxt) expr
(item_attributes ctxt) pmb.pmb_attributes
(fun f l2 -> List.iter (aux f) l2) l2
| pmb :: l2 ->
pp f "@[<hv>@[<hov2>module@ rec@ %s@ =@ %a@]%a@ %a@]"
(Option.value pmb.pmb_name.txt ~default:"_")
(module_expr ctxt) pmb.pmb_expr
(item_attributes ctxt) pmb.pmb_attributes
(fun f l2 -> List.iter (aux f) l2) l2
| _ -> assert false
end
| Pstr_attribute a -> floating_attribute ctxt f a
| Pstr_extension(e, a) ->
item_extension ctxt f e;
item_attributes ctxt f a
and type_param ctxt f (ct, (a,b)) =
pp f "%s%s%a" (type_variance a) (type_injectivity b) (core_type ctxt) ct
and type_params ctxt f = function
| [] -> ()
| l -> pp f "%a " (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",@;") l
and type_def_list ctxt f (rf, exported, l) =
let type_decl kwd rf f x =
let eq =
if (x.ptype_kind = Ptype_abstract)
&& (x.ptype_manifest = None) then ""
else if exported then " ="
else " :="
in
pp f "@[<2>%s %a%a%s%s%a@]%a" kwd
nonrec_flag rf
(type_params ctxt) x.ptype_params
x.ptype_name.txt eq
(type_declaration ctxt) x
(item_attributes ctxt) x.ptype_attributes
in
match l with
| [] -> assert false
| [x] -> type_decl "type" rf f x
| x :: xs -> pp f "@[<v>%a@,%a@]"
(type_decl "type" rf) x
(list ~sep:"@," (type_decl "and" Recursive)) xs
and record_declaration ctxt f lbls =
let type_record_field f pld =
pp f "@[<2>%a%s:@;%a@;%a@]"
mutable_flag pld.pld_mutable
pld.pld_name.txt
(core_type ctxt) pld.pld_type
(attributes ctxt) pld.pld_attributes
in
pp f "{@\n%a}"
(list type_record_field ~sep:";@\n" ) lbls
and type_declaration ctxt f x =
let priv f =
match x.ptype_private with
| Public -> ()
| Private -> pp f "@;private"
in
let manifest f =
match x.ptype_manifest with
| None -> ()
| Some y ->
if x.ptype_kind = Ptype_abstract then
pp f "%t@;%a" priv (core_type ctxt) y
else
pp f "@;%a" (core_type ctxt) y
in
let constructor_declaration f pcd =
pp f "|@;";
constructor_declaration ctxt f
(pcd.pcd_name.txt, pcd.pcd_vars,
pcd.pcd_args, pcd.pcd_res, pcd.pcd_attributes)
in
let repr f =
let intro f =
if x.ptype_manifest = None then ()
else pp f "@;="
in
match x.ptype_kind with
| Ptype_variant xs ->
let variants fmt xs =
if xs = [] then pp fmt " |" else
pp fmt "@\n%a" (list ~sep:"@\n" constructor_declaration) xs
in pp f "%t%t%a" intro priv variants xs
| Ptype_abstract -> ()
| Ptype_record l ->
pp f "%t%t@;%a" intro priv (record_declaration ctxt) l
| Ptype_open -> pp f "%t%t@;.." intro priv
in
let constraints f =
List.iter
(fun (ct1,ct2,_) ->
pp f "@[<hov2>@ constraint@ %a@ =@ %a@]"
(core_type ctxt) ct1 (core_type ctxt) ct2)
x.ptype_cstrs
in
pp f "%t%t%t" manifest repr constraints
and type_extension ctxt f x =
let extension_constructor f x =
pp f "@\n|@;%a" (extension_constructor ctxt) x
in
pp f "@[<2>type %a%a += %a@ %a@]%a"
(fun f -> function
| [] -> ()
| l ->
pp f "%a@;" (list (type_param ctxt) ~first:"(" ~last:")" ~sep:",") l)
x.ptyext_params
longident_loc x.ptyext_path
Cf : # 7200
(list ~sep:"" extension_constructor)
x.ptyext_constructors
(item_attributes ctxt) x.ptyext_attributes
and constructor_declaration ctxt f (name, vars, args, res, attrs) =
let name =
match name with
| "::" -> "(::)"
| s -> s in
let pp_vars f vs =
match vs with
| [] -> ()
| vs -> pp f "%a@;.@;" (list tyvar_loc ~sep:"@;") vs in
match res with
| None ->
pp f "%s%a@;%a" name
(fun f -> function
| Pcstr_tuple [] -> ()
| Pcstr_tuple l ->
pp f "@;of@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l
| Pcstr_record l -> pp f "@;of@;%a" (record_declaration ctxt) l
) args
(attributes ctxt) attrs
| Some r ->
pp f "%s:@;%a%a@;%a" name
pp_vars vars
(fun f -> function
| Pcstr_tuple [] -> core_type1 ctxt f r
| Pcstr_tuple l -> pp f "%a@;->@;%a"
(list (core_type1 ctxt) ~sep:"@;*@;") l
(core_type1 ctxt) r
| Pcstr_record l ->
pp f "%a@;->@;%a" (record_declaration ctxt) l (core_type1 ctxt) r
)
args
(attributes ctxt) attrs
and extension_constructor ctxt f x =
Cf : # 7200
match x.pext_kind with
| Pext_decl(v, l, r) ->
constructor_declaration ctxt f
(x.pext_name.txt, v, l, r, x.pext_attributes)
| Pext_rebind li ->
pp f "%s@;=@;%a%a" x.pext_name.txt
longident_loc li
(attributes ctxt) x.pext_attributes
and case_list ctxt f l : unit =
let aux f {pc_lhs; pc_guard; pc_rhs} =
pp f "@;| @[<2>%a%a@;->@;%a@]"
(pattern ctxt) pc_lhs (option (expression ctxt) ~first:"@;when@;")
pc_guard (expression (under_pipe ctxt)) pc_rhs
in
list aux f l ~sep:""
and label_x_expression_param ctxt f (l,e) =
let simple_name = match e with
| {pexp_desc=Pexp_ident {txt=Lident l;_};
pexp_attributes=[]} -> Some l
| _ -> None
in match l with
level 2
| Optional str ->
if Some str = simple_name then
pp f "?%s" str
else
pp f "?%s:%a" str (simple_expr ctxt) e
| Labelled lbl ->
if Some lbl = simple_name then
pp f "~%s" lbl
else
pp f "~%s:%a" lbl (simple_expr ctxt) e
and directive_argument f x =
match x.pdira_desc with
| Pdir_string (s) -> pp f "@ %S" s
| Pdir_int (n, None) -> pp f "@ %s" n
| Pdir_int (n, Some m) -> pp f "@ %s%c" n m
| Pdir_ident (li) -> pp f "@ %a" longident li
| Pdir_bool (b) -> pp f "@ %s" (string_of_bool b)
let toplevel_phrase f x =
match x with
| Ptop_def (s) ->pp f "@[<hov0>%a@]" (list (structure_item reset_ctxt)) s
pp_close_box f ( ) ;
| Ptop_dir {pdir_name; pdir_arg = None; _} ->
pp f "@[<hov2>#%s@]" pdir_name.txt
| Ptop_dir {pdir_name; pdir_arg = Some pdir_arg; _} ->
pp f "@[<hov2>#%s@ %a@]" pdir_name.txt directive_argument pdir_arg
let expression f x =
pp f "@[%a@]" (expression reset_ctxt) x
let string_of_expression x =
ignore (flush_str_formatter ()) ;
let f = str_formatter in
expression f x;
flush_str_formatter ()
let string_of_structure x =
ignore (flush_str_formatter ());
let f = str_formatter in
structure reset_ctxt f x;
flush_str_formatter ()
let top_phrase f x =
pp_print_newline f ();
toplevel_phrase f x;
pp f ";;";
pp_print_newline f ()
let core_type = core_type reset_ctxt
let pattern = pattern reset_ctxt
let signature = signature reset_ctxt
let structure = structure reset_ctxt
let module_expr = module_expr reset_ctxt
let module_type = module_type reset_ctxt
let class_field = class_field reset_ctxt
let class_type_field = class_type_field reset_ctxt
let class_expr = class_expr reset_ctxt
let class_type = class_type reset_ctxt
let structure_item = structure_item reset_ctxt
let signature_item = signature_item reset_ctxt
let binding = binding reset_ctxt
let payload = payload reset_ctxt
|
36f5a7811a9986942b0fd56dfbfaeeb27fe2f472913cd477dc4cfce982907e28 | footprintanalytics/footprint-web | annotate_test.clj | (ns metabase.query-processor.middleware.annotate-test
(:require [clojure.test :refer :all]
[medley.core :as m]
[metabase.driver :as driver]
[metabase.models :refer [Card Field]]
[metabase.query-processor :as qp]
[metabase.query-processor.middleware.annotate :as annotate]
[metabase.query-processor.store :as qp.store]
[metabase.test :as mt]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(defn- add-column-info [query metadata]
(mt/with-everything-store
(driver/with-driver :h2
((annotate/add-column-info query identity) metadata))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | column-info (:native) |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest native-column-info-test
(testing "native column info"
(testing "should still infer types even if the initial value(s) are `nil` (#4256, #6924)"
(is (= [:type/Integer]
(transduce identity (#'annotate/base-type-inferer {:cols [{}]})
(concat (repeat 1000 [nil]) [[1] [2]])))))
(testing "should use default `base_type` of `type/*` if there are no non-nil values in the sample"
(is (= [:type/*]
(transduce identity (#'annotate/base-type-inferer {:cols [{}]})
[[nil]]))))
(testing "should attempt to infer better base type if driver returns :type/* (#12150)"
;; `merged-column-info` handles merging info returned by driver & inferred by annotate
(is (= [:type/Integer]
(transduce identity (#'annotate/base-type-inferer {:cols [{:base_type :type/*}]})
[[1] [2] [nil] [3]]))))
(testing "should disambiguate duplicate names"
(is (= [{:name "a", :display_name "a", :base_type :type/Integer, :source :native, :field_ref [:field "a" {:base-type :type/Integer}]}
{:name "a", :display_name "a", :base_type :type/Integer, :source :native, :field_ref [:field "a_2" {:base-type :type/Integer}]}]
(annotate/column-info
{:type :native}
{:cols [{:name "a" :base_type :type/Integer} {:name "a" :base_type :type/Integer}]
:rows [[1 nil]]}))))))
;;; +----------------------------------------------------------------------------------------------------------------+
| ( MBQL ) Col info for Field clauses |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- info-for-field
([field-id]
(into {} (db/select-one (into [Field] (disj (set @#'qp.store/field-columns-to-fetch) :database_type))
:id field-id)))
([table-key field-key]
(info-for-field (mt/id table-key field-key))))
(deftest col-info-field-ids-test
(testing {:base-type "make sure columns are comming back the way we'd expect for :field clauses"}
(mt/with-everything-store
(mt/$ids venues
(is (= [(merge (info-for-field :venues :price)
{:source :fields
:field_ref $price})]
(doall
(annotate/column-info
{:type :query, :query {:fields [$price]}}
{:columns [:price]}))))))))
(deftest col-info-for-fks-and-joins-test
(mt/with-everything-store
(mt/$ids venues
(testing (str "when a `:field` with `:source-field` (implicit join) is used, we should add in `:fk_field_id` "
"info about the source Field")
(is (= [(merge (info-for-field :categories :name)
{:fk_field_id %category_id
:source :fields
:field_ref $category_id->categories.name})]
(doall
(annotate/column-info
{:type :query, :query {:fields [$category_id->categories.name]}}
{:columns [:name]})))))
(testing "joins"
(testing (str "we should get `:fk_field_id` and information where possible when using joins; "
"display_name should include the display name of the FK field (for IMPLICIT JOINS)")
(is (= [(merge (info-for-field :categories :name)
{:display_name "Category → Name"
:source :fields
:field_ref $category_id->categories.name
:fk_field_id %category_id
:source_alias "CATEGORIES__via__CATEGORY_ID"})]
(doall
(annotate/column-info
{:type :query
:query {:fields [&CATEGORIES__via__CATEGORY_ID.categories.name]
:joins [{:alias "CATEGORIES__via__CATEGORY_ID"
:source-table $$venues
:condition [:= $category_id &CATEGORIES__via__CATEGORY_ID.categories.id]
:strategy :left-join
:fk-field-id %category_id}]}}
{:columns [:name]})))))
(testing (str "for EXPLICIT JOINS (which do not include an `:fk-field-id` in the Join info) the returned "
"`:field_ref` should be have only `:join-alias`, and no `:source-field`")
(is (= [(merge (info-for-field :categories :name)
{:display_name "Categories → Name"
:source :fields
:field_ref &Categories.categories.name
:source_alias "Categories"})]
(doall
(annotate/column-info
{:type :query
:query {:fields [&Categories.categories.name]
:joins [{:alias "Categories"
:source-table $$venues
:condition [:= $category_id &Categories.categories.id]
:strategy :left-join}]}}
{:columns [:name]})))))))))
(deftest col-info-for-field-with-temporal-unit-test
(mt/with-everything-store
(mt/$ids venues
(testing "when a `:field` with `:temporal-unit` is used, we should add in info about the `:unit`"
(is (= [(merge (info-for-field :venues :price)
{:unit :month
:source :fields
:field_ref !month.price})]
(doall
(annotate/column-info
{:type :query, :query {:fields (mt/$ids venues [!month.price])}}
{:columns [:price]})))))
(testing "datetime unit should work on field literals too"
(is (= [{:name "price"
:base_type :type/Number
:display_name "Price"
:unit :month
:source :fields
:field_ref !month.*price/Number}]
(doall
(annotate/column-info
{:type :query, :query {:fields [[:field "price" {:base-type :type/Number, :temporal-unit :month}]]}}
{:columns [:price]}))))))
(testing "should add the correct info if the Field originally comes from a nested query"
(mt/$ids checkins
(is (= [{:name "DATE", :unit :month, :field_ref [:field %date {:temporal-unit :default}]}
{:name "LAST_LOGIN", :unit :month, :field_ref [:field
%users.last_login
{:temporal-unit :default
:join-alias "USERS__via__USER_ID"}]}]
(mapv
(fn [col]
(select-keys col [:name :unit :field_ref]))
(annotate/column-info
{:type :query
:query {:source-query {:source-table $$checkins
:breakout [[:field %date {:temporal-unit :month}]
[:field
%users.last_login
{:temporal-unit :month, :source-field %user_id}]]}
:source-metadata [{:name "DATE"
:id %date
:unit :month
:field_ref [:field %date {:temporal-unit :month}]}
{:name "LAST_LOGIN"
:id %users.last_login
:unit :month
:field_ref [:field %users.last_login {:temporal-unit :month
:source-field %user_id}]}]
:fields [[:field %date {:temporal-unit :default}]
[:field %users.last_login {:temporal-unit :default, :join-alias "USERS__via__USER_ID"}]]
:limit 1}}
nil))))))))
(deftest col-info-for-binning-strategy-test
(testing "when binning strategy is used, include `:binning_info`"
(is (= [{:name "price"
:base_type :type/Number
:display_name "Price"
:unit :month
:source :fields
:binning_info {:num_bins 10, :bin_width 5, :min_value -100, :max_value 100, :binning_strategy :num-bins}
:field_ref [:field "price" {:base-type :type/Number
:temporal-unit :month
:binning {:strategy :num-bins
:num-bins 10
:bin-width 5
:min-value -100
:max-value 100}}]}]
(doall
(annotate/column-info
{:type :query
:query {:fields [[:field "price" {:base-type :type/Number
:temporal-unit :month
:binning {:strategy :num-bins
:num-bins 10
:bin-width 5
:min-value -100
:max-value 100}}]]}}
{:columns [:price]}))))))
(deftest col-info-combine-parent-field-names-test
(testing "For fields with parents we should return them with a combined name including parent's name"
(tt/with-temp* [Field [parent {:name "parent", :table_id (mt/id :venues)}]
Field [child {:name "child", :table_id (mt/id :venues), :parent_id (u/the-id parent)}]]
(mt/with-everything-store
(is (= {:description nil
:table_id (mt/id :venues)
:semantic_type nil
:effective_type nil
these two are a gross symptom . there 's some tension . sometimes it makes sense to have an effective
;; type: the db type is different and we have a way to convert. Othertimes, it doesn't make sense:
;; when the info is inferred. the solution to this might be quite extensive renaming
:coercion_strategy nil
:name "parent.child"
:settings nil
:field_ref [:field (u/the-id child) nil]
:nfc_path nil
:parent_id (u/the-id parent)
:id (u/the-id child)
:visibility_type :normal
:display_name "Child"
:fingerprint nil
:base_type :type/Text}
(into {} (#'annotate/col-info-for-field-clause {} [:field (u/the-id child) nil])))))))
(testing "nested-nested fields should include grandparent name (etc)"
(tt/with-temp* [Field [grandparent {:name "grandparent", :table_id (mt/id :venues)}]
Field [parent {:name "parent", :table_id (mt/id :venues), :parent_id (u/the-id grandparent)}]
Field [child {:name "child", :table_id (mt/id :venues), :parent_id (u/the-id parent)}]]
(mt/with-everything-store
(is (= {:description nil
:table_id (mt/id :venues)
:semantic_type nil
:effective_type nil
:coercion_strategy nil
:name "grandparent.parent.child"
:settings nil
:field_ref [:field (u/the-id child) nil]
:nfc_path nil
:parent_id (u/the-id parent)
:id (u/the-id child)
:visibility_type :normal
:display_name "Child"
:fingerprint nil
:base_type :type/Text}
(into {} (#'annotate/col-info-for-field-clause {} [:field (u/the-id child) nil]))))))))
(deftest col-info-field-literals-test
(testing "field literals should get the information from the matching `:source-metadata` if it was supplied"
(mt/with-everything-store
(is (= {:name "sum"
:display_name "sum of User ID"
:base_type :type/Integer
:field_ref [:field "sum" {:base-type :type/Integer}]
:semantic_type :type/FK}
(#'annotate/col-info-for-field-clause
{:source-metadata
[{:name "abc", :display_name "another Field", :base_type :type/Integer, :semantic_type :type/FK}
{:name "sum", :display_name "sum of User ID", :base_type :type/Integer, :semantic_type :type/FK}]}
[:field "sum" {:base-type :type/Integer}]))))))
(deftest col-info-expressions-test
(mt/with-everything-store
(testing "col info for an `expression` should work as expected"
(is (= {:base_type :type/Float
:name "double-price"
:display_name "double-price"
:expression_name "double-price"
:field_ref [:expression "double-price"]}
(mt/$ids venues
(#'annotate/col-info-for-field-clause
{:expressions {"double-price" [:* $price 2]}}
[:expression "double-price"])))))
(testing "if there is no matching expression it should give a meaningful error message"
(is (= {:data {:expression-name "double-price"
:tried ["double-price" :double-price]
:found #{"one-hundred"}
:type :invalid-query}
:message "No expression named 'double-price'"}
(try
(mt/$ids venues
(#'annotate/col-info-for-field-clause {:expressions {"one-hundred" 100}} [:expression "double-price"]))
(catch Throwable e {:message (.getMessage e), :data (ex-data e)})))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | (MBQL) Col info for Aggregation clauses |
;;; +----------------------------------------------------------------------------------------------------------------+
;; test that added information about aggregations looks the way we'd expect
(defn- aggregation-names
([ag-clause]
(aggregation-names {} ag-clause))
([inner-query ag-clause]
(binding [driver/*driver* :h2]
(mt/with-everything-store
{:name (annotate/aggregation-name ag-clause)
:display_name (annotate/aggregation-display-name inner-query ag-clause)}))))
(deftest aggregation-names-test
(testing "basic aggregations"
(testing ":count"
(is (= {:name "count", :display_name "Count"}
(aggregation-names [:count]))))
(testing ":distinct"
(is (= {:name "count", :display_name "Distinct values of ID"}
(aggregation-names [:distinct [:field (mt/id :venues :id) nil]]))))
(testing ":sum"
(is (= {:name "sum", :display_name "Sum of ID"}
(aggregation-names [:sum [:field (mt/id :venues :id) nil]])))))
(testing "expressions"
(testing "simple expression"
(is (= {:name "expression", :display_name "Count + 1"}
(aggregation-names [:+ [:count] 1]))))
(testing "expression with nested expressions"
(is (= {:name "expression", :display_name "Min of ID + (2 * Average of Price)"}
(aggregation-names
[:+
[:min [:field (mt/id :venues :id) nil]]
[:* 2 [:avg [:field (mt/id :venues :price) nil]]]]))))
(testing "very complicated expression"
(is (= {:name "expression", :display_name "Min of ID + (2 * Average of Price * 3 * (Max of Category ID - 4))"}
(aggregation-names
[:+
[:min [:field (mt/id :venues :id) nil]]
[:*
2
[:avg [:field (mt/id :venues :price) nil]]
3
[:- [:max [:field (mt/id :venues :category_id) nil]] 4]]])))))
(testing "`aggregation-options`"
(testing "`:name` and `:display-name`"
(is (= {:name "generated_name", :display_name "User-specified Name"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:name "generated_name", :display-name "User-specified Name"}]))))
(testing "`:name` only"
(is (= {:name "generated_name", :display_name "Min of ID + (2 * Average of Price)"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:name "generated_name"}]))))
(testing "`:display-name` only"
(is (= {:name "expression", :display_name "User-specified Name"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:display-name "User-specified Name"}]))))))
(defn- col-info-for-aggregation-clause
([clause]
(col-info-for-aggregation-clause {} clause))
([inner-query clause]
(binding [driver/*driver* :h2]
(#'annotate/col-info-for-aggregation-clause inner-query clause))))
(deftest col-info-for-aggregation-clause-test
(mt/with-everything-store
(testing "basic aggregation clauses"
(testing "`:count` (no field)"
(is (= {:base_type :type/Float, :name "expression", :display_name "Count / 2"}
(col-info-for-aggregation-clause [:/ [:count] 2]))))
(testing "`:sum`"
(is (= {:base_type :type/Float, :name "sum", :display_name "Sum of Price + 1"}
(mt/$ids venues
(col-info-for-aggregation-clause [:sum [:+ $price 1]]))))))
(testing "`:aggregation-options`"
(testing "`:name` and `:display-name`"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum_2"
:display_name "My custom name"}
(mt/$ids venues
(col-info-for-aggregation-clause
[:aggregation-options [:sum $price] {:name "sum_2", :display-name "My custom name"}])))))
(testing "`:name` only"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum_2"
:display_name "Sum of Price"}
(mt/$ids venues
(col-info-for-aggregation-clause [:aggregation-options [:sum $price] {:name "sum_2"}])))))
(testing "`:display-name` only"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum"
:display_name "My Custom Name"}
(mt/$ids venues
(col-info-for-aggregation-clause
[:aggregation-options [:sum $price] {:display-name "My Custom Name"}]))))))
(testing (str "if a driver is kind enough to supply us with some information about the `:cols` that come back, we "
"should include that information in the results. Their information should be preferred over ours")
(is (= {:cols [{:name "metric"
:display_name "Total Events"
:base_type :type/Text
:effective_type :type/Text
:source :aggregation
:field_ref [:aggregation 0]}]}
(add-column-info
(mt/mbql-query venues {:aggregation [[:metric "ga:totalEvents"]]})
{:cols [{:name "totalEvents", :display_name "Total Events", :base_type :type/Text}]}))))
(testing "col info for an `expression` aggregation w/ a named expression should work as expected"
(is (= {:base_type :type/Float, :name "sum", :display_name "Sum of double-price"}
(mt/$ids venues
(col-info-for-aggregation-clause {:expressions {"double-price" [:* $price 2]}} [:sum [:expression "double-price"]])))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Other MBQL col info tests |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- infered-col-type
[expr]
(-> (add-column-info (mt/mbql-query venues {:expressions {"expr" expr}
:fields [[:expression "expr"]]
:limit 10})
{})
:cols
first
(select-keys [:base_type :semantic_type])))
(deftest computed-columns-inference
(letfn [(infer [expr] (-> (mt/mbql-query venues
{:expressions {"expr" expr}
:fields [[:expression "expr"]]
:limit 10})
(add-column-info {})
:cols
first))]
(testing "Coalesce"
(testing "Uses the first clause"
(testing "Gets the type information from the field"
(is (= {:semantic_type :type/Name,
:coercion_strategy nil,
:name "expr",
:expression_name "expr",
:source :fields,
:field_ref [:expression "expr"],
:effective_type :type/Text,
:display_name "expr",
:base_type :type/Text}
(infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])))
(testing "Does not contain a field id in its analysis (#18513)"
(is (false? (contains? (infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])
:id)))))
(testing "Gets the type information from the literal"
(is (= {:base_type :type/Text,
:name "expr",
:display_name "expr",
:expression_name "expr",
:field_ref [:expression "expr"],
:source :fields}
(infer [:coalesce "bar" [:field (mt/id :venues :name) nil]]))))))
(testing "Case"
(testing "Uses first available type information"
(testing "From a field"
(is (= {:semantic_type :type/Name,
:coercion_strategy nil,
:name "expr",
:expression_name "expr",
:source :fields,
:field_ref [:expression "expr"],
:effective_type :type/Text,
:display_name "expr",
:base_type :type/Text}
(infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])))
(testing "does not contain a field id in its analysis (#17512)"
(is (false?
(contains? (infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])
:id))))))
(is (= {:base_type :type/Text}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2] "big"]]])))
(is (= {:base_type :type/Float}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2]
[:+ [:field (mt/id :venues :price) nil] 1]]]])))
(testing "Make sure we skip nils when infering case return type"
(is (= {:base_type :type/Number}
(infered-col-type [:case [[[:< [:field (mt/id :venues :price) nil] 10] [:value nil {:base_type :type/Number}]]
[[:> [:field (mt/id :venues :price) nil] 2] 10]]]))))
(is (= {:base_type :type/Float}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2] [:+ [:field (mt/id :venues :price) nil] 1]]]]))))))
(deftest ^:parallel datetime-arithmetics?-test
(is (#'annotate/datetime-arithmetics? [:+ [:field (mt/id :checkins :date) nil] [:interval -1 :month]]))
(is (#'annotate/datetime-arithmetics? [:field (mt/id :checkins :date) {:temporal-unit :month}]))
(is (not (#'annotate/datetime-arithmetics? [:+ 1 [:temporal-extract
[:+ [:field (mt/id :checkins :date) nil] [:interval -1 :month]]
:year]])))
(is (not (#'annotate/datetime-arithmetics? [:+ [:field (mt/id :checkins :date) nil] 3]))))
(deftest temporal-extract-test
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :checkins :date) nil] 2 :month])))
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :checkins :date) nil] 2 :hour])))
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :users :last_login) nil] 2 :month]))))
(deftest test-string-extracts
(is (= {:base_type :type/Text}
(infered-col-type [:trim "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:ltrim "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:rtrim "foo"])))
(is (= {:base_type :type/BigInteger}
(infered-col-type [:length "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:upper "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:lower "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:substring "foo" 2])))
(is (= {:base_type :type/Text}
(infered-col-type [:replace "foo" "f" "b"])))
(is (= {:base_type :type/Text}
(infered-col-type [:regex-match-first "foo" "f"])))
(is (= {:base_type :type/Text}
(infered-col-type [:concat "foo" "bar"])))
(is (= {:base_type :type/Text}
(infered-col-type [:coalesce "foo" "bar"])))
(is (= {:base_type :type/Text
:semantic_type :type/Name}
(infered-col-type [:coalesce [:field (mt/id :venues :name) nil] "bar"]))))
(deftest unique-name-key-test
(testing "Make sure `:cols` always come back with a unique `:name` key (#8759)"
(is (= {:cols
[{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count"
:display_name "count"
:source :aggregation
:field_ref [:aggregation 0]}
{:source :aggregation
:name "sum"
:display_name "sum"
:base_type :type/Number
:effective_type :type/Number
:field_ref [:aggregation 1]}
{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count_2"
:display_name "count"
:source :aggregation
:field_ref [:aggregation 2]}
{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count_3"
:display_name "count_2"
:source :aggregation
:field_ref [:aggregation 3]}]}
(add-column-info
(mt/mbql-query venues
{:aggregation [[:count]
[:sum]
[:count]
[:aggregation-options [:count] {:display-name "count_2"}]]})
{:cols [{:name "count", :display_name "count", :base_type :type/Number}
{:name "sum", :display_name "sum", :base_type :type/Number}
{:name "count", :display_name "count", :base_type :type/Number}
{:name "count_2", :display_name "count_2", :base_type :type/Number}]})))))
(deftest expressions-keys-test
(testing "make sure expressions come back with the right set of keys, including `:expression_name` (#8854)"
(is (= {:name "discount_price"
:display_name "discount_price"
:base_type :type/Float
:expression_name "discount_price"
:source :fields
:field_ref [:expression "discount_price"]}
(-> (add-column-info
(mt/mbql-query venues
{:expressions {"discount_price" [:* 0.9 $price]}
:fields [$name [:expression "discount_price"]]
:limit 10})
{})
:cols
second)))))
(deftest deduplicate-expression-names-test
(testing "make sure multiple expressions come back with deduplicated names"
(testing "expressions in aggregations"
(is (= [{:base_type :type/Float, :name "expression", :display_name "0.9 * Average of Price", :source :aggregation, :field_ref [:aggregation 0]}
{:base_type :type/Float, :name "expression_2", :display_name "0.8 * Average of Price", :source :aggregation, :field_ref [:aggregation 1]}]
(:cols (add-column-info
(mt/mbql-query venues
{:aggregation [[:* 0.9 [:avg $price]] [:* 0.8 [:avg $price]]]
:limit 10})
{})))))
(testing "named :expressions"
(is (= [{:name "prev_month", :display_name "prev_month", :base_type :type/DateTime, :expression_name "prev_month", :source :fields, :field_ref [:expression "prev_month"]}]
(:cols (add-column-info
(mt/mbql-query users
{:expressions {:prev_month [:+ $last_login [:interval -1 :month]]}
:fields [[:expression "prev_month"]], :limit 10})
{})))))))
(deftest mbql-cols-nested-queries-test
(testing "Should be able to infer MBQL columns with nested queries"
(let [base-query (qp/preprocess
(mt/mbql-query venues
{:joins [{:fields :all
:source-table $$categories
:condition [:= $category_id &c.categories.id]
:alias "c"}]}))]
(doseq [level [0 1 2 3]]
(testing (format "%d level(s) of nesting" level)
(let [nested-query (mt/nest-query base-query level)]
(testing (format "\nQuery = %s" (u/pprint-to-str nested-query))
(is (= (mt/$ids venues
[{:name "ID", :id %id, :field_ref $id}
{:name "NAME", :id %name, :field_ref $name}
{:name "CATEGORY_ID", :id %category_id, :field_ref $category_id}
{:name "LATITUDE", :id %latitude, :field_ref $latitude}
{:name "LONGITUDE", :id %longitude, :field_ref $longitude}
{:name "PRICE", :id %price, :field_ref $price}
{:name "ID_2", :id %categories.id, :field_ref &c.categories.id}
{:name "NAME_2", :id %categories.name, :field_ref &c.categories.name}])
(map #(select-keys % [:name :id :field_ref])
(:cols (add-column-info nested-query {})))))))))))
(testing "Aggregated question with source is an aggregated models should infer display_name correctly (#23248)"
(mt/dataset sample-dataset
(mt/with-temp* [Card [{card-id :id}
{:dataset true
:dataset_query
(mt/$ids :products
{:type :query
:database (mt/id)
:query {:source-table $$products
:aggregation
[[:aggregation-options
[:sum $price]
{:name "sum"}]
[:aggregation-options
[:max $rating]
{:name "max"}]]
:breakout $category
:order-by [[:asc $category]]}})}]]
(let [query (qp/preprocess
(mt/mbql-query nil
{:source-table (str "card__" card-id)
:aggregation [[:aggregation-options
[:sum
[:field
"sum"
{:base-type :type/Float}]]
{:name "sum"}]
[:aggregation-options
[:count]
{:name "count"}]]
:limit 1}))]
(is (= ["Sum of Sum of Price" "Count"]
(->> (add-column-info query {})
:cols
(map :display_name)))))))))
(deftest inception-test
(testing "Should return correct metadata for an 'inception-style' nesting of source > source > source with a join (#14745)"
(mt/dataset sample-dataset
these tests look at the metadata for just one column so it 's easier to spot the differences .
(letfn [(ean-metadata [result]
(as-> (:cols result) result
(m/index-by :name result)
(get result "EAN")
(select-keys result [:name :display_name :base_type :semantic_type :id :field_ref])))]
(testing "Make sure metadata is correct for the 'EAN' column with"
(let [base-query (qp/preprocess
(mt/mbql-query orders
{:joins [{:fields :all
:source-table $$products
:condition [:= $product_id &Products.products.id]
:alias "Products"}]
:limit 10}))]
(doseq [level (range 4)]
(testing (format "%d level(s) of nesting" level)
(let [nested-query (mt/nest-query base-query level)]
(testing (format "\nQuery = %s" (u/pprint-to-str nested-query))
(is (= (mt/$ids products
{:name "EAN"
:display_name "Products → Ean"
:base_type :type/Text
:semantic_type nil
:id %ean
:field_ref &Products.ean})
(ean-metadata (add-column-info nested-query {}))))))))))))))
;; metabase#14787
(deftest col-info-for-fields-from-card-test
(mt/dataset sample-dataset
(let [card-1-query (mt/mbql-query orders
{:joins [{:fields :all
:source-table $$products
:condition [:= $product_id &Products.products.id]
:alias "Products"}]})]
(mt/with-temp* [Card [{card-1-id :id} {:dataset_query card-1-query}]
Card [{card-2-id :id} {:dataset_query (mt/mbql-query people)}]]
(testing "when a nested query is from a saved question, there should be no `:join-alias` on the left side"
(mt/$ids nil
(let [base-query (qp/preprocess
(mt/mbql-query nil
{:source-table (str "card__" card-1-id)
:joins [{:fields :all
:source-table (str "card__" card-2-id)
:condition [:= $orders.user_id &Products.products.id]
:alias "Q"}]
:limit 1}))
fields #{%orders.discount %products.title %people.source}]
(is (= [{:display_name "Discount" :field_ref [:field %orders.discount nil]}
{:display_name "Products → Title" :field_ref [:field %products.title nil]}
{:display_name "Q → Source" :field_ref [:field %people.source {:join-alias "Q"}]}]
(->> (:cols (add-column-info base-query {}))
(filter #(fields (:id %)))
(map #(select-keys % [:display_name :field_ref])))))))))))
(testing "Has the correct display names for joined fields from cards"
(letfn [(native [query] {:type :native
:native {:query query :template-tags {}}
:database (mt/id)})]
(mt/with-temp* [Card [{card1-id :id} {:dataset_query
(native "select 'foo' as A_COLUMN")}]
Card [{card2-id :id} {:dataset_query
(native "select 'foo' as B_COLUMN")}]]
(doseq [card-id [card1-id card2-id]]
;; populate metadata
(mt/user-http-request :rasta :post 202 (format "card/%d/query" card-id)))
(let [query {:database (mt/id)
:type :query
:query {:source-table (str "card__" card1-id)
:joins [{:fields "all"
:source-table (str "card__" card2-id)
:condition [:=
[:field "A_COLUMN" {:base-type :type/Text}]
[:field "B_COLUMN" {:base-type :type/Text
:join-alias "alias"}]]
:alias "alias"}]}}
results (qp/process-query query)]
(is (= "alias → B Column" (-> results :data :cols second :display_name))
"cols has wrong display name")
(is (= "alias → B Column" (-> results :data :results_metadata
:columns second :display_name))
"Results metadata cols has wrong display name"))))))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/query_processor/middleware/annotate_test.clj | clojure | +----------------------------------------------------------------------------------------------------------------+
| column-info (:native) |
+----------------------------------------------------------------------------------------------------------------+
`merged-column-info` handles merging info returned by driver & inferred by annotate
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+
type: the db type is different and we have a way to convert. Othertimes, it doesn't make sense:
when the info is inferred. the solution to this might be quite extensive renaming
+----------------------------------------------------------------------------------------------------------------+
| (MBQL) Col info for Aggregation clauses |
+----------------------------------------------------------------------------------------------------------------+
test that added information about aggregations looks the way we'd expect
+----------------------------------------------------------------------------------------------------------------+
| Other MBQL col info tests |
+----------------------------------------------------------------------------------------------------------------+
metabase#14787
populate metadata | (ns metabase.query-processor.middleware.annotate-test
(:require [clojure.test :refer :all]
[medley.core :as m]
[metabase.driver :as driver]
[metabase.models :refer [Card Field]]
[metabase.query-processor :as qp]
[metabase.query-processor.middleware.annotate :as annotate]
[metabase.query-processor.store :as qp.store]
[metabase.test :as mt]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(defn- add-column-info [query metadata]
(mt/with-everything-store
(driver/with-driver :h2
((annotate/add-column-info query identity) metadata))))
(deftest native-column-info-test
(testing "native column info"
(testing "should still infer types even if the initial value(s) are `nil` (#4256, #6924)"
(is (= [:type/Integer]
(transduce identity (#'annotate/base-type-inferer {:cols [{}]})
(concat (repeat 1000 [nil]) [[1] [2]])))))
(testing "should use default `base_type` of `type/*` if there are no non-nil values in the sample"
(is (= [:type/*]
(transduce identity (#'annotate/base-type-inferer {:cols [{}]})
[[nil]]))))
(testing "should attempt to infer better base type if driver returns :type/* (#12150)"
(is (= [:type/Integer]
(transduce identity (#'annotate/base-type-inferer {:cols [{:base_type :type/*}]})
[[1] [2] [nil] [3]]))))
(testing "should disambiguate duplicate names"
(is (= [{:name "a", :display_name "a", :base_type :type/Integer, :source :native, :field_ref [:field "a" {:base-type :type/Integer}]}
{:name "a", :display_name "a", :base_type :type/Integer, :source :native, :field_ref [:field "a_2" {:base-type :type/Integer}]}]
(annotate/column-info
{:type :native}
{:cols [{:name "a" :base_type :type/Integer} {:name "a" :base_type :type/Integer}]
:rows [[1 nil]]}))))))
| ( MBQL ) Col info for Field clauses |
(defn- info-for-field
([field-id]
(into {} (db/select-one (into [Field] (disj (set @#'qp.store/field-columns-to-fetch) :database_type))
:id field-id)))
([table-key field-key]
(info-for-field (mt/id table-key field-key))))
(deftest col-info-field-ids-test
(testing {:base-type "make sure columns are comming back the way we'd expect for :field clauses"}
(mt/with-everything-store
(mt/$ids venues
(is (= [(merge (info-for-field :venues :price)
{:source :fields
:field_ref $price})]
(doall
(annotate/column-info
{:type :query, :query {:fields [$price]}}
{:columns [:price]}))))))))
(deftest col-info-for-fks-and-joins-test
(mt/with-everything-store
(mt/$ids venues
(testing (str "when a `:field` with `:source-field` (implicit join) is used, we should add in `:fk_field_id` "
"info about the source Field")
(is (= [(merge (info-for-field :categories :name)
{:fk_field_id %category_id
:source :fields
:field_ref $category_id->categories.name})]
(doall
(annotate/column-info
{:type :query, :query {:fields [$category_id->categories.name]}}
{:columns [:name]})))))
(testing "joins"
(testing (str "we should get `:fk_field_id` and information where possible when using joins; "
"display_name should include the display name of the FK field (for IMPLICIT JOINS)")
(is (= [(merge (info-for-field :categories :name)
{:display_name "Category → Name"
:source :fields
:field_ref $category_id->categories.name
:fk_field_id %category_id
:source_alias "CATEGORIES__via__CATEGORY_ID"})]
(doall
(annotate/column-info
{:type :query
:query {:fields [&CATEGORIES__via__CATEGORY_ID.categories.name]
:joins [{:alias "CATEGORIES__via__CATEGORY_ID"
:source-table $$venues
:condition [:= $category_id &CATEGORIES__via__CATEGORY_ID.categories.id]
:strategy :left-join
:fk-field-id %category_id}]}}
{:columns [:name]})))))
(testing (str "for EXPLICIT JOINS (which do not include an `:fk-field-id` in the Join info) the returned "
"`:field_ref` should be have only `:join-alias`, and no `:source-field`")
(is (= [(merge (info-for-field :categories :name)
{:display_name "Categories → Name"
:source :fields
:field_ref &Categories.categories.name
:source_alias "Categories"})]
(doall
(annotate/column-info
{:type :query
:query {:fields [&Categories.categories.name]
:joins [{:alias "Categories"
:source-table $$venues
:condition [:= $category_id &Categories.categories.id]
:strategy :left-join}]}}
{:columns [:name]})))))))))
(deftest col-info-for-field-with-temporal-unit-test
(mt/with-everything-store
(mt/$ids venues
(testing "when a `:field` with `:temporal-unit` is used, we should add in info about the `:unit`"
(is (= [(merge (info-for-field :venues :price)
{:unit :month
:source :fields
:field_ref !month.price})]
(doall
(annotate/column-info
{:type :query, :query {:fields (mt/$ids venues [!month.price])}}
{:columns [:price]})))))
(testing "datetime unit should work on field literals too"
(is (= [{:name "price"
:base_type :type/Number
:display_name "Price"
:unit :month
:source :fields
:field_ref !month.*price/Number}]
(doall
(annotate/column-info
{:type :query, :query {:fields [[:field "price" {:base-type :type/Number, :temporal-unit :month}]]}}
{:columns [:price]}))))))
(testing "should add the correct info if the Field originally comes from a nested query"
(mt/$ids checkins
(is (= [{:name "DATE", :unit :month, :field_ref [:field %date {:temporal-unit :default}]}
{:name "LAST_LOGIN", :unit :month, :field_ref [:field
%users.last_login
{:temporal-unit :default
:join-alias "USERS__via__USER_ID"}]}]
(mapv
(fn [col]
(select-keys col [:name :unit :field_ref]))
(annotate/column-info
{:type :query
:query {:source-query {:source-table $$checkins
:breakout [[:field %date {:temporal-unit :month}]
[:field
%users.last_login
{:temporal-unit :month, :source-field %user_id}]]}
:source-metadata [{:name "DATE"
:id %date
:unit :month
:field_ref [:field %date {:temporal-unit :month}]}
{:name "LAST_LOGIN"
:id %users.last_login
:unit :month
:field_ref [:field %users.last_login {:temporal-unit :month
:source-field %user_id}]}]
:fields [[:field %date {:temporal-unit :default}]
[:field %users.last_login {:temporal-unit :default, :join-alias "USERS__via__USER_ID"}]]
:limit 1}}
nil))))))))
(deftest col-info-for-binning-strategy-test
(testing "when binning strategy is used, include `:binning_info`"
(is (= [{:name "price"
:base_type :type/Number
:display_name "Price"
:unit :month
:source :fields
:binning_info {:num_bins 10, :bin_width 5, :min_value -100, :max_value 100, :binning_strategy :num-bins}
:field_ref [:field "price" {:base-type :type/Number
:temporal-unit :month
:binning {:strategy :num-bins
:num-bins 10
:bin-width 5
:min-value -100
:max-value 100}}]}]
(doall
(annotate/column-info
{:type :query
:query {:fields [[:field "price" {:base-type :type/Number
:temporal-unit :month
:binning {:strategy :num-bins
:num-bins 10
:bin-width 5
:min-value -100
:max-value 100}}]]}}
{:columns [:price]}))))))
(deftest col-info-combine-parent-field-names-test
(testing "For fields with parents we should return them with a combined name including parent's name"
(tt/with-temp* [Field [parent {:name "parent", :table_id (mt/id :venues)}]
Field [child {:name "child", :table_id (mt/id :venues), :parent_id (u/the-id parent)}]]
(mt/with-everything-store
(is (= {:description nil
:table_id (mt/id :venues)
:semantic_type nil
:effective_type nil
these two are a gross symptom . there 's some tension . sometimes it makes sense to have an effective
:coercion_strategy nil
:name "parent.child"
:settings nil
:field_ref [:field (u/the-id child) nil]
:nfc_path nil
:parent_id (u/the-id parent)
:id (u/the-id child)
:visibility_type :normal
:display_name "Child"
:fingerprint nil
:base_type :type/Text}
(into {} (#'annotate/col-info-for-field-clause {} [:field (u/the-id child) nil])))))))
(testing "nested-nested fields should include grandparent name (etc)"
(tt/with-temp* [Field [grandparent {:name "grandparent", :table_id (mt/id :venues)}]
Field [parent {:name "parent", :table_id (mt/id :venues), :parent_id (u/the-id grandparent)}]
Field [child {:name "child", :table_id (mt/id :venues), :parent_id (u/the-id parent)}]]
(mt/with-everything-store
(is (= {:description nil
:table_id (mt/id :venues)
:semantic_type nil
:effective_type nil
:coercion_strategy nil
:name "grandparent.parent.child"
:settings nil
:field_ref [:field (u/the-id child) nil]
:nfc_path nil
:parent_id (u/the-id parent)
:id (u/the-id child)
:visibility_type :normal
:display_name "Child"
:fingerprint nil
:base_type :type/Text}
(into {} (#'annotate/col-info-for-field-clause {} [:field (u/the-id child) nil]))))))))
(deftest col-info-field-literals-test
(testing "field literals should get the information from the matching `:source-metadata` if it was supplied"
(mt/with-everything-store
(is (= {:name "sum"
:display_name "sum of User ID"
:base_type :type/Integer
:field_ref [:field "sum" {:base-type :type/Integer}]
:semantic_type :type/FK}
(#'annotate/col-info-for-field-clause
{:source-metadata
[{:name "abc", :display_name "another Field", :base_type :type/Integer, :semantic_type :type/FK}
{:name "sum", :display_name "sum of User ID", :base_type :type/Integer, :semantic_type :type/FK}]}
[:field "sum" {:base-type :type/Integer}]))))))
(deftest col-info-expressions-test
(mt/with-everything-store
(testing "col info for an `expression` should work as expected"
(is (= {:base_type :type/Float
:name "double-price"
:display_name "double-price"
:expression_name "double-price"
:field_ref [:expression "double-price"]}
(mt/$ids venues
(#'annotate/col-info-for-field-clause
{:expressions {"double-price" [:* $price 2]}}
[:expression "double-price"])))))
(testing "if there is no matching expression it should give a meaningful error message"
(is (= {:data {:expression-name "double-price"
:tried ["double-price" :double-price]
:found #{"one-hundred"}
:type :invalid-query}
:message "No expression named 'double-price'"}
(try
(mt/$ids venues
(#'annotate/col-info-for-field-clause {:expressions {"one-hundred" 100}} [:expression "double-price"]))
(catch Throwable e {:message (.getMessage e), :data (ex-data e)})))))))
(defn- aggregation-names
([ag-clause]
(aggregation-names {} ag-clause))
([inner-query ag-clause]
(binding [driver/*driver* :h2]
(mt/with-everything-store
{:name (annotate/aggregation-name ag-clause)
:display_name (annotate/aggregation-display-name inner-query ag-clause)}))))
(deftest aggregation-names-test
(testing "basic aggregations"
(testing ":count"
(is (= {:name "count", :display_name "Count"}
(aggregation-names [:count]))))
(testing ":distinct"
(is (= {:name "count", :display_name "Distinct values of ID"}
(aggregation-names [:distinct [:field (mt/id :venues :id) nil]]))))
(testing ":sum"
(is (= {:name "sum", :display_name "Sum of ID"}
(aggregation-names [:sum [:field (mt/id :venues :id) nil]])))))
(testing "expressions"
(testing "simple expression"
(is (= {:name "expression", :display_name "Count + 1"}
(aggregation-names [:+ [:count] 1]))))
(testing "expression with nested expressions"
(is (= {:name "expression", :display_name "Min of ID + (2 * Average of Price)"}
(aggregation-names
[:+
[:min [:field (mt/id :venues :id) nil]]
[:* 2 [:avg [:field (mt/id :venues :price) nil]]]]))))
(testing "very complicated expression"
(is (= {:name "expression", :display_name "Min of ID + (2 * Average of Price * 3 * (Max of Category ID - 4))"}
(aggregation-names
[:+
[:min [:field (mt/id :venues :id) nil]]
[:*
2
[:avg [:field (mt/id :venues :price) nil]]
3
[:- [:max [:field (mt/id :venues :category_id) nil]] 4]]])))))
(testing "`aggregation-options`"
(testing "`:name` and `:display-name`"
(is (= {:name "generated_name", :display_name "User-specified Name"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:name "generated_name", :display-name "User-specified Name"}]))))
(testing "`:name` only"
(is (= {:name "generated_name", :display_name "Min of ID + (2 * Average of Price)"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:name "generated_name"}]))))
(testing "`:display-name` only"
(is (= {:name "expression", :display_name "User-specified Name"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:display-name "User-specified Name"}]))))))
(defn- col-info-for-aggregation-clause
([clause]
(col-info-for-aggregation-clause {} clause))
([inner-query clause]
(binding [driver/*driver* :h2]
(#'annotate/col-info-for-aggregation-clause inner-query clause))))
(deftest col-info-for-aggregation-clause-test
(mt/with-everything-store
(testing "basic aggregation clauses"
(testing "`:count` (no field)"
(is (= {:base_type :type/Float, :name "expression", :display_name "Count / 2"}
(col-info-for-aggregation-clause [:/ [:count] 2]))))
(testing "`:sum`"
(is (= {:base_type :type/Float, :name "sum", :display_name "Sum of Price + 1"}
(mt/$ids venues
(col-info-for-aggregation-clause [:sum [:+ $price 1]]))))))
(testing "`:aggregation-options`"
(testing "`:name` and `:display-name`"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum_2"
:display_name "My custom name"}
(mt/$ids venues
(col-info-for-aggregation-clause
[:aggregation-options [:sum $price] {:name "sum_2", :display-name "My custom name"}])))))
(testing "`:name` only"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum_2"
:display_name "Sum of Price"}
(mt/$ids venues
(col-info-for-aggregation-clause [:aggregation-options [:sum $price] {:name "sum_2"}])))))
(testing "`:display-name` only"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum"
:display_name "My Custom Name"}
(mt/$ids venues
(col-info-for-aggregation-clause
[:aggregation-options [:sum $price] {:display-name "My Custom Name"}]))))))
(testing (str "if a driver is kind enough to supply us with some information about the `:cols` that come back, we "
"should include that information in the results. Their information should be preferred over ours")
(is (= {:cols [{:name "metric"
:display_name "Total Events"
:base_type :type/Text
:effective_type :type/Text
:source :aggregation
:field_ref [:aggregation 0]}]}
(add-column-info
(mt/mbql-query venues {:aggregation [[:metric "ga:totalEvents"]]})
{:cols [{:name "totalEvents", :display_name "Total Events", :base_type :type/Text}]}))))
(testing "col info for an `expression` aggregation w/ a named expression should work as expected"
(is (= {:base_type :type/Float, :name "sum", :display_name "Sum of double-price"}
(mt/$ids venues
(col-info-for-aggregation-clause {:expressions {"double-price" [:* $price 2]}} [:sum [:expression "double-price"]])))))))
(defn- infered-col-type
[expr]
(-> (add-column-info (mt/mbql-query venues {:expressions {"expr" expr}
:fields [[:expression "expr"]]
:limit 10})
{})
:cols
first
(select-keys [:base_type :semantic_type])))
(deftest computed-columns-inference
(letfn [(infer [expr] (-> (mt/mbql-query venues
{:expressions {"expr" expr}
:fields [[:expression "expr"]]
:limit 10})
(add-column-info {})
:cols
first))]
(testing "Coalesce"
(testing "Uses the first clause"
(testing "Gets the type information from the field"
(is (= {:semantic_type :type/Name,
:coercion_strategy nil,
:name "expr",
:expression_name "expr",
:source :fields,
:field_ref [:expression "expr"],
:effective_type :type/Text,
:display_name "expr",
:base_type :type/Text}
(infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])))
(testing "Does not contain a field id in its analysis (#18513)"
(is (false? (contains? (infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])
:id)))))
(testing "Gets the type information from the literal"
(is (= {:base_type :type/Text,
:name "expr",
:display_name "expr",
:expression_name "expr",
:field_ref [:expression "expr"],
:source :fields}
(infer [:coalesce "bar" [:field (mt/id :venues :name) nil]]))))))
(testing "Case"
(testing "Uses first available type information"
(testing "From a field"
(is (= {:semantic_type :type/Name,
:coercion_strategy nil,
:name "expr",
:expression_name "expr",
:source :fields,
:field_ref [:expression "expr"],
:effective_type :type/Text,
:display_name "expr",
:base_type :type/Text}
(infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])))
(testing "does not contain a field id in its analysis (#17512)"
(is (false?
(contains? (infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])
:id))))))
(is (= {:base_type :type/Text}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2] "big"]]])))
(is (= {:base_type :type/Float}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2]
[:+ [:field (mt/id :venues :price) nil] 1]]]])))
(testing "Make sure we skip nils when infering case return type"
(is (= {:base_type :type/Number}
(infered-col-type [:case [[[:< [:field (mt/id :venues :price) nil] 10] [:value nil {:base_type :type/Number}]]
[[:> [:field (mt/id :venues :price) nil] 2] 10]]]))))
(is (= {:base_type :type/Float}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2] [:+ [:field (mt/id :venues :price) nil] 1]]]]))))))
(deftest ^:parallel datetime-arithmetics?-test
(is (#'annotate/datetime-arithmetics? [:+ [:field (mt/id :checkins :date) nil] [:interval -1 :month]]))
(is (#'annotate/datetime-arithmetics? [:field (mt/id :checkins :date) {:temporal-unit :month}]))
(is (not (#'annotate/datetime-arithmetics? [:+ 1 [:temporal-extract
[:+ [:field (mt/id :checkins :date) nil] [:interval -1 :month]]
:year]])))
(is (not (#'annotate/datetime-arithmetics? [:+ [:field (mt/id :checkins :date) nil] 3]))))
(deftest temporal-extract-test
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :checkins :date) nil] 2 :month])))
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :checkins :date) nil] 2 :hour])))
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :users :last_login) nil] 2 :month]))))
(deftest test-string-extracts
(is (= {:base_type :type/Text}
(infered-col-type [:trim "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:ltrim "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:rtrim "foo"])))
(is (= {:base_type :type/BigInteger}
(infered-col-type [:length "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:upper "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:lower "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:substring "foo" 2])))
(is (= {:base_type :type/Text}
(infered-col-type [:replace "foo" "f" "b"])))
(is (= {:base_type :type/Text}
(infered-col-type [:regex-match-first "foo" "f"])))
(is (= {:base_type :type/Text}
(infered-col-type [:concat "foo" "bar"])))
(is (= {:base_type :type/Text}
(infered-col-type [:coalesce "foo" "bar"])))
(is (= {:base_type :type/Text
:semantic_type :type/Name}
(infered-col-type [:coalesce [:field (mt/id :venues :name) nil] "bar"]))))
(deftest unique-name-key-test
(testing "Make sure `:cols` always come back with a unique `:name` key (#8759)"
(is (= {:cols
[{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count"
:display_name "count"
:source :aggregation
:field_ref [:aggregation 0]}
{:source :aggregation
:name "sum"
:display_name "sum"
:base_type :type/Number
:effective_type :type/Number
:field_ref [:aggregation 1]}
{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count_2"
:display_name "count"
:source :aggregation
:field_ref [:aggregation 2]}
{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count_3"
:display_name "count_2"
:source :aggregation
:field_ref [:aggregation 3]}]}
(add-column-info
(mt/mbql-query venues
{:aggregation [[:count]
[:sum]
[:count]
[:aggregation-options [:count] {:display-name "count_2"}]]})
{:cols [{:name "count", :display_name "count", :base_type :type/Number}
{:name "sum", :display_name "sum", :base_type :type/Number}
{:name "count", :display_name "count", :base_type :type/Number}
{:name "count_2", :display_name "count_2", :base_type :type/Number}]})))))
(deftest expressions-keys-test
(testing "make sure expressions come back with the right set of keys, including `:expression_name` (#8854)"
(is (= {:name "discount_price"
:display_name "discount_price"
:base_type :type/Float
:expression_name "discount_price"
:source :fields
:field_ref [:expression "discount_price"]}
(-> (add-column-info
(mt/mbql-query venues
{:expressions {"discount_price" [:* 0.9 $price]}
:fields [$name [:expression "discount_price"]]
:limit 10})
{})
:cols
second)))))
(deftest deduplicate-expression-names-test
(testing "make sure multiple expressions come back with deduplicated names"
(testing "expressions in aggregations"
(is (= [{:base_type :type/Float, :name "expression", :display_name "0.9 * Average of Price", :source :aggregation, :field_ref [:aggregation 0]}
{:base_type :type/Float, :name "expression_2", :display_name "0.8 * Average of Price", :source :aggregation, :field_ref [:aggregation 1]}]
(:cols (add-column-info
(mt/mbql-query venues
{:aggregation [[:* 0.9 [:avg $price]] [:* 0.8 [:avg $price]]]
:limit 10})
{})))))
(testing "named :expressions"
(is (= [{:name "prev_month", :display_name "prev_month", :base_type :type/DateTime, :expression_name "prev_month", :source :fields, :field_ref [:expression "prev_month"]}]
(:cols (add-column-info
(mt/mbql-query users
{:expressions {:prev_month [:+ $last_login [:interval -1 :month]]}
:fields [[:expression "prev_month"]], :limit 10})
{})))))))
(deftest mbql-cols-nested-queries-test
(testing "Should be able to infer MBQL columns with nested queries"
(let [base-query (qp/preprocess
(mt/mbql-query venues
{:joins [{:fields :all
:source-table $$categories
:condition [:= $category_id &c.categories.id]
:alias "c"}]}))]
(doseq [level [0 1 2 3]]
(testing (format "%d level(s) of nesting" level)
(let [nested-query (mt/nest-query base-query level)]
(testing (format "\nQuery = %s" (u/pprint-to-str nested-query))
(is (= (mt/$ids venues
[{:name "ID", :id %id, :field_ref $id}
{:name "NAME", :id %name, :field_ref $name}
{:name "CATEGORY_ID", :id %category_id, :field_ref $category_id}
{:name "LATITUDE", :id %latitude, :field_ref $latitude}
{:name "LONGITUDE", :id %longitude, :field_ref $longitude}
{:name "PRICE", :id %price, :field_ref $price}
{:name "ID_2", :id %categories.id, :field_ref &c.categories.id}
{:name "NAME_2", :id %categories.name, :field_ref &c.categories.name}])
(map #(select-keys % [:name :id :field_ref])
(:cols (add-column-info nested-query {})))))))))))
(testing "Aggregated question with source is an aggregated models should infer display_name correctly (#23248)"
(mt/dataset sample-dataset
(mt/with-temp* [Card [{card-id :id}
{:dataset true
:dataset_query
(mt/$ids :products
{:type :query
:database (mt/id)
:query {:source-table $$products
:aggregation
[[:aggregation-options
[:sum $price]
{:name "sum"}]
[:aggregation-options
[:max $rating]
{:name "max"}]]
:breakout $category
:order-by [[:asc $category]]}})}]]
(let [query (qp/preprocess
(mt/mbql-query nil
{:source-table (str "card__" card-id)
:aggregation [[:aggregation-options
[:sum
[:field
"sum"
{:base-type :type/Float}]]
{:name "sum"}]
[:aggregation-options
[:count]
{:name "count"}]]
:limit 1}))]
(is (= ["Sum of Sum of Price" "Count"]
(->> (add-column-info query {})
:cols
(map :display_name)))))))))
(deftest inception-test
(testing "Should return correct metadata for an 'inception-style' nesting of source > source > source with a join (#14745)"
(mt/dataset sample-dataset
these tests look at the metadata for just one column so it 's easier to spot the differences .
(letfn [(ean-metadata [result]
(as-> (:cols result) result
(m/index-by :name result)
(get result "EAN")
(select-keys result [:name :display_name :base_type :semantic_type :id :field_ref])))]
(testing "Make sure metadata is correct for the 'EAN' column with"
(let [base-query (qp/preprocess
(mt/mbql-query orders
{:joins [{:fields :all
:source-table $$products
:condition [:= $product_id &Products.products.id]
:alias "Products"}]
:limit 10}))]
(doseq [level (range 4)]
(testing (format "%d level(s) of nesting" level)
(let [nested-query (mt/nest-query base-query level)]
(testing (format "\nQuery = %s" (u/pprint-to-str nested-query))
(is (= (mt/$ids products
{:name "EAN"
:display_name "Products → Ean"
:base_type :type/Text
:semantic_type nil
:id %ean
:field_ref &Products.ean})
(ean-metadata (add-column-info nested-query {}))))))))))))))
(deftest col-info-for-fields-from-card-test
(mt/dataset sample-dataset
(let [card-1-query (mt/mbql-query orders
{:joins [{:fields :all
:source-table $$products
:condition [:= $product_id &Products.products.id]
:alias "Products"}]})]
(mt/with-temp* [Card [{card-1-id :id} {:dataset_query card-1-query}]
Card [{card-2-id :id} {:dataset_query (mt/mbql-query people)}]]
(testing "when a nested query is from a saved question, there should be no `:join-alias` on the left side"
(mt/$ids nil
(let [base-query (qp/preprocess
(mt/mbql-query nil
{:source-table (str "card__" card-1-id)
:joins [{:fields :all
:source-table (str "card__" card-2-id)
:condition [:= $orders.user_id &Products.products.id]
:alias "Q"}]
:limit 1}))
fields #{%orders.discount %products.title %people.source}]
(is (= [{:display_name "Discount" :field_ref [:field %orders.discount nil]}
{:display_name "Products → Title" :field_ref [:field %products.title nil]}
{:display_name "Q → Source" :field_ref [:field %people.source {:join-alias "Q"}]}]
(->> (:cols (add-column-info base-query {}))
(filter #(fields (:id %)))
(map #(select-keys % [:display_name :field_ref])))))))))))
(testing "Has the correct display names for joined fields from cards"
(letfn [(native [query] {:type :native
:native {:query query :template-tags {}}
:database (mt/id)})]
(mt/with-temp* [Card [{card1-id :id} {:dataset_query
(native "select 'foo' as A_COLUMN")}]
Card [{card2-id :id} {:dataset_query
(native "select 'foo' as B_COLUMN")}]]
(doseq [card-id [card1-id card2-id]]
(mt/user-http-request :rasta :post 202 (format "card/%d/query" card-id)))
(let [query {:database (mt/id)
:type :query
:query {:source-table (str "card__" card1-id)
:joins [{:fields "all"
:source-table (str "card__" card2-id)
:condition [:=
[:field "A_COLUMN" {:base-type :type/Text}]
[:field "B_COLUMN" {:base-type :type/Text
:join-alias "alias"}]]
:alias "alias"}]}}
results (qp/process-query query)]
(is (= "alias → B Column" (-> results :data :cols second :display_name))
"cols has wrong display name")
(is (= "alias → B Column" (-> results :data :results_metadata
:columns second :display_name))
"Results metadata cols has wrong display name"))))))
|
b5fe71a230f38538162bb1237ba73d36ab6f3bf8b224bcff6e5db30b5fdc84d2 | helium/ebus-gatt | gatt_application_sup.erl | -module(gatt_application_sup).
-behavior(supervisor).
-export([start_link/2, init/1]).
-export([service_sup/1]).
-define(SERVICES, services).
start_link(Module, Args) ->
supervisor:start_link(?MODULE, [Module, Args]).
init([Module, Args]) ->
SupFlags = {rest_for_one, 3, 10},
ChildSpecs = [
#{ id => application,
type => worker,
start => {gatt_application, start_link, [self(), Module, Args]}
},
#{ id => ?SERVICES,
type => supervisor,
start => {gatt_service_sup, start_link, []}
}
],
{ok, {SupFlags, ChildSpecs}}.
service_sup(Sup) ->
Children = supervisor:which_children(Sup),
{?SERVICES, Pid, _, _} = lists:keyfind(?SERVICES, 1, Children),
Pid.
| null | https://raw.githubusercontent.com/helium/ebus-gatt/92732d7d7c153e46f4a7b9bde46c676b8d8476fd/src/gatt_application_sup.erl | erlang | -module(gatt_application_sup).
-behavior(supervisor).
-export([start_link/2, init/1]).
-export([service_sup/1]).
-define(SERVICES, services).
start_link(Module, Args) ->
supervisor:start_link(?MODULE, [Module, Args]).
init([Module, Args]) ->
SupFlags = {rest_for_one, 3, 10},
ChildSpecs = [
#{ id => application,
type => worker,
start => {gatt_application, start_link, [self(), Module, Args]}
},
#{ id => ?SERVICES,
type => supervisor,
start => {gatt_service_sup, start_link, []}
}
],
{ok, {SupFlags, ChildSpecs}}.
service_sup(Sup) ->
Children = supervisor:which_children(Sup),
{?SERVICES, Pid, _, _} = lists:keyfind(?SERVICES, 1, Children),
Pid.
|
|
7dcf5b66ced54b3b27a845f52370da3af7e351773d3cb4390c4a718843449143 | camllight/camllight | ouster-f16.11.ml | #open "tk";;
let top = OpenTk() in
let files = listbox__create top
[Relief Raised; Borderwidth (Pixels 2)]
and scroll = scrollbar__create top [] in
listbox__configure files
[YScrollCommand (scrollbar__set scroll)];
scrollbar__configure scroll
[Slidecommand (fun n -> listbox__yview files (Number n))];
pack [files] [Side Side_Left];
pack [scroll] [Side Side_Right; Fill Fill_Y];
(* replaced [glob *] by arbitrary strings *)
listbox__insert files End
["this";"is";"a";"test";"of";"linked";"listbox";"and";"scrollbar";
"widgets"];
MainLoop()
;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/camltk/books-examples/ouster-f16.11.ml | ocaml | replaced [glob *] by arbitrary strings | #open "tk";;
let top = OpenTk() in
let files = listbox__create top
[Relief Raised; Borderwidth (Pixels 2)]
and scroll = scrollbar__create top [] in
listbox__configure files
[YScrollCommand (scrollbar__set scroll)];
scrollbar__configure scroll
[Slidecommand (fun n -> listbox__yview files (Number n))];
pack [files] [Side Side_Left];
pack [scroll] [Side Side_Right; Fill Fill_Y];
listbox__insert files End
["this";"is";"a";"test";"of";"linked";"listbox";"and";"scrollbar";
"widgets"];
MainLoop()
;;
|
4ff4c9943f4271deb2c6cc0d2eafbf7af0d74a5d6c28e335abf75eb9b624dbad | AlexKnauth/debug | helpers.rkt | #lang racket/base
;; Any helper functions that the report macros expand into should be
;; defined in this file.
;; Type annotations for these helpers should go in
;; typed/debug/report/helpers.rkt
(provide pass-through-values
effect/report
effect/report/line
effect/report/file)
(require racket/match
racket/struct
pretty-format)
;; pass-through-values :
;; (∀ (X ...)
;; (-> (-> (values X ...))
( - > ( Any ) Void )
;; (values X ...)))
(define (pass-through-values thunk effect)
(let ([lst (call-with-values thunk list)])
(effect lst)
(apply values lst)))
effect / report : Any - > [ ( Any ) - > Void ]
(define ((effect/report name) expr-results)
(pretty-eprintf "~a = ~v\n"
name (show-results expr-results)))
effect / report / line : Any Natural - > [ ( Any ) - > Void ]
(define ((effect/report/line name line) expr-results)
(pretty-eprintf "~a = ~v on line ~a\n"
name (show-results expr-results) line))
effect / report / file : Any Natural Any - > [ ( Any ) - > Void ]
(define ((effect/report/file name line file) expr-results)
(pretty-eprintf "~a = ~v on line ~a in ~v\n"
name (show-results expr-results) line file))
;; -------------------------------------------------------------------
(struct printed-values (vs)
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer
(λ (self) 'values)
(λ (self) (printed-values-vs self))))])
show - results : ( Any ) - > Any
(define (show-results expr-results)
(match expr-results
[(list expr-result) expr-result]
[_ (printed-values expr-results)]))
| null | https://raw.githubusercontent.com/AlexKnauth/debug/aa798842c09ece55c2a088f09d30e398d2b77fee/debug/report/helpers.rkt | racket | Any helper functions that the report macros expand into should be
defined in this file.
Type annotations for these helpers should go in
typed/debug/report/helpers.rkt
pass-through-values :
(∀ (X ...)
(-> (-> (values X ...))
(values X ...)))
------------------------------------------------------------------- | #lang racket/base
(provide pass-through-values
effect/report
effect/report/line
effect/report/file)
(require racket/match
racket/struct
pretty-format)
( - > ( Any ) Void )
(define (pass-through-values thunk effect)
(let ([lst (call-with-values thunk list)])
(effect lst)
(apply values lst)))
effect / report : Any - > [ ( Any ) - > Void ]
(define ((effect/report name) expr-results)
(pretty-eprintf "~a = ~v\n"
name (show-results expr-results)))
effect / report / line : Any Natural - > [ ( Any ) - > Void ]
(define ((effect/report/line name line) expr-results)
(pretty-eprintf "~a = ~v on line ~a\n"
name (show-results expr-results) line))
effect / report / file : Any Natural Any - > [ ( Any ) - > Void ]
(define ((effect/report/file name line file) expr-results)
(pretty-eprintf "~a = ~v on line ~a in ~v\n"
name (show-results expr-results) line file))
(struct printed-values (vs)
#:methods gen:custom-write
[(define write-proc
(make-constructor-style-printer
(λ (self) 'values)
(λ (self) (printed-values-vs self))))])
show - results : ( Any ) - > Any
(define (show-results expr-results)
(match expr-results
[(list expr-result) expr-result]
[_ (printed-values expr-results)]))
|
d97d06e4258532e98cc8d53cfe0fb7cae1511523a01a4bc5c10fbfbd5b67803a | huangjs/cl | lbfgs.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 ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :common-lisp-user)
(let ((finish nil)
(iter 0)
(nfun 0)
(point 0)
(ispt 0)
(iypt 0)
(maxfev 0)
(info 0)
(bound 0)
(npt 0)
(cp 0)
(i 0)
(nfev 0)
(inmc 0)
(iycn 0)
(iscn 0)
(one 1.0)
(zero 0.0)
(gnorm 0.0)
(stp1 0.0)
(ftol 0.0)
(stp 0.0)
(ys 0.0)
(yy 0.0)
(sq 0.0)
(yr 0.0)
(beta 0.0)
(xnorm 0.0))
(declare (type f2cl-lib:logical finish)
(type (f2cl-lib:integer4) iter nfun point ispt iypt maxfev info
bound npt cp i nfev inmc iycn iscn)
(type (double-float) one zero gnorm stp1 ftol stp ys yy sq yr beta
xnorm))
(defun lbfgs (n m x f g diagco diag iprint eps xtol w iflag scache)
(declare (type (array f2cl-lib:integer4 (*)) iprint)
(type f2cl-lib:logical diagco)
(type (double-float) xtol eps f)
(type (array double-float (*)) scache w diag g x)
(type (f2cl-lib:integer4) iflag m n))
(let ()
(symbol-macrolet ((gtol (lb3-gtol *lb3-common-block*))
(lp (lb3-lp *lb3-common-block*)))
(f2cl-lib:with-multi-array-data
((x double-float x-%data% x-%offset%)
(g double-float g-%data% g-%offset%)
(diag double-float diag-%data% diag-%offset%)
(w double-float w-%data% w-%offset%)
(scache double-float scache-%data% scache-%offset%)
(iprint f2cl-lib:integer4 iprint-%data% iprint-%offset%))
(prog ()
(declare)
(if (= iflag 0) (go label10))
(f2cl-lib:computed-goto (label172 label100) iflag)
label10
(setf iter 0)
(if (or (<= n 0) (<= m 0)) (go label196))
(cond
((<= gtol 1.0e-4)
(if (> lp 0)
(f2cl-lib:fformat lp
("~%"
" GTOL IS LESS THAN OR EQUAL TO 1.D-04"
"~%" " IT HAS BEEN RESET TO 9.D-01"
"~%")))
(setf gtol 0.9)))
(setf nfun 1)
(setf point 0)
(setf finish f2cl-lib:%false%)
(cond
(diagco
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label30
(if
(<= (f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
zero)
(go label195)))))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label40
(setf (f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
1.0)))))
(setf ispt (f2cl-lib:int-add n (f2cl-lib:int-mul 2 m)))
(setf iypt (f2cl-lib:int-add ispt (f2cl-lib:int-mul n m)))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label50
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add ispt i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(* (- (f2cl-lib:fref g-%data% (i) ((1 n)) g-%offset%))
(f2cl-lib:fref diag-%data%
(i)
((1 n))
diag-%offset%)))))
(setf gnorm
(f2cl-lib:dsqrt
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n g 1 g 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val)))
(setf stp1 (/ one gnorm))
(setf ftol 1.0e-4)
(setf maxfev 20)
(if
(>= (f2cl-lib:fref iprint-%data% (1) ((1 2)) iprint-%offset%) 0)
(lb1 iprint iter nfun gnorm n m x f g stp finish))
label80
(setf iter (f2cl-lib:int-add iter 1))
(setf info 0)
(setf bound (f2cl-lib:int-sub iter 1))
(if (= iter 1) (go label165))
(if (> iter m) (setf bound m))
(setf ys
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n
(f2cl-lib:array-slice w
double-float
((+ iypt npt 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1
(f2cl-lib:array-slice w
double-float
((+ ispt npt 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val))
(cond
((not diagco)
(setf yy
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n
(f2cl-lib:array-slice w
double-float
((+ iypt npt 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1
(f2cl-lib:array-slice w
double-float
((+ iypt npt 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label90
(setf (f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
(/ ys yy)))))
(t
(setf iflag 2)
(go end_label)))
label100
(cond
(diagco
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label110
(if
(<= (f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
zero)
(go label195))))))
(setf cp point)
(if (= point 0) (setf cp m))
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add n cp))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2 m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(/ one ys))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label112
(setf (f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(- (f2cl-lib:fref g-%data% (i) ((1 n)) g-%offset%)))))
(setf cp point)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i bound) nil)
(tagbody
(setf cp (f2cl-lib:int-sub cp 1))
(if (= cp -1) (setf cp (f2cl-lib:int-sub m 1)))
(setf sq
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n
(f2cl-lib:array-slice w
double-float
((+ ispt
(f2cl-lib:int-mul cp n)
1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2
m)))))
1 w 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val))
(setf inmc (f2cl-lib:int-add n m cp 1))
(setf iycn (f2cl-lib:int-add iypt (f2cl-lib:int-mul cp n)))
(setf (f2cl-lib:fref w-%data%
(inmc)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(*
(f2cl-lib:fref w-%data%
((f2cl-lib:int-add n cp 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
sq))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(daxpy n
(-
(f2cl-lib:fref w-%data%
(inmc)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%))
(f2cl-lib:array-slice w
double-float
((+ iycn 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1 w 1)
(declare (ignore var-1 var-2 var-3 var-4 var-5))
(when var-0
(setf n var-0)))
label125))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label130
(setf (f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(*
(f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
(f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)))))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i bound) nil)
(tagbody
(setf yr
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n
(f2cl-lib:array-slice w
double-float
((+ iypt
(f2cl-lib:int-mul cp n)
1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2
m)))))
1 w 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val))
(setf beta
(*
(f2cl-lib:fref w-%data%
((f2cl-lib:int-add n cp 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
yr))
(setf inmc (f2cl-lib:int-add n m cp 1))
(setf beta
(-
(f2cl-lib:fref w-%data%
(inmc)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
beta))
(setf iscn (f2cl-lib:int-add ispt (f2cl-lib:int-mul cp n)))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(daxpy n beta
(f2cl-lib:array-slice w
double-float
((+ iscn 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1 w 1)
(declare (ignore var-2 var-3 var-4 var-5))
(when var-0
(setf n var-0))
(when var-1
(setf beta var-1)))
(setf cp (f2cl-lib:int-add cp 1))
(if (= cp m) (setf cp 0))
label145))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label160
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add ispt
(f2cl-lib:int-mul point
n)
i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%))))
label165
(setf nfev 0)
(setf stp one)
(if (= iter 1) (setf stp stp1))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label170
(setf (f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(f2cl-lib:fref g-%data% (i) ((1 n)) g-%offset%))))
label172
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9
var-10 var-11)
(mcsrch n x f g
(f2cl-lib:array-slice w
double-float
((+ ispt (f2cl-lib:int-mul point n) 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
stp ftol xtol maxfev info nfev diag)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-6 var-7 var-8
var-11))
(setf stp var-5)
(setf info var-9)
(setf nfev var-10))
(cond
((= info (f2cl-lib:int-sub 1))
(setf iflag 1)
(go end_label)))
(if (/= info 1) (go label190))
(setf nfun (f2cl-lib:int-add nfun nfev))
(setf npt (f2cl-lib:int-mul point n))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add ispt npt i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(* stp
(f2cl-lib:fref w-%data%
((f2cl-lib:int-add ispt npt i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)))
label175
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add iypt npt i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(- (f2cl-lib:fref g-%data% (i) ((1 n)) g-%offset%)
(f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)))))
(setf point (f2cl-lib:int-add point 1))
(if (= point m) (setf point 0))
(setf gnorm
(f2cl-lib:dsqrt
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n g 1 g 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val)))
(setf xnorm
(f2cl-lib:dsqrt
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n x 1 x 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val)))
(setf xnorm (f2cl-lib:dmax1 1.0 xnorm))
(if (<= (/ gnorm xnorm) eps) (setf finish f2cl-lib:%true%))
(if
(>= (f2cl-lib:fref iprint-%data% (1) ((1 2)) iprint-%offset%) 0)
(lb1 iprint iter nfun gnorm n m x f g stp finish))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref scache-%data% (i) ((1 n)) scache-%offset%)
(f2cl-lib:fref x-%data% (i) ((1 n)) x-%offset%))
label177))
(cond
(finish
(setf iflag 0)
(go end_label)))
(go label80)
label190
(setf iflag -1)
(if (> lp 0)
(f2cl-lib:fformat lp
("~%" " IFLAG= -1 " "~%"
" LINE SEARCH FAILED. SEE"
" DOCUMENTATION OF ROUTINE MCSRCH" "~%"
" ERROR RETURN" " OF LINE SEARCH: INFO= " 1
(("~2D")) "~%"
" POSSIBLE CAUSES: FUNCTION OR GRADIENT ARE INCORRECT"
"~%" " OR INCORRECT TOLERANCES" "~%")
info))
(go end_label)
label195
(setf iflag -2)
(if (> lp 0)
(f2cl-lib:fformat lp
("~%" " IFLAG= -2" "~%" " THE" 1 (("~5D"))
"-TH DIAGONAL ELEMENT OF THE" "~%"
" INVERSE HESSIAN APPROXIMATION IS NOT POSITIVE"
"~%")
i))
(go end_label)
label196
(setf iflag -3)
(if (> lp 0)
(f2cl-lib:fformat lp
("~%" " IFLAG= -3" "~%"
" IMPROPER INPUT PARAMETERS (N OR M"
" ARE NOT POSITIVE)" "~%")))
(go end_label)
end_label
(return
(values n nil nil nil nil nil nil nil nil nil nil iflag nil))))))))
(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::lbfgs fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(array double-float (*)) (double-float)
(array double-float (*)) fortran-to-lisp::logical
(array double-float (*))
(array fortran-to-lisp::integer4 (2)) (double-float)
(double-float) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*)))
:return-values '(fortran-to-lisp::n nil nil nil nil nil nil nil nil
nil nil fortran-to-lisp::iflag nil)
:calls '(fortran-to-lisp::mcsrch fortran-to-lisp::lb1))))
| null | https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/share/lbfgs/lbfgs.lisp | lisp | Compiled by f2cl version:
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (: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 :common-lisp-user)
(let ((finish nil)
(iter 0)
(nfun 0)
(point 0)
(ispt 0)
(iypt 0)
(maxfev 0)
(info 0)
(bound 0)
(npt 0)
(cp 0)
(i 0)
(nfev 0)
(inmc 0)
(iycn 0)
(iscn 0)
(one 1.0)
(zero 0.0)
(gnorm 0.0)
(stp1 0.0)
(ftol 0.0)
(stp 0.0)
(ys 0.0)
(yy 0.0)
(sq 0.0)
(yr 0.0)
(beta 0.0)
(xnorm 0.0))
(declare (type f2cl-lib:logical finish)
(type (f2cl-lib:integer4) iter nfun point ispt iypt maxfev info
bound npt cp i nfev inmc iycn iscn)
(type (double-float) one zero gnorm stp1 ftol stp ys yy sq yr beta
xnorm))
(defun lbfgs (n m x f g diagco diag iprint eps xtol w iflag scache)
(declare (type (array f2cl-lib:integer4 (*)) iprint)
(type f2cl-lib:logical diagco)
(type (double-float) xtol eps f)
(type (array double-float (*)) scache w diag g x)
(type (f2cl-lib:integer4) iflag m n))
(let ()
(symbol-macrolet ((gtol (lb3-gtol *lb3-common-block*))
(lp (lb3-lp *lb3-common-block*)))
(f2cl-lib:with-multi-array-data
((x double-float x-%data% x-%offset%)
(g double-float g-%data% g-%offset%)
(diag double-float diag-%data% diag-%offset%)
(w double-float w-%data% w-%offset%)
(scache double-float scache-%data% scache-%offset%)
(iprint f2cl-lib:integer4 iprint-%data% iprint-%offset%))
(prog ()
(declare)
(if (= iflag 0) (go label10))
(f2cl-lib:computed-goto (label172 label100) iflag)
label10
(setf iter 0)
(if (or (<= n 0) (<= m 0)) (go label196))
(cond
((<= gtol 1.0e-4)
(if (> lp 0)
(f2cl-lib:fformat lp
("~%"
" GTOL IS LESS THAN OR EQUAL TO 1.D-04"
"~%" " IT HAS BEEN RESET TO 9.D-01"
"~%")))
(setf gtol 0.9)))
(setf nfun 1)
(setf point 0)
(setf finish f2cl-lib:%false%)
(cond
(diagco
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label30
(if
(<= (f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
zero)
(go label195)))))
(t
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label40
(setf (f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
1.0)))))
(setf ispt (f2cl-lib:int-add n (f2cl-lib:int-mul 2 m)))
(setf iypt (f2cl-lib:int-add ispt (f2cl-lib:int-mul n m)))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label50
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add ispt i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(* (- (f2cl-lib:fref g-%data% (i) ((1 n)) g-%offset%))
(f2cl-lib:fref diag-%data%
(i)
((1 n))
diag-%offset%)))))
(setf gnorm
(f2cl-lib:dsqrt
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n g 1 g 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val)))
(setf stp1 (/ one gnorm))
(setf ftol 1.0e-4)
(setf maxfev 20)
(if
(>= (f2cl-lib:fref iprint-%data% (1) ((1 2)) iprint-%offset%) 0)
(lb1 iprint iter nfun gnorm n m x f g stp finish))
label80
(setf iter (f2cl-lib:int-add iter 1))
(setf info 0)
(setf bound (f2cl-lib:int-sub iter 1))
(if (= iter 1) (go label165))
(if (> iter m) (setf bound m))
(setf ys
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n
(f2cl-lib:array-slice w
double-float
((+ iypt npt 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1
(f2cl-lib:array-slice w
double-float
((+ ispt npt 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val))
(cond
((not diagco)
(setf yy
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n
(f2cl-lib:array-slice w
double-float
((+ iypt npt 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1
(f2cl-lib:array-slice w
double-float
((+ iypt npt 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label90
(setf (f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
(/ ys yy)))))
(t
(setf iflag 2)
(go end_label)))
label100
(cond
(diagco
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label110
(if
(<= (f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
zero)
(go label195))))))
(setf cp point)
(if (= point 0) (setf cp m))
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add n cp))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2 m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(/ one ys))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label112
(setf (f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(- (f2cl-lib:fref g-%data% (i) ((1 n)) g-%offset%)))))
(setf cp point)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i bound) nil)
(tagbody
(setf cp (f2cl-lib:int-sub cp 1))
(if (= cp -1) (setf cp (f2cl-lib:int-sub m 1)))
(setf sq
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n
(f2cl-lib:array-slice w
double-float
((+ ispt
(f2cl-lib:int-mul cp n)
1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2
m)))))
1 w 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val))
(setf inmc (f2cl-lib:int-add n m cp 1))
(setf iycn (f2cl-lib:int-add iypt (f2cl-lib:int-mul cp n)))
(setf (f2cl-lib:fref w-%data%
(inmc)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(*
(f2cl-lib:fref w-%data%
((f2cl-lib:int-add n cp 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
sq))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(daxpy n
(-
(f2cl-lib:fref w-%data%
(inmc)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%))
(f2cl-lib:array-slice w
double-float
((+ iycn 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1 w 1)
(declare (ignore var-1 var-2 var-3 var-4 var-5))
(when var-0
(setf n var-0)))
label125))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label130
(setf (f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(*
(f2cl-lib:fref diag-%data% (i) ((1 n)) diag-%offset%)
(f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)))))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i bound) nil)
(tagbody
(setf yr
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n
(f2cl-lib:array-slice w
double-float
((+ iypt
(f2cl-lib:int-mul cp n)
1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2
m)))))
1 w 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val))
(setf beta
(*
(f2cl-lib:fref w-%data%
((f2cl-lib:int-add n cp 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
yr))
(setf inmc (f2cl-lib:int-add n m cp 1))
(setf beta
(-
(f2cl-lib:fref w-%data%
(inmc)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
beta))
(setf iscn (f2cl-lib:int-add ispt (f2cl-lib:int-mul cp n)))
(multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5)
(daxpy n beta
(f2cl-lib:array-slice w
double-float
((+ iscn 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
1 w 1)
(declare (ignore var-2 var-3 var-4 var-5))
(when var-0
(setf n var-0))
(when var-1
(setf beta var-1)))
(setf cp (f2cl-lib:int-add cp 1))
(if (= cp m) (setf cp 0))
label145))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label160
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add ispt
(f2cl-lib:int-mul point
n)
i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%))))
label165
(setf nfev 0)
(setf stp one)
(if (= iter 1) (setf stp stp1))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
label170
(setf (f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(f2cl-lib:fref g-%data% (i) ((1 n)) g-%offset%))))
label172
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9
var-10 var-11)
(mcsrch n x f g
(f2cl-lib:array-slice w
double-float
((+ ispt (f2cl-lib:int-mul point n) 1))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m)))))
stp ftol xtol maxfev info nfev diag)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-6 var-7 var-8
var-11))
(setf stp var-5)
(setf info var-9)
(setf nfev var-10))
(cond
((= info (f2cl-lib:int-sub 1))
(setf iflag 1)
(go end_label)))
(if (/= info 1) (go label190))
(setf nfun (f2cl-lib:int-add nfun nfev))
(setf npt (f2cl-lib:int-mul point n))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add ispt npt i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(* stp
(f2cl-lib:fref w-%data%
((f2cl-lib:int-add ispt npt i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)))
label175
(setf (f2cl-lib:fref w-%data%
((f2cl-lib:int-add iypt npt i))
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul 2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)
(- (f2cl-lib:fref g-%data% (i) ((1 n)) g-%offset%)
(f2cl-lib:fref w-%data%
(i)
((1
(f2cl-lib:int-add
(f2cl-lib:int-mul n
(f2cl-lib:int-add
(f2cl-lib:int-mul
2
m)
1))
(f2cl-lib:int-mul 2 m))))
w-%offset%)))))
(setf point (f2cl-lib:int-add point 1))
(if (= point m) (setf point 0))
(setf gnorm
(f2cl-lib:dsqrt
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n g 1 g 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val)))
(setf xnorm
(f2cl-lib:dsqrt
(multiple-value-bind
(ret-val var-0 var-1 var-2 var-3 var-4)
(ddot n x 1 x 1)
(declare (ignore var-1 var-2 var-3 var-4))
(when var-0
(setf n var-0))
ret-val)))
(setf xnorm (f2cl-lib:dmax1 1.0 xnorm))
(if (<= (/ gnorm xnorm) eps) (setf finish f2cl-lib:%true%))
(if
(>= (f2cl-lib:fref iprint-%data% (1) ((1 2)) iprint-%offset%) 0)
(lb1 iprint iter nfun gnorm n m x f g stp finish))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(setf (f2cl-lib:fref scache-%data% (i) ((1 n)) scache-%offset%)
(f2cl-lib:fref x-%data% (i) ((1 n)) x-%offset%))
label177))
(cond
(finish
(setf iflag 0)
(go end_label)))
(go label80)
label190
(setf iflag -1)
(if (> lp 0)
(f2cl-lib:fformat lp
("~%" " IFLAG= -1 " "~%"
" LINE SEARCH FAILED. SEE"
" DOCUMENTATION OF ROUTINE MCSRCH" "~%"
" ERROR RETURN" " OF LINE SEARCH: INFO= " 1
(("~2D")) "~%"
" POSSIBLE CAUSES: FUNCTION OR GRADIENT ARE INCORRECT"
"~%" " OR INCORRECT TOLERANCES" "~%")
info))
(go end_label)
label195
(setf iflag -2)
(if (> lp 0)
(f2cl-lib:fformat lp
("~%" " IFLAG= -2" "~%" " THE" 1 (("~5D"))
"-TH DIAGONAL ELEMENT OF THE" "~%"
" INVERSE HESSIAN APPROXIMATION IS NOT POSITIVE"
"~%")
i))
(go end_label)
label196
(setf iflag -3)
(if (> lp 0)
(f2cl-lib:fformat lp
("~%" " IFLAG= -3" "~%"
" IMPROPER INPUT PARAMETERS (N OR M"
" ARE NOT POSITIVE)" "~%")))
(go end_label)
end_label
(return
(values n nil nil nil nil nil nil nil nil nil nil iflag nil))))))))
(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::lbfgs fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(array double-float (*)) (double-float)
(array double-float (*)) fortran-to-lisp::logical
(array double-float (*))
(array fortran-to-lisp::integer4 (2)) (double-float)
(double-float) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*)))
:return-values '(fortran-to-lisp::n nil nil nil nil nil nil nil nil
nil nil fortran-to-lisp::iflag nil)
:calls '(fortran-to-lisp::mcsrch fortran-to-lisp::lb1))))
|
7c04f962f86edeb89374d890eb53e3460d752e5a385cdb5d0fd23e82f2308321 | bitemyapp/fp-course | Comonad.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE InstanceSigs #
module Course.Comonad where
import Course.Core
import Course.ExactlyOne
import Course.Extend
| All instances of the ` Comonad ` type - class must satisfy two laws . These
-- laws are not checked by the compiler. These laws are given as:
--
-- * The law of left identity
` ∀x . < < = x ≅ x `
--
-- * The law of right identity
` ∀f . . ( f < < =) = = f
class Extend f => Comonad f where
copure ::
f a
-> a
-- | Implement the @Comonad@ instance for @ExactlyOne@.
--
-- >>> copure (ExactlyOne 7)
7
instance Comonad ExactlyOne where
copure ::
ExactlyOne a
-> a
copure =
error "todo: Course.Comonad copure#instance ExactlyOne"
-- | Witness that all things with (<<=) and copure also have (<$>).
--
-- >>> (+10) <$$> ExactlyOne 7
ExactlyOne 17
(<$$>) ::
Comonad f =>
(a -> b)
-> f a
-> f b
(<$$>) =
error "todo: Course.Comonad#(<$>)"
| null | https://raw.githubusercontent.com/bitemyapp/fp-course/a9a325cd895a0953151ec3d02f40006eb7993fb8/src/Course/Comonad.hs | haskell | laws are not checked by the compiler. These laws are given as:
* The law of left identity
* The law of right identity
| Implement the @Comonad@ instance for @ExactlyOne@.
>>> copure (ExactlyOne 7)
| Witness that all things with (<<=) and copure also have (<$>).
>>> (+10) <$$> ExactlyOne 7 | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE InstanceSigs #
module Course.Comonad where
import Course.Core
import Course.ExactlyOne
import Course.Extend
| All instances of the ` Comonad ` type - class must satisfy two laws . These
` ∀x . < < = x ≅ x `
` ∀f . . ( f < < =) = = f
class Extend f => Comonad f where
copure ::
f a
-> a
7
instance Comonad ExactlyOne where
copure ::
ExactlyOne a
-> a
copure =
error "todo: Course.Comonad copure#instance ExactlyOne"
ExactlyOne 17
(<$$>) ::
Comonad f =>
(a -> b)
-> f a
-> f b
(<$$>) =
error "todo: Course.Comonad#(<$>)"
|
c0029466cc3c6fa71b06a4550b465d4bde5a0528b1e0e9a8bd0f1a129d08a24d | flodihn/NextGen | http_api_callback.erl | -module(http_api_callback).
-export([handle/2, handle_event/3]).
-include_lib("elli/include/elli.hrl").
-behaviour(elli_handler).
handle(Req, Args) ->
handle(Req#req.method, elli_request:path(Req), Req, Args).
handle('GET',[<<"crossdomain.xml">>], Req, Args) ->
{200, [], <<"<?xml version=\"1.0\"?>\n<cross-domain-policy>\n<allow-access-from domain=\"*\"/>\n</cross-domain-policy>">>};
handle(_, _, _Req, Args) ->
{404, [], <<"Not Found">>}.
%% @doc: Handle request events, like request completed, exception
%% thrown, client timeout, etc. Must return 'ok'.
handle_event(_Event, _Data, _Args) ->
ok.
| null | https://raw.githubusercontent.com/flodihn/NextGen/3da1c3ee0d8f658383bdf5fccbdd49ace3cdb323/CrossDomainPolicyServer/src/http_api_callback.erl | erlang | @doc: Handle request events, like request completed, exception
thrown, client timeout, etc. Must return 'ok'. | -module(http_api_callback).
-export([handle/2, handle_event/3]).
-include_lib("elli/include/elli.hrl").
-behaviour(elli_handler).
handle(Req, Args) ->
handle(Req#req.method, elli_request:path(Req), Req, Args).
handle('GET',[<<"crossdomain.xml">>], Req, Args) ->
{200, [], <<"<?xml version=\"1.0\"?>\n<cross-domain-policy>\n<allow-access-from domain=\"*\"/>\n</cross-domain-policy>">>};
handle(_, _, _Req, Args) ->
{404, [], <<"Not Found">>}.
handle_event(_Event, _Data, _Args) ->
ok.
|
48bdfdc45c3a32483e0059eabafe3b34b5aa777f255a7f3ddf5c4ccf58622f35 | ros/roslisp_common | simple-action-client.lisp | Copyright ( c ) 2014 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of the Institute for Artificial Intelligence/
Universitaet Bremen nor the names of its contributors may be used to
;;; endorse or promote products derived from this software without specific
;;; prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;;; POSSIBILITY OF SUCH DAMAGE.
(in-package actionlib-lisp)
;;;
;;; Exported
;;;
(defclass simple-action-client (action-client)
((goal-handle :initform nil
:accessor goal-handle))
(:documentation "Action-client that always only tracks one goal, so no
goal-handle is needed and all functions to influence or
get information about the goal need the client.
The API is based on the API for the simple-action-client
in the c-code actionlib."))
(defgeneric send-goal-and-wait (client goal-msg execute-timeout preempt-timeout)
(:documentation "Sends a goal to the action server and waits unitl it's done
or a timeout is reached.
`client' the client that handles the goal.
`goal-msg' goal message send to the server.
`execute-timeout' time to wait for the goal to get done until
the client cancels the goal. 0 implies forever.
`preempt-timeout' time to wait for the goal to get preemted.
0 implies forever."))
(defgeneric cancel-goal (client)
(:documentation "Cancels the goal that the client is currently pursuing"))
(defgeneric stop-tracking-goal (client)
(:documentation "Stops the client from tracking the goal without canceling it."))
(defgeneric state (client)
(:documentation "Gets the state information for the goal pursued by the client.
Possible states are PENDING, ACTIVE, REJECTED, ABORTED, SUCCEEDED
and LOST."))
(defgeneric wait-for-result (client timeout)
(:documentation "Blocks until the goal finishes or the timeout is reached.
Returns TRUE if the goal finishes or NIL if the timeout is reached.
A timeout of 0 implies wait forever."))
(defun make-simple-action-client (action-name action-type)
"Returns an instance of simple-action-client initialized and subscribes to
to the topics of the action-server."
(create-action-client action-name action-type t))
(defmethod send-goal ((client simple-action-client) goal-msg &key
done-cb active-cb feedback-cb)
"Sends a goal to the action server.
`done-cb' Callback that gets called when the goal received a result and is done.
It takes the state information of the goal and the result as parameters.
`active-cb' Callback that gets called when the state of the goal changes to active.
It takes no parameters.
`feedbak-cb' Callback that gets callback everytime feeback for the goal is received.
It takes the feedback message as parameter."
(with-recursive-lock ((client-mutex client))
(stop-tracking-goal client)
(setf (goal-handle client)
(call-next-method client goal-msg
:transition-cb #'(lambda (goal-handle)
(if (eql (comm-state goal-handle) :active)
(if active-cb (funcall active-cb))
(if (eql (comm-state goal-handle) :done)
(if done-cb
(funcall done-cb (state client)
(result goal-handle))))))
:feedback-cb #'(lambda (goal-handle feedback)
(declare (ignore goal-handle))
(if feedback-cb
(funcall feedback-cb feedback))))))
t)
(defmethod send-goal-and-wait ((client simple-action-client) goal-msg
execute-timeout preempt-timeout)
"Sends a goal to the action server and loops until the goal is done or
the `execute-timeout' is reached and then cancels the goal and waits until the
goal preempted or the `preempt-timeout' is reached. A timeout of 0 implies forever.
Returns the state information of the goal"
;; in case this method is evaporated during execution, unwind-protect
;; ensure that we inform the server by canceling the goal
(let ((clean-finish nil))
(unwind-protect
(progn
(send-goal client goal-msg)
;; waiting for execution timeout
(unless (wait-for-result client execute-timeout)
(ros-info (actionlib) "Reached execute timeout.")
(cancel-goal client)
(with-timeout-handler preempt-timeout
#'(lambda ()
(ros-info (actionlib) "Reached preempt timeout.")
(setf clean-finish t)
(return-from send-goal-and-wait (state client)))
(with-recursive-lock ((csm-mutex (comm-state-machine (goal-handle client))))
(loop until (goal-finished client) do
(condition-wait (gethash (goal-id (goal-handle client))
(goal-conditions (goal-manager client)))
(csm-mutex (comm-state-machine (goal-handle client))))))))
;; returning the state of the action client
(setf clean-finish t)
(state client))
;; cancel the goal in case we have been evaporated
(when (and (not clean-finish) (goal-handle client)) ; making sure we still have a goal-handle
(cancel-goal client)))))
(defmethod state ((client simple-action-client))
"Returns the state information of the goal tracked by the client.
RECALLING gets mapped to PENDING and PREEMPTING to ACTIVE.
Throws an error if the client tracks no goal."
(goal-handle-not-nil (goal-handle client))
(let ((status (goal-status (goal-handle client))))
(cond
((eql status :recalling)
:pending)
((eql status :preempting)
:active)
(t
status))))
(defmethod result ((client simple-action-client))
"Returns the result of the goal tracked by the client. NIL if no result has
been received yet. Throws an error if the client doesn't track any goal."
(goal-handle-not-nil (goal-handle client))
(result (goal-handle client)))
(defmethod cancel-goal ((client simple-action-client))
"Cancels the goal tracked by the client. Throwns an error if the client
tracks no goal."
(goal-handle-not-nil (goal-handle client))
(cancel (goal-handle client)))
(defmethod stop-tracking-goal ((client simple-action-client))
"Removes all goals that form the goal-manager and sets the goal-handle to NIL
so no information about old goals remain."
(stop-tracking-goals (goal-manager client))
(setf (goal-handle client) nil)
t)
(defmethod wait-for-result ((client simple-action-client) timeout)
"Waits until a result is received or the timeout is reached. Returns TRUE
if the goal finished before the timeout or NIL otherwise. An Error is
thrown if the client hasn't sent a goal yet or stopped tracking it."
(goal-handle-not-nil (goal-handle client))
(with-timeout-handler timeout
#'(lambda () (return-from wait-for-result nil))
(with-recursive-lock ((csm-mutex (comm-state-machine (goal-handle client))))
(loop until (is-done client) do
(condition-wait (gethash (goal-id (goal-handle client))
(goal-conditions (goal-manager client)))
(csm-mutex (comm-state-machine (goal-handle client)))))))
t)
;;;
Internal
;;;
(defun goal-handle-not-nil (goal-handle)
"Checks if the goal-handle is NIL"
(assert goal-handle nil
"The client tracks no goal."))
(defun goal-finished (client)
"Checks if the goal is in a finished state. This doesn't checks if
a result was received."
(let ((state (state client)))
(or (eql state :SUCCEEDED)
(eql state :LOST)
(eql state :PREEMPTED))))
(defun is-done (client)
"Checks if a goal is done."
(and (eql (comm-state (goal-handle client)) :done)
(goal-finished client)))
| null | https://raw.githubusercontent.com/ros/roslisp_common/4db311da26497d84a147f190200e50c7a5b4106e/actionlib_lisp/src/new_implementation/simple-action-client.lisp | lisp | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
endorse or promote products derived from this software without specific
prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Exported
in case this method is evaporated during execution, unwind-protect
ensure that we inform the server by canceling the goal
waiting for execution timeout
returning the state of the action client
cancel the goal in case we have been evaporated
making sure we still have a goal-handle
| Copyright ( c ) 2014 , < >
* Neither the name of the Institute for Artificial Intelligence/
Universitaet Bremen nor the names of its contributors may be used to
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package actionlib-lisp)
(defclass simple-action-client (action-client)
((goal-handle :initform nil
:accessor goal-handle))
(:documentation "Action-client that always only tracks one goal, so no
goal-handle is needed and all functions to influence or
get information about the goal need the client.
The API is based on the API for the simple-action-client
in the c-code actionlib."))
(defgeneric send-goal-and-wait (client goal-msg execute-timeout preempt-timeout)
(:documentation "Sends a goal to the action server and waits unitl it's done
or a timeout is reached.
`client' the client that handles the goal.
`goal-msg' goal message send to the server.
`execute-timeout' time to wait for the goal to get done until
the client cancels the goal. 0 implies forever.
`preempt-timeout' time to wait for the goal to get preemted.
0 implies forever."))
(defgeneric cancel-goal (client)
(:documentation "Cancels the goal that the client is currently pursuing"))
(defgeneric stop-tracking-goal (client)
(:documentation "Stops the client from tracking the goal without canceling it."))
(defgeneric state (client)
(:documentation "Gets the state information for the goal pursued by the client.
Possible states are PENDING, ACTIVE, REJECTED, ABORTED, SUCCEEDED
and LOST."))
(defgeneric wait-for-result (client timeout)
(:documentation "Blocks until the goal finishes or the timeout is reached.
Returns TRUE if the goal finishes or NIL if the timeout is reached.
A timeout of 0 implies wait forever."))
(defun make-simple-action-client (action-name action-type)
"Returns an instance of simple-action-client initialized and subscribes to
to the topics of the action-server."
(create-action-client action-name action-type t))
(defmethod send-goal ((client simple-action-client) goal-msg &key
done-cb active-cb feedback-cb)
"Sends a goal to the action server.
`done-cb' Callback that gets called when the goal received a result and is done.
It takes the state information of the goal and the result as parameters.
`active-cb' Callback that gets called when the state of the goal changes to active.
It takes no parameters.
`feedbak-cb' Callback that gets callback everytime feeback for the goal is received.
It takes the feedback message as parameter."
(with-recursive-lock ((client-mutex client))
(stop-tracking-goal client)
(setf (goal-handle client)
(call-next-method client goal-msg
:transition-cb #'(lambda (goal-handle)
(if (eql (comm-state goal-handle) :active)
(if active-cb (funcall active-cb))
(if (eql (comm-state goal-handle) :done)
(if done-cb
(funcall done-cb (state client)
(result goal-handle))))))
:feedback-cb #'(lambda (goal-handle feedback)
(declare (ignore goal-handle))
(if feedback-cb
(funcall feedback-cb feedback))))))
t)
(defmethod send-goal-and-wait ((client simple-action-client) goal-msg
execute-timeout preempt-timeout)
"Sends a goal to the action server and loops until the goal is done or
the `execute-timeout' is reached and then cancels the goal and waits until the
goal preempted or the `preempt-timeout' is reached. A timeout of 0 implies forever.
Returns the state information of the goal"
(let ((clean-finish nil))
(unwind-protect
(progn
(send-goal client goal-msg)
(unless (wait-for-result client execute-timeout)
(ros-info (actionlib) "Reached execute timeout.")
(cancel-goal client)
(with-timeout-handler preempt-timeout
#'(lambda ()
(ros-info (actionlib) "Reached preempt timeout.")
(setf clean-finish t)
(return-from send-goal-and-wait (state client)))
(with-recursive-lock ((csm-mutex (comm-state-machine (goal-handle client))))
(loop until (goal-finished client) do
(condition-wait (gethash (goal-id (goal-handle client))
(goal-conditions (goal-manager client)))
(csm-mutex (comm-state-machine (goal-handle client))))))))
(setf clean-finish t)
(state client))
(cancel-goal client)))))
(defmethod state ((client simple-action-client))
"Returns the state information of the goal tracked by the client.
RECALLING gets mapped to PENDING and PREEMPTING to ACTIVE.
Throws an error if the client tracks no goal."
(goal-handle-not-nil (goal-handle client))
(let ((status (goal-status (goal-handle client))))
(cond
((eql status :recalling)
:pending)
((eql status :preempting)
:active)
(t
status))))
(defmethod result ((client simple-action-client))
"Returns the result of the goal tracked by the client. NIL if no result has
been received yet. Throws an error if the client doesn't track any goal."
(goal-handle-not-nil (goal-handle client))
(result (goal-handle client)))
(defmethod cancel-goal ((client simple-action-client))
"Cancels the goal tracked by the client. Throwns an error if the client
tracks no goal."
(goal-handle-not-nil (goal-handle client))
(cancel (goal-handle client)))
(defmethod stop-tracking-goal ((client simple-action-client))
"Removes all goals that form the goal-manager and sets the goal-handle to NIL
so no information about old goals remain."
(stop-tracking-goals (goal-manager client))
(setf (goal-handle client) nil)
t)
(defmethod wait-for-result ((client simple-action-client) timeout)
"Waits until a result is received or the timeout is reached. Returns TRUE
if the goal finished before the timeout or NIL otherwise. An Error is
thrown if the client hasn't sent a goal yet or stopped tracking it."
(goal-handle-not-nil (goal-handle client))
(with-timeout-handler timeout
#'(lambda () (return-from wait-for-result nil))
(with-recursive-lock ((csm-mutex (comm-state-machine (goal-handle client))))
(loop until (is-done client) do
(condition-wait (gethash (goal-id (goal-handle client))
(goal-conditions (goal-manager client)))
(csm-mutex (comm-state-machine (goal-handle client)))))))
t)
Internal
(defun goal-handle-not-nil (goal-handle)
"Checks if the goal-handle is NIL"
(assert goal-handle nil
"The client tracks no goal."))
(defun goal-finished (client)
"Checks if the goal is in a finished state. This doesn't checks if
a result was received."
(let ((state (state client)))
(or (eql state :SUCCEEDED)
(eql state :LOST)
(eql state :PREEMPTED))))
(defun is-done (client)
"Checks if a goal is done."
(and (eql (comm-state (goal-handle client)) :done)
(goal-finished client)))
|
2bd5d55186c2610a7a7670e8b84ff4348da84919d84a77437a341fdbd931d6a1 | elektronaut/advent-of-code | day06.clj | (ns advent-of-code.2020.06
(:require [clojure.string :as str]
[clojure.set :as set]))
(def groups (str/split (slurp "2020/day06/input.txt") #"\n\n"))
(defn questions-any [g]
(set (str/replace g #"[^\w]" "")))
(defn questions-all [g]
(let [member-count (count (str/split-lines g))]
(->> (frequencies (str/replace g #"[^\w]" ""))
(filter #(= member-count (last %)))
(map first))))
(defn group-count [fn]
(->> (map fn groups)
(map count)
(reduce +)))
(println "Part 1:" (group-count questions-any))
(println "Part 2:" (group-count questions-all))
| null | https://raw.githubusercontent.com/elektronaut/advent-of-code/a8bb7bbadc8167ebb1df0d532493317705bb7f0d/2020/day06/day06.clj | clojure | (ns advent-of-code.2020.06
(:require [clojure.string :as str]
[clojure.set :as set]))
(def groups (str/split (slurp "2020/day06/input.txt") #"\n\n"))
(defn questions-any [g]
(set (str/replace g #"[^\w]" "")))
(defn questions-all [g]
(let [member-count (count (str/split-lines g))]
(->> (frequencies (str/replace g #"[^\w]" ""))
(filter #(= member-count (last %)))
(map first))))
(defn group-count [fn]
(->> (map fn groups)
(map count)
(reduce +)))
(println "Part 1:" (group-count questions-any))
(println "Part 2:" (group-count questions-all))
|
|
8bd10f02ae0182194838084a4ee0a4a657264601be5a659a3dec1928fdefdb4b | intermine/bluegenes | views.cljs | (ns bluegenes.pages.profile.views
(:require [reagent.core :as r]
[re-frame.core :refer [subscribe dispatch]]
[oops.core :refer [oget ocall]]
[bluegenes.pages.profile.events :as events]
[bluegenes.pages.profile.subs :as subs]
[bluegenes.components.loader :refer [mini-loader]]
[bluegenes.components.ui.inputs :refer [password-input]]
[bluegenes.version :refer [proper-login-support]]))
(defn generate-api-key []
(let [bg-uses-api-key? (< @(subscribe [:api-version]) proper-login-support)
response @(subscribe [::subs/responses :generate-api-key])]
[:div.settings-group
[:h3 "API access key"]
[:p "You can access the features of the InterMine API securely using an API access key. A key uniquely identifies you to the webservice, without requiring you to transmit your username or password. At any time you can change, or delete your API key, without having to change your password. If you do not yet have an API key, click on the button below to generate a new token."]
[:p [:strong "Note: "] "Generating a new API key will invalidate any existing one. If you wish to reuse an API key, you should save it in a safe place. You will only be able to view the API key for the length of this session."]
(if bg-uses-api-key?
[:pre.token-box @(subscribe [:active-token])]
[:pre.token-box (or @(subscribe [::subs/api-key]) "-")])
[:div.save-button.flex-row
[:button.btn.btn-primary.btn-raised
{:type "button"
:disabled (or bg-uses-api-key? @(subscribe [::subs/requests :generate-api-key]))
:on-click #(dispatch [::events/generate-api-key])}
"Generate a new API key"]
(if bg-uses-api-key?
[:p.failure "Generating a new API key is not supported in this version of InterMine."]
(when-let [{:keys [type message]} response]
[:p {:class type} message]))]]))
(defn password-settings []
(let [old-password (r/atom "")
new-password (r/atom "")
response (subscribe [::subs/responses :change-password])
submit-fn #(dispatch [::events/change-password @old-password @new-password])
oauth2? (subscribe [:bluegenes.subs.auth/oauth2?])]
(fn []
[:div.settings-group
[:h3 "Change password"]
(when @oauth2?
[:p [:code "You are logged in through an external authentication provider. Please use their services to change your password."]])
[password-input {:value @old-password
:on-change #(reset! old-password (oget % :target :value))
:on-submit submit-fn
:container-class "input-container"
:label "Old password"
:disabled @oauth2?}]
[password-input {:value @new-password
:on-change #(reset! new-password (oget % :target :value))
:on-submit submit-fn
:container-class "input-container"
:new-password? true
:label "New password"
:disabled @oauth2?}]
[:div.save-button.flex-row
[:button.btn.btn-primary.btn-raised
{:type "button"
:disabled (some empty? [@old-password @new-password])
:on-click submit-fn}
"Save password"]
(when-let [{:keys [type message]} @response]
[:p {:class type} message])]])))
(defn input [{:keys [group id label type] :or {type "text"}}]
[:div.form-group
[:label {:for (str "input" id)} label]
[:div.input-container
[:input.form-control
{:type type
:id (str "input" id)
:value @(subscribe [::subs/inputs [group id]])
:on-change #(dispatch [::events/set-input [group id] (oget % :target :value)])}]]])
(defn checkbox [{:keys [group id label reversed?]}]
[:div.form-group
[:label label
[:input {:type "checkbox"
:checked (cond-> @(subscribe [::subs/inputs [group id]]) reversed? not)
:on-change #(dispatch [::events/update-input [group id] not])}]]])
(defn user-preferences []
(let [requesting? (subscribe [::subs/requests :get-preferences])
response (subscribe [::subs/responses :user-preferences])
loader-ref (atom nil)
;; It's possible to do this with CSS transitions, except the dark
;; background will abruptly appear and disappear even though the
;; request is so quick the transition doesn't have time to finish.
loader-timeout (when @requesting?
(js/setTimeout
#(some-> (js/$ @loader-ref)
(ocall :addClass "is-loading"))
500))]
(fn []
(when (not @requesting?)
(js/clearTimeout loader-timeout)
(some-> (js/$ @loader-ref) (ocall :removeClass "is-loading")))
[:div.settings-group
[:div.settings-loader {:ref #(reset! loader-ref %)}
[mini-loader]]
[:h3 "User preferences"]
[checkbox {:id :do_not_spam
:group :user-preferences
:reversed? true
:label "Inform me by email of newly shared lists"}]
[checkbox {:id :hidden
:group :user-preferences
:reversed? true
:label "Allow other users to share lists with me without confirmation"}]
[input {:id :alias
:group :user-preferences
:label "Public name (use this name to share lists with me)"}]
[input {:id :email
:group :user-preferences
:type "email"
:label "My preferred email address"}]
[input {:id :galaxy-url
:group :user-preferences
:label "The URL of your preferred Galaxy instance"}]
(let [input-prefs @(subscribe [::subs/inputs [:user-preferences]])
saved-prefs @(subscribe [::subs/preferences])]
[:div.save-button.flex-row
[:button.btn.btn-primary.btn-raised
{:type "button"
:disabled (= input-prefs saved-prefs)
:on-click #(dispatch [::events/save-preferences input-prefs])}
"Save changes"]
(when-let [{:keys [type message]} @response]
[:p {:class type} message])])])))
(defn delete-account []
(let [deregistration-token (subscribe [::subs/responses :deregistration-token])
mine-name (subscribe [:current-mine-human-name])
deregistration-input (r/atom "")]
(fn []
[:div.settings-group
[:h3 "Delete account"]
(if (not-empty @deregistration-token)
[:<>
[:p "Copy the following code into the input field below, then press the button to delete your account on " [:strong @mine-name] "."
[:br]
[:code @deregistration-token]]
[:div.alert.alert-danger
"Once completed, you will no longer be able to login to your account and access your saved lists, queries, templates, tags and user preferences on this InterMine instance."
[:br]
[:strong "THIS CANNOT BE UNDONE."]]
[:div.form-group
[:label "Code for account deletion"]
[:div.input-container
[:input.form-control
{:type "text"
:value @deregistration-input
:on-change #(reset! deregistration-input (oget % :target :value))}]]
[:div.flex-row
[:button.btn.btn-danger.btn-raised
{:type "button"
:disabled @(subscribe [::subs/requests :delete-account])
:on-click #(dispatch [::events/delete-account @deregistration-input])}
"Delete account"]
(when-let [{:keys [type message]} @(subscribe [::subs/responses :delete-account])]
[:p {:class type} message])]]]
[:<>
[:p "Delete your account on " [:strong @mine-name] " including all your saved lists, queries, templates, tags and user preferences on this InterMine instance."]
[:div.save-button.flex-row
[:button.btn.btn-danger.btn-raised
{:type "button"
:disabled @(subscribe [::subs/requests :start-deregistration])
:on-click #(dispatch [::events/start-deregistration])}
"Start account deletion"]
(when-let [{:keys [type message]} @(subscribe [::subs/responses :deregistration])]
[:p {:class type} message])]])])))
(defn main []
[:div.profile-page.container
[user-preferences]
[generate-api-key]
[password-settings]
[delete-account]])
| null | https://raw.githubusercontent.com/intermine/bluegenes/417ea23b2d00fdca20ce4810bb2838326a09010e/src/cljs/bluegenes/pages/profile/views.cljs | clojure | It's possible to do this with CSS transitions, except the dark
background will abruptly appear and disappear even though the
request is so quick the transition doesn't have time to finish. | (ns bluegenes.pages.profile.views
(:require [reagent.core :as r]
[re-frame.core :refer [subscribe dispatch]]
[oops.core :refer [oget ocall]]
[bluegenes.pages.profile.events :as events]
[bluegenes.pages.profile.subs :as subs]
[bluegenes.components.loader :refer [mini-loader]]
[bluegenes.components.ui.inputs :refer [password-input]]
[bluegenes.version :refer [proper-login-support]]))
(defn generate-api-key []
(let [bg-uses-api-key? (< @(subscribe [:api-version]) proper-login-support)
response @(subscribe [::subs/responses :generate-api-key])]
[:div.settings-group
[:h3 "API access key"]
[:p "You can access the features of the InterMine API securely using an API access key. A key uniquely identifies you to the webservice, without requiring you to transmit your username or password. At any time you can change, or delete your API key, without having to change your password. If you do not yet have an API key, click on the button below to generate a new token."]
[:p [:strong "Note: "] "Generating a new API key will invalidate any existing one. If you wish to reuse an API key, you should save it in a safe place. You will only be able to view the API key for the length of this session."]
(if bg-uses-api-key?
[:pre.token-box @(subscribe [:active-token])]
[:pre.token-box (or @(subscribe [::subs/api-key]) "-")])
[:div.save-button.flex-row
[:button.btn.btn-primary.btn-raised
{:type "button"
:disabled (or bg-uses-api-key? @(subscribe [::subs/requests :generate-api-key]))
:on-click #(dispatch [::events/generate-api-key])}
"Generate a new API key"]
(if bg-uses-api-key?
[:p.failure "Generating a new API key is not supported in this version of InterMine."]
(when-let [{:keys [type message]} response]
[:p {:class type} message]))]]))
(defn password-settings []
(let [old-password (r/atom "")
new-password (r/atom "")
response (subscribe [::subs/responses :change-password])
submit-fn #(dispatch [::events/change-password @old-password @new-password])
oauth2? (subscribe [:bluegenes.subs.auth/oauth2?])]
(fn []
[:div.settings-group
[:h3 "Change password"]
(when @oauth2?
[:p [:code "You are logged in through an external authentication provider. Please use their services to change your password."]])
[password-input {:value @old-password
:on-change #(reset! old-password (oget % :target :value))
:on-submit submit-fn
:container-class "input-container"
:label "Old password"
:disabled @oauth2?}]
[password-input {:value @new-password
:on-change #(reset! new-password (oget % :target :value))
:on-submit submit-fn
:container-class "input-container"
:new-password? true
:label "New password"
:disabled @oauth2?}]
[:div.save-button.flex-row
[:button.btn.btn-primary.btn-raised
{:type "button"
:disabled (some empty? [@old-password @new-password])
:on-click submit-fn}
"Save password"]
(when-let [{:keys [type message]} @response]
[:p {:class type} message])]])))
(defn input [{:keys [group id label type] :or {type "text"}}]
[:div.form-group
[:label {:for (str "input" id)} label]
[:div.input-container
[:input.form-control
{:type type
:id (str "input" id)
:value @(subscribe [::subs/inputs [group id]])
:on-change #(dispatch [::events/set-input [group id] (oget % :target :value)])}]]])
(defn checkbox [{:keys [group id label reversed?]}]
[:div.form-group
[:label label
[:input {:type "checkbox"
:checked (cond-> @(subscribe [::subs/inputs [group id]]) reversed? not)
:on-change #(dispatch [::events/update-input [group id] not])}]]])
(defn user-preferences []
(let [requesting? (subscribe [::subs/requests :get-preferences])
response (subscribe [::subs/responses :user-preferences])
loader-ref (atom nil)
loader-timeout (when @requesting?
(js/setTimeout
#(some-> (js/$ @loader-ref)
(ocall :addClass "is-loading"))
500))]
(fn []
(when (not @requesting?)
(js/clearTimeout loader-timeout)
(some-> (js/$ @loader-ref) (ocall :removeClass "is-loading")))
[:div.settings-group
[:div.settings-loader {:ref #(reset! loader-ref %)}
[mini-loader]]
[:h3 "User preferences"]
[checkbox {:id :do_not_spam
:group :user-preferences
:reversed? true
:label "Inform me by email of newly shared lists"}]
[checkbox {:id :hidden
:group :user-preferences
:reversed? true
:label "Allow other users to share lists with me without confirmation"}]
[input {:id :alias
:group :user-preferences
:label "Public name (use this name to share lists with me)"}]
[input {:id :email
:group :user-preferences
:type "email"
:label "My preferred email address"}]
[input {:id :galaxy-url
:group :user-preferences
:label "The URL of your preferred Galaxy instance"}]
(let [input-prefs @(subscribe [::subs/inputs [:user-preferences]])
saved-prefs @(subscribe [::subs/preferences])]
[:div.save-button.flex-row
[:button.btn.btn-primary.btn-raised
{:type "button"
:disabled (= input-prefs saved-prefs)
:on-click #(dispatch [::events/save-preferences input-prefs])}
"Save changes"]
(when-let [{:keys [type message]} @response]
[:p {:class type} message])])])))
(defn delete-account []
(let [deregistration-token (subscribe [::subs/responses :deregistration-token])
mine-name (subscribe [:current-mine-human-name])
deregistration-input (r/atom "")]
(fn []
[:div.settings-group
[:h3 "Delete account"]
(if (not-empty @deregistration-token)
[:<>
[:p "Copy the following code into the input field below, then press the button to delete your account on " [:strong @mine-name] "."
[:br]
[:code @deregistration-token]]
[:div.alert.alert-danger
"Once completed, you will no longer be able to login to your account and access your saved lists, queries, templates, tags and user preferences on this InterMine instance."
[:br]
[:strong "THIS CANNOT BE UNDONE."]]
[:div.form-group
[:label "Code for account deletion"]
[:div.input-container
[:input.form-control
{:type "text"
:value @deregistration-input
:on-change #(reset! deregistration-input (oget % :target :value))}]]
[:div.flex-row
[:button.btn.btn-danger.btn-raised
{:type "button"
:disabled @(subscribe [::subs/requests :delete-account])
:on-click #(dispatch [::events/delete-account @deregistration-input])}
"Delete account"]
(when-let [{:keys [type message]} @(subscribe [::subs/responses :delete-account])]
[:p {:class type} message])]]]
[:<>
[:p "Delete your account on " [:strong @mine-name] " including all your saved lists, queries, templates, tags and user preferences on this InterMine instance."]
[:div.save-button.flex-row
[:button.btn.btn-danger.btn-raised
{:type "button"
:disabled @(subscribe [::subs/requests :start-deregistration])
:on-click #(dispatch [::events/start-deregistration])}
"Start account deletion"]
(when-let [{:keys [type message]} @(subscribe [::subs/responses :deregistration])]
[:p {:class type} message])]])])))
(defn main []
[:div.profile-page.container
[user-preferences]
[generate-api-key]
[password-settings]
[delete-account]])
|
aa44d8f99fde7359759bcd8f5801c3ada9655bdacda904aaa9e97ba9d622d324 | chaoxu/fancy-walks | C.hs | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances #
{-# OPTIONS_GHC -O2 #-}
import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control . Monad . State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
import Control.Monad.ST
import Data.Array.ST
import Data.STRef
parseInput = do
n <- readInt
m <- readInt
edges <- replicateM m ((,) <$> readInt <*> readInt)
return (n, edges)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = BS.putStr =<< solve . evalState parseInput <$> BS.getContents
modulo :: Int
modulo = 1000000009
newtype ModP = ModP Int deriving Eq
instance Num ModP where
ModP a + ModP b = ModP $ (a + b) `mod` modulo
ModP a - ModP b = ModP $ (a - b) `mod` modulo
ModP a * ModP b = ModP $ (a * b) `mod` modulo
fromInteger = ModP . fromInteger
signum = undefined
abs = undefined
instance Show ModP where
show (ModP a) = show a
solve :: (Int, [(Int, Int)]) -> ByteString
solve (n, edges) = BS.unlines . map (BS.pack . show . (\x -> x-1)) $ runST stMonad
where
stMonad :: ST s [ModP]
stMonad = do
uf <- buildUF (1, n) :: ST s (UnionFind s)
eqs <- newSTRef 1 :: ST s (STRef s ModP)
mapM (solveEdge uf eqs) edges
solveEdge :: UnionFind s -> STRef s ModP -> (Int, Int) -> ST s ModP
solveEdge uf eqs (a, b) = do
merged <- mergeUF uf a b
unless merged $ modifySTRef eqs (*2)
readSTRef eqs
type UnionFind s = STUArray s Int Int
buildUF :: (Int, Int) -> ST s (UnionFind s)
buildUF bnds = newArray bnds (-1)
findUF :: UnionFind s -> Int -> ST s Int
findUF uf a = do
fa <- readArray uf a
if fa == -1
then return a
else do
ret <- findUF uf fa
writeArray uf a ret
return ret
mergeUF :: UnionFind s -> Int -> Int -> ST s Bool
mergeUF uf a b = do
fa <- findUF uf a
fb <- findUF uf b
if fa == fb
then return False
else do
writeArray uf fa fb
return True
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
class (Monad m) => MonadState s m | m -> s where
get :: m s
put :: s -> m ()
modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
s <- get
put (f s)
gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
s <- get
return (f s)
newtype State s a = State { runState :: s -> (a, s) }
instance Functor (State s) where
fmap f m = State $ \s -> let
(a, s') = runState m s
in (f a, s')
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return a = State $ \s -> (a, s)
m >>= k = State $ \s -> let
(a, s') = runState m s
in runState (k a) s'
instance MonadState s (State s) where
get = State $ \s -> (s, s)
put s = State $ \_ -> ((), s)
evalState :: State s a -> s -> a
evalState m s = fst (runState m s)
execState :: State s a -> s -> s
execState m s = snd (runState m s)
mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m
withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f
state = State
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/codeforces.com/91/C.hs | haskell | # OPTIONS_GHC -O2 #
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances #
import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control . Monad . State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
import Control.Monad.ST
import Data.Array.ST
import Data.STRef
parseInput = do
n <- readInt
m <- readInt
edges <- replicateM m ((,) <$> readInt <*> readInt)
return (n, edges)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = BS.putStr =<< solve . evalState parseInput <$> BS.getContents
modulo :: Int
modulo = 1000000009
newtype ModP = ModP Int deriving Eq
instance Num ModP where
ModP a + ModP b = ModP $ (a + b) `mod` modulo
ModP a - ModP b = ModP $ (a - b) `mod` modulo
ModP a * ModP b = ModP $ (a * b) `mod` modulo
fromInteger = ModP . fromInteger
signum = undefined
abs = undefined
instance Show ModP where
show (ModP a) = show a
solve :: (Int, [(Int, Int)]) -> ByteString
solve (n, edges) = BS.unlines . map (BS.pack . show . (\x -> x-1)) $ runST stMonad
where
stMonad :: ST s [ModP]
stMonad = do
uf <- buildUF (1, n) :: ST s (UnionFind s)
eqs <- newSTRef 1 :: ST s (STRef s ModP)
mapM (solveEdge uf eqs) edges
solveEdge :: UnionFind s -> STRef s ModP -> (Int, Int) -> ST s ModP
solveEdge uf eqs (a, b) = do
merged <- mergeUF uf a b
unless merged $ modifySTRef eqs (*2)
readSTRef eqs
type UnionFind s = STUArray s Int Int
buildUF :: (Int, Int) -> ST s (UnionFind s)
buildUF bnds = newArray bnds (-1)
findUF :: UnionFind s -> Int -> ST s Int
findUF uf a = do
fa <- readArray uf a
if fa == -1
then return a
else do
ret <- findUF uf fa
writeArray uf a ret
return ret
mergeUF :: UnionFind s -> Int -> Int -> ST s Bool
mergeUF uf a b = do
fa <- findUF uf a
fb <- findUF uf b
if fa == fb
then return False
else do
writeArray uf fa fb
return True
class (Monad m) => MonadState s m | m -> s where
get :: m s
put :: s -> m ()
modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
s <- get
put (f s)
gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
s <- get
return (f s)
newtype State s a = State { runState :: s -> (a, s) }
instance Functor (State s) where
fmap f m = State $ \s -> let
(a, s') = runState m s
in (f a, s')
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return a = State $ \s -> (a, s)
m >>= k = State $ \s -> let
(a, s') = runState m s
in runState (k a) s'
instance MonadState s (State s) where
get = State $ \s -> (s, s)
put s = State $ \_ -> ((), s)
evalState :: State s a -> s -> a
evalState m s = fst (runState m s)
execState :: State s a -> s -> s
execState m s = snd (runState m s)
mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m
withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f
state = State
|
c52e5b89e0c4409ad972cf8be43d4fbdf18b42c32081ec0a663f05293e30529b | serokell/time-warp | Main.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
module Main
( main
, yohohoScenario
,
, transferScenario
, proxyScenario
, slowpokeScenario
, closingServerScenario
, pendingForkStrategy
, runEmulation
-- , runReal
) where
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Concurrent.STM.TVar (modifyTVar, newTVar, readTVar)
import Control.Monad (forM_, replicateM_, when)
import Control.Monad.STM (atomically)
import Control.Monad.Trans (MonadIO (liftIO))
import Data.Binary (Binary, Get, Put, get, put)
import Data.Conduit (yield, (=$=))
import qualified Data.Conduit.List as CL
import Data.Conduit.Serialization.Binary (conduitGet, conduitPut)
import Data.Data (Data)
import Data.Default (def)
import Data.MessagePack (MessagePack (..))
import Data.Monoid ((<>))
import Data.Text.Buildable (Buildable (..))
import Data.Word (Word16)
import Formatting (sformat, shown, string, (%))
import GHC.Generics (Generic)
import System.Wlog (LoggerConfig (..), LoggerName,
Severity (Debug), logDebug, logInfo,
setupLogging, usingLoggerName)
import Control.TimeWarp.Rpc (BinaryP (..), Binding (..),
ForkStrategy (..), Listener (..),
ListenerH (..), Message,
MonadTransfer (..), NetworkAddress,
Port, listen, listenH, listenR,
localhost, messageName', plainBinaryP,
reconnectPolicy, reply, replyRaw,
runDialog, runTransfer, runTransferS,
send, sendH, sendR, setForkStrategy)
import Control.TimeWarp.Timed (MonadTimed (wait), Second, after, for,
fork_, interval, ms, runTimedIO,
schedule, sec, sec', till)
-- use ghci; this is only for logger debugging
main :: IO ()
main = return ()
runReal : : MsgPackRpc a - > IO a
runReal = runMsgPackRpc
runEmulation : : a - > IO a
runEmulation scenario = do
gen < - newStdGen
runPureRpc delays gen scenario
where
delays : : Microsecond
delays = interval 50 ms
runReal :: MsgPackRpc a -> IO a
runReal = runMsgPackRpc
runEmulation :: PureRpc IO a -> IO a
runEmulation scenario = do
gen <- newStdGen
runPureRpc delays gen scenario
where
delays :: Microsecond
delays = interval 50 ms
-}
-- * data types
data Ping = Ping
deriving (Generic, Data, Binary, MessagePack, Message)
instance Buildable Ping where
build _ = "Ping"
data Pong = Pong
deriving (Generic, Data, Binary, MessagePack, Message)
instance Buildable Pong where
build _ = "Pong"
data EpicRequest = EpicRequest
{ num :: Int
, msg :: String
} deriving (Generic, Data, Binary, MessagePack)
instance Buildable EpicRequest where
build EpicRequest{..} = "EpicRequest " <> build num <> " " <> build msg
instance Message EpicRequest
-- * scenarios
-- | Examples management info.
narrator :: LoggerName
narrator = "*"
initLogging :: MonadIO m => m ()
initLogging =
setupLogging Nothing mempty{ _lcTermSeverity = Just Debug }
Emulates dialog of two guys , maybe several times , in parallel :
1 :
2 : Pong
1 : EpicRequest ...
2 : < prints result >
yohohoScenario :: IO ()
yohohoScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
guy 1
newNode "guy.1" . fork_ $ do
saveWorker $ listen (AtPort $ guysPort 1)
[ Listener $ \Pong ->
do logDebug "Got Pong!"
reply $ EpicRequest 14 " men on the dead man's chest"
]
guy 1 initiates dialog
wait (for 100 ms)
replicateM_ 2 $ do
send (guy 2) Ping
logInfo "Sent"
guy 2
newNode "guy.2" . fork_ $ do
saveWorker $ listen (AtPort $ guysPort 2)
[ Listener $ \Ping ->
do logDebug "Got Ping!"
send (guy 1) Pong
]
saveWorker $ listen (AtConnTo $ guy 1)
[ Listener $ \EpicRequest{..} ->
do logDebug "Got EpicRequest!"
wait (for 0.1 sec')
logInfo $ sformat (shown%string) (num + 1) msg
]
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 5
newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
guy :: Word16 -> NetworkAddress
guy = (localhost, ) . guysPort
guysPort :: Word16 -> Port
guysPort = (+10000)
-- | Example of `Transfer` usage
transferScenario :: IO ()
transferScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
newNode "node.server" $
let listener req = do
logInfo $ sformat ("Got "%shown) req
replyRaw $ yield (put $ sformat "Ok!") =$= conduitPut
in saveWorker $ listenRaw (AtPort 1234) $
conduitGet decoder =$= CL.mapM_ listener
wait (for 100 ms)
newNode "node.client-1" $
schedule (after 200 ms) $ do
saveWorker $ listenRaw (AtConnTo (localhost, 1234)) $
conduitGet get =$= CL.mapM_ logInfo
forM_ ([1..5] :: [Int]) $ \i ->
sendRaw (localhost, 1234) $ yield i
=$= CL.map Left
=$= CL.map encoder
=$= conduitPut
-- =$= awaitForever (\m -> yield "trash" >> yield m)
newNode "node.client-2" $
schedule (after 200 ms) $ do
sendRaw (localhost, 1234) $ CL.sourceList ([1..5] :: [Int])
=$= CL.map (, -1)
=$= CL.map Right
=$= CL.map encoder
=$= conduitPut
saveWorker $ listenRaw (AtConnTo (localhost, 1234)) $
conduitGet get =$= CL.mapM_ logInfo
wait (for 1000 ms)
newNode narrator killWorkers
wait (for 100 ms)
where
decoder :: Get (Either Int (Int, Int))
decoder = do
magic <- get
when (magic /= magicVal) $
fail "Missed magic constant!"
get
encoder :: Either Int (Int, Int) -> Put
encoder d = put magicVal >> put d
magicVal :: Int
magicVal = 234
newNode name = usingLoggerName name . runTransfer (pure ())
rpcScenario : : IO ( )
rpcScenario = runTimedIO $ do
liftIO $ initLogging [ " server " , " cli " ] Debug
usingLoggerName " server " . runTransfer . runBinaryDialog . runRpc $
work ( till finish ) $
serve 1234
[ Method $ \Ping - > do
do ! Wait a sec ... "
wait ( for 1000 ms )
logInfo " Replying "
return Pong
]
wait ( for 100 ms )
usingLoggerName " client " . runTransfer . runBinaryDialog . runRpc $ do
( localhost , 1234 )
logInfo " Got Pong ! "
return ( )
where
finish : : Second
finish = 5
rpcScenario :: IO ()
rpcScenario = runTimedIO $ do
liftIO $ initLogging ["server", "cli"] Debug
usingLoggerName "server" . runTransfer . runBinaryDialog . runRpc $
work (till finish) $
serve 1234
[ Method $ \Ping -> do
do logInfo "Got Ping! Wait a sec..."
wait (for 1000 ms)
logInfo "Replying"
return Pong
]
wait (for 100 ms)
usingLoggerName "client" . runTransfer . runBinaryDialog . runRpc $ do
Pong <- call (localhost, 1234) Ping
logInfo "Got Pong!"
return ()
where
finish :: Second
finish = 5
-}
-- * Blind proxy scenario, illustrates work with headers and raw data.
proxyScenario :: IO ()
proxyScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
lock <- liftIO newEmptyMVar
let sync act = liftIO (putMVar lock ()) >> act >> liftIO (takeMVar lock)
-- server
newNode "server" . fork_ $
saveWorker $ listenH (AtPort 5678)
[ ListenerH $ \(h, EpicRequest{..}) -> sync . logInfo $
sformat ("Got request!: "%shown%" "%shown%"; h = "%shown)
num msg (int h)
]
-- proxy
newNode "proxy" . fork_ $
saveWorker $ listenR (AtPort 1234)
[ ListenerH $ \(h, EpicRequest _ _) -> sync . logInfo $
sformat ("Proxy! h = "%shown) h
]
$ \(h, raw) -> do
when (h < 5) $ do
sendR (localhost, 5678) h raw
sync $ logInfo $ sformat ("Resend "%shown) h
return $ even (int h)
wait (for 100 ms)
-- client
newNode "client" . fork_ $
forM_ [1..10] $
\i -> sendH (localhost, 1234) (int i) $ EpicRequest 34 "lol"
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 1
newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog packing
packing :: BinaryP Int
packing = BinaryP
int :: Int -> Int
int = id
-- | Slowpoke server scenario
slowpokeScenario :: IO ()
slowpokeScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
newNode "server" . fork_ $ do
wait (for 3 sec)
saveWorker $ listen (AtPort 1234)
[ Listener $ \Ping -> logDebug "Got Ping!"
]
newNode "client" . fork_ $ do
wait (for 100 ms)
replicateM_ 3 $ send (localhost, 1234) Ping
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 5
newNode name = usingLoggerName name . runTransferS settings (pure ())
. runDialog plainBinaryP
settings = def
{ reconnectPolicy = \failsInRow -> return $
if failsInRow < 5 then Just (interval 1 sec) else Nothing
}
closingServerScenario :: IO ()
closingServerScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
newNode "server" . fork_ $
saveWorker $ listen (AtPort 1234) []
wait (for 100 ms)
newNode "client" $
replicateM_ 3 $ do
closer <- listen (AtConnTo (localhost, 1234)) []
wait (for 500 ms)
closer
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 3
newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
pendingForkStrategy :: IO ()
pendingForkStrategy = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
newNode "server" . fork_ $
saveWorker $ setForkStrategy forkStrategy $
listen (AtPort 1234)
[ Listener $ \Ping -> do
logInfo "Got Ping, wait 1 sec"
wait (for 1 sec)
]
wait (for 100 ms)
newNode "client" . fork_ $ do
wait (for 100 ms)
replicateM_ 5 $ send (localhost, 1234) Ping
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 6
forkStrategy = ForkStrategy $ \msgName act ->
if msgName == messageName' Ping
then act -- execute in-place
else fork_ act -- execute in another thread
newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
workersManager :: MonadIO m => m (m (m ()) -> m (), m ())
workersManager = do
t <- liftIO . atomically $ newTVar []
let saveWorker action = do
closer <- action
liftIO . atomically $ modifyTVar t (closer:)
killWorkers = sequence_ =<< liftIO (atomically $ readTVar t)
return (saveWorker, killWorkers)
| null | https://raw.githubusercontent.com/serokell/time-warp/2783f81957a2e5b02e9d3425d760247a6c5a766b/examples/playground/Main.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
, runReal
use ghci; this is only for logger debugging
* data types
* scenarios
| Examples management info.
| Example of `Transfer` usage
=$= awaitForever (\m -> yield "trash" >> yield m)
* Blind proxy scenario, illustrates work with headers and raw data.
server
proxy
client
| Slowpoke server scenario
execute in-place
execute in another thread | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
module Main
( main
, yohohoScenario
,
, transferScenario
, proxyScenario
, slowpokeScenario
, closingServerScenario
, pendingForkStrategy
, runEmulation
) where
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Concurrent.STM.TVar (modifyTVar, newTVar, readTVar)
import Control.Monad (forM_, replicateM_, when)
import Control.Monad.STM (atomically)
import Control.Monad.Trans (MonadIO (liftIO))
import Data.Binary (Binary, Get, Put, get, put)
import Data.Conduit (yield, (=$=))
import qualified Data.Conduit.List as CL
import Data.Conduit.Serialization.Binary (conduitGet, conduitPut)
import Data.Data (Data)
import Data.Default (def)
import Data.MessagePack (MessagePack (..))
import Data.Monoid ((<>))
import Data.Text.Buildable (Buildable (..))
import Data.Word (Word16)
import Formatting (sformat, shown, string, (%))
import GHC.Generics (Generic)
import System.Wlog (LoggerConfig (..), LoggerName,
Severity (Debug), logDebug, logInfo,
setupLogging, usingLoggerName)
import Control.TimeWarp.Rpc (BinaryP (..), Binding (..),
ForkStrategy (..), Listener (..),
ListenerH (..), Message,
MonadTransfer (..), NetworkAddress,
Port, listen, listenH, listenR,
localhost, messageName', plainBinaryP,
reconnectPolicy, reply, replyRaw,
runDialog, runTransfer, runTransferS,
send, sendH, sendR, setForkStrategy)
import Control.TimeWarp.Timed (MonadTimed (wait), Second, after, for,
fork_, interval, ms, runTimedIO,
schedule, sec, sec', till)
main :: IO ()
main = return ()
runReal : : MsgPackRpc a - > IO a
runReal = runMsgPackRpc
runEmulation : : a - > IO a
runEmulation scenario = do
gen < - newStdGen
runPureRpc delays gen scenario
where
delays : : Microsecond
delays = interval 50 ms
runReal :: MsgPackRpc a -> IO a
runReal = runMsgPackRpc
runEmulation :: PureRpc IO a -> IO a
runEmulation scenario = do
gen <- newStdGen
runPureRpc delays gen scenario
where
delays :: Microsecond
delays = interval 50 ms
-}
data Ping = Ping
deriving (Generic, Data, Binary, MessagePack, Message)
instance Buildable Ping where
build _ = "Ping"
data Pong = Pong
deriving (Generic, Data, Binary, MessagePack, Message)
instance Buildable Pong where
build _ = "Pong"
data EpicRequest = EpicRequest
{ num :: Int
, msg :: String
} deriving (Generic, Data, Binary, MessagePack)
instance Buildable EpicRequest where
build EpicRequest{..} = "EpicRequest " <> build num <> " " <> build msg
instance Message EpicRequest
narrator :: LoggerName
narrator = "*"
initLogging :: MonadIO m => m ()
initLogging =
setupLogging Nothing mempty{ _lcTermSeverity = Just Debug }
Emulates dialog of two guys , maybe several times , in parallel :
1 :
2 : Pong
1 : EpicRequest ...
2 : < prints result >
yohohoScenario :: IO ()
yohohoScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
guy 1
newNode "guy.1" . fork_ $ do
saveWorker $ listen (AtPort $ guysPort 1)
[ Listener $ \Pong ->
do logDebug "Got Pong!"
reply $ EpicRequest 14 " men on the dead man's chest"
]
guy 1 initiates dialog
wait (for 100 ms)
replicateM_ 2 $ do
send (guy 2) Ping
logInfo "Sent"
guy 2
newNode "guy.2" . fork_ $ do
saveWorker $ listen (AtPort $ guysPort 2)
[ Listener $ \Ping ->
do logDebug "Got Ping!"
send (guy 1) Pong
]
saveWorker $ listen (AtConnTo $ guy 1)
[ Listener $ \EpicRequest{..} ->
do logDebug "Got EpicRequest!"
wait (for 0.1 sec')
logInfo $ sformat (shown%string) (num + 1) msg
]
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 5
newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
guy :: Word16 -> NetworkAddress
guy = (localhost, ) . guysPort
guysPort :: Word16 -> Port
guysPort = (+10000)
transferScenario :: IO ()
transferScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
newNode "node.server" $
let listener req = do
logInfo $ sformat ("Got "%shown) req
replyRaw $ yield (put $ sformat "Ok!") =$= conduitPut
in saveWorker $ listenRaw (AtPort 1234) $
conduitGet decoder =$= CL.mapM_ listener
wait (for 100 ms)
newNode "node.client-1" $
schedule (after 200 ms) $ do
saveWorker $ listenRaw (AtConnTo (localhost, 1234)) $
conduitGet get =$= CL.mapM_ logInfo
forM_ ([1..5] :: [Int]) $ \i ->
sendRaw (localhost, 1234) $ yield i
=$= CL.map Left
=$= CL.map encoder
=$= conduitPut
newNode "node.client-2" $
schedule (after 200 ms) $ do
sendRaw (localhost, 1234) $ CL.sourceList ([1..5] :: [Int])
=$= CL.map (, -1)
=$= CL.map Right
=$= CL.map encoder
=$= conduitPut
saveWorker $ listenRaw (AtConnTo (localhost, 1234)) $
conduitGet get =$= CL.mapM_ logInfo
wait (for 1000 ms)
newNode narrator killWorkers
wait (for 100 ms)
where
decoder :: Get (Either Int (Int, Int))
decoder = do
magic <- get
when (magic /= magicVal) $
fail "Missed magic constant!"
get
encoder :: Either Int (Int, Int) -> Put
encoder d = put magicVal >> put d
magicVal :: Int
magicVal = 234
newNode name = usingLoggerName name . runTransfer (pure ())
rpcScenario : : IO ( )
rpcScenario = runTimedIO $ do
liftIO $ initLogging [ " server " , " cli " ] Debug
usingLoggerName " server " . runTransfer . runBinaryDialog . runRpc $
work ( till finish ) $
serve 1234
[ Method $ \Ping - > do
do ! Wait a sec ... "
wait ( for 1000 ms )
logInfo " Replying "
return Pong
]
wait ( for 100 ms )
usingLoggerName " client " . runTransfer . runBinaryDialog . runRpc $ do
( localhost , 1234 )
logInfo " Got Pong ! "
return ( )
where
finish : : Second
finish = 5
rpcScenario :: IO ()
rpcScenario = runTimedIO $ do
liftIO $ initLogging ["server", "cli"] Debug
usingLoggerName "server" . runTransfer . runBinaryDialog . runRpc $
work (till finish) $
serve 1234
[ Method $ \Ping -> do
do logInfo "Got Ping! Wait a sec..."
wait (for 1000 ms)
logInfo "Replying"
return Pong
]
wait (for 100 ms)
usingLoggerName "client" . runTransfer . runBinaryDialog . runRpc $ do
Pong <- call (localhost, 1234) Ping
logInfo "Got Pong!"
return ()
where
finish :: Second
finish = 5
-}
proxyScenario :: IO ()
proxyScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
lock <- liftIO newEmptyMVar
let sync act = liftIO (putMVar lock ()) >> act >> liftIO (takeMVar lock)
newNode "server" . fork_ $
saveWorker $ listenH (AtPort 5678)
[ ListenerH $ \(h, EpicRequest{..}) -> sync . logInfo $
sformat ("Got request!: "%shown%" "%shown%"; h = "%shown)
num msg (int h)
]
newNode "proxy" . fork_ $
saveWorker $ listenR (AtPort 1234)
[ ListenerH $ \(h, EpicRequest _ _) -> sync . logInfo $
sformat ("Proxy! h = "%shown) h
]
$ \(h, raw) -> do
when (h < 5) $ do
sendR (localhost, 5678) h raw
sync $ logInfo $ sformat ("Resend "%shown) h
return $ even (int h)
wait (for 100 ms)
newNode "client" . fork_ $
forM_ [1..10] $
\i -> sendH (localhost, 1234) (int i) $ EpicRequest 34 "lol"
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 1
newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog packing
packing :: BinaryP Int
packing = BinaryP
int :: Int -> Int
int = id
slowpokeScenario :: IO ()
slowpokeScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
newNode "server" . fork_ $ do
wait (for 3 sec)
saveWorker $ listen (AtPort 1234)
[ Listener $ \Ping -> logDebug "Got Ping!"
]
newNode "client" . fork_ $ do
wait (for 100 ms)
replicateM_ 3 $ send (localhost, 1234) Ping
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 5
newNode name = usingLoggerName name . runTransferS settings (pure ())
. runDialog plainBinaryP
settings = def
{ reconnectPolicy = \failsInRow -> return $
if failsInRow < 5 then Just (interval 1 sec) else Nothing
}
closingServerScenario :: IO ()
closingServerScenario = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
newNode "server" . fork_ $
saveWorker $ listen (AtPort 1234) []
wait (for 100 ms)
newNode "client" $
replicateM_ 3 $ do
closer <- listen (AtConnTo (localhost, 1234)) []
wait (for 500 ms)
closer
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 3
newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
pendingForkStrategy :: IO ()
pendingForkStrategy = runTimedIO $ do
initLogging
(saveWorker, killWorkers) <- newNode narrator workersManager
newNode "server" . fork_ $
saveWorker $ setForkStrategy forkStrategy $
listen (AtPort 1234)
[ Listener $ \Ping -> do
logInfo "Got Ping, wait 1 sec"
wait (for 1 sec)
]
wait (for 100 ms)
newNode "client" . fork_ $ do
wait (for 100 ms)
replicateM_ 5 $ send (localhost, 1234) Ping
wait (till finish)
newNode narrator killWorkers
wait (for 100 ms)
where
finish :: Second
finish = 6
forkStrategy = ForkStrategy $ \msgName act ->
if msgName == messageName' Ping
newNode name = usingLoggerName name . runTransfer (pure ()) . runDialog plainBinaryP
workersManager :: MonadIO m => m (m (m ()) -> m (), m ())
workersManager = do
t <- liftIO . atomically $ newTVar []
let saveWorker action = do
closer <- action
liftIO . atomically $ modifyTVar t (closer:)
killWorkers = sequence_ =<< liftIO (atomically $ readTVar t)
return (saveWorker, killWorkers)
|
8edfd5dea27810c039000f22e9637a013763444e2dc46f1347b412bdb23725e0 | simonmar/monad-par | issue21.hs |
$ cabal install -O2 monad - par-0.3
$ ghc -O2 -threaded -rtsopts -with - rtsopts -N issue21.hs -o issue21.exe
$ ./issue21.exe 10000000
2089877
$ ./issue21.exe 10000000
issue21 : < < loop>>issue21 : issue21 : issue21 : thread blocked indefinitely in an MVar operation
< < loop > >
< < loop > >
issue21 : < < loop > >
$ ghc -V
The Glorious Glasgow Haskell Compilation System , version 7.4.1
$ cabal install -O2 monad-par-0.3
$ ghc -O2 -threaded -rtsopts -with-rtsopts -N issue21.hs -o issue21.exe
$ ./issue21.exe 10000000
2089877
$ ./issue21.exe 10000000
issue21: <<loop>>issue21: issue21: issue21: thread blocked indefinitely in an MVar operation
<<loop>>
<<loop>>
issue21: <<loop>>
$ ghc -V
The Glorious Glasgow Haskell Compilation System, version 7.4.1
-}
# LANGUAGE CPP #
#ifdef PARSCHED
import PARSCHED
#else
import Control . . Par
This bug was reported for the Trace scheduler :
import Control . . Par . . Trace
import Control . . Par . .
import Control.Monad.Par.Scheds.Direct
This is ALSO failing for 's meta - par scheduler !
import Control . . Par . Meta . SMP ( runPar , spawn , get )
#endif
import System.Environment (getArgs)
import Control.DeepSeq
import GHC.Conc (myThreadId, numCapabilities)
import System.IO (hPutStrLn,stderr)
data M = M !Integer !Integer !Integer !Integer
deriving Show
instance NFData M
instance Num M where
m * n = runPar $ do
m' <- spawn (return m)
n' <- spawn (return n)
m'' <- get m'
n'' <- get n'
return (m'' `mul` n'')
(M a b c d) `mul` (M x y z w) = M
(a * x + b * z) (a * y + b * w)
(c * x + d * z) (c * y + d * w)
fib :: Integer -> Integer
fib n = let M f _ _ _ = M 0 1 1 1 ^ (n + 1) in f
main :: IO ()
main = do
args <- getArgs
tid <- myThreadId
hPutStrLn stderr$"Beginning benchmark on: "++show tid ++ ", numCapabilities "++show numCapabilities
let n = case args of
-- Default to 10M to trigger the bug.
[] -> 10 * 1000 * 1000
[s] -> read s
print $ length $ show $ fib n
| null | https://raw.githubusercontent.com/simonmar/monad-par/1266b0ac1b4040963ab356cf032c6aae6b8a7add/tests/issue21.hs | haskell | Default to 10M to trigger the bug. |
$ cabal install -O2 monad - par-0.3
$ ghc -O2 -threaded -rtsopts -with - rtsopts -N issue21.hs -o issue21.exe
$ ./issue21.exe 10000000
2089877
$ ./issue21.exe 10000000
issue21 : < < loop>>issue21 : issue21 : issue21 : thread blocked indefinitely in an MVar operation
< < loop > >
< < loop > >
issue21 : < < loop > >
$ ghc -V
The Glorious Glasgow Haskell Compilation System , version 7.4.1
$ cabal install -O2 monad-par-0.3
$ ghc -O2 -threaded -rtsopts -with-rtsopts -N issue21.hs -o issue21.exe
$ ./issue21.exe 10000000
2089877
$ ./issue21.exe 10000000
issue21: <<loop>>issue21: issue21: issue21: thread blocked indefinitely in an MVar operation
<<loop>>
<<loop>>
issue21: <<loop>>
$ ghc -V
The Glorious Glasgow Haskell Compilation System, version 7.4.1
-}
# LANGUAGE CPP #
#ifdef PARSCHED
import PARSCHED
#else
import Control . . Par
This bug was reported for the Trace scheduler :
import Control . . Par . . Trace
import Control . . Par . .
import Control.Monad.Par.Scheds.Direct
This is ALSO failing for 's meta - par scheduler !
import Control . . Par . Meta . SMP ( runPar , spawn , get )
#endif
import System.Environment (getArgs)
import Control.DeepSeq
import GHC.Conc (myThreadId, numCapabilities)
import System.IO (hPutStrLn,stderr)
data M = M !Integer !Integer !Integer !Integer
deriving Show
instance NFData M
instance Num M where
m * n = runPar $ do
m' <- spawn (return m)
n' <- spawn (return n)
m'' <- get m'
n'' <- get n'
return (m'' `mul` n'')
(M a b c d) `mul` (M x y z w) = M
(a * x + b * z) (a * y + b * w)
(c * x + d * z) (c * y + d * w)
fib :: Integer -> Integer
fib n = let M f _ _ _ = M 0 1 1 1 ^ (n + 1) in f
main :: IO ()
main = do
args <- getArgs
tid <- myThreadId
hPutStrLn stderr$"Beginning benchmark on: "++show tid ++ ", numCapabilities "++show numCapabilities
let n = case args of
[] -> 10 * 1000 * 1000
[s] -> read s
print $ length $ show $ fib n
|
28ef6e93aa294efafefeda14a43bec8eecb399107e375acf6cf1f0745cf117d0 | YoshikuniJujo/test_haskell | makeEnumVkDynamicState.hs | # OPTIONS_GHC -Wall -fno - warn - tabs #
module Main where
import MakeEnum
main :: IO ()
main = makeEnum'
"/usr/include/vulkan/vulkan_core.h" ["Foreign.Ptr"]
"DynamicState" "VkDynamicState"
["Show", "Eq", "Storable"]
"type PtrDynamicState = Ptr DynamicState"
| null | https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/abf9fb3dd4be311e1182751f0888270ea431630d/themes/gui/vulkan/try-my-vulkan/tools/makeEnumVkDynamicState.hs | haskell | # OPTIONS_GHC -Wall -fno - warn - tabs #
module Main where
import MakeEnum
main :: IO ()
main = makeEnum'
"/usr/include/vulkan/vulkan_core.h" ["Foreign.Ptr"]
"DynamicState" "VkDynamicState"
["Show", "Eq", "Storable"]
"type PtrDynamicState = Ptr DynamicState"
|
|
19c9ffeaa50e997a824724cb4a3083b5413e6c6ec673f3a579e670727774c328 | roterski/syncrate-fulcro | validations.cljc | (ns app.posts.validations
(:require
#?(:clj [clojure.spec.alpha :as s]
:cljs [cljs.spec.alpha :as s])))
(s/def :post/title (s/and string? #(<= 3 (count %))))
(s/def :post/body (s/and string? #(< 0 (count %))))
(s/def ::post (s/keys :req [:post/title :post/body]))
(defn valid-post? [attrs] (s/valid? ::post attrs))
| null | https://raw.githubusercontent.com/roterski/syncrate-fulcro/3fda40b12973e64c7ff976174498ec512b411323/src/main/app/posts/validations.cljc | clojure | (ns app.posts.validations
(:require
#?(:clj [clojure.spec.alpha :as s]
:cljs [cljs.spec.alpha :as s])))
(s/def :post/title (s/and string? #(<= 3 (count %))))
(s/def :post/body (s/and string? #(< 0 (count %))))
(s/def ::post (s/keys :req [:post/title :post/body]))
(defn valid-post? [attrs] (s/valid? ::post attrs))
|
|
596c25af1d6e38e65e4a77a744bc9bfb9dc2384fa51bc16c6c8326f7766db2a1 | lucassouzamatos/chico.lang | chico_tokenizer.erl | -file("/opt/homebrew/Cellar/erlang/25.2/lib/erlang/lib/parsetools-2.4.1/include/leexinc.hrl", 0).
%% The source of this file is part of leex distribution, as such it
%% has the same Copyright as the other files in the leex
%% distribution. The Copyright is defined in the accompanying file
COPYRIGHT . However , the resultant scanner generated by is the
%% property of the creator of the scanner and is not covered by that
%% Copyright.
-module(chico_tokenizer).
-export([string/1, string/2, token/2, token/3, tokens/2, tokens/3]).
-export([format_error/1]).
%% User code. This is placed here to allow extra attributes.
-file("./chico_tokenizer.xrl", 54).
get_string(TokenChars, TokenLen) ->
S = lists:sublist(TokenChars, 2, TokenLen - 2),
list_to_atom(S).
-file("/opt/homebrew/Cellar/erlang/25.2/lib/erlang/lib/parsetools-2.4.1/include/leexinc.hrl", 14).
format_error({illegal, S}) -> ["illegal characters ", io_lib:write_string(S)];
format_error({user, S}) -> S.
string(String) -> string(String, 1).
string(String, Line) -> string(String, Line, String, []).
string(InChars , , , Tokens ) - >
{ ok , Tokens , Line } | { error , ErrorInfo , Line } .
Note the line number going into yystate , L0 , is line of token
%% start while line number returned is line of token end. We want line
%% of token start.
string([], L, [], Ts) ->
% No partial tokens!
{ok, yyrev(Ts), L};
string(Ics0, L0, Tcs, Ts) ->
case yystate(yystate(), Ics0, L0, 0, reject, 0) of
{A, Alen, Ics1, L1} ->
% Accepting end state
string_cont(Ics1, L1, yyaction(A, Alen, Tcs, L0), Ts);
{A, Alen, Ics1, L1, _S1} ->
% Accepting transition state
string_cont(Ics1, L1, yyaction(A, Alen, Tcs, L0), Ts);
{reject, _Alen, Tlen, _Ics1, L1, _S1} ->
% After a non-accepting state
{error, {L0, ?MODULE, {illegal, yypre(Tcs, Tlen + 1)}}, L1};
{A, Alen, Tlen, _Ics1, L1, _S1} ->
Tcs1 = yysuf(Tcs, Alen),
L2 = adjust_line(Tlen, Alen, Tcs1, L1),
string_cont(Tcs1, L2, yyaction(A, Alen, Tcs, L0), Ts)
end.
%% string_cont(RestChars, Line, Token, Tokens)
%% Test for and remove the end token wrapper. Push back characters
are prepended to RestChars .
-dialyzer({nowarn_function, string_cont/4}).
string_cont(Rest, Line, {token, T}, Ts) -> string(Rest, Line, Rest, [T | Ts]);
string_cont(Rest, Line, {token, T, Push}, Ts) ->
NewRest = Push ++ Rest,
string(NewRest, Line, NewRest, [T | Ts]);
string_cont(Rest, Line, {end_token, T}, Ts) -> string(Rest, Line, Rest, [T | Ts]);
string_cont(Rest, Line, {end_token, T, Push}, Ts) ->
NewRest = Push ++ Rest,
string(NewRest, Line, NewRest, [T | Ts]);
string_cont(Rest, Line, skip_token, Ts) -> string(Rest, Line, Rest, Ts);
string_cont(Rest, Line, {skip_token, Push}, Ts) ->
NewRest = Push ++ Rest,
string(NewRest, Line, NewRest, Ts);
string_cont(_Rest, Line, {error, S}, _Ts) -> {error, {Line, ?MODULE, {user, S}}, Line}.
%% token(Continuation, Chars) ->
%% token(Continuation, Chars, Line) ->
{ more , Continuation } | { done , ReturnVal , RestChars } .
%% Must be careful when re-entering to append the latest characters to the
%% after characters in an accept. The continuation is:
{ token , State , CurrLine , , TokenLen , TokenLine , AccAction , AccLen }
token(Cont, Chars) -> token(Cont, Chars, 1).
token([], Chars, Line) -> token(yystate(), Chars, Line, Chars, 0, Line, reject, 0);
token({token, State, Line, Tcs, Tlen, Tline, Action, Alen}, Chars, _) ->
token(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Action, Alen).
token(State , InChars , Line , , TokenLen , TokenLine ,
AcceptAction , AcceptLen ) - >
{ more , Continuation } | { done , ReturnVal , RestChars } .
%% The argument order is chosen to be more efficient.
token(S0, Ics0, L0, Tcs, Tlen0, Tline, A0, Alen0) ->
case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of
%% Accepting end state, we have a token.
{A1, Alen1, Ics1, L1} -> token_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline));
%% Accepting transition state, can take more chars.
{A1, Alen1, [], L1, S1} ->
% Need more chars to check
{more, {token, S1, L1, Tcs, Alen1, Tline, A1, Alen1}};
{A1, Alen1, Ics1, L1, _S1} ->
% Take what we got
token_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline));
%% After a non-accepting state, maybe reach accept state later.
{A1, Alen1, Tlen1, [], L1, S1} ->
% Need more chars to check
{more, {token, S1, L1, Tcs, Tlen1, Tline, A1, Alen1}};
{reject, _Alen1, Tlen1, eof, L1, _S1} ->
% No token match
%% Check for partial token which is error.
Ret =
if
Tlen1 > 0 ->
{
error,
{
Tline,
?MODULE,
Skip eof tail in Tcs .
{illegal, yypre(Tcs, Tlen1)}
},
L1
};
true -> {eof, L1}
end,
{done, Ret, eof};
{reject, _Alen1, Tlen1, Ics1, L1, _S1} ->
% No token match
Error = {Tline, ?MODULE, {illegal, yypre(Tcs, Tlen1 + 1)}},
{done, {error, Error, L1}, Ics1};
{A1, Alen1, Tlen1, _Ics1, L1, _S1} ->
% Use last accept match
Tcs1 = yysuf(Tcs, Alen1),
L2 = adjust_line(Tlen1, Alen1, Tcs1, L1),
token_cont(Tcs1, L2, yyaction(A1, Alen1, Tcs, Tline))
end.
%% token_cont(RestChars, Line, Token)
%% If we have a token or error then return done, else if we have a
%% skip_token then continue.
-dialyzer({nowarn_function, token_cont/3}).
token_cont(Rest, Line, {token, T}) -> {done, {ok, T, Line}, Rest};
token_cont(Rest, Line, {token, T, Push}) ->
NewRest = Push ++ Rest,
{done, {ok, T, Line}, NewRest};
token_cont(Rest, Line, {end_token, T}) -> {done, {ok, T, Line}, Rest};
token_cont(Rest, Line, {end_token, T, Push}) ->
NewRest = Push ++ Rest,
{done, {ok, T, Line}, NewRest};
token_cont(Rest, Line, skip_token) -> token(yystate(), Rest, Line, Rest, 0, Line, reject, 0);
token_cont(Rest, Line, {skip_token, Push}) ->
NewRest = Push ++ Rest,
token(yystate(), NewRest, Line, NewRest, 0, Line, reject, 0);
token_cont(Rest, Line, {error, S}) -> {done, {error, {Line, ?MODULE, {user, S}}, Line}, Rest}.
tokens(Continuation , Chars , Line ) - >
{ more , Continuation } | { done , ReturnVal , RestChars } .
%% Must be careful when re-entering to append the latest characters to the
%% after characters in an accept. The continuation is:
{ tokens , State , CurrLine , , TokenLen , TokenLine , Tokens , AccAction , AccLen }
{ skip_tokens , State , CurrLine , , TokenLen , TokenLine , Error , AccAction , AccLen }
tokens(Cont, Chars) -> tokens(Cont, Chars, 1).
tokens([], Chars, Line) -> tokens(yystate(), Chars, Line, Chars, 0, Line, [], reject, 0);
tokens({tokens, State, Line, Tcs, Tlen, Tline, Ts, Action, Alen}, Chars, _) ->
tokens(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Ts, Action, Alen);
tokens({skip_tokens, State, Line, Tcs, Tlen, Tline, Error, Action, Alen}, Chars, _) ->
skip_tokens(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Error, Action, Alen).
tokens(State , InChars , Line , , TokenLen , TokenLine , Tokens ,
AcceptAction , AcceptLen ) - >
{ more , Continuation } | { done , ReturnVal , RestChars } .
tokens(S0, Ics0, L0, Tcs, Tlen0, Tline, Ts, A0, Alen0) ->
case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of
%% Accepting end state, we have a token.
{A1, Alen1, Ics1, L1} -> tokens_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Ts);
%% Accepting transition state, can take more chars.
{A1, Alen1, [], L1, S1} ->
% Need more chars to check
{more, {tokens, S1, L1, Tcs, Alen1, Tline, Ts, A1, Alen1}};
{A1, Alen1, Ics1, L1, _S1} ->
% Take what we got
tokens_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Ts);
%% After a non-accepting state, maybe reach accept state later.
{A1, Alen1, Tlen1, [], L1, S1} ->
% Need more chars to check
{more, {tokens, S1, L1, Tcs, Tlen1, Tline, Ts, A1, Alen1}};
{reject, _Alen1, Tlen1, eof, L1, _S1} ->
% No token match
%% Check for partial token which is error, no need to skip here.
Ret =
if
Tlen1 > 0 ->
{
error,
{
Tline,
?MODULE,
Skip eof tail in Tcs .
{illegal, yypre(Tcs, Tlen1)}
},
L1
};
Ts == [] -> {eof, L1};
true -> {ok, yyrev(Ts), L1}
end,
{done, Ret, eof};
{reject, _Alen1, Tlen1, _Ics1, L1, _S1} ->
%% Skip rest of tokens.
Error = {L1, ?MODULE, {illegal, yypre(Tcs, Tlen1 + 1)}},
skip_tokens(yysuf(Tcs, Tlen1 + 1), L1, Error);
{A1, Alen1, Tlen1, _Ics1, L1, _S1} ->
Token = yyaction(A1, Alen1, Tcs, Tline),
Tcs1 = yysuf(Tcs, Alen1),
L2 = adjust_line(Tlen1, Alen1, Tcs1, L1),
tokens_cont(Tcs1, L2, Token, Ts)
end.
%% tokens_cont(RestChars, Line, Token, Tokens)
%% If we have an end_token or error then return done, else if we have
a token then save it and continue , else if we have a
%% just continue.
-dialyzer({nowarn_function, tokens_cont/4}).
tokens_cont(Rest, Line, {token, T}, Ts) ->
tokens(yystate(), Rest, Line, Rest, 0, Line, [T | Ts], reject, 0);
tokens_cont(Rest, Line, {token, T, Push}, Ts) ->
NewRest = Push ++ Rest,
tokens(yystate(), NewRest, Line, NewRest, 0, Line, [T | Ts], reject, 0);
tokens_cont(Rest, Line, {end_token, T}, Ts) -> {done, {ok, yyrev(Ts, [T]), Line}, Rest};
tokens_cont(Rest, Line, {end_token, T, Push}, Ts) ->
NewRest = Push ++ Rest,
{done, {ok, yyrev(Ts, [T]), Line}, NewRest};
tokens_cont(Rest, Line, skip_token, Ts) ->
tokens(yystate(), Rest, Line, Rest, 0, Line, Ts, reject, 0);
tokens_cont(Rest, Line, {skip_token, Push}, Ts) ->
NewRest = Push ++ Rest,
tokens(yystate(), NewRest, Line, NewRest, 0, Line, Ts, reject, 0);
tokens_cont(Rest, Line, {error, S}, _Ts) -> skip_tokens(Rest, Line, {Line, ?MODULE, {user, S}}).
skip_tokens(InChars , Line , Error ) - > { done,{error , Error , } .
%% Skip tokens until an end token, junk everything and return the error.
skip_tokens(Ics, Line, Error) -> skip_tokens(yystate(), Ics, Line, Ics, 0, Line, Error, reject, 0).
skip_tokens(State , InChars , Line , , TokenLen , TokenLine , Tokens ,
AcceptAction , AcceptLen ) - >
{ more , Continuation } | { done , ReturnVal , RestChars } .
skip_tokens(S0, Ics0, L0, Tcs, Tlen0, Tline, Error, A0, Alen0) ->
case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of
{A1, Alen1, Ics1, L1} ->
% Accepting end state
skip_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Error);
{A1, Alen1, [], L1, S1} ->
% After an accepting state
{more, {skip_tokens, S1, L1, Tcs, Alen1, Tline, Error, A1, Alen1}};
{A1, Alen1, Ics1, L1, _S1} -> skip_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Error);
{A1, Alen1, Tlen1, [], L1, S1} ->
% After a non-accepting state
{more, {skip_tokens, S1, L1, Tcs, Tlen1, Tline, Error, A1, Alen1}};
{reject, _Alen1, _Tlen1, eof, L1, _S1} -> {done, {error, Error, L1}, eof};
{reject, _Alen1, Tlen1, _Ics1, L1, _S1} -> skip_tokens(yysuf(Tcs, Tlen1 + 1), L1, Error);
{A1, Alen1, Tlen1, _Ics1, L1, _S1} ->
Token = yyaction(A1, Alen1, Tcs, Tline),
Tcs1 = yysuf(Tcs, Alen1),
L2 = adjust_line(Tlen1, Alen1, Tcs1, L1),
skip_cont(Tcs1, L2, Token, Error)
end.
%% skip_cont(RestChars, Line, Token, Error)
%% Skip tokens until we have an end_token or error then return done
%% with the original rror.
-dialyzer({nowarn_function, skip_cont/4}).
skip_cont(Rest, Line, {token, _T}, Error) ->
skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0);
skip_cont(Rest, Line, {token, _T, Push}, Error) ->
NewRest = Push ++ Rest,
skip_tokens(yystate(), NewRest, Line, NewRest, 0, Line, Error, reject, 0);
skip_cont(Rest, Line, {end_token, _T}, Error) -> {done, {error, Error, Line}, Rest};
skip_cont(Rest, Line, {end_token, _T, Push}, Error) ->
NewRest = Push ++ Rest,
{done, {error, Error, Line}, NewRest};
skip_cont(Rest, Line, skip_token, Error) ->
skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0);
skip_cont(Rest, Line, {skip_token, Push}, Error) ->
NewRest = Push ++ Rest,
skip_tokens(yystate(), NewRest, Line, NewRest, 0, Line, Error, reject, 0);
skip_cont(Rest, Line, {error, _S}, Error) ->
skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0).
-compile({nowarn_unused_function, [yyrev/1, yyrev/2, yypre/2, yysuf/2]}).
yyrev(List) -> lists:reverse(List).
yyrev(List, Tail) -> lists:reverse(List, Tail).
yypre(List, N) -> lists:sublist(List, N).
yysuf(List, N) -> lists:nthtail(N, List).
adjust_line(TokenLength , AcceptLength , Chars , Line ) - > NewLine
Make sure that newlines in are not counted twice .
%% Line has been updated with respect to newlines in the prefix of
Chars consisting of ( TokenLength - AcceptLength ) characters .
-compile({nowarn_unused_function, adjust_line/4}).
adjust_line(N, N, _Cs, L) -> L;
adjust_line(T, A, [$\n | Cs], L) -> adjust_line(T - 1, A, Cs, L - 1);
adjust_line(T, A, [_ | Cs], L) -> adjust_line(T - 1, A, Cs, L).
yystate ( ) - > InitialState .
yystate(State , InChars , Line , CurrTokLen , AcceptAction , AcceptLen ) - >
{ Action , AcceptLen , RestChars , Line } |
{ Action , AcceptLen , RestChars , Line , State } |
{ reject , AcceptLen , CurrTokLen , RestChars , Line , State } |
{ Action , AcceptLen , CurrTokLen , RestChars , Line , State } .
%% Generated state transition functions. The non-accepting end state
%% return signal either an unrecognised character or end of current
%% input.
-file("./chico_tokenizer.erl", 311).
yystate() -> 62.
yystate(65, [101 | Ics], Line, Tlen, _, _) -> yystate(63, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 100 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [C | Ics], Line, Tlen, _, _) when C >= 102, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 65};
yystate(64, [32 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 0, Tlen);
yystate(64, [13 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 0, Tlen);
yystate(64, [9 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 0, Tlen);
yystate(64, [10 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line + 1, Tlen + 1, 0, Tlen);
yystate(64, Ics, Line, Tlen, _, _) -> {0, Tlen, Ics, Line, 64};
yystate(63, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 7, Tlen);
yystate(63, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 7, Tlen);
yystate(63, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 7, Tlen);
yystate(63, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 7, Tlen);
yystate(63, Ics, Line, Tlen, _, _) -> {7, Tlen, Ics, Line, 63};
yystate(62, [126 | Ics], Line, Tlen, _, _) -> yystate(58, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [125 | Ics], Line, Tlen, _, _) -> yystate(50, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [123 | Ics], Line, Tlen, _, _) -> yystate(46, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [119 | Ics], Line, Tlen, _, _) -> yystate(42, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [112 | Ics], Line, Tlen, _, _) -> yystate(22, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [110 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [111 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [109 | Ics], Line, Tlen, _, _) -> yystate(10, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [108 | Ics], Line, Tlen, _, _) -> yystate(9, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [102 | Ics], Line, Tlen, _, _) -> yystate(21, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [101 | Ics], Line, Tlen, _, _) -> yystate(33, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [100 | Ics], Line, Tlen, _, _) -> yystate(57, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [98 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [99 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [97 | Ics], Line, Tlen, _, _) -> yystate(59, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [93 | Ics], Line, Tlen, _, _) -> yystate(39, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [91 | Ics], Line, Tlen, _, _) -> yystate(35, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [61 | Ics], Line, Tlen, _, _) -> yystate(31, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [58 | Ics], Line, Tlen, _, _) -> yystate(27, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [47 | Ics], Line, Tlen, _, _) -> yystate(7, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [46 | Ics], Line, Tlen, _, _) -> yystate(3, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [45 | Ics], Line, Tlen, _, _) -> yystate(0, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [43 | Ics], Line, Tlen, _, _) -> yystate(8, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [42 | Ics], Line, Tlen, _, _) -> yystate(12, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [41 | Ics], Line, Tlen, _, _) -> yystate(16, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [40 | Ics], Line, Tlen, _, _) -> yystate(20, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [39 | Ics], Line, Tlen, _, _) -> yystate(36, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [35 | Ics], Line, Tlen, _, _) -> yystate(40, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [34 | Ics], Line, Tlen, _, _) -> yystate(60, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [32 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [13 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [9 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [10 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line + 1, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(19, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 103, C =< 107 ->
yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 113, C =< 118 ->
yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 120, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, Ics, Line, Tlen, _, _) -> {29, Tlen, Ics, Line, 62};
yystate(61, [110 | Ics], Line, Tlen, _, _) -> yystate(65, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 109 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [C | Ics], Line, Tlen, _, _) when C >= 111, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 61};
yystate(60, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(48, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(56, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(60, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(60, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [C | Ics], Line, Tlen, Action, Alen) when C >= 93 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 60};
yystate(59, [112 | Ics], Line, Tlen, _, _) -> yystate(55, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 111 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [C | Ics], Line, Tlen, _, _) when C >= 113, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 59};
yystate(58, [97 | Ics], Line, Tlen, _, _) -> yystate(54, Ics, Line, Tlen + 1, 17, Tlen);
yystate(58, Ics, Line, Tlen, _, _) -> {17, Tlen, Ics, Line, 58};
yystate(57, [111 | Ics], Line, Tlen, _, _) -> yystate(61, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 110 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [C | Ics], Line, Tlen, _, _) when C >= 112, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 57};
yystate(56, Ics, Line, Tlen, _, _) -> {10, Tlen, Ics, Line};
yystate(55, [112 | Ics], Line, Tlen, _, _) -> yystate(51, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 111 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [C | Ics], Line, Tlen, _, _) when C >= 113, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 55};
yystate(54, Ics, Line, Tlen, _, _) -> {18, Tlen, Ics, Line};
yystate(53, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 19, Tlen);
yystate(53, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 19, Tlen);
yystate(53, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 19, Tlen);
yystate(53, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 19, Tlen);
yystate(53, Ics, Line, Tlen, _, _) -> {19, Tlen, Ics, Line, 53};
yystate(52, [92 | Ics], Line, Tlen, _, _) -> yystate(48, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [34 | Ics], Line, Tlen, _, _) -> yystate(56, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [10 | Ics], Line, Tlen, _, _) -> yystate(60, Ics, Line + 1, Tlen + 1, 10, Tlen);
yystate(52, [C | Ics], Line, Tlen, _, _) when C >= 0, C =< 9 ->
yystate(60, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [C | Ics], Line, Tlen, _, _) when C >= 11, C =< 33 ->
yystate(60, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [C | Ics], Line, Tlen, _, _) when C >= 35, C =< 91 ->
yystate(60, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [C | Ics], Line, Tlen, _, _) when C >= 93 -> yystate(60, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, Ics, Line, Tlen, _, _) -> {10, Tlen, Ics, Line, 52};
yystate(51, [108 | Ics], Line, Tlen, _, _) -> yystate(47, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 107 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [C | Ics], Line, Tlen, _, _) when C >= 109, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 51};
yystate(50, Ics, Line, Tlen, _, _) -> {14, Tlen, Ics, Line};
yystate(49, [116 | Ics], Line, Tlen, _, _) -> yystate(53, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 115 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [C | Ics], Line, Tlen, _, _) when C >= 117, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 49};
yystate(48, [94 | Ics], Line, Tlen, Action, Alen) -> yystate(44, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [93 | Ics], Line, Tlen, Action, Alen) -> yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(48, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(52, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(60, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(48, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [C | Ics], Line, Tlen, Action, Alen) when C >= 95 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 48};
yystate(47, [122 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [121 | Ics], Line, Tlen, _, _) -> yystate(43, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 120 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 47};
yystate(46, Ics, Line, Tlen, _, _) -> {13, Tlen, Ics, Line};
yystate(45, [114 | Ics], Line, Tlen, _, _) -> yystate(49, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 113 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [C | Ics], Line, Tlen, _, _) when C >= 115, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 45};
yystate(44, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(48, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(52, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(60, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(44, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [C | Ics], Line, Tlen, Action, Alen) when C >= 93 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 44};
yystate(43, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 20, Tlen);
yystate(43, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 20, Tlen);
yystate(43, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 20, Tlen);
yystate(43, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 20, Tlen);
yystate(43, Ics, Line, Tlen, _, _) -> {20, Tlen, Ics, Line, 43};
yystate(42, [105 | Ics], Line, Tlen, _, _) -> yystate(38, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 104 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [C | Ics], Line, Tlen, _, _) when C >= 106, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 42};
yystate(41, [111 | Ics], Line, Tlen, _, _) -> yystate(45, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 110 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [C | Ics], Line, Tlen, _, _) when C >= 112, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 41};
yystate(40, Ics, Line, Tlen, _, _) -> {12, Tlen, Ics, Line};
yystate(39, Ics, Line, Tlen, _, _) -> {16, Tlen, Ics, Line};
yystate(38, [116 | Ics], Line, Tlen, _, _) -> yystate(34, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 115 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [C | Ics], Line, Tlen, _, _) when C >= 117, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 38};
yystate(37, [112 | Ics], Line, Tlen, _, _) -> yystate(41, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 111 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [C | Ics], Line, Tlen, _, _) when C >= 113, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 37};
yystate(36, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(28, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [39 | Ics], Line, Tlen, Action, Alen) -> yystate(32, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(36, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 38 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 93 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 36};
yystate(35, Ics, Line, Tlen, _, _) -> {15, Tlen, Ics, Line};
yystate(34, [104 | Ics], Line, Tlen, _, _) -> yystate(30, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 103 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [C | Ics], Line, Tlen, _, _) when C >= 105, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 34};
yystate(33, [121 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [122 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [120 | Ics], Line, Tlen, _, _) -> yystate(37, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 119 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 33};
yystate(32, [92 | Ics], Line, Tlen, _, _) -> yystate(28, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [39 | Ics], Line, Tlen, _, _) -> yystate(32, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [10 | Ics], Line, Tlen, _, _) -> yystate(36, Ics, Line + 1, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 0, C =< 9 ->
yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 11, C =< 33 ->
yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 35, C =< 38 ->
yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 40, C =< 91 ->
yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 93 -> yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, Ics, Line, Tlen, _, _) -> {11, Tlen, Ics, Line, 32};
yystate(31, Ics, Line, Tlen, _, _) -> {26, Tlen, Ics, Line};
yystate(30, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 9, Tlen);
yystate(30, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 9, Tlen);
yystate(30, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 9, Tlen);
yystate(30, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 9, Tlen);
yystate(30, Ics, Line, Tlen, _, _) -> {9, Tlen, Ics, Line, 30};
yystate(29, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 3, Tlen);
yystate(29, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 3, Tlen);
yystate(29, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 3, Tlen);
yystate(29, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 3, Tlen);
yystate(29, Ics, Line, Tlen, _, _) -> {3, Tlen, Ics, Line, 29};
yystate(28, [94 | Ics], Line, Tlen, Action, Alen) -> yystate(24, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [93 | Ics], Line, Tlen, Action, Alen) -> yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(28, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [39 | Ics], Line, Tlen, Action, Alen) -> yystate(32, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(36, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 38 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 95 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 28};
yystate(27, [58 | Ics], Line, Tlen, Action, Alen) -> yystate(23, Ics, Line, Tlen + 1, Action, Alen);
yystate(27, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 27};
yystate(26, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(26, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(26, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(26, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(26, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 26};
yystate(25, [110 | Ics], Line, Tlen, _, _) -> yystate(29, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 109 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [C | Ics], Line, Tlen, _, _) when C >= 111, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 25};
yystate(24, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(28, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [39 | Ics], Line, Tlen, Action, Alen) -> yystate(32, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(36, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 38 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 93 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 24};
yystate(23, Ics, Line, Tlen, _, _) -> {27, Tlen, Ics, Line};
yystate(22, [117 | Ics], Line, Tlen, _, _) -> yystate(18, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 116 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [C | Ics], Line, Tlen, _, _) when C >= 118, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 22};
yystate(21, [117 | Ics], Line, Tlen, _, _) -> yystate(25, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 116 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [C | Ics], Line, Tlen, _, _) when C >= 118, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 21};
yystate(20, Ics, Line, Tlen, _, _) -> {4, Tlen, Ics, Line};
yystate(19, [46 | Ics], Line, Tlen, _, _) -> yystate(15, Ics, Line, Tlen + 1, 29, Tlen);
yystate(19, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(19, Ics, Line, Tlen + 1, 29, Tlen);
yystate(19, Ics, Line, Tlen, _, _) -> {29, Tlen, Ics, Line, 19};
yystate(18, [98 | Ics], Line, Tlen, _, _) -> yystate(14, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [97 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [C | Ics], Line, Tlen, _, _) when C >= 99, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 18};
yystate(17, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 25, Tlen);
yystate(17, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 25, Tlen);
yystate(17, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 25, Tlen);
yystate(17, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 25, Tlen);
yystate(17, Ics, Line, Tlen, _, _) -> {25, Tlen, Ics, Line, 17};
yystate(16, Ics, Line, Tlen, _, _) -> {5, Tlen, Ics, Line};
yystate(15, [C | Ics], Line, Tlen, Action, Alen) when C >= 48, C =< 57 ->
yystate(11, Ics, Line, Tlen + 1, Action, Alen);
yystate(15, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 15};
yystate(14, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 2, Tlen);
yystate(14, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 2, Tlen);
yystate(14, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 2, Tlen);
yystate(14, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 2, Tlen);
yystate(14, Ics, Line, Tlen, _, _) -> {2, Tlen, Ics, Line, 14};
yystate(13, [116 | Ics], Line, Tlen, _, _) -> yystate(17, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 115 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [C | Ics], Line, Tlen, _, _) when C >= 117, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 13};
yystate(12, Ics, Line, Tlen, _, _) -> {24, Tlen, Ics, Line};
yystate(11, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(11, Ics, Line, Tlen + 1, 30, Tlen);
yystate(11, Ics, Line, Tlen, _, _) -> {30, Tlen, Ics, Line, 11};
yystate(10, [97 | Ics], Line, Tlen, _, _) -> yystate(6, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, [C | Ics], Line, Tlen, _, _) when C >= 98, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 10};
yystate(9, [101 | Ics], Line, Tlen, _, _) -> yystate(13, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 100 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [C | Ics], Line, Tlen, _, _) when C >= 102, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 9};
yystate(8, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(19, Ics, Line, Tlen + 1, 21, Tlen);
yystate(8, Ics, Line, Tlen, _, _) -> {21, Tlen, Ics, Line, 8};
yystate(7, Ics, Line, Tlen, _, _) -> {23, Tlen, Ics, Line};
yystate(6, [116 | Ics], Line, Tlen, _, _) -> yystate(2, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 115 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [C | Ics], Line, Tlen, _, _) when C >= 117, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 6};
yystate(5, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 8, Tlen);
yystate(5, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 8, Tlen);
yystate(5, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 8, Tlen);
yystate(5, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 8, Tlen);
yystate(5, Ics, Line, Tlen, _, _) -> {8, Tlen, Ics, Line, 5};
yystate(4, Ics, Line, Tlen, _, _) -> {6, Tlen, Ics, Line};
yystate(3, Ics, Line, Tlen, _, _) -> {1, Tlen, Ics, Line};
yystate(2, [99 | Ics], Line, Tlen, _, _) -> yystate(1, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [97 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [98 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [C | Ics], Line, Tlen, _, _) when C >= 100, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 2};
yystate(1, [104 | Ics], Line, Tlen, _, _) -> yystate(5, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 103 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [C | Ics], Line, Tlen, _, _) when C >= 105, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 1};
yystate(0, [62 | Ics], Line, Tlen, _, _) -> yystate(4, Ics, Line, Tlen + 1, 22, Tlen);
yystate(0, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(19, Ics, Line, Tlen + 1, 22, Tlen);
yystate(0, Ics, Line, Tlen, _, _) -> {22, Tlen, Ics, Line, 0};
yystate(S, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, S}.
yyaction(Action , TokenLength , , ) - >
{ token , } | { end_token , } | skip_token | { error , String } .
%% Generated action function.
yyaction(0, _, _, _) -> yyaction_0();
yyaction(1, _, _, TokenLine) -> yyaction_1(TokenLine);
yyaction(2, _, _, TokenLine) -> yyaction_2(TokenLine);
yyaction(3, _, _, TokenLine) -> yyaction_3(TokenLine);
yyaction(4, _, _, TokenLine) -> yyaction_4(TokenLine);
yyaction(5, _, _, TokenLine) -> yyaction_5(TokenLine);
yyaction(6, _, _, TokenLine) -> yyaction_6(TokenLine);
yyaction(7, _, _, TokenLine) -> yyaction_7(TokenLine);
yyaction(8, _, _, TokenLine) -> yyaction_8(TokenLine);
yyaction(9, _, _, TokenLine) -> yyaction_9(TokenLine);
yyaction(10, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_10(TokenChars, TokenLen, TokenLine);
yyaction(11, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_11(TokenChars, TokenLen, TokenLine);
yyaction(12, _, _, TokenLine) -> yyaction_12(TokenLine);
yyaction(13, _, _, TokenLine) -> yyaction_13(TokenLine);
yyaction(14, _, _, TokenLine) -> yyaction_14(TokenLine);
yyaction(15, _, _, TokenLine) -> yyaction_15(TokenLine);
yyaction(16, _, _, TokenLine) -> yyaction_16(TokenLine);
yyaction(17, _, _, TokenLine) -> yyaction_17(TokenLine);
yyaction(18, _, _, TokenLine) -> yyaction_18(TokenLine);
yyaction(19, _, _, TokenLine) -> yyaction_19(TokenLine);
yyaction(20, _, _, TokenLine) -> yyaction_20(TokenLine);
yyaction(21, _, _, TokenLine) -> yyaction_21(TokenLine);
yyaction(22, _, _, TokenLine) -> yyaction_22(TokenLine);
yyaction(23, _, _, TokenLine) -> yyaction_23(TokenLine);
yyaction(24, _, _, TokenLine) -> yyaction_24(TokenLine);
yyaction(25, _, _, TokenLine) -> yyaction_25(TokenLine);
yyaction(26, _, _, TokenLine) -> yyaction_26(TokenLine);
yyaction(27, _, _, TokenLine) -> yyaction_27(TokenLine);
yyaction(28, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_28(TokenChars, TokenLine);
yyaction(29, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_29(TokenChars, TokenLine);
yyaction(30, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_30(TokenChars, TokenLine);
yyaction(31, _, _, TokenLine) -> yyaction_31(TokenLine);
yyaction(_, _, _, _) -> error.
-compile({inline, yyaction_0/0}).
-file("./chico_tokenizer.xrl", 11).
yyaction_0() -> skip_token.
-compile({inline, yyaction_1/1}).
-file("./chico_tokenizer.xrl", 12).
yyaction_1(TokenLine) -> {token, {dot, TokenLine, none}}.
-compile({inline, yyaction_2/1}).
-file("./chico_tokenizer.xrl", 14).
yyaction_2(TokenLine) -> {token, {public, TokenLine, none}}.
-compile({inline, yyaction_3/1}).
-file("./chico_tokenizer.xrl", 15).
yyaction_3(TokenLine) -> {token, {function, TokenLine, none}}.
-compile({inline, yyaction_4/1}).
-file("./chico_tokenizer.xrl", 16).
yyaction_4(TokenLine) -> {token, {left_parenthesis, TokenLine, none}}.
-compile({inline, yyaction_5/1}).
-file("./chico_tokenizer.xrl", 17).
yyaction_5(TokenLine) -> {token, {right_parenthesis, TokenLine, none}}.
-compile({inline, yyaction_6/1}).
-file("./chico_tokenizer.xrl", 18).
yyaction_6(TokenLine) -> {token, {open_function, TokenLine, none}}.
-compile({inline, yyaction_7/1}).
-file("./chico_tokenizer.xrl", 19).
yyaction_7(TokenLine) -> {token, {done, TokenLine, none}}.
-compile({inline, yyaction_8/1}).
-file("./chico_tokenizer.xrl", 20).
yyaction_8(TokenLine) -> {token, {match, TokenLine, none}}.
-compile({inline, yyaction_9/1}).
-file("./chico_tokenizer.xrl", 21).
yyaction_9(TokenLine) -> {token, {with, TokenLine, none}}.
-compile({inline, yyaction_10/3}).
-file("./chico_tokenizer.xrl", 23).
yyaction_10(TokenChars, TokenLen, TokenLine) ->
{token, {string, TokenLine, atom_to_list(get_string(TokenChars, TokenLen))}}.
-compile({inline, yyaction_11/3}).
-file("./chico_tokenizer.xrl", 24).
yyaction_11(TokenChars, TokenLen, TokenLine) ->
{token, {atom, TokenLine, get_string(TokenChars, TokenLen)}}.
-compile({inline, yyaction_12/1}).
-file("./chico_tokenizer.xrl", 26).
yyaction_12(TokenLine) -> {token, {'#', TokenLine, none}}.
-compile({inline, yyaction_13/1}).
-file("./chico_tokenizer.xrl", 27).
yyaction_13(TokenLine) -> {token, {'{', TokenLine, none}}.
-compile({inline, yyaction_14/1}).
-file("./chico_tokenizer.xrl", 28).
yyaction_14(TokenLine) -> {token, {'}', TokenLine, none}}.
-compile({inline, yyaction_15/1}).
-file("./chico_tokenizer.xrl", 29).
yyaction_15(TokenLine) -> {token, {'[', TokenLine, none}}.
-compile({inline, yyaction_16/1}).
-file("./chico_tokenizer.xrl", 30).
yyaction_16(TokenLine) -> {token, {']', TokenLine, none}}.
-compile({inline, yyaction_17/1}).
-file("./chico_tokenizer.xrl", 31).
yyaction_17(TokenLine) -> {token, {'~', TokenLine, none}}.
-compile({inline, yyaction_18/1}).
-file("./chico_tokenizer.xrl", 32).
yyaction_18(TokenLine) -> {token, {'~a', TokenLine, none}}.
-compile({inline, yyaction_19/1}).
-file("./chico_tokenizer.xrl", 34).
yyaction_19(TokenLine) -> {token, {export, TokenLine, export}}.
-compile({inline, yyaction_20/1}).
-file("./chico_tokenizer.xrl", 35).
yyaction_20(TokenLine) -> {token, {apply, TokenLine, apply}}.
-compile({inline, yyaction_21/1}).
-file("./chico_tokenizer.xrl", 36).
yyaction_21(TokenLine) -> {token, {operator, TokenLine, '+'}}.
-compile({inline, yyaction_22/1}).
-file("./chico_tokenizer.xrl", 37).
yyaction_22(TokenLine) -> {token, {operator, TokenLine, '-'}}.
-compile({inline, yyaction_23/1}).
-file("./chico_tokenizer.xrl", 38).
yyaction_23(TokenLine) -> {token, {operator, TokenLine, '/'}}.
-compile({inline, yyaction_24/1}).
-file("./chico_tokenizer.xrl", 39).
yyaction_24(TokenLine) -> {token, {operator, TokenLine, '*'}}.
-compile({inline, yyaction_25/1}).
-file("./chico_tokenizer.xrl", 42).
yyaction_25(TokenLine) -> {token, {variable, TokenLine, none}}.
-compile({inline, yyaction_26/1}).
-file("./chico_tokenizer.xrl", 43).
yyaction_26(TokenLine) -> {token, {assigment, TokenLine, none}}.
-compile({inline, yyaction_27/1}).
-file("./chico_tokenizer.xrl", 44).
yyaction_27(TokenLine) -> {token, {type_assigment, TokenLine, none}}.
-compile({inline, yyaction_28/2}).
-file("./chico_tokenizer.xrl", 45).
yyaction_28(TokenChars, TokenLine) -> {token, {declaration, TokenLine, list_to_atom(TokenChars)}}.
-compile({inline, yyaction_29/2}).
-file("./chico_tokenizer.xrl", 47).
yyaction_29(TokenChars, TokenLine) -> {token, {integer, TokenLine, list_to_integer(TokenChars)}}.
-compile({inline, yyaction_30/2}).
-file("./chico_tokenizer.xrl", 48).
yyaction_30(TokenChars, TokenLine) -> {token, {float, TokenLine, list_to_float(TokenChars)}}.
-compile({inline, yyaction_31/1}).
-file("./chico_tokenizer.xrl", 50).
yyaction_31(TokenLine) -> {token, {declaration, TokenLine, '_'}}.
-file("/opt/homebrew/Cellar/erlang/25.2/lib/erlang/lib/parsetools-2.4.1/include/leexinc.hrl", 313).
| null | https://raw.githubusercontent.com/lucassouzamatos/chico.lang/8d2d120ecbf1a4d7d9958da0f13a085c0cb7e429/src/chico_tokenizer.erl | erlang | The source of this file is part of leex distribution, as such it
has the same Copyright as the other files in the leex
distribution. The Copyright is defined in the accompanying file
property of the creator of the scanner and is not covered by that
Copyright.
User code. This is placed here to allow extra attributes.
start while line number returned is line of token end. We want line
of token start.
No partial tokens!
Accepting end state
Accepting transition state
After a non-accepting state
string_cont(RestChars, Line, Token, Tokens)
Test for and remove the end token wrapper. Push back characters
token(Continuation, Chars) ->
token(Continuation, Chars, Line) ->
Must be careful when re-entering to append the latest characters to the
after characters in an accept. The continuation is:
The argument order is chosen to be more efficient.
Accepting end state, we have a token.
Accepting transition state, can take more chars.
Need more chars to check
Take what we got
After a non-accepting state, maybe reach accept state later.
Need more chars to check
No token match
Check for partial token which is error.
No token match
Use last accept match
token_cont(RestChars, Line, Token)
If we have a token or error then return done, else if we have a
skip_token then continue.
Must be careful when re-entering to append the latest characters to the
after characters in an accept. The continuation is:
Accepting end state, we have a token.
Accepting transition state, can take more chars.
Need more chars to check
Take what we got
After a non-accepting state, maybe reach accept state later.
Need more chars to check
No token match
Check for partial token which is error, no need to skip here.
Skip rest of tokens.
tokens_cont(RestChars, Line, Token, Tokens)
If we have an end_token or error then return done, else if we have
just continue.
Skip tokens until an end token, junk everything and return the error.
Accepting end state
After an accepting state
After a non-accepting state
skip_cont(RestChars, Line, Token, Error)
Skip tokens until we have an end_token or error then return done
with the original rror.
Line has been updated with respect to newlines in the prefix of
Generated state transition functions. The non-accepting end state
return signal either an unrecognised character or end of current
input.
Generated action function. | -file("/opt/homebrew/Cellar/erlang/25.2/lib/erlang/lib/parsetools-2.4.1/include/leexinc.hrl", 0).
COPYRIGHT . However , the resultant scanner generated by is the
-module(chico_tokenizer).
-export([string/1, string/2, token/2, token/3, tokens/2, tokens/3]).
-export([format_error/1]).
-file("./chico_tokenizer.xrl", 54).
get_string(TokenChars, TokenLen) ->
S = lists:sublist(TokenChars, 2, TokenLen - 2),
list_to_atom(S).
-file("/opt/homebrew/Cellar/erlang/25.2/lib/erlang/lib/parsetools-2.4.1/include/leexinc.hrl", 14).
format_error({illegal, S}) -> ["illegal characters ", io_lib:write_string(S)];
format_error({user, S}) -> S.
string(String) -> string(String, 1).
string(String, Line) -> string(String, Line, String, []).
string(InChars , , , Tokens ) - >
{ ok , Tokens , Line } | { error , ErrorInfo , Line } .
Note the line number going into yystate , L0 , is line of token
string([], L, [], Ts) ->
{ok, yyrev(Ts), L};
string(Ics0, L0, Tcs, Ts) ->
case yystate(yystate(), Ics0, L0, 0, reject, 0) of
{A, Alen, Ics1, L1} ->
string_cont(Ics1, L1, yyaction(A, Alen, Tcs, L0), Ts);
{A, Alen, Ics1, L1, _S1} ->
string_cont(Ics1, L1, yyaction(A, Alen, Tcs, L0), Ts);
{reject, _Alen, Tlen, _Ics1, L1, _S1} ->
{error, {L0, ?MODULE, {illegal, yypre(Tcs, Tlen + 1)}}, L1};
{A, Alen, Tlen, _Ics1, L1, _S1} ->
Tcs1 = yysuf(Tcs, Alen),
L2 = adjust_line(Tlen, Alen, Tcs1, L1),
string_cont(Tcs1, L2, yyaction(A, Alen, Tcs, L0), Ts)
end.
are prepended to RestChars .
-dialyzer({nowarn_function, string_cont/4}).
string_cont(Rest, Line, {token, T}, Ts) -> string(Rest, Line, Rest, [T | Ts]);
string_cont(Rest, Line, {token, T, Push}, Ts) ->
NewRest = Push ++ Rest,
string(NewRest, Line, NewRest, [T | Ts]);
string_cont(Rest, Line, {end_token, T}, Ts) -> string(Rest, Line, Rest, [T | Ts]);
string_cont(Rest, Line, {end_token, T, Push}, Ts) ->
NewRest = Push ++ Rest,
string(NewRest, Line, NewRest, [T | Ts]);
string_cont(Rest, Line, skip_token, Ts) -> string(Rest, Line, Rest, Ts);
string_cont(Rest, Line, {skip_token, Push}, Ts) ->
NewRest = Push ++ Rest,
string(NewRest, Line, NewRest, Ts);
string_cont(_Rest, Line, {error, S}, _Ts) -> {error, {Line, ?MODULE, {user, S}}, Line}.
{ more , Continuation } | { done , ReturnVal , RestChars } .
{ token , State , CurrLine , , TokenLen , TokenLine , AccAction , AccLen }
token(Cont, Chars) -> token(Cont, Chars, 1).
token([], Chars, Line) -> token(yystate(), Chars, Line, Chars, 0, Line, reject, 0);
token({token, State, Line, Tcs, Tlen, Tline, Action, Alen}, Chars, _) ->
token(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Action, Alen).
token(State , InChars , Line , , TokenLen , TokenLine ,
AcceptAction , AcceptLen ) - >
{ more , Continuation } | { done , ReturnVal , RestChars } .
token(S0, Ics0, L0, Tcs, Tlen0, Tline, A0, Alen0) ->
case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of
{A1, Alen1, Ics1, L1} -> token_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline));
{A1, Alen1, [], L1, S1} ->
{more, {token, S1, L1, Tcs, Alen1, Tline, A1, Alen1}};
{A1, Alen1, Ics1, L1, _S1} ->
token_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline));
{A1, Alen1, Tlen1, [], L1, S1} ->
{more, {token, S1, L1, Tcs, Tlen1, Tline, A1, Alen1}};
{reject, _Alen1, Tlen1, eof, L1, _S1} ->
Ret =
if
Tlen1 > 0 ->
{
error,
{
Tline,
?MODULE,
Skip eof tail in Tcs .
{illegal, yypre(Tcs, Tlen1)}
},
L1
};
true -> {eof, L1}
end,
{done, Ret, eof};
{reject, _Alen1, Tlen1, Ics1, L1, _S1} ->
Error = {Tline, ?MODULE, {illegal, yypre(Tcs, Tlen1 + 1)}},
{done, {error, Error, L1}, Ics1};
{A1, Alen1, Tlen1, _Ics1, L1, _S1} ->
Tcs1 = yysuf(Tcs, Alen1),
L2 = adjust_line(Tlen1, Alen1, Tcs1, L1),
token_cont(Tcs1, L2, yyaction(A1, Alen1, Tcs, Tline))
end.
-dialyzer({nowarn_function, token_cont/3}).
token_cont(Rest, Line, {token, T}) -> {done, {ok, T, Line}, Rest};
token_cont(Rest, Line, {token, T, Push}) ->
NewRest = Push ++ Rest,
{done, {ok, T, Line}, NewRest};
token_cont(Rest, Line, {end_token, T}) -> {done, {ok, T, Line}, Rest};
token_cont(Rest, Line, {end_token, T, Push}) ->
NewRest = Push ++ Rest,
{done, {ok, T, Line}, NewRest};
token_cont(Rest, Line, skip_token) -> token(yystate(), Rest, Line, Rest, 0, Line, reject, 0);
token_cont(Rest, Line, {skip_token, Push}) ->
NewRest = Push ++ Rest,
token(yystate(), NewRest, Line, NewRest, 0, Line, reject, 0);
token_cont(Rest, Line, {error, S}) -> {done, {error, {Line, ?MODULE, {user, S}}, Line}, Rest}.
tokens(Continuation , Chars , Line ) - >
{ more , Continuation } | { done , ReturnVal , RestChars } .
{ tokens , State , CurrLine , , TokenLen , TokenLine , Tokens , AccAction , AccLen }
{ skip_tokens , State , CurrLine , , TokenLen , TokenLine , Error , AccAction , AccLen }
tokens(Cont, Chars) -> tokens(Cont, Chars, 1).
tokens([], Chars, Line) -> tokens(yystate(), Chars, Line, Chars, 0, Line, [], reject, 0);
tokens({tokens, State, Line, Tcs, Tlen, Tline, Ts, Action, Alen}, Chars, _) ->
tokens(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Ts, Action, Alen);
tokens({skip_tokens, State, Line, Tcs, Tlen, Tline, Error, Action, Alen}, Chars, _) ->
skip_tokens(State, Chars, Line, Tcs ++ Chars, Tlen, Tline, Error, Action, Alen).
tokens(State , InChars , Line , , TokenLen , TokenLine , Tokens ,
AcceptAction , AcceptLen ) - >
{ more , Continuation } | { done , ReturnVal , RestChars } .
tokens(S0, Ics0, L0, Tcs, Tlen0, Tline, Ts, A0, Alen0) ->
case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of
{A1, Alen1, Ics1, L1} -> tokens_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Ts);
{A1, Alen1, [], L1, S1} ->
{more, {tokens, S1, L1, Tcs, Alen1, Tline, Ts, A1, Alen1}};
{A1, Alen1, Ics1, L1, _S1} ->
tokens_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Ts);
{A1, Alen1, Tlen1, [], L1, S1} ->
{more, {tokens, S1, L1, Tcs, Tlen1, Tline, Ts, A1, Alen1}};
{reject, _Alen1, Tlen1, eof, L1, _S1} ->
Ret =
if
Tlen1 > 0 ->
{
error,
{
Tline,
?MODULE,
Skip eof tail in Tcs .
{illegal, yypre(Tcs, Tlen1)}
},
L1
};
Ts == [] -> {eof, L1};
true -> {ok, yyrev(Ts), L1}
end,
{done, Ret, eof};
{reject, _Alen1, Tlen1, _Ics1, L1, _S1} ->
Error = {L1, ?MODULE, {illegal, yypre(Tcs, Tlen1 + 1)}},
skip_tokens(yysuf(Tcs, Tlen1 + 1), L1, Error);
{A1, Alen1, Tlen1, _Ics1, L1, _S1} ->
Token = yyaction(A1, Alen1, Tcs, Tline),
Tcs1 = yysuf(Tcs, Alen1),
L2 = adjust_line(Tlen1, Alen1, Tcs1, L1),
tokens_cont(Tcs1, L2, Token, Ts)
end.
a token then save it and continue , else if we have a
-dialyzer({nowarn_function, tokens_cont/4}).
tokens_cont(Rest, Line, {token, T}, Ts) ->
tokens(yystate(), Rest, Line, Rest, 0, Line, [T | Ts], reject, 0);
tokens_cont(Rest, Line, {token, T, Push}, Ts) ->
NewRest = Push ++ Rest,
tokens(yystate(), NewRest, Line, NewRest, 0, Line, [T | Ts], reject, 0);
tokens_cont(Rest, Line, {end_token, T}, Ts) -> {done, {ok, yyrev(Ts, [T]), Line}, Rest};
tokens_cont(Rest, Line, {end_token, T, Push}, Ts) ->
NewRest = Push ++ Rest,
{done, {ok, yyrev(Ts, [T]), Line}, NewRest};
tokens_cont(Rest, Line, skip_token, Ts) ->
tokens(yystate(), Rest, Line, Rest, 0, Line, Ts, reject, 0);
tokens_cont(Rest, Line, {skip_token, Push}, Ts) ->
NewRest = Push ++ Rest,
tokens(yystate(), NewRest, Line, NewRest, 0, Line, Ts, reject, 0);
tokens_cont(Rest, Line, {error, S}, _Ts) -> skip_tokens(Rest, Line, {Line, ?MODULE, {user, S}}).
skip_tokens(InChars , Line , Error ) - > { done,{error , Error , } .
skip_tokens(Ics, Line, Error) -> skip_tokens(yystate(), Ics, Line, Ics, 0, Line, Error, reject, 0).
skip_tokens(State , InChars , Line , , TokenLen , TokenLine , Tokens ,
AcceptAction , AcceptLen ) - >
{ more , Continuation } | { done , ReturnVal , RestChars } .
skip_tokens(S0, Ics0, L0, Tcs, Tlen0, Tline, Error, A0, Alen0) ->
case yystate(S0, Ics0, L0, Tlen0, A0, Alen0) of
{A1, Alen1, Ics1, L1} ->
skip_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Error);
{A1, Alen1, [], L1, S1} ->
{more, {skip_tokens, S1, L1, Tcs, Alen1, Tline, Error, A1, Alen1}};
{A1, Alen1, Ics1, L1, _S1} -> skip_cont(Ics1, L1, yyaction(A1, Alen1, Tcs, Tline), Error);
{A1, Alen1, Tlen1, [], L1, S1} ->
{more, {skip_tokens, S1, L1, Tcs, Tlen1, Tline, Error, A1, Alen1}};
{reject, _Alen1, _Tlen1, eof, L1, _S1} -> {done, {error, Error, L1}, eof};
{reject, _Alen1, Tlen1, _Ics1, L1, _S1} -> skip_tokens(yysuf(Tcs, Tlen1 + 1), L1, Error);
{A1, Alen1, Tlen1, _Ics1, L1, _S1} ->
Token = yyaction(A1, Alen1, Tcs, Tline),
Tcs1 = yysuf(Tcs, Alen1),
L2 = adjust_line(Tlen1, Alen1, Tcs1, L1),
skip_cont(Tcs1, L2, Token, Error)
end.
-dialyzer({nowarn_function, skip_cont/4}).
skip_cont(Rest, Line, {token, _T}, Error) ->
skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0);
skip_cont(Rest, Line, {token, _T, Push}, Error) ->
NewRest = Push ++ Rest,
skip_tokens(yystate(), NewRest, Line, NewRest, 0, Line, Error, reject, 0);
skip_cont(Rest, Line, {end_token, _T}, Error) -> {done, {error, Error, Line}, Rest};
skip_cont(Rest, Line, {end_token, _T, Push}, Error) ->
NewRest = Push ++ Rest,
{done, {error, Error, Line}, NewRest};
skip_cont(Rest, Line, skip_token, Error) ->
skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0);
skip_cont(Rest, Line, {skip_token, Push}, Error) ->
NewRest = Push ++ Rest,
skip_tokens(yystate(), NewRest, Line, NewRest, 0, Line, Error, reject, 0);
skip_cont(Rest, Line, {error, _S}, Error) ->
skip_tokens(yystate(), Rest, Line, Rest, 0, Line, Error, reject, 0).
-compile({nowarn_unused_function, [yyrev/1, yyrev/2, yypre/2, yysuf/2]}).
yyrev(List) -> lists:reverse(List).
yyrev(List, Tail) -> lists:reverse(List, Tail).
yypre(List, N) -> lists:sublist(List, N).
yysuf(List, N) -> lists:nthtail(N, List).
adjust_line(TokenLength , AcceptLength , Chars , Line ) - > NewLine
Make sure that newlines in are not counted twice .
Chars consisting of ( TokenLength - AcceptLength ) characters .
-compile({nowarn_unused_function, adjust_line/4}).
adjust_line(N, N, _Cs, L) -> L;
adjust_line(T, A, [$\n | Cs], L) -> adjust_line(T - 1, A, Cs, L - 1);
adjust_line(T, A, [_ | Cs], L) -> adjust_line(T - 1, A, Cs, L).
yystate ( ) - > InitialState .
yystate(State , InChars , Line , CurrTokLen , AcceptAction , AcceptLen ) - >
{ Action , AcceptLen , RestChars , Line } |
{ Action , AcceptLen , RestChars , Line , State } |
{ reject , AcceptLen , CurrTokLen , RestChars , Line , State } |
{ Action , AcceptLen , CurrTokLen , RestChars , Line , State } .
-file("./chico_tokenizer.erl", 311).
yystate() -> 62.
yystate(65, [101 | Ics], Line, Tlen, _, _) -> yystate(63, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 100 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, [C | Ics], Line, Tlen, _, _) when C >= 102, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(65, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 65};
yystate(64, [32 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 0, Tlen);
yystate(64, [13 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 0, Tlen);
yystate(64, [9 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 0, Tlen);
yystate(64, [10 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line + 1, Tlen + 1, 0, Tlen);
yystate(64, Ics, Line, Tlen, _, _) -> {0, Tlen, Ics, Line, 64};
yystate(63, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 7, Tlen);
yystate(63, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 7, Tlen);
yystate(63, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 7, Tlen);
yystate(63, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 7, Tlen);
yystate(63, Ics, Line, Tlen, _, _) -> {7, Tlen, Ics, Line, 63};
yystate(62, [126 | Ics], Line, Tlen, _, _) -> yystate(58, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [125 | Ics], Line, Tlen, _, _) -> yystate(50, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [123 | Ics], Line, Tlen, _, _) -> yystate(46, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [119 | Ics], Line, Tlen, _, _) -> yystate(42, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [112 | Ics], Line, Tlen, _, _) -> yystate(22, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [110 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [111 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [109 | Ics], Line, Tlen, _, _) -> yystate(10, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [108 | Ics], Line, Tlen, _, _) -> yystate(9, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [102 | Ics], Line, Tlen, _, _) -> yystate(21, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [101 | Ics], Line, Tlen, _, _) -> yystate(33, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [100 | Ics], Line, Tlen, _, _) -> yystate(57, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [98 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [99 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [97 | Ics], Line, Tlen, _, _) -> yystate(59, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [93 | Ics], Line, Tlen, _, _) -> yystate(39, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [91 | Ics], Line, Tlen, _, _) -> yystate(35, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [61 | Ics], Line, Tlen, _, _) -> yystate(31, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [58 | Ics], Line, Tlen, _, _) -> yystate(27, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [47 | Ics], Line, Tlen, _, _) -> yystate(7, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [46 | Ics], Line, Tlen, _, _) -> yystate(3, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [45 | Ics], Line, Tlen, _, _) -> yystate(0, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [43 | Ics], Line, Tlen, _, _) -> yystate(8, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [42 | Ics], Line, Tlen, _, _) -> yystate(12, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [41 | Ics], Line, Tlen, _, _) -> yystate(16, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [40 | Ics], Line, Tlen, _, _) -> yystate(20, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [39 | Ics], Line, Tlen, _, _) -> yystate(36, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [35 | Ics], Line, Tlen, _, _) -> yystate(40, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [34 | Ics], Line, Tlen, _, _) -> yystate(60, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [32 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [13 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [9 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [10 | Ics], Line, Tlen, _, _) -> yystate(64, Ics, Line + 1, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(19, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 103, C =< 107 ->
yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 113, C =< 118 ->
yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, [C | Ics], Line, Tlen, _, _) when C >= 120, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 29, Tlen);
yystate(62, Ics, Line, Tlen, _, _) -> {29, Tlen, Ics, Line, 62};
yystate(61, [110 | Ics], Line, Tlen, _, _) -> yystate(65, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 109 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, [C | Ics], Line, Tlen, _, _) when C >= 111, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(61, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 61};
yystate(60, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(48, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(56, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(60, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(60, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, [C | Ics], Line, Tlen, Action, Alen) when C >= 93 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(60, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 60};
yystate(59, [112 | Ics], Line, Tlen, _, _) -> yystate(55, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 111 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, [C | Ics], Line, Tlen, _, _) when C >= 113, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(59, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 59};
yystate(58, [97 | Ics], Line, Tlen, _, _) -> yystate(54, Ics, Line, Tlen + 1, 17, Tlen);
yystate(58, Ics, Line, Tlen, _, _) -> {17, Tlen, Ics, Line, 58};
yystate(57, [111 | Ics], Line, Tlen, _, _) -> yystate(61, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 110 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, [C | Ics], Line, Tlen, _, _) when C >= 112, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(57, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 57};
yystate(56, Ics, Line, Tlen, _, _) -> {10, Tlen, Ics, Line};
yystate(55, [112 | Ics], Line, Tlen, _, _) -> yystate(51, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 111 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, [C | Ics], Line, Tlen, _, _) when C >= 113, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(55, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 55};
yystate(54, Ics, Line, Tlen, _, _) -> {18, Tlen, Ics, Line};
yystate(53, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 19, Tlen);
yystate(53, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 19, Tlen);
yystate(53, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 19, Tlen);
yystate(53, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 19, Tlen);
yystate(53, Ics, Line, Tlen, _, _) -> {19, Tlen, Ics, Line, 53};
yystate(52, [92 | Ics], Line, Tlen, _, _) -> yystate(48, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [34 | Ics], Line, Tlen, _, _) -> yystate(56, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [10 | Ics], Line, Tlen, _, _) -> yystate(60, Ics, Line + 1, Tlen + 1, 10, Tlen);
yystate(52, [C | Ics], Line, Tlen, _, _) when C >= 0, C =< 9 ->
yystate(60, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [C | Ics], Line, Tlen, _, _) when C >= 11, C =< 33 ->
yystate(60, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [C | Ics], Line, Tlen, _, _) when C >= 35, C =< 91 ->
yystate(60, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, [C | Ics], Line, Tlen, _, _) when C >= 93 -> yystate(60, Ics, Line, Tlen + 1, 10, Tlen);
yystate(52, Ics, Line, Tlen, _, _) -> {10, Tlen, Ics, Line, 52};
yystate(51, [108 | Ics], Line, Tlen, _, _) -> yystate(47, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 107 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, [C | Ics], Line, Tlen, _, _) when C >= 109, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(51, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 51};
yystate(50, Ics, Line, Tlen, _, _) -> {14, Tlen, Ics, Line};
yystate(49, [116 | Ics], Line, Tlen, _, _) -> yystate(53, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 115 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, [C | Ics], Line, Tlen, _, _) when C >= 117, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(49, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 49};
yystate(48, [94 | Ics], Line, Tlen, Action, Alen) -> yystate(44, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [93 | Ics], Line, Tlen, Action, Alen) -> yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(48, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(52, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(60, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(48, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, [C | Ics], Line, Tlen, Action, Alen) when C >= 95 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(48, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 48};
yystate(47, [122 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [121 | Ics], Line, Tlen, _, _) -> yystate(43, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 120 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(47, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 47};
yystate(46, Ics, Line, Tlen, _, _) -> {13, Tlen, Ics, Line};
yystate(45, [114 | Ics], Line, Tlen, _, _) -> yystate(49, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 113 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, [C | Ics], Line, Tlen, _, _) when C >= 115, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(45, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 45};
yystate(44, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(48, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(52, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(60, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(44, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 91 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, [C | Ics], Line, Tlen, Action, Alen) when C >= 93 ->
yystate(60, Ics, Line, Tlen + 1, Action, Alen);
yystate(44, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 44};
yystate(43, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 20, Tlen);
yystate(43, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 20, Tlen);
yystate(43, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 20, Tlen);
yystate(43, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 20, Tlen);
yystate(43, Ics, Line, Tlen, _, _) -> {20, Tlen, Ics, Line, 43};
yystate(42, [105 | Ics], Line, Tlen, _, _) -> yystate(38, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 104 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, [C | Ics], Line, Tlen, _, _) when C >= 106, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(42, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 42};
yystate(41, [111 | Ics], Line, Tlen, _, _) -> yystate(45, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 110 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, [C | Ics], Line, Tlen, _, _) when C >= 112, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(41, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 41};
yystate(40, Ics, Line, Tlen, _, _) -> {12, Tlen, Ics, Line};
yystate(39, Ics, Line, Tlen, _, _) -> {16, Tlen, Ics, Line};
yystate(38, [116 | Ics], Line, Tlen, _, _) -> yystate(34, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 115 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, [C | Ics], Line, Tlen, _, _) when C >= 117, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(38, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 38};
yystate(37, [112 | Ics], Line, Tlen, _, _) -> yystate(41, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 111 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, [C | Ics], Line, Tlen, _, _) when C >= 113, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(37, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 37};
yystate(36, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(28, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [39 | Ics], Line, Tlen, Action, Alen) -> yystate(32, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(36, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 38 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, [C | Ics], Line, Tlen, Action, Alen) when C >= 93 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(36, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 36};
yystate(35, Ics, Line, Tlen, _, _) -> {15, Tlen, Ics, Line};
yystate(34, [104 | Ics], Line, Tlen, _, _) -> yystate(30, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 103 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, [C | Ics], Line, Tlen, _, _) when C >= 105, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(34, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 34};
yystate(33, [121 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [122 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [120 | Ics], Line, Tlen, _, _) -> yystate(37, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 119 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(33, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 33};
yystate(32, [92 | Ics], Line, Tlen, _, _) -> yystate(28, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [39 | Ics], Line, Tlen, _, _) -> yystate(32, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [10 | Ics], Line, Tlen, _, _) -> yystate(36, Ics, Line + 1, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 0, C =< 9 ->
yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 11, C =< 33 ->
yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 35, C =< 38 ->
yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 40, C =< 91 ->
yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, [C | Ics], Line, Tlen, _, _) when C >= 93 -> yystate(36, Ics, Line, Tlen + 1, 11, Tlen);
yystate(32, Ics, Line, Tlen, _, _) -> {11, Tlen, Ics, Line, 32};
yystate(31, Ics, Line, Tlen, _, _) -> {26, Tlen, Ics, Line};
yystate(30, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 9, Tlen);
yystate(30, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 9, Tlen);
yystate(30, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 9, Tlen);
yystate(30, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 9, Tlen);
yystate(30, Ics, Line, Tlen, _, _) -> {9, Tlen, Ics, Line, 30};
yystate(29, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 3, Tlen);
yystate(29, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 3, Tlen);
yystate(29, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 3, Tlen);
yystate(29, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 3, Tlen);
yystate(29, Ics, Line, Tlen, _, _) -> {3, Tlen, Ics, Line, 29};
yystate(28, [94 | Ics], Line, Tlen, Action, Alen) -> yystate(24, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [93 | Ics], Line, Tlen, Action, Alen) -> yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(28, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [39 | Ics], Line, Tlen, Action, Alen) -> yystate(32, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(36, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 38 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, [C | Ics], Line, Tlen, Action, Alen) when C >= 95 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(28, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 28};
yystate(27, [58 | Ics], Line, Tlen, Action, Alen) -> yystate(23, Ics, Line, Tlen + 1, Action, Alen);
yystate(27, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 27};
yystate(26, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(26, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(26, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(26, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(26, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 26};
yystate(25, [110 | Ics], Line, Tlen, _, _) -> yystate(29, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 109 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, [C | Ics], Line, Tlen, _, _) when C >= 111, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(25, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 25};
yystate(24, [92 | Ics], Line, Tlen, Action, Alen) -> yystate(28, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [39 | Ics], Line, Tlen, Action, Alen) -> yystate(32, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [34 | Ics], Line, Tlen, Action, Alen) -> yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [10 | Ics], Line, Tlen, Action, Alen) ->
yystate(36, Ics, Line + 1, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 0, C =< 9 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 11, C =< 33 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 35, C =< 38 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 40, C =< 91 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, [C | Ics], Line, Tlen, Action, Alen) when C >= 93 ->
yystate(36, Ics, Line, Tlen + 1, Action, Alen);
yystate(24, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 24};
yystate(23, Ics, Line, Tlen, _, _) -> {27, Tlen, Ics, Line};
yystate(22, [117 | Ics], Line, Tlen, _, _) -> yystate(18, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 116 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, [C | Ics], Line, Tlen, _, _) when C >= 118, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(22, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 22};
yystate(21, [117 | Ics], Line, Tlen, _, _) -> yystate(25, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 116 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, [C | Ics], Line, Tlen, _, _) when C >= 118, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(21, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 21};
yystate(20, Ics, Line, Tlen, _, _) -> {4, Tlen, Ics, Line};
yystate(19, [46 | Ics], Line, Tlen, _, _) -> yystate(15, Ics, Line, Tlen + 1, 29, Tlen);
yystate(19, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(19, Ics, Line, Tlen + 1, 29, Tlen);
yystate(19, Ics, Line, Tlen, _, _) -> {29, Tlen, Ics, Line, 19};
yystate(18, [98 | Ics], Line, Tlen, _, _) -> yystate(14, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [97 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, [C | Ics], Line, Tlen, _, _) when C >= 99, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(18, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 18};
yystate(17, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 25, Tlen);
yystate(17, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 25, Tlen);
yystate(17, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 25, Tlen);
yystate(17, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 25, Tlen);
yystate(17, Ics, Line, Tlen, _, _) -> {25, Tlen, Ics, Line, 17};
yystate(16, Ics, Line, Tlen, _, _) -> {5, Tlen, Ics, Line};
yystate(15, [C | Ics], Line, Tlen, Action, Alen) when C >= 48, C =< 57 ->
yystate(11, Ics, Line, Tlen + 1, Action, Alen);
yystate(15, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, 15};
yystate(14, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 2, Tlen);
yystate(14, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 2, Tlen);
yystate(14, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 2, Tlen);
yystate(14, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 2, Tlen);
yystate(14, Ics, Line, Tlen, _, _) -> {2, Tlen, Ics, Line, 14};
yystate(13, [116 | Ics], Line, Tlen, _, _) -> yystate(17, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 115 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, [C | Ics], Line, Tlen, _, _) when C >= 117, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(13, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 13};
yystate(12, Ics, Line, Tlen, _, _) -> {24, Tlen, Ics, Line};
yystate(11, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(11, Ics, Line, Tlen + 1, 30, Tlen);
yystate(11, Ics, Line, Tlen, _, _) -> {30, Tlen, Ics, Line, 11};
yystate(10, [97 | Ics], Line, Tlen, _, _) -> yystate(6, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, [C | Ics], Line, Tlen, _, _) when C >= 98, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(10, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 10};
yystate(9, [101 | Ics], Line, Tlen, _, _) -> yystate(13, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 100 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, [C | Ics], Line, Tlen, _, _) when C >= 102, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(9, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 9};
yystate(8, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(19, Ics, Line, Tlen + 1, 21, Tlen);
yystate(8, Ics, Line, Tlen, _, _) -> {21, Tlen, Ics, Line, 8};
yystate(7, Ics, Line, Tlen, _, _) -> {23, Tlen, Ics, Line};
yystate(6, [116 | Ics], Line, Tlen, _, _) -> yystate(2, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 115 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, [C | Ics], Line, Tlen, _, _) when C >= 117, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(6, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 6};
yystate(5, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 8, Tlen);
yystate(5, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 8, Tlen);
yystate(5, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 8, Tlen);
yystate(5, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 8, Tlen);
yystate(5, Ics, Line, Tlen, _, _) -> {8, Tlen, Ics, Line, 5};
yystate(4, Ics, Line, Tlen, _, _) -> {6, Tlen, Ics, Line};
yystate(3, Ics, Line, Tlen, _, _) -> {1, Tlen, Ics, Line};
yystate(2, [99 | Ics], Line, Tlen, _, _) -> yystate(1, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [97 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [98 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, [C | Ics], Line, Tlen, _, _) when C >= 100, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(2, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 2};
yystate(1, [104 | Ics], Line, Tlen, _, _) -> yystate(5, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [95 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [64 | Ics], Line, Tlen, _, _) -> yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [C | Ics], Line, Tlen, _, _) when C >= 65, C =< 90 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [C | Ics], Line, Tlen, _, _) when C >= 97, C =< 103 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, [C | Ics], Line, Tlen, _, _) when C >= 105, C =< 122 ->
yystate(26, Ics, Line, Tlen + 1, 28, Tlen);
yystate(1, Ics, Line, Tlen, _, _) -> {28, Tlen, Ics, Line, 1};
yystate(0, [62 | Ics], Line, Tlen, _, _) -> yystate(4, Ics, Line, Tlen + 1, 22, Tlen);
yystate(0, [C | Ics], Line, Tlen, _, _) when C >= 48, C =< 57 ->
yystate(19, Ics, Line, Tlen + 1, 22, Tlen);
yystate(0, Ics, Line, Tlen, _, _) -> {22, Tlen, Ics, Line, 0};
yystate(S, Ics, Line, Tlen, Action, Alen) -> {Action, Alen, Tlen, Ics, Line, S}.
yyaction(Action , TokenLength , , ) - >
{ token , } | { end_token , } | skip_token | { error , String } .
yyaction(0, _, _, _) -> yyaction_0();
yyaction(1, _, _, TokenLine) -> yyaction_1(TokenLine);
yyaction(2, _, _, TokenLine) -> yyaction_2(TokenLine);
yyaction(3, _, _, TokenLine) -> yyaction_3(TokenLine);
yyaction(4, _, _, TokenLine) -> yyaction_4(TokenLine);
yyaction(5, _, _, TokenLine) -> yyaction_5(TokenLine);
yyaction(6, _, _, TokenLine) -> yyaction_6(TokenLine);
yyaction(7, _, _, TokenLine) -> yyaction_7(TokenLine);
yyaction(8, _, _, TokenLine) -> yyaction_8(TokenLine);
yyaction(9, _, _, TokenLine) -> yyaction_9(TokenLine);
yyaction(10, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_10(TokenChars, TokenLen, TokenLine);
yyaction(11, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_11(TokenChars, TokenLen, TokenLine);
yyaction(12, _, _, TokenLine) -> yyaction_12(TokenLine);
yyaction(13, _, _, TokenLine) -> yyaction_13(TokenLine);
yyaction(14, _, _, TokenLine) -> yyaction_14(TokenLine);
yyaction(15, _, _, TokenLine) -> yyaction_15(TokenLine);
yyaction(16, _, _, TokenLine) -> yyaction_16(TokenLine);
yyaction(17, _, _, TokenLine) -> yyaction_17(TokenLine);
yyaction(18, _, _, TokenLine) -> yyaction_18(TokenLine);
yyaction(19, _, _, TokenLine) -> yyaction_19(TokenLine);
yyaction(20, _, _, TokenLine) -> yyaction_20(TokenLine);
yyaction(21, _, _, TokenLine) -> yyaction_21(TokenLine);
yyaction(22, _, _, TokenLine) -> yyaction_22(TokenLine);
yyaction(23, _, _, TokenLine) -> yyaction_23(TokenLine);
yyaction(24, _, _, TokenLine) -> yyaction_24(TokenLine);
yyaction(25, _, _, TokenLine) -> yyaction_25(TokenLine);
yyaction(26, _, _, TokenLine) -> yyaction_26(TokenLine);
yyaction(27, _, _, TokenLine) -> yyaction_27(TokenLine);
yyaction(28, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_28(TokenChars, TokenLine);
yyaction(29, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_29(TokenChars, TokenLine);
yyaction(30, TokenLen, YYtcs, TokenLine) ->
TokenChars = yypre(YYtcs, TokenLen),
yyaction_30(TokenChars, TokenLine);
yyaction(31, _, _, TokenLine) -> yyaction_31(TokenLine);
yyaction(_, _, _, _) -> error.
-compile({inline, yyaction_0/0}).
-file("./chico_tokenizer.xrl", 11).
yyaction_0() -> skip_token.
-compile({inline, yyaction_1/1}).
-file("./chico_tokenizer.xrl", 12).
yyaction_1(TokenLine) -> {token, {dot, TokenLine, none}}.
-compile({inline, yyaction_2/1}).
-file("./chico_tokenizer.xrl", 14).
yyaction_2(TokenLine) -> {token, {public, TokenLine, none}}.
-compile({inline, yyaction_3/1}).
-file("./chico_tokenizer.xrl", 15).
yyaction_3(TokenLine) -> {token, {function, TokenLine, none}}.
-compile({inline, yyaction_4/1}).
-file("./chico_tokenizer.xrl", 16).
yyaction_4(TokenLine) -> {token, {left_parenthesis, TokenLine, none}}.
-compile({inline, yyaction_5/1}).
-file("./chico_tokenizer.xrl", 17).
yyaction_5(TokenLine) -> {token, {right_parenthesis, TokenLine, none}}.
-compile({inline, yyaction_6/1}).
-file("./chico_tokenizer.xrl", 18).
yyaction_6(TokenLine) -> {token, {open_function, TokenLine, none}}.
-compile({inline, yyaction_7/1}).
-file("./chico_tokenizer.xrl", 19).
yyaction_7(TokenLine) -> {token, {done, TokenLine, none}}.
-compile({inline, yyaction_8/1}).
-file("./chico_tokenizer.xrl", 20).
yyaction_8(TokenLine) -> {token, {match, TokenLine, none}}.
-compile({inline, yyaction_9/1}).
-file("./chico_tokenizer.xrl", 21).
yyaction_9(TokenLine) -> {token, {with, TokenLine, none}}.
-compile({inline, yyaction_10/3}).
-file("./chico_tokenizer.xrl", 23).
yyaction_10(TokenChars, TokenLen, TokenLine) ->
{token, {string, TokenLine, atom_to_list(get_string(TokenChars, TokenLen))}}.
-compile({inline, yyaction_11/3}).
-file("./chico_tokenizer.xrl", 24).
yyaction_11(TokenChars, TokenLen, TokenLine) ->
{token, {atom, TokenLine, get_string(TokenChars, TokenLen)}}.
-compile({inline, yyaction_12/1}).
-file("./chico_tokenizer.xrl", 26).
yyaction_12(TokenLine) -> {token, {'#', TokenLine, none}}.
-compile({inline, yyaction_13/1}).
-file("./chico_tokenizer.xrl", 27).
yyaction_13(TokenLine) -> {token, {'{', TokenLine, none}}.
-compile({inline, yyaction_14/1}).
-file("./chico_tokenizer.xrl", 28).
yyaction_14(TokenLine) -> {token, {'}', TokenLine, none}}.
-compile({inline, yyaction_15/1}).
-file("./chico_tokenizer.xrl", 29).
yyaction_15(TokenLine) -> {token, {'[', TokenLine, none}}.
-compile({inline, yyaction_16/1}).
-file("./chico_tokenizer.xrl", 30).
yyaction_16(TokenLine) -> {token, {']', TokenLine, none}}.
-compile({inline, yyaction_17/1}).
-file("./chico_tokenizer.xrl", 31).
yyaction_17(TokenLine) -> {token, {'~', TokenLine, none}}.
-compile({inline, yyaction_18/1}).
-file("./chico_tokenizer.xrl", 32).
yyaction_18(TokenLine) -> {token, {'~a', TokenLine, none}}.
-compile({inline, yyaction_19/1}).
-file("./chico_tokenizer.xrl", 34).
yyaction_19(TokenLine) -> {token, {export, TokenLine, export}}.
-compile({inline, yyaction_20/1}).
-file("./chico_tokenizer.xrl", 35).
yyaction_20(TokenLine) -> {token, {apply, TokenLine, apply}}.
-compile({inline, yyaction_21/1}).
-file("./chico_tokenizer.xrl", 36).
yyaction_21(TokenLine) -> {token, {operator, TokenLine, '+'}}.
-compile({inline, yyaction_22/1}).
-file("./chico_tokenizer.xrl", 37).
yyaction_22(TokenLine) -> {token, {operator, TokenLine, '-'}}.
-compile({inline, yyaction_23/1}).
-file("./chico_tokenizer.xrl", 38).
yyaction_23(TokenLine) -> {token, {operator, TokenLine, '/'}}.
-compile({inline, yyaction_24/1}).
-file("./chico_tokenizer.xrl", 39).
yyaction_24(TokenLine) -> {token, {operator, TokenLine, '*'}}.
-compile({inline, yyaction_25/1}).
-file("./chico_tokenizer.xrl", 42).
yyaction_25(TokenLine) -> {token, {variable, TokenLine, none}}.
-compile({inline, yyaction_26/1}).
-file("./chico_tokenizer.xrl", 43).
yyaction_26(TokenLine) -> {token, {assigment, TokenLine, none}}.
-compile({inline, yyaction_27/1}).
-file("./chico_tokenizer.xrl", 44).
yyaction_27(TokenLine) -> {token, {type_assigment, TokenLine, none}}.
-compile({inline, yyaction_28/2}).
-file("./chico_tokenizer.xrl", 45).
yyaction_28(TokenChars, TokenLine) -> {token, {declaration, TokenLine, list_to_atom(TokenChars)}}.
-compile({inline, yyaction_29/2}).
-file("./chico_tokenizer.xrl", 47).
yyaction_29(TokenChars, TokenLine) -> {token, {integer, TokenLine, list_to_integer(TokenChars)}}.
-compile({inline, yyaction_30/2}).
-file("./chico_tokenizer.xrl", 48).
yyaction_30(TokenChars, TokenLine) -> {token, {float, TokenLine, list_to_float(TokenChars)}}.
-compile({inline, yyaction_31/1}).
-file("./chico_tokenizer.xrl", 50).
yyaction_31(TokenLine) -> {token, {declaration, TokenLine, '_'}}.
-file("/opt/homebrew/Cellar/erlang/25.2/lib/erlang/lib/parsetools-2.4.1/include/leexinc.hrl", 313).
|
a6a696bcdfa2d3ae44f14f9fc2ad54c8d9befd6d6083df3bed1ef925407f6d8b | takeoutweight/clojure-scheme | macros.clj | (ns cljscm.macro-test.macros
(:refer-clojure :exclude [==]))
(defmacro == [a b]
`(+ ~a ~b)) | null | https://raw.githubusercontent.com/takeoutweight/clojure-scheme/6121de1690a6a52c7dbbe7fa722aaf3ddd4920dd/test/cljscm/cljscm/macro_test/macros.clj | clojure | (ns cljscm.macro-test.macros
(:refer-clojure :exclude [==]))
(defmacro == [a b]
`(+ ~a ~b)) |
|
f8aa53c3ec0206bc2e2ae2f1af2c196c05926ab169742c14531bb59be6eae4e6 | clojure-interop/aws-api | AbstractAmazonWorkLinkAsync.clj | (ns com.amazonaws.services.worklink.AbstractAmazonWorkLinkAsync
"Abstract implementation of AmazonWorkLinkAsync. Convenient method forms pass through to the corresponding
overload that takes a request object and an AsyncHandler, which throws an
UnsupportedOperationException."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.worklink AbstractAmazonWorkLinkAsync]))
(defn update-fleet-metadata-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateFleetMetadataRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateFleetMetadata operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateFleetMetadataResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateFleetMetadataRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateFleetMetadataAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateFleetMetadataRequest request]
(-> this (.updateFleetMetadataAsync request))))
(defn associate-website-certificate-authority-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.AssociateWebsiteCertificateAuthorityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the AssociateWebsiteCertificateAuthority operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.AssociateWebsiteCertificateAuthorityResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateWebsiteCertificateAuthorityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.associateWebsiteCertificateAuthorityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateWebsiteCertificateAuthorityRequest request]
(-> this (.associateWebsiteCertificateAuthorityAsync request))))
(defn describe-identity-provider-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeIdentityProviderConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeIdentityProviderConfiguration operation returned by
the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeIdentityProviderConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeIdentityProviderConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeIdentityProviderConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeIdentityProviderConfigurationRequest request]
(-> this (.describeIdentityProviderConfigurationAsync request))))
(defn associate-website-authorization-provider-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.AssociateWebsiteAuthorizationProviderRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the AssociateWebsiteAuthorizationProvider operation returned by
the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.AssociateWebsiteAuthorizationProviderResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateWebsiteAuthorizationProviderRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.associateWebsiteAuthorizationProviderAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateWebsiteAuthorizationProviderRequest request]
(-> this (.associateWebsiteAuthorizationProviderAsync request))))
(defn disassociate-website-certificate-authority-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DisassociateWebsiteCertificateAuthorityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DisassociateWebsiteCertificateAuthority operation returned by
the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DisassociateWebsiteCertificateAuthorityResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateWebsiteCertificateAuthorityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.disassociateWebsiteCertificateAuthorityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateWebsiteCertificateAuthorityRequest request]
(-> this (.disassociateWebsiteCertificateAuthorityAsync request))))
(defn describe-fleet-metadata-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeFleetMetadataRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeFleetMetadata operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeFleetMetadataResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeFleetMetadataRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeFleetMetadataAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeFleetMetadataRequest request]
(-> this (.describeFleetMetadataAsync request))))
(defn list-website-certificate-authorities-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListWebsiteCertificateAuthoritiesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListWebsiteCertificateAuthorities operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListWebsiteCertificateAuthoritiesResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListWebsiteCertificateAuthoritiesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listWebsiteCertificateAuthoritiesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListWebsiteCertificateAuthoritiesRequest request]
(-> this (.listWebsiteCertificateAuthoritiesAsync request))))
(defn revoke-domain-access-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.RevokeDomainAccessRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the RevokeDomainAccess operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.RevokeDomainAccessResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.RevokeDomainAccessRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.revokeDomainAccessAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.RevokeDomainAccessRequest request]
(-> this (.revokeDomainAccessAsync request))))
(defn update-domain-metadata-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateDomainMetadataRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateDomainMetadata operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateDomainMetadataResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateDomainMetadataRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateDomainMetadataAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateDomainMetadataRequest request]
(-> this (.updateDomainMetadataAsync request))))
(defn restore-domain-access-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.RestoreDomainAccessRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the RestoreDomainAccess operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.RestoreDomainAccessResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.RestoreDomainAccessRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.restoreDomainAccessAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.RestoreDomainAccessRequest request]
(-> this (.restoreDomainAccessAsync request))))
(defn update-company-network-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateCompanyNetworkConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateCompanyNetworkConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateCompanyNetworkConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateCompanyNetworkConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateCompanyNetworkConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateCompanyNetworkConfigurationRequest request]
(-> this (.updateCompanyNetworkConfigurationAsync request))))
(defn sign-out-user-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.SignOutUserRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the SignOutUser operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.SignOutUserResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.SignOutUserRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.signOutUserAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.SignOutUserRequest request]
(-> this (.signOutUserAsync request))))
(defn describe-audit-stream-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeAuditStreamConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeAuditStreamConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeAuditStreamConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeAuditStreamConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeAuditStreamConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeAuditStreamConfigurationRequest request]
(-> this (.describeAuditStreamConfigurationAsync request))))
(defn describe-device-policy-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeDevicePolicyConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeDevicePolicyConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeDevicePolicyConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDevicePolicyConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeDevicePolicyConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDevicePolicyConfigurationRequest request]
(-> this (.describeDevicePolicyConfigurationAsync request))))
(defn create-fleet-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.CreateFleetRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateFleet operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.CreateFleetResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.CreateFleetRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createFleetAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.CreateFleetRequest request]
(-> this (.createFleetAsync request))))
(defn describe-company-network-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeCompanyNetworkConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeCompanyNetworkConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeCompanyNetworkConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeCompanyNetworkConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeCompanyNetworkConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeCompanyNetworkConfigurationRequest request]
(-> this (.describeCompanyNetworkConfigurationAsync request))))
(defn disassociate-domain-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DisassociateDomainRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DisassociateDomain operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DisassociateDomainResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateDomainRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.disassociateDomainAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateDomainRequest request]
(-> this (.disassociateDomainAsync request))))
(defn describe-website-certificate-authority-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeWebsiteCertificateAuthorityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeWebsiteCertificateAuthority operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeWebsiteCertificateAuthorityResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeWebsiteCertificateAuthorityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeWebsiteCertificateAuthorityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeWebsiteCertificateAuthorityRequest request]
(-> this (.describeWebsiteCertificateAuthorityAsync request))))
(defn delete-fleet-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DeleteFleetRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteFleet operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DeleteFleetResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DeleteFleetRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteFleetAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DeleteFleetRequest request]
(-> this (.deleteFleetAsync request))))
(defn disassociate-website-authorization-provider-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DisassociateWebsiteAuthorizationProviderRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DisassociateWebsiteAuthorizationProvider operation returned by
the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DisassociateWebsiteAuthorizationProviderResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateWebsiteAuthorizationProviderRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.disassociateWebsiteAuthorizationProviderAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateWebsiteAuthorizationProviderRequest request]
(-> this (.disassociateWebsiteAuthorizationProviderAsync request))))
(defn describe-domain-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeDomainRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeDomain operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeDomainResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDomainRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeDomainAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDomainRequest request]
(-> this (.describeDomainAsync request))))
(defn list-devices-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListDevicesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListDevices operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListDevicesResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListDevicesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listDevicesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListDevicesRequest request]
(-> this (.listDevicesAsync request))))
(defn update-audit-stream-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateAuditStreamConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateAuditStreamConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateAuditStreamConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateAuditStreamConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateAuditStreamConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateAuditStreamConfigurationRequest request]
(-> this (.updateAuditStreamConfigurationAsync request))))
(defn list-fleets-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListFleetsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListFleets operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListFleetsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListFleetsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listFleetsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListFleetsRequest request]
(-> this (.listFleetsAsync request))))
(defn update-device-policy-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateDevicePolicyConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateDevicePolicyConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateDevicePolicyConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateDevicePolicyConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateDevicePolicyConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateDevicePolicyConfigurationRequest request]
(-> this (.updateDevicePolicyConfigurationAsync request))))
(defn list-website-authorization-providers-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListWebsiteAuthorizationProvidersRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListWebsiteAuthorizationProviders operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListWebsiteAuthorizationProvidersResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListWebsiteAuthorizationProvidersRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listWebsiteAuthorizationProvidersAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListWebsiteAuthorizationProvidersRequest request]
(-> this (.listWebsiteAuthorizationProvidersAsync request))))
(defn associate-domain-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.AssociateDomainRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the AssociateDomain operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.AssociateDomainResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateDomainRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.associateDomainAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateDomainRequest request]
(-> this (.associateDomainAsync request))))
(defn describe-device-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeDeviceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeDevice operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeDeviceResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDeviceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeDeviceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDeviceRequest request]
(-> this (.describeDeviceAsync request))))
(defn list-domains-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListDomainsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListDomains operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListDomainsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListDomainsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listDomainsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListDomainsRequest request]
(-> this (.listDomainsAsync request))))
(defn update-identity-provider-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateIdentityProviderConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateIdentityProviderConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateIdentityProviderConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateIdentityProviderConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateIdentityProviderConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateIdentityProviderConfigurationRequest request]
(-> this (.updateIdentityProviderConfigurationAsync request))))
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.worklink/src/com/amazonaws/services/worklink/AbstractAmazonWorkLinkAsync.clj | clojure | (ns com.amazonaws.services.worklink.AbstractAmazonWorkLinkAsync
"Abstract implementation of AmazonWorkLinkAsync. Convenient method forms pass through to the corresponding
overload that takes a request object and an AsyncHandler, which throws an
UnsupportedOperationException."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.worklink AbstractAmazonWorkLinkAsync]))
(defn update-fleet-metadata-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateFleetMetadataRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateFleetMetadata operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateFleetMetadataResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateFleetMetadataRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateFleetMetadataAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateFleetMetadataRequest request]
(-> this (.updateFleetMetadataAsync request))))
(defn associate-website-certificate-authority-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.AssociateWebsiteCertificateAuthorityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the AssociateWebsiteCertificateAuthority operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.AssociateWebsiteCertificateAuthorityResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateWebsiteCertificateAuthorityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.associateWebsiteCertificateAuthorityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateWebsiteCertificateAuthorityRequest request]
(-> this (.associateWebsiteCertificateAuthorityAsync request))))
(defn describe-identity-provider-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeIdentityProviderConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeIdentityProviderConfiguration operation returned by
the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeIdentityProviderConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeIdentityProviderConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeIdentityProviderConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeIdentityProviderConfigurationRequest request]
(-> this (.describeIdentityProviderConfigurationAsync request))))
(defn associate-website-authorization-provider-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.AssociateWebsiteAuthorizationProviderRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the AssociateWebsiteAuthorizationProvider operation returned by
the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.AssociateWebsiteAuthorizationProviderResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateWebsiteAuthorizationProviderRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.associateWebsiteAuthorizationProviderAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateWebsiteAuthorizationProviderRequest request]
(-> this (.associateWebsiteAuthorizationProviderAsync request))))
(defn disassociate-website-certificate-authority-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DisassociateWebsiteCertificateAuthorityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DisassociateWebsiteCertificateAuthority operation returned by
the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DisassociateWebsiteCertificateAuthorityResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateWebsiteCertificateAuthorityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.disassociateWebsiteCertificateAuthorityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateWebsiteCertificateAuthorityRequest request]
(-> this (.disassociateWebsiteCertificateAuthorityAsync request))))
(defn describe-fleet-metadata-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeFleetMetadataRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeFleetMetadata operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeFleetMetadataResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeFleetMetadataRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeFleetMetadataAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeFleetMetadataRequest request]
(-> this (.describeFleetMetadataAsync request))))
(defn list-website-certificate-authorities-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListWebsiteCertificateAuthoritiesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListWebsiteCertificateAuthorities operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListWebsiteCertificateAuthoritiesResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListWebsiteCertificateAuthoritiesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listWebsiteCertificateAuthoritiesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListWebsiteCertificateAuthoritiesRequest request]
(-> this (.listWebsiteCertificateAuthoritiesAsync request))))
(defn revoke-domain-access-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.RevokeDomainAccessRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the RevokeDomainAccess operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.RevokeDomainAccessResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.RevokeDomainAccessRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.revokeDomainAccessAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.RevokeDomainAccessRequest request]
(-> this (.revokeDomainAccessAsync request))))
(defn update-domain-metadata-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateDomainMetadataRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateDomainMetadata operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateDomainMetadataResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateDomainMetadataRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateDomainMetadataAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateDomainMetadataRequest request]
(-> this (.updateDomainMetadataAsync request))))
(defn restore-domain-access-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.RestoreDomainAccessRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the RestoreDomainAccess operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.RestoreDomainAccessResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.RestoreDomainAccessRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.restoreDomainAccessAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.RestoreDomainAccessRequest request]
(-> this (.restoreDomainAccessAsync request))))
(defn update-company-network-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateCompanyNetworkConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateCompanyNetworkConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateCompanyNetworkConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateCompanyNetworkConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateCompanyNetworkConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateCompanyNetworkConfigurationRequest request]
(-> this (.updateCompanyNetworkConfigurationAsync request))))
(defn sign-out-user-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.SignOutUserRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the SignOutUser operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.SignOutUserResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.SignOutUserRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.signOutUserAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.SignOutUserRequest request]
(-> this (.signOutUserAsync request))))
(defn describe-audit-stream-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeAuditStreamConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeAuditStreamConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeAuditStreamConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeAuditStreamConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeAuditStreamConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeAuditStreamConfigurationRequest request]
(-> this (.describeAuditStreamConfigurationAsync request))))
(defn describe-device-policy-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeDevicePolicyConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeDevicePolicyConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeDevicePolicyConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDevicePolicyConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeDevicePolicyConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDevicePolicyConfigurationRequest request]
(-> this (.describeDevicePolicyConfigurationAsync request))))
(defn create-fleet-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.CreateFleetRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the CreateFleet operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.CreateFleetResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.CreateFleetRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.createFleetAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.CreateFleetRequest request]
(-> this (.createFleetAsync request))))
(defn describe-company-network-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeCompanyNetworkConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeCompanyNetworkConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeCompanyNetworkConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeCompanyNetworkConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeCompanyNetworkConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeCompanyNetworkConfigurationRequest request]
(-> this (.describeCompanyNetworkConfigurationAsync request))))
(defn disassociate-domain-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DisassociateDomainRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DisassociateDomain operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DisassociateDomainResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateDomainRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.disassociateDomainAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateDomainRequest request]
(-> this (.disassociateDomainAsync request))))
(defn describe-website-certificate-authority-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeWebsiteCertificateAuthorityRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeWebsiteCertificateAuthority operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeWebsiteCertificateAuthorityResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeWebsiteCertificateAuthorityRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeWebsiteCertificateAuthorityAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeWebsiteCertificateAuthorityRequest request]
(-> this (.describeWebsiteCertificateAuthorityAsync request))))
(defn delete-fleet-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DeleteFleetRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DeleteFleet operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DeleteFleetResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DeleteFleetRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.deleteFleetAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DeleteFleetRequest request]
(-> this (.deleteFleetAsync request))))
(defn disassociate-website-authorization-provider-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DisassociateWebsiteAuthorizationProviderRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DisassociateWebsiteAuthorizationProvider operation returned by
the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DisassociateWebsiteAuthorizationProviderResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateWebsiteAuthorizationProviderRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.disassociateWebsiteAuthorizationProviderAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DisassociateWebsiteAuthorizationProviderRequest request]
(-> this (.disassociateWebsiteAuthorizationProviderAsync request))))
(defn describe-domain-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeDomainRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeDomain operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeDomainResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDomainRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeDomainAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDomainRequest request]
(-> this (.describeDomainAsync request))))
(defn list-devices-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListDevicesRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListDevices operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListDevicesResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListDevicesRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listDevicesAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListDevicesRequest request]
(-> this (.listDevicesAsync request))))
(defn update-audit-stream-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateAuditStreamConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateAuditStreamConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateAuditStreamConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateAuditStreamConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateAuditStreamConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateAuditStreamConfigurationRequest request]
(-> this (.updateAuditStreamConfigurationAsync request))))
(defn list-fleets-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListFleetsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListFleets operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListFleetsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListFleetsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listFleetsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListFleetsRequest request]
(-> this (.listFleetsAsync request))))
(defn update-device-policy-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateDevicePolicyConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateDevicePolicyConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateDevicePolicyConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateDevicePolicyConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateDevicePolicyConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateDevicePolicyConfigurationRequest request]
(-> this (.updateDevicePolicyConfigurationAsync request))))
(defn list-website-authorization-providers-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListWebsiteAuthorizationProvidersRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListWebsiteAuthorizationProviders operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListWebsiteAuthorizationProvidersResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListWebsiteAuthorizationProvidersRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listWebsiteAuthorizationProvidersAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListWebsiteAuthorizationProvidersRequest request]
(-> this (.listWebsiteAuthorizationProvidersAsync request))))
(defn associate-domain-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.AssociateDomainRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the AssociateDomain operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.AssociateDomainResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateDomainRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.associateDomainAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.AssociateDomainRequest request]
(-> this (.associateDomainAsync request))))
(defn describe-device-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.DescribeDeviceRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the DescribeDevice operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.DescribeDeviceResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDeviceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.describeDeviceAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.DescribeDeviceRequest request]
(-> this (.describeDeviceAsync request))))
(defn list-domains-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.ListDomainsRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the ListDomains operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.ListDomainsResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListDomainsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.listDomainsAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.ListDomainsRequest request]
(-> this (.listDomainsAsync request))))
(defn update-identity-provider-configuration-async
"Description copied from interface: AmazonWorkLinkAsync
request - `com.amazonaws.services.worklink.model.UpdateIdentityProviderConfigurationRequest`
async-handler - `com.amazonaws.handlers.AsyncHandler`
returns: A Java Future containing the result of the UpdateIdentityProviderConfiguration operation returned by the
service. - `java.util.concurrent.Future<com.amazonaws.services.worklink.model.UpdateIdentityProviderConfigurationResult>`"
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateIdentityProviderConfigurationRequest request ^com.amazonaws.handlers.AsyncHandler async-handler]
(-> this (.updateIdentityProviderConfigurationAsync request async-handler)))
(^java.util.concurrent.Future [^AbstractAmazonWorkLinkAsync this ^com.amazonaws.services.worklink.model.UpdateIdentityProviderConfigurationRequest request]
(-> this (.updateIdentityProviderConfigurationAsync request))))
|
|
b3290fe6891dea68a1df29ccdc15fb5b8322e19248cf0541116d2efc231bfe7b | nuttycom/aftok | WorkLog.hs | # LANGUAGE InstanceSigs #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
module Aftok.Snaplet.WorkLog where
import Aftok.Database
import Aftok.Interval
( Interval (..),
intervalJSON,
)
import Aftok.Json
import Aftok.Snaplet
import Aftok.Snaplet.Auth
import Aftok.Snaplet.Util
import Aftok.TimeLog
( AmendmentId,
EventAmendment (..),
EventId (..),
LogEntry (LogEntry),
LogEvent,
ModTime (..),
WorkIndex (..),
eventName,
eventTime,
workIndex,
_AmendmentId,
_EventId,
)
import Aftok.Types
( CreditTo (..),
ProjectId,
UserId,
_ProjectId,
_UserId,
)
import Control.Lens (view, (^.))
import Data.Aeson (Value (Object), eitherDecode, object, (.:), (.=))
import Data.Aeson.Key (fromText)
import Data.Aeson.Types (Pair, Parser, parseEither)
import qualified Data.List.NonEmpty as L
import qualified Data.Map.Strict as MS
import qualified Data.Text as T
import qualified Data.Thyme.Clock as C
import qualified Data.UUID as U
import Snap.Core
import qualified Snap.Snaplet as S
----------------------
-- Handlers
----------------------
logWorkHandler ::
(C.UTCTime -> LogEvent) ->
S.Handler App App (ProjectId, UserId, KeyedLogEntry)
logWorkHandler evCtr = do
uid <- requireUserId
pid <- requireProjectId
requestBody <- readRequestBody 4096
timestamp <- liftIO C.getCurrentTime
case (eitherDecode requestBody >>= parseEither (parseLogEntry uid evCtr)) of
Left err ->
snapError 400 $
"Unable to parse log entry "
<> (show requestBody)
<> ": "
<> show err
Right entry -> do
eid <- snapEval $ createEvent pid uid (entry timestamp)
ev <- snapEval $ findEvent eid
maybe
( snapError 500 $
"An error occured retrieving the newly created event record."
)
pure
ev
amendEventHandler :: S.Handler App App (EventId, AmendmentId)
amendEventHandler = do
uid <- requireUserId
eventIdBytes <- getParam "eventId"
eventId <-
maybe
(snapError 400 "eventId parameter is required")
(pure . EventId)
(eventIdBytes >>= U.fromASCIIBytes)
modTime <- ModTime <$> liftIO C.getCurrentTime
requestJSON <- readRequestJSON 4096
either
(snapError 400 . T.pack)
(snapEval . amendEvent uid eventId)
(parseEither (parseEventAmendment modTime) requestJSON)
projectWorkIndex :: S.Handler App App (WorkIndex KeyedLogEntry)
projectWorkIndex = do
uid <- requireUserId
pid <- requireProjectId
snapEval $ readWorkIndex pid uid
userEvents :: S.Handler App App [KeyedLogEntry]
userEvents = do
uid <- requireUserId
pid <- requireProjectId
ival <- rangeQueryParam
limit <- Limit . fromMaybe 1 <$> decimalParam "limit"
snapEval $ findEvents pid uid ival limit
userWorkIndex :: S.Handler App App (WorkIndex KeyedLogEntry)
userWorkIndex = workIndex (view logEntry) <$> userEvents
----------------------
-- Parsing
----------------------
parseEventAmendment ::
ModTime ->
Value ->
Parser EventAmendment
parseEventAmendment t = \case
Object o ->
let parseA :: Text -> Parser EventAmendment
parseA "timeChange" = TimeChange t <$> o .: "eventTime"
parseA "creditToChange" = CreditToChange t <$> parseCreditToV2 o
parseA "metadataChange" = MetadataChange t <$> o .: "eventMeta"
parseA tid =
fail . T.unpack $ "Amendment type " <> tid <> " not recognized."
in o .: "amendment" >>= parseA
val ->
fail $ "Value " <> show val <> " is not a JSON object."
----------------------
-- Rendering
----------------------
logEventJSON :: LogEvent -> Value
logEventJSON ev =
object [fromText (eventName ev) .= object ["eventTime" .= (ev ^. eventTime)]]
logEntryFields :: LogEntry -> [Pair]
logEntryFields (LogEntry c ev m) =
[ "creditTo" .= creditToJSON c,
"event" .= logEventJSON ev,
"eventMeta" .= m
]
keyedLogEntryFields :: KeyedLogEntry -> [Pair]
keyedLogEntryFields (KeyedLogEntry eid le) =
["eventId" .= idValue _EventId eid] <> logEntryFields le
keyedLogEntryJSON :: KeyedLogEntry -> Value
keyedLogEntryJSON kle =
object (keyedLogEntryFields kle)
extendedLogEntryJSON :: (ProjectId, UserId, KeyedLogEntry) -> Value
extendedLogEntryJSON (pid, uid, le) =
v1
. obj
$ [ "projectId" .= idValue _ProjectId pid,
"loggedBy" .= idValue _UserId uid
]
<> keyedLogEntryFields le
workIndexJSON :: forall t. (t -> Value) -> WorkIndex t -> Value
workIndexJSON leJSON (WorkIndex widx) =
v1 $
obj ["workIndex" .= fmap widxRec (MS.assocs widx)]
where
widxRec :: (CreditTo, NonEmpty (Interval t)) -> Value
widxRec (c, l) =
object
[ "creditTo" .= creditToJSON c,
"intervals" .= (intervalJSON leJSON <$> L.toList l)
]
amendEventResultJSON :: (EventId, AmendmentId) -> Value
amendEventResultJSON (eid, aid) =
object
[ "replacement_event" .= idValue _EventId eid,
"amendment_id" .= idValue _AmendmentId aid
]
| null | https://raw.githubusercontent.com/nuttycom/aftok/58feefe675cea908cf10619cc88ca4770152e82e/server/Aftok/Snaplet/WorkLog.hs | haskell | --------------------
Handlers
--------------------
--------------------
Parsing
--------------------
--------------------
Rendering
-------------------- | # LANGUAGE InstanceSigs #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
module Aftok.Snaplet.WorkLog where
import Aftok.Database
import Aftok.Interval
( Interval (..),
intervalJSON,
)
import Aftok.Json
import Aftok.Snaplet
import Aftok.Snaplet.Auth
import Aftok.Snaplet.Util
import Aftok.TimeLog
( AmendmentId,
EventAmendment (..),
EventId (..),
LogEntry (LogEntry),
LogEvent,
ModTime (..),
WorkIndex (..),
eventName,
eventTime,
workIndex,
_AmendmentId,
_EventId,
)
import Aftok.Types
( CreditTo (..),
ProjectId,
UserId,
_ProjectId,
_UserId,
)
import Control.Lens (view, (^.))
import Data.Aeson (Value (Object), eitherDecode, object, (.:), (.=))
import Data.Aeson.Key (fromText)
import Data.Aeson.Types (Pair, Parser, parseEither)
import qualified Data.List.NonEmpty as L
import qualified Data.Map.Strict as MS
import qualified Data.Text as T
import qualified Data.Thyme.Clock as C
import qualified Data.UUID as U
import Snap.Core
import qualified Snap.Snaplet as S
logWorkHandler ::
(C.UTCTime -> LogEvent) ->
S.Handler App App (ProjectId, UserId, KeyedLogEntry)
logWorkHandler evCtr = do
uid <- requireUserId
pid <- requireProjectId
requestBody <- readRequestBody 4096
timestamp <- liftIO C.getCurrentTime
case (eitherDecode requestBody >>= parseEither (parseLogEntry uid evCtr)) of
Left err ->
snapError 400 $
"Unable to parse log entry "
<> (show requestBody)
<> ": "
<> show err
Right entry -> do
eid <- snapEval $ createEvent pid uid (entry timestamp)
ev <- snapEval $ findEvent eid
maybe
( snapError 500 $
"An error occured retrieving the newly created event record."
)
pure
ev
amendEventHandler :: S.Handler App App (EventId, AmendmentId)
amendEventHandler = do
uid <- requireUserId
eventIdBytes <- getParam "eventId"
eventId <-
maybe
(snapError 400 "eventId parameter is required")
(pure . EventId)
(eventIdBytes >>= U.fromASCIIBytes)
modTime <- ModTime <$> liftIO C.getCurrentTime
requestJSON <- readRequestJSON 4096
either
(snapError 400 . T.pack)
(snapEval . amendEvent uid eventId)
(parseEither (parseEventAmendment modTime) requestJSON)
projectWorkIndex :: S.Handler App App (WorkIndex KeyedLogEntry)
projectWorkIndex = do
uid <- requireUserId
pid <- requireProjectId
snapEval $ readWorkIndex pid uid
userEvents :: S.Handler App App [KeyedLogEntry]
userEvents = do
uid <- requireUserId
pid <- requireProjectId
ival <- rangeQueryParam
limit <- Limit . fromMaybe 1 <$> decimalParam "limit"
snapEval $ findEvents pid uid ival limit
userWorkIndex :: S.Handler App App (WorkIndex KeyedLogEntry)
userWorkIndex = workIndex (view logEntry) <$> userEvents
parseEventAmendment ::
ModTime ->
Value ->
Parser EventAmendment
parseEventAmendment t = \case
Object o ->
let parseA :: Text -> Parser EventAmendment
parseA "timeChange" = TimeChange t <$> o .: "eventTime"
parseA "creditToChange" = CreditToChange t <$> parseCreditToV2 o
parseA "metadataChange" = MetadataChange t <$> o .: "eventMeta"
parseA tid =
fail . T.unpack $ "Amendment type " <> tid <> " not recognized."
in o .: "amendment" >>= parseA
val ->
fail $ "Value " <> show val <> " is not a JSON object."
logEventJSON :: LogEvent -> Value
logEventJSON ev =
object [fromText (eventName ev) .= object ["eventTime" .= (ev ^. eventTime)]]
logEntryFields :: LogEntry -> [Pair]
logEntryFields (LogEntry c ev m) =
[ "creditTo" .= creditToJSON c,
"event" .= logEventJSON ev,
"eventMeta" .= m
]
keyedLogEntryFields :: KeyedLogEntry -> [Pair]
keyedLogEntryFields (KeyedLogEntry eid le) =
["eventId" .= idValue _EventId eid] <> logEntryFields le
keyedLogEntryJSON :: KeyedLogEntry -> Value
keyedLogEntryJSON kle =
object (keyedLogEntryFields kle)
extendedLogEntryJSON :: (ProjectId, UserId, KeyedLogEntry) -> Value
extendedLogEntryJSON (pid, uid, le) =
v1
. obj
$ [ "projectId" .= idValue _ProjectId pid,
"loggedBy" .= idValue _UserId uid
]
<> keyedLogEntryFields le
workIndexJSON :: forall t. (t -> Value) -> WorkIndex t -> Value
workIndexJSON leJSON (WorkIndex widx) =
v1 $
obj ["workIndex" .= fmap widxRec (MS.assocs widx)]
where
widxRec :: (CreditTo, NonEmpty (Interval t)) -> Value
widxRec (c, l) =
object
[ "creditTo" .= creditToJSON c,
"intervals" .= (intervalJSON leJSON <$> L.toList l)
]
amendEventResultJSON :: (EventId, AmendmentId) -> Value
amendEventResultJSON (eid, aid) =
object
[ "replacement_event" .= idValue _EventId eid,
"amendment_id" .= idValue _AmendmentId aid
]
|
5dff12b652410330336ba9c3d913087696175b7df77142e3913afb982d16be69 | ekmett/eq | Type.hs | # LANGUAGE CPP , , ScopedTypeVariables , TypeOperators #
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706
#define LANGUAGE_PolyKinds
# LANGUAGE PolyKinds #
#endif
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
# LANGUAGE RoleAnnotations #
#endif
#if defined(__GLASGOW_HASKELL__) && MIN_VERSION_base(4,7,0)
#define HAS_DATA_TYPE_COERCION 1
#endif
{-# LANGUAGE GADTs #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Eq.Type
Copyright : ( C ) 2011 - 2014
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : provisional
-- Portability : rank2 types, type operators, (optional) type families
--
Leibnizian equality . Injectivity in the presence of type families
is provided by a generalization of a trick by posted here :
--
-- <-cafe/2010-May/077177.html>
----------------------------------------------------------------------------
module Data.Eq.Type
(
-- * Leibnizian equality
(:=)(..)
-- * Equality as an equivalence relation
, refl
, trans
, symm
, coerce
#ifdef LANGUAGE_PolyKinds
, apply
#endif
-- * Lifting equality
, lift
, lift2, lift2'
, lift3, lift3'
-- * Lowering equality
, lower
, lower2
, lower3
-- * 'Eq.:~:' equivalence
-- | "Data.Type.Equality" GADT definition is equivalent in power
, fromLeibniz
, toLeibniz
#ifdef HAS_DATA_TYPE_COERCION
-- * 'Co.Coercion' conversion
| Leibnizian equality can be converted to representational equality
, reprLeibniz
#endif
) where
import Prelude (Maybe(..))
import Control.Category
import Data.Semigroupoid
import Data.Groupoid
#ifdef HAS_DATA_TYPE_COERCION
import qualified Data.Type.Coercion as Co
#endif
import qualified Data.Type.Equality as Eq
infixl 4 :=
| Leibnizian equality states that two things are equal if you can
-- substitute one for the other in all contexts
newtype a := b = Refl { subst :: forall c. c a -> c b }
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
type role (:=) nominal nominal
#endif
-- | Equality is reflexive
refl :: a := a
refl = Refl id
newtype Coerce a = Coerce { uncoerce :: a }
| If two things are equal you can convert one to the other
coerce :: a := b -> a -> b
coerce f = uncoerce . subst f . Coerce
#ifdef LANGUAGE_PolyKinds
newtype Apply a b f g = Apply { unapply :: f a := g b }
| Apply one equality to another , respectively
apply :: f := g -> a := b -> f a := g b
apply fg ab = unapply (subst fg (Apply (lift ab)))
#endif
-- | Equality forms a category
instance Category (:=) where
id = Refl id
bc . ab = subst bc ab
instance Semigroupoid (:=) where
bc `o` ab = subst bc ab
instance Groupoid (:=) where
inv = symm
-- | Equality is transitive
trans :: a := b -> b := c -> a := c
trans ab bc = subst bc ab
newtype Symm p a b = Symm { unsymm :: p b a }
-- | Equality is symmetric
symm :: (a := b) -> (b := a)
symm a = unsymm (subst a (Symm refl))
newtype Lift f a b = Lift { unlift :: f a := f b }
-- | You can lift equality into any type constructor
lift :: a := b -> f a := f b
lift a = unlift (subst a (Lift refl))
newtype Lift2 f c a b = Lift2 { unlift2 :: f a c := f b c }
-- | ... in any position
lift2 :: a := b -> f a c := f b c
lift2 a = unlift2 (subst a (Lift2 refl))
lift2' :: a := b -> c := d -> f a c := f b d
lift2' ab cd = subst (lift2 ab) (lift cd)
newtype Lift3 f c d a b = Lift3 { unlift3 :: f a c d := f b c d }
lift3 :: a := b -> f a c d := f b c d
lift3 a = unlift3 (subst a (Lift3 refl))
lift3' :: a := b -> c := d -> e := f -> g a c e := g b d f
lift3' ab cd ef = lift3 ab `subst` lift2 cd `subst` lift ef
#ifdef LANGUAGE_PolyKinds
-- This is all more complicated than it needs to be. Ideally, we would just
-- write:
--
-- data family Lower (a :: j) (b :: k)
-- newtype instance Lower a (f x) = Lower { unlower :: a := x }
--
-- lower :: forall a b f g. f a := g b -> a := b
-- lower eq = unlower (subst eq (Lower refl :: Lower a (f a)))
--
And similarly for Lower{2,3 } . Unfortunately , this wo n't typecheck on
GHC 7.6 through 7.10 due to an old typechecker bug . To work around the
-- issue, we must:
--
1 . Pass ` f ` and ` g ` as explicit arguments to the GenInj{,2,3 } type family ,
-- and
--
2 . Define overlapping instances for GenInj{,2,3 } .
--
Part ( 2 ) of this workaround prevents us from using a data family here , as
GHC will reject overlapping data family instances as conflicting .
type family GenInj (f :: j -> k) (g :: j -> k) (x :: k) :: j
type family GenInj2 (f :: i -> j -> k) (g :: i -> j' -> k) (x :: k) :: i
type family GenInj3 (f :: h -> i -> j -> k) (g :: h -> i' -> j' -> k) (x :: k) :: h
#else
type family GenInj (f :: * -> *) (g :: * -> *) (x :: *) :: *
type family GenInj2 (f :: * -> * -> *) (g :: * -> * -> *) (x :: *) :: *
type family GenInj3 (f :: * -> * -> * -> *) (g :: * -> * -> * -> *) (x :: *) :: *
#endif
type instance GenInj f g (f a) = a
type instance GenInj f g (g b) = b
type instance GenInj2 f g (f a c) = a
type instance GenInj2 f g (g b c') = b
type instance GenInj3 f g (f a c d) = a
type instance GenInj3 f g (g b c' d') = b
newtype Lower f g a x = Lower { unlower :: a := GenInj f g x }
newtype Lower2 f g a x = Lower2 { unlower2 :: a := GenInj2 f g x }
newtype Lower3 f g a x = Lower3 { unlower3 :: a := GenInj3 f g x }
-- | Type constructors are generative and injective, so you can lower equality
-- through any type constructors ...
lower :: forall a b f g. f a := g b -> a := b
lower eq = unlower (subst eq (Lower refl :: Lower f g a (f a)))
-- | ... in any position ...
lower2 :: forall a b f g c c'. f a c := g b c' -> a := b
lower2 eq = unlower2 (subst eq (Lower2 refl :: Lower2 f g a (f a c)))
| ... these definitions are poly - kinded on GHC 7.6 and up .
lower3 :: forall a b f g c c' d d'. f a c d := g b c' d' -> a := b
lower3 eq = unlower3 (subst eq (Lower3 refl :: Lower3 f g a (f a c d)))
fromLeibniz :: a := b -> a Eq.:~: b
fromLeibniz a = subst a Eq.Refl
toLeibniz :: a Eq.:~: b -> a := b
toLeibniz Eq.Refl = refl
instance Eq.TestEquality ((:=) a) where
testEquality fa fb = Just (fromLeibniz (trans (symm fa) fb))
#ifdef HAS_DATA_TYPE_COERCION
reprLeibniz :: a := b -> Co.Coercion a b
reprLeibniz a = subst a Co.Coercion
instance Co.TestCoercion ((:=) a) where
testCoercion fa fb = Just (reprLeibniz (trans (symm fa) fb))
#endif
| null | https://raw.githubusercontent.com/ekmett/eq/4bba24b6d41c76931d22651f3250ad8eeb81e339/src/Data/Eq/Type.hs | haskell | # LANGUAGE GADTs #
---------------------------------------------------------------------------
|
Module : Data.Eq.Type
License : BSD-style (see the file LICENSE)
Stability : provisional
Portability : rank2 types, type operators, (optional) type families
<-cafe/2010-May/077177.html>
--------------------------------------------------------------------------
* Leibnizian equality
* Equality as an equivalence relation
* Lifting equality
* Lowering equality
* 'Eq.:~:' equivalence
| "Data.Type.Equality" GADT definition is equivalent in power
* 'Co.Coercion' conversion
substitute one for the other in all contexts
| Equality is reflexive
| Equality forms a category
| Equality is transitive
| Equality is symmetric
| You can lift equality into any type constructor
| ... in any position
This is all more complicated than it needs to be. Ideally, we would just
write:
data family Lower (a :: j) (b :: k)
newtype instance Lower a (f x) = Lower { unlower :: a := x }
lower :: forall a b f g. f a := g b -> a := b
lower eq = unlower (subst eq (Lower refl :: Lower a (f a)))
issue, we must:
and
| Type constructors are generative and injective, so you can lower equality
through any type constructors ...
| ... in any position ... | # LANGUAGE CPP , , ScopedTypeVariables , TypeOperators #
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 706
#define LANGUAGE_PolyKinds
# LANGUAGE PolyKinds #
#endif
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
# LANGUAGE RoleAnnotations #
#endif
#if defined(__GLASGOW_HASKELL__) && MIN_VERSION_base(4,7,0)
#define HAS_DATA_TYPE_COERCION 1
#endif
Copyright : ( C ) 2011 - 2014
Maintainer : < >
Leibnizian equality . Injectivity in the presence of type families
is provided by a generalization of a trick by posted here :
module Data.Eq.Type
(
(:=)(..)
, refl
, trans
, symm
, coerce
#ifdef LANGUAGE_PolyKinds
, apply
#endif
, lift
, lift2, lift2'
, lift3, lift3'
, lower
, lower2
, lower3
, fromLeibniz
, toLeibniz
#ifdef HAS_DATA_TYPE_COERCION
| Leibnizian equality can be converted to representational equality
, reprLeibniz
#endif
) where
import Prelude (Maybe(..))
import Control.Category
import Data.Semigroupoid
import Data.Groupoid
#ifdef HAS_DATA_TYPE_COERCION
import qualified Data.Type.Coercion as Co
#endif
import qualified Data.Type.Equality as Eq
infixl 4 :=
| Leibnizian equality states that two things are equal if you can
newtype a := b = Refl { subst :: forall c. c a -> c b }
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
type role (:=) nominal nominal
#endif
refl :: a := a
refl = Refl id
newtype Coerce a = Coerce { uncoerce :: a }
| If two things are equal you can convert one to the other
coerce :: a := b -> a -> b
coerce f = uncoerce . subst f . Coerce
#ifdef LANGUAGE_PolyKinds
newtype Apply a b f g = Apply { unapply :: f a := g b }
| Apply one equality to another , respectively
apply :: f := g -> a := b -> f a := g b
apply fg ab = unapply (subst fg (Apply (lift ab)))
#endif
instance Category (:=) where
id = Refl id
bc . ab = subst bc ab
instance Semigroupoid (:=) where
bc `o` ab = subst bc ab
instance Groupoid (:=) where
inv = symm
trans :: a := b -> b := c -> a := c
trans ab bc = subst bc ab
newtype Symm p a b = Symm { unsymm :: p b a }
symm :: (a := b) -> (b := a)
symm a = unsymm (subst a (Symm refl))
newtype Lift f a b = Lift { unlift :: f a := f b }
lift :: a := b -> f a := f b
lift a = unlift (subst a (Lift refl))
newtype Lift2 f c a b = Lift2 { unlift2 :: f a c := f b c }
lift2 :: a := b -> f a c := f b c
lift2 a = unlift2 (subst a (Lift2 refl))
lift2' :: a := b -> c := d -> f a c := f b d
lift2' ab cd = subst (lift2 ab) (lift cd)
newtype Lift3 f c d a b = Lift3 { unlift3 :: f a c d := f b c d }
lift3 :: a := b -> f a c d := f b c d
lift3 a = unlift3 (subst a (Lift3 refl))
lift3' :: a := b -> c := d -> e := f -> g a c e := g b d f
lift3' ab cd ef = lift3 ab `subst` lift2 cd `subst` lift ef
#ifdef LANGUAGE_PolyKinds
And similarly for Lower{2,3 } . Unfortunately , this wo n't typecheck on
GHC 7.6 through 7.10 due to an old typechecker bug . To work around the
1 . Pass ` f ` and ` g ` as explicit arguments to the GenInj{,2,3 } type family ,
2 . Define overlapping instances for GenInj{,2,3 } .
Part ( 2 ) of this workaround prevents us from using a data family here , as
GHC will reject overlapping data family instances as conflicting .
type family GenInj (f :: j -> k) (g :: j -> k) (x :: k) :: j
type family GenInj2 (f :: i -> j -> k) (g :: i -> j' -> k) (x :: k) :: i
type family GenInj3 (f :: h -> i -> j -> k) (g :: h -> i' -> j' -> k) (x :: k) :: h
#else
type family GenInj (f :: * -> *) (g :: * -> *) (x :: *) :: *
type family GenInj2 (f :: * -> * -> *) (g :: * -> * -> *) (x :: *) :: *
type family GenInj3 (f :: * -> * -> * -> *) (g :: * -> * -> * -> *) (x :: *) :: *
#endif
type instance GenInj f g (f a) = a
type instance GenInj f g (g b) = b
type instance GenInj2 f g (f a c) = a
type instance GenInj2 f g (g b c') = b
type instance GenInj3 f g (f a c d) = a
type instance GenInj3 f g (g b c' d') = b
newtype Lower f g a x = Lower { unlower :: a := GenInj f g x }
newtype Lower2 f g a x = Lower2 { unlower2 :: a := GenInj2 f g x }
newtype Lower3 f g a x = Lower3 { unlower3 :: a := GenInj3 f g x }
lower :: forall a b f g. f a := g b -> a := b
lower eq = unlower (subst eq (Lower refl :: Lower f g a (f a)))
lower2 :: forall a b f g c c'. f a c := g b c' -> a := b
lower2 eq = unlower2 (subst eq (Lower2 refl :: Lower2 f g a (f a c)))
| ... these definitions are poly - kinded on GHC 7.6 and up .
lower3 :: forall a b f g c c' d d'. f a c d := g b c' d' -> a := b
lower3 eq = unlower3 (subst eq (Lower3 refl :: Lower3 f g a (f a c d)))
fromLeibniz :: a := b -> a Eq.:~: b
fromLeibniz a = subst a Eq.Refl
toLeibniz :: a Eq.:~: b -> a := b
toLeibniz Eq.Refl = refl
instance Eq.TestEquality ((:=) a) where
testEquality fa fb = Just (fromLeibniz (trans (symm fa) fb))
#ifdef HAS_DATA_TYPE_COERCION
reprLeibniz :: a := b -> Co.Coercion a b
reprLeibniz a = subst a Co.Coercion
instance Co.TestCoercion ((:=) a) where
testCoercion fa fb = Just (reprLeibniz (trans (symm fa) fb))
#endif
|
4f955337f7e6b2eb2e3a86e1b0785e220bfe32fceb1668187087a7685fc7b660 | dbenoit17/dynamic-ffi | inline.rkt | #lang at-exp racket/base
(require rackunit
rackunit/text-ui
"../unsafe.rkt")
@define-inline-ffi[mylib]{
#include <stdio.h>
#include <string.h>
int int_add(int x, int y) {
return x + y;
}
int int_sub(int x, int y) {
return x - y;
}
int int_mult(int x, int y) {
return x * y;
}
int int_div(int x, int y) {
return x / y;
}
int int_mod(int x, int y) {
return x % y;
}
int add_ten_args(int a, int b, int c, int d, int e,
int f, int g, int h, int i, int j) {
return a + b + c + d + e + f + g + h + i + j;
}
double double_add(double x, double y) {
return x + y;
}
double double_sub(double x, double y) {
return x - y;
}
double double_mult(double x, double y) {
return x * y;
}
double double_div(double x, double y) {
return x / y;
}
char* shorten(char* string) {
int len = strlen(string);
string[len/2] = '\0';
return string;
}
}
@define-inline-ffi[oh-my-racket!]{
int add(int x, int y) {
__asm__("addl %%ebx, %%eax;"
:"=r"(y)
:"a"(x),"b"(y));
return y;
}
}
@define-inline-ffi[libm #:compile-flags "-lm" #:compiler "clang"]{
#include <math.h>
double square_root(double x) {
return sqrt(x);
}
}
(define tests
(test-suite
"test inline ffi"
(test-case
"check ffi integer addition"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_add x y) (+ x y))))
(test-case
"check ffi integer subtraction"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_sub x y) (- x y))))
(test-case
"check ffi integer multiplication"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_mult x y) (* x y))))
(test-case
"check ffi integer division"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_div x y) (quotient x y))))
(test-case
"check ffi integer modulo"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_mod x y) (remainder x y))))
;; I was pleasantly surprised these floating point tests
;; work. Are Racket's real numbers implemented with
;; IEEE floats? If these ever break, it's likely
a difference in rounding between Racket and IEEE ,
;; and its probably ok to just delete the tests.
(test-case
"check ffi floating double addition"
(let ([x (random)]
[y (random)])
(check-equal? (mylib 'double_add x y) (+ x y))))
(test-case
"check ffi floating double subtraction"
(let ([x (random)]
[y (random)])
(check-equal? (mylib 'double_sub x y) (- x y))))
(test-case
"check ffi floating double multiplication"
(let ([x (random)]
[y (random)])
(check-equal? (mylib 'double_mult x y) (* x y))))
(test-case
"check ffi floating double division"
(let ([x (random)]
[y (random)])
(check-equal? (mylib 'double_div x y) (/ x y))))
(test-case
"check ffi ten args"
(let ([nums (build-list 10 (λ (x) (random 10000)))])
(check-equal? (apply mylib (cons 'add_ten_args nums)) (apply + nums))))
(test-case
"check ffi inline assembly language"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (oh-my-racket! 'add x y ) (+ x y))))
(test-case
"shorten string"
(check-equal? (mylib 'shorten "hello world") "hello"))
(test-case
"test linking libm"
(let ([num (random 10000)])
(check-equal? (libm 'square_root num) (sqrt num))))
))
(run-tests tests)
| null | https://raw.githubusercontent.com/dbenoit17/dynamic-ffi/c82f5cb25932e9cab31844569b1364e23a02f205/test/inline.rkt | racket |
I was pleasantly surprised these floating point tests
work. Are Racket's real numbers implemented with
IEEE floats? If these ever break, it's likely
and its probably ok to just delete the tests. | #lang at-exp racket/base
(require rackunit
rackunit/text-ui
"../unsafe.rkt")
@define-inline-ffi[mylib]{
#include <stdio.h>
#include <string.h>
int int_add(int x, int y) {
}
int int_sub(int x, int y) {
}
int int_mult(int x, int y) {
}
int int_div(int x, int y) {
}
int int_mod(int x, int y) {
}
int add_ten_args(int a, int b, int c, int d, int e,
int f, int g, int h, int i, int j) {
}
double double_add(double x, double y) {
}
double double_sub(double x, double y) {
}
double double_mult(double x, double y) {
}
double double_div(double x, double y) {
}
char* shorten(char* string) {
}
}
@define-inline-ffi[oh-my-racket!]{
int add(int x, int y) {
__asm__("addl %%ebx, %%eax;"
:"=r"(y)
}
}
@define-inline-ffi[libm #:compile-flags "-lm" #:compiler "clang"]{
#include <math.h>
double square_root(double x) {
}
}
(define tests
(test-suite
"test inline ffi"
(test-case
"check ffi integer addition"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_add x y) (+ x y))))
(test-case
"check ffi integer subtraction"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_sub x y) (- x y))))
(test-case
"check ffi integer multiplication"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_mult x y) (* x y))))
(test-case
"check ffi integer division"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_div x y) (quotient x y))))
(test-case
"check ffi integer modulo"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (mylib 'int_mod x y) (remainder x y))))
a difference in rounding between Racket and IEEE ,
(test-case
"check ffi floating double addition"
(let ([x (random)]
[y (random)])
(check-equal? (mylib 'double_add x y) (+ x y))))
(test-case
"check ffi floating double subtraction"
(let ([x (random)]
[y (random)])
(check-equal? (mylib 'double_sub x y) (- x y))))
(test-case
"check ffi floating double multiplication"
(let ([x (random)]
[y (random)])
(check-equal? (mylib 'double_mult x y) (* x y))))
(test-case
"check ffi floating double division"
(let ([x (random)]
[y (random)])
(check-equal? (mylib 'double_div x y) (/ x y))))
(test-case
"check ffi ten args"
(let ([nums (build-list 10 (λ (x) (random 10000)))])
(check-equal? (apply mylib (cons 'add_ten_args nums)) (apply + nums))))
(test-case
"check ffi inline assembly language"
(let ([x (random 10000)]
[y (random 10000)])
(check-equal? (oh-my-racket! 'add x y ) (+ x y))))
(test-case
"shorten string"
(check-equal? (mylib 'shorten "hello world") "hello"))
(test-case
"test linking libm"
(let ([num (random 10000)])
(check-equal? (libm 'square_root num) (sqrt num))))
))
(run-tests tests)
|
70f060e8bbea8280b2c68a20be5e2dffc9cc36a0240e7e3a183f75785f69ee3b | racket/gui | only-one-child.rkt | (require
mred
mzlib/class
mzlib/etc
mzlib/list
mzlib/match
(prefix a: "../alignment.rkt")
"../alignment-helpers.rkt"
"../dllist.rkt"
mrlib/click-forwarding-editor
"../on-show-pasteboard.rkt"
"../really-resized-pasteboard.rkt"
"../interface.rkt"
"../locked-pasteboard.rkt"
"../suppress-modify-editor.rkt")
;;;;;;;;;;
;; alignment
(define (vert/horiz-alignment type)
(class* dllist% ()
(init-field [parent #f])
(field
[head (new head%)]
[tail (new tail%)])
(send head next tail)
(send tail prev head)
#;(((is-a?/c alignment<%>)) ((union (is-a?/c alignment<%>) false?)) . opt-> . void?)
;; Add the given alignment as a child before the existing child
(define/public add-child
(opt-lambda (child (after #f))
(define (link p item n)
(send p next child)
(send child prev p)
(send n prev child)
(send child next n))
(if after
(link after child (send after next))
(link (send tail prev) child tail))))
(super-new)
(when parent (send parent add-child this))))
(define vertical-alignment% (vert/horiz-alignment 'vertical))
(define horizontal-alignment% (vert/horiz-alignment 'horizontal))
(let* ([interactions (new vertical-alignment% (parent (new vertical-alignment%)))])
(new horizontal-alignment% (parent interactions))
(new horizontal-alignment% (parent interactions))
`(equal? ,(length (send interactions map-to-list (lambda (x) x))) 2))
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/embedded-gui/private/tests/only-one-child.rkt | racket |
alignment
(((is-a?/c alignment<%>)) ((union (is-a?/c alignment<%>) false?)) . opt-> . void?)
Add the given alignment as a child before the existing child | (require
mred
mzlib/class
mzlib/etc
mzlib/list
mzlib/match
(prefix a: "../alignment.rkt")
"../alignment-helpers.rkt"
"../dllist.rkt"
mrlib/click-forwarding-editor
"../on-show-pasteboard.rkt"
"../really-resized-pasteboard.rkt"
"../interface.rkt"
"../locked-pasteboard.rkt"
"../suppress-modify-editor.rkt")
(define (vert/horiz-alignment type)
(class* dllist% ()
(init-field [parent #f])
(field
[head (new head%)]
[tail (new tail%)])
(send head next tail)
(send tail prev head)
(define/public add-child
(opt-lambda (child (after #f))
(define (link p item n)
(send p next child)
(send child prev p)
(send n prev child)
(send child next n))
(if after
(link after child (send after next))
(link (send tail prev) child tail))))
(super-new)
(when parent (send parent add-child this))))
(define vertical-alignment% (vert/horiz-alignment 'vertical))
(define horizontal-alignment% (vert/horiz-alignment 'horizontal))
(let* ([interactions (new vertical-alignment% (parent (new vertical-alignment%)))])
(new horizontal-alignment% (parent interactions))
(new horizontal-alignment% (parent interactions))
`(equal? ,(length (send interactions map-to-list (lambda (x) x))) 2))
|
d78872f1156d2d449de101db5cf5d658bd2dab3fed09fed043a390f7910422c8 | ocurrent/ocaml-ci | test.ml | let () =
Alcotest.run "ocaml-ci"
[ ("obuilder_specs", Test_spec.tests); ("pipeline", Test_pipeline.tests) ]
| null | https://raw.githubusercontent.com/ocurrent/ocaml-ci/755fe5e74264e0d40ece51afbd4ebf6ff5061600/test/service/test.ml | ocaml | let () =
Alcotest.run "ocaml-ci"
[ ("obuilder_specs", Test_spec.tests); ("pipeline", Test_pipeline.tests) ]
|
|
dd2aa22d6da85ca805496d9e2a46107d8da73a3a99dac6b3f32093d5f435b898 | joinr/clclojure | pmap.lisp | This is an implementation of Clojure 's
;persistent map for Common Lisp.
(defpackage :clclojure.pmap
(:use :common-lisp)
(:export :persistent-map
:empty-map?
:pmap-count
:pmap-map
:pmap-reduce)
(:shadow :assoc
:find))
; :pmap-chunks
; :pmap-element-type
; :pmap-assoc
; :pmap-nth))
(in-package clojure.pmap)
Original from Stack Overflow , with some slight modifications .
(defun |brace-reader| (stream char)
"A reader macro that allows us to define persistent maps
inline, just like Clojure."
(declare (ignore char))
`(persistent-map ,@(read-delimited-list #\] stream t)))
(set-macro-character #\{ #'|brace-reader|)
(set-syntax-from-char #\} #\))
;;Currently deferred...
For now , we 'll just use a COW map implementation
;;i.e. wrap a hashtable and copy its contents...
(define-condition not-implemented (error)
((text :initarg :text :reader text)))
;utility functions
;Persistent maps require a lot of array copying, and
;according to the clojure implementation, bit-twiddling.
porting from 's excellent blog post ,
which is a port from Clojure 's implementation .
use a 32 - way trie ....
a bytespec is like a window ..
;it's a user-defined set of continugous bits in an integer
;use (byte width position) to define the window...
(defconstant +bit-width+ 5)
denotes [ 00000 ] with " weights " [ 2 ^ 4 2 ^ 3 2 ^ 2 2 ^ 1 2 ^ 0 ]
(defun >>> (i n)
"Shift integer i by n bits to the right."
(ash i (* -1 n)))
(defun <<< (i n)
"Shift integer i by n bits to the left."
(ash i n))
(defun last-five-bits (n)
"Helper to mask everything but the 5 least-significant bits."
(mask-field +mask+ n))
(defun mask (hash shift)
"Helper, used by maps. Maps a hash into a local index at
given level in the trie."
(last-five-bits (>>> hash shift)))
(defun bit-pos (hash shift)
"Helper to compute the bit-position of n from a mask. This provides
a mapping to the nth bit"
(<<< 1 (mask hash shift)))
(defun index (n)
"Given an index into a hash, which represents a sparse mapping of values
from [0 31] to n children, we can find out which child the index represents
by using a logical count of the 1 bits in n."
(logcount (1- n)))
(define-condition index-out-of-bounds (error)
((text :initarg :text :reader text)))
(defun copy-vector (array n &key
(element-type (array-element-type array))
(fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array)))
(adjustable (adjustable-array-p array)))
"Returns an undisplaced copy of ARRAY, with same fill-pointer and
adjustability (if any) as the original, unless overridden by the keyword
arguments. "
(let* ((dimensions (incf (first (array-dimensions array)) n))
(new-array (make-array dimensions
:element-type element-type
:adjustable adjustable
:fill-pointer fill-pointer)))
(dotimes (i (array-total-size array))
(setf (row-major-aref new-array i)
(row-major-aref array i)))
new-array))
;Persistent Map definition:
A persistent hashmap is a small structure that points to a root node .
;It also contains information about the underlying trie, such as null
;keys, the count of elements, etc.
(defstruct pmap (count 0) (root nil) (has-null nil) (null-value nil))
(defun ->pmap (count root has-null null-value)
(make-instance pmap :count count
:root root
:has-null has-null
:null-value null-value))
(defconstant +empty-map+ (->pmap))
(defun empty-map () +empty-map+)
The INode interface is crucial . We dispatch based on the node types ...
;We'll implement the interface as a set of generic functions.
(defgeneric assoc (nd shift hash key val &optional addedLeaf))
(defgeneric without (nd shift hash key))
(defgeneric find (shift hash key))
( defgeneric find(shift hash key notFound ) )
(defgeneric nodeSeq (nd))
; assoc(AtomicReference<Thread> edit, int shift, int hash, Object key, Object val, Box addedLeaf);
INode without(AtomicReference < Thread > edit , int shift , int hash , Object key , Box removedLeaf ) ;
(defgeneric kvreduce (f init))
( defgeneric fold ( fjjoin ) )
;;note -> clojure's implementation uses an object array...
;;so that the distinction between nodes and data is blurred.
;;a node is just a thread-safe wrapper around an object array.
in CL , this is just an array without an initial type arg .
(defun make-data (&key (branches +branches+) (element-type t) (initial-element nil))
"Standard constructor for a node in our hash trie."
(if (and (null initial-element)
(not (eq element-type t)))
(make-array branches :element-type element-type)
(make-array branches :element-type element-type :initial-element initial-element)))
(defun make-node () (make-data))
(defun make-indexed-node ()
(make-data :branches +indexed-branches+))
;define implementations for different node types:
;-Type identifier for empty nodes, i.e. empty maps.
;empty-node
;(defstruct empty-node
;-Type identifier for nodes with a single value.
;-This is optimized away in the clojure java implementation...
;leaf-node
-Type identifier for nodes with 16 key / vals ( full or array nodes ) .
(defstruct array-node count (nodes (make-data)))
(defun ->array-node (count nodes)
(make-array-node :count count :nodes nodes))
-Type identifier for nodes that project a 32 - bit index , the
-bitmap , onto an array with less than 32 elements .
bitmapindexed - node
indexes contained 8 keyval pairs .
(defstruct indexed-node (bitmap 0) (nodes (make-data :branches +indexed-branches+)) )
(defun ->indexed-node (bitmap nodes)
(make-indexed-node :bitmap bitmap :nodes nodes))
(defconstant +empty-indexed-node+ (make-indexed-node))
(defun empty-indexed-node () +empty-indexed-node+)
(declaim (inline key-idx val-idx key-at-idx val-at-idx))
(defun key-idx (idx)
"Return the offset key of an index"
(* 2 idx))
(defun val-idx (idx)
"Return the offset value of an index"
(1+ (* 2 idx)))
(defun equiv (x y)
"Generic equality predicate."
(error 'not-implemented))
(defun key-at-idx (idx nodes)
"Fetches the offset key from an array
packed like a propertylist, key/val/key/val/..."
(aref nodes (* 2 idx)))
(defun val-at-idx (idx nodes)
"Fetches the offset value from an array
packed like a propertylist, key/val/key/val/..."
(aref nodes (1+ (* 2 idx))))
(defun pairs (xs)
"Aux function that converts a list of xs into
a list of pairs."
(do ((acc (list))
(remaining xs (rest (rest remaining))))
((null remaining) (nreverse acc))
(let ((x (first remaining))
(y (second remaining)))
(when (and x y)
(push (list x y) acc)))))
(defun assoc-array (arr idx k v)
(progn (setf (aref arr (key-idx idx)) k)
(setf (aref arr (val-idx idx)) v)))
(defun hash (o)
"Generic hash function."
(error 'not-implemented))
(defun remove-pair (array idx)
"Auxillary function to drop pairs from an array
where the pairs are packed akin to a plist, ex.
key/val/key/val....returns a new, smaller array
with the pair removed."
(error 'not-implemented)
(cond ((> idx (- (1- (array-total-size array)) 2))
(error 'index-out-of-bounds))
((and (= (array-total-size array) 2) (= idx 0))
nil)
(t
(let* ((dimensions (decf (first (array-dimensions array)) 2))
(new-array (make-array dimensions
:element-type (array-element-type array)
:fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array))
:adjustable (adjustable-array-p array))))
(loop for i from 0 to (1- idx)
do (assoc-array new-array i (key-at-idx i array) (val-at-idx i array)))
(loop for i from (1+ idx) to (- (array-total-size new-array) 2)
do (assoc-array new-array (1- i) (key-at-idx i array) (val-at-idx i array)))
new-array))))
(defun insert-pair (array idx k v)
"Auxillary function to drop pairs from an array
where the pairs are packed akin to a plist, ex.
key/val/key/val....returns a new, smaller array
with the pair removed."
(error 'not-implemented)
(cond ((> idx (1- (- (array-total-size array) 2)))
(error 'index-out-of-bounds))
(t
(let* ((dimensions (incf (first (array-dimensions array)) 2))
(new-array (make-array dimensions
:element-type (array-element-type array)
:fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array))
:adjustable (adjustable-array-p array))))
(loop for i from 0 to (1- idx)
do (assoc-array new-array i (key-at-idx i array) (val-at-idx i array)))
(assoc-array new-array idx k v)
(when (< idx (1- (/ (array-total-size array) 2)))
(loop for i from idx to (1- (/ (array-total-size new-array) 2))
do (assoc-array new-array (1+ i) (key-at-idx i array) (val-at-idx i array))))
new-array))))
INode createNode(int shift , Object key1 , Object val1 , int key2hash , Object key2 , Object val2 ) {
;; int key1hash = hash(key1);
;; if(key1hash == key2hash)
return new HashCollisionNode(null , key1hash , 2 , new Object [ ] { key1 , val1 , key2 , val2 } ) ;
Box _ = new Box(null ) ;
AtomicReference < Thread > edit = new AtomicReference < Thread > ( ) ;
return . EMPTY
.assoc(edit , shift , key1hash , key1 , val1 , _ )
.assoc(edit , shift , key2hash , key2 , val2 , _ )
;
(defun create-node (shift key1 val1 key2hash key2 val2)
"Generic function to create nodes....I need a better
explanation. Also, the box var may not be necessary.
I have to see how it's used..."
(let ((key1hash (hash key1)))
(if (= key1hash key2hash)
;record the hash collision with a new collision node, these will chain.
(->collision-node key1hash 2 (vector key1 val1 key2 val2))
(let ((box (list))) ;else assoc both values into an empty indexed node.
(assoc (assoc (empty-indexed-node) shift key1hash key1 val1 box)
shift key2hash key2 val2 box)))))
(defun clone-and-set (arr &rest kvps)
"Aux function that clones an array and
sets the element at idx = to v, where
idx and v are drawn from the list kvps."
(let ((acc (copy-vector arr 0)))
(loop for (idx v) in (pairs kvps)
do (setf (aref acc idx) v)
finally (return acc))))
(declaim (inline bit-set?))
(defun bit-set? (bitmap i)
"Determines if the ith bit is set in bitmap."
(not (zerop (logand (>>> bitmap i) 1))))
(defun indexed-array->full-array (nodes bitmap shift hash key val addedleaf)
"Projects an indexed array, indexed by a 32-bit map, 16 (unknown)
bits of which indicate the presence of a key in an an underlying
32-element assoc array, onto an full array. The full array is
a direct mapping of a 32-bit key, projected onto a 32 element
array of nodes, by masking all but the last 5 bits. This is
basically an optimization, so that we use indexed nodes while
the node is sparse, when the keys are <= 16, then shift to a
node with no intermediate bit mapping."
create the 32 element array for the arraynode .
(jdx (mask hash shift)) ;set the index for the element we're adding.
(j 0))
(progn (setf (aref newnodes jdx) ;initialze the newly added node.
(assoc (empty-indexed-node)
(+ 5 shift) hash key val addedleaf))
(loop for i from 0 to 32 ;traverse the bitmap, cloning...
do (when (bit-set? bitmap i) ;bit i is stored at j
(if (null (aref nodes j))
(setf (aref newnodes i) (aref nodes (1+ j)))
(assoc (empty-indexed-node)
(+ 5 shift)
(hash (aref nodes j))
(aref nodes j)
(aref nodes (1+ j))
addedleaf))
(incf j 2)))
newnodes)))
(defun indexed-node->array-node (nd shift hash key val addedleaf)
"Projects an indexed node, indexed by a 32-bit map, 16 (unknown)
bits of which indicate the presence of a key in an an underlying
32-element assoc array, onto an array node. The array node is
a direct mapping of a 32-bit key, projected onto a 32 element
array of nodes, by masking all but the last 5 bits. This is
basically an optimization, so that we use indexed nodes while
the node is sparse, when the keys are <= 16, then shift to a
node with no intermediate bit mapping."
(with-slots (bitmap nodes) nd
(->array-node (1+ (logcount bitmap))
(indexed-array->full-array nodes bitmap shift
hash key val addedleaf))))
;Partially implemented.
( defmethod assoc ( ( nd indexed - node ) shift hash key addedLeaf )
;; (with-slots (bitmap nodes) nd
;; (let ((b (bit-pos hash shift))
( idx ( index b ) )
( exists ? ( not ( zerop ( logand bitmap b ) ) ) ) )
;; (if exists?
;; (let ((k (key-at-idx idx nodes))
;; (v (val-at-idx idx nodes)))
;; (cond ((null k)
( let ( ( newnode ( assoc v ( + 5 shift ) hash key ) ) )
( if ( at - idx newnode )
;; nd ;no node to add to null key.
;; ;actually have val associated with null, causes changed.
;; (->indexed-node bitmap (clone-and-set nodes (val-idx idx) newnode)))))
;; ((equiv key k) ;key exists.
;; (if (eq v val)
;; nd ;no change
;; ;value changed
( ->indexed - node bitmap ( clone - and - set nodes ( val - idx idx ) ) ) ) )
;; (t
;; (->indexed-node bitmap (clone-and-set nodes (key-idx idx) nil
( val - idx idx ) ( create - node ( + 5 shift ) k v hash key ) ) ) ) )
;; )
( if ( > = ( ) + indexed - branches+ )
;; ;create an array node, or full node, if the number of on-bits is excessive.
( indexed - node->array - node nd shift hash key )
( let ( ( newarray ( copy - vector nodes 2 ) ) )
( progn (
;; ))))))
;-Type identifier for nodes that have a direct correspondence
-between a 5 bit integer hash and an entry in the 32 element
;-node array.
;full-node
-Type identifier for nodes that collide . Essentially , a 32
;-element array of nodes that have the same hash. I have an
-idea of how this works using the 5 bit hashing scheme .
;collision-node
(defstruct collision-node hash count nodes)
(defun ->collision-node (hash count nodes)
(make-instance collision-node
:hash hash
:count count
:nodes nodes))
(defconstant +empty-pvec+ (make-pvec))
(defun empty-vec () +empty-pvec+)
(defun empty-vec? (v) (eq v +empty-pvec+))
(defgeneric vector-count (v)
(:documentation
"Fetches the count of items in the persistent vector."))
(defmethod vector-count ((v pvec))
(pvec-counter v))
(defun tail-end (n &optional (b +branches+))
"Given a count of items, n, where is the tail located in an integer
hash? Note, this assumes a 5 bit encoding for levels in an 32-way
trie. I might generalize this later..."
(if (< n b)
0
(<<< (>>> (1- n) +bit-width+) +bit-width+)))
(defun tail-off (v)
"Defines the integer index at which the tail starts."
(tail-end (pvec-counter v) +branches+))
(defun count-tail (v) (length (pvec-tail v)))
(defun find-node (rootnode shift idx)
"Given a rootnode with child nodes, a bit-shift amount, and an index,
traverses the rootnode's children for the node defined by idx."
(if (<= shift 0)
rootnode ;found our guy
(find-node (aref rootnode (last-five-bits (>>> idx shift)))
(- shift +bit-width+) idx)))
(defun copy-path (root shift0 idx &optional (leaf-function #'identity))
"Copies the nodes from root to idx, returning a new root. If a leaf function
is provided, it will be applied to the final node. If the path does not exist,
intermediate structures WILL be created."
(labels ((walk (rootnode shift)
(if (zerop shift)
(funcall leaf-function rootnode)
(let ((childidx (last-five-bits (>>> idx shift)))
(newnode (if (null rootnode)
(make-node)
(copy-vector rootnode 0))))
(progn (setf (aref newnode childidx)
(walk (if (null rootnode)
(make-node)
(aref rootnode childidx))
(- shift +bit-width+)))
newnode)))))
(walk root shift0)))
(defun insert-path (rootnode shift idx x)
"Copies the path to the node at idx, replacing the value of the final node
on the path, the address at idx, with value x."
(copy-path rootnode shift idx
#'(lambda (node)
(progn (setf (aref node (last-five-bits idx)) x)
node))))
(defgeneric get-node (v idx)
(:documentation
"Fetches the node (an object array) at index idx, from
persistent vector v, where idx is 0-based. Currently assumes
5-bit encoding of integer keys for each level, thus 32 elements
per level."))
(defmethod get-node ((v pvec) idx)
(if (and (<= idx (pvec-counter v)) (>= idx 0))
(if (>= idx (tail-end (pvec-counter v) +branches+))
(pvec-tail v)
(find-node (pvec-root v) (pvec-shift v) idx))
(error 'index-out-of-bounds)))
(defgeneric nth-vec (v idx)
(:documentation "Returns the nth element in a persistent vector."))
(defmethod nth-vec ((v pvec) idx)
(aref (get-node v idx) (last-five-bits idx)))
;copy-vector should probably use displaced arrays.
(defun conj-tail (v x)
"Conjoins item x onto pvector v's tail node, returning a new pvector that
uses the new tail, along with an incremented count."
(let ((newtail (if (null (pvec-tail v))
(vector x)
(let ((growntail (copy-vector (pvec-tail v) 1)))
(progn (setf (aref growntail (1- (length growntail))) x)
growntail)))))
(make-pvec :root (pvec-root v)
:tail newtail
:shift (pvec-shift v)
:counter (1+ (pvec-counter v)))))
(defun new-path (shift node)
"Given a node and an amount of initial 'shift', recursively builds
a nested tree of nodes, currently 32-wide arrays, linked by the first element,
with node at the logical 'bottom' of the tree, where shift = 0. This allows us
to inject a node, with the required path structure, into the trie, if the path did
not exist before. Typically used for inserting the tail into the pvector."
(if (zerop shift)
node
(let ((newnode (make-node)))
(progn (setf (aref newnode 0)
(new-path (- shift +bit-width+) node))
newnode))))
| null | https://raw.githubusercontent.com/joinr/clclojure/8b51214891c4da6dfbec393dffac70846ee1d0c5/dustbin/pmap.lisp | lisp | persistent map for Common Lisp.
:pmap-chunks
:pmap-element-type
:pmap-assoc
:pmap-nth))
Currently deferred...
i.e. wrap a hashtable and copy its contents...
utility functions
Persistent maps require a lot of array copying, and
according to the clojure implementation, bit-twiddling.
it's a user-defined set of continugous bits in an integer
use (byte width position) to define the window...
Persistent Map definition:
It also contains information about the underlying trie, such as null
keys, the count of elements, etc.
We'll implement the interface as a set of generic functions.
assoc(AtomicReference<Thread> edit, int shift, int hash, Object key, Object val, Box addedLeaf);
note -> clojure's implementation uses an object array...
so that the distinction between nodes and data is blurred.
a node is just a thread-safe wrapper around an object array.
define implementations for different node types:
-Type identifier for empty nodes, i.e. empty maps.
empty-node
(defstruct empty-node
-Type identifier for nodes with a single value.
-This is optimized away in the clojure java implementation...
leaf-node
int key1hash = hash(key1);
if(key1hash == key2hash)
record the hash collision with a new collision node, these will chain.
else assoc both values into an empty indexed node.
set the index for the element we're adding.
initialze the newly added node.
traverse the bitmap, cloning...
bit i is stored at j
Partially implemented.
(with-slots (bitmap nodes) nd
(let ((b (bit-pos hash shift))
(if exists?
(let ((k (key-at-idx idx nodes))
(v (val-at-idx idx nodes)))
(cond ((null k)
nd ;no node to add to null key.
;actually have val associated with null, causes changed.
(->indexed-node bitmap (clone-and-set nodes (val-idx idx) newnode)))))
((equiv key k) ;key exists.
(if (eq v val)
nd ;no change
;value changed
(t
(->indexed-node bitmap (clone-and-set nodes (key-idx idx) nil
)
;create an array node, or full node, if the number of on-bits is excessive.
))))))
-Type identifier for nodes that have a direct correspondence
-node array.
full-node
-element array of nodes that have the same hash. I have an
collision-node
found our guy
copy-vector should probably use displaced arrays. | This is an implementation of Clojure 's
(defpackage :clclojure.pmap
(:use :common-lisp)
(:export :persistent-map
:empty-map?
:pmap-count
:pmap-map
:pmap-reduce)
(:shadow :assoc
:find))
(in-package clojure.pmap)
Original from Stack Overflow , with some slight modifications .
(defun |brace-reader| (stream char)
"A reader macro that allows us to define persistent maps
inline, just like Clojure."
(declare (ignore char))
`(persistent-map ,@(read-delimited-list #\] stream t)))
(set-macro-character #\{ #'|brace-reader|)
(set-syntax-from-char #\} #\))
For now , we 'll just use a COW map implementation
(define-condition not-implemented (error)
((text :initarg :text :reader text)))
porting from 's excellent blog post ,
which is a port from Clojure 's implementation .
use a 32 - way trie ....
a bytespec is like a window ..
(defconstant +bit-width+ 5)
denotes [ 00000 ] with " weights " [ 2 ^ 4 2 ^ 3 2 ^ 2 2 ^ 1 2 ^ 0 ]
(defun >>> (i n)
"Shift integer i by n bits to the right."
(ash i (* -1 n)))
(defun <<< (i n)
"Shift integer i by n bits to the left."
(ash i n))
(defun last-five-bits (n)
"Helper to mask everything but the 5 least-significant bits."
(mask-field +mask+ n))
(defun mask (hash shift)
"Helper, used by maps. Maps a hash into a local index at
given level in the trie."
(last-five-bits (>>> hash shift)))
(defun bit-pos (hash shift)
"Helper to compute the bit-position of n from a mask. This provides
a mapping to the nth bit"
(<<< 1 (mask hash shift)))
(defun index (n)
"Given an index into a hash, which represents a sparse mapping of values
from [0 31] to n children, we can find out which child the index represents
by using a logical count of the 1 bits in n."
(logcount (1- n)))
(define-condition index-out-of-bounds (error)
((text :initarg :text :reader text)))
(defun copy-vector (array n &key
(element-type (array-element-type array))
(fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array)))
(adjustable (adjustable-array-p array)))
"Returns an undisplaced copy of ARRAY, with same fill-pointer and
adjustability (if any) as the original, unless overridden by the keyword
arguments. "
(let* ((dimensions (incf (first (array-dimensions array)) n))
(new-array (make-array dimensions
:element-type element-type
:adjustable adjustable
:fill-pointer fill-pointer)))
(dotimes (i (array-total-size array))
(setf (row-major-aref new-array i)
(row-major-aref array i)))
new-array))
A persistent hashmap is a small structure that points to a root node .
(defstruct pmap (count 0) (root nil) (has-null nil) (null-value nil))
(defun ->pmap (count root has-null null-value)
(make-instance pmap :count count
:root root
:has-null has-null
:null-value null-value))
(defconstant +empty-map+ (->pmap))
(defun empty-map () +empty-map+)
The INode interface is crucial . We dispatch based on the node types ...
(defgeneric assoc (nd shift hash key val &optional addedLeaf))
(defgeneric without (nd shift hash key))
(defgeneric find (shift hash key))
( defgeneric find(shift hash key notFound ) )
(defgeneric nodeSeq (nd))
(defgeneric kvreduce (f init))
( defgeneric fold ( fjjoin ) )
in CL , this is just an array without an initial type arg .
(defun make-data (&key (branches +branches+) (element-type t) (initial-element nil))
"Standard constructor for a node in our hash trie."
(if (and (null initial-element)
(not (eq element-type t)))
(make-array branches :element-type element-type)
(make-array branches :element-type element-type :initial-element initial-element)))
(defun make-node () (make-data))
(defun make-indexed-node ()
(make-data :branches +indexed-branches+))
-Type identifier for nodes with 16 key / vals ( full or array nodes ) .
(defstruct array-node count (nodes (make-data)))
(defun ->array-node (count nodes)
(make-array-node :count count :nodes nodes))
-Type identifier for nodes that project a 32 - bit index , the
-bitmap , onto an array with less than 32 elements .
bitmapindexed - node
indexes contained 8 keyval pairs .
(defstruct indexed-node (bitmap 0) (nodes (make-data :branches +indexed-branches+)) )
(defun ->indexed-node (bitmap nodes)
(make-indexed-node :bitmap bitmap :nodes nodes))
(defconstant +empty-indexed-node+ (make-indexed-node))
(defun empty-indexed-node () +empty-indexed-node+)
(declaim (inline key-idx val-idx key-at-idx val-at-idx))
(defun key-idx (idx)
"Return the offset key of an index"
(* 2 idx))
(defun val-idx (idx)
"Return the offset value of an index"
(1+ (* 2 idx)))
(defun equiv (x y)
"Generic equality predicate."
(error 'not-implemented))
(defun key-at-idx (idx nodes)
"Fetches the offset key from an array
packed like a propertylist, key/val/key/val/..."
(aref nodes (* 2 idx)))
(defun val-at-idx (idx nodes)
"Fetches the offset value from an array
packed like a propertylist, key/val/key/val/..."
(aref nodes (1+ (* 2 idx))))
(defun pairs (xs)
"Aux function that converts a list of xs into
a list of pairs."
(do ((acc (list))
(remaining xs (rest (rest remaining))))
((null remaining) (nreverse acc))
(let ((x (first remaining))
(y (second remaining)))
(when (and x y)
(push (list x y) acc)))))
(defun assoc-array (arr idx k v)
(progn (setf (aref arr (key-idx idx)) k)
(setf (aref arr (val-idx idx)) v)))
(defun hash (o)
"Generic hash function."
(error 'not-implemented))
(defun remove-pair (array idx)
"Auxillary function to drop pairs from an array
where the pairs are packed akin to a plist, ex.
key/val/key/val....returns a new, smaller array
with the pair removed."
(error 'not-implemented)
(cond ((> idx (- (1- (array-total-size array)) 2))
(error 'index-out-of-bounds))
((and (= (array-total-size array) 2) (= idx 0))
nil)
(t
(let* ((dimensions (decf (first (array-dimensions array)) 2))
(new-array (make-array dimensions
:element-type (array-element-type array)
:fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array))
:adjustable (adjustable-array-p array))))
(loop for i from 0 to (1- idx)
do (assoc-array new-array i (key-at-idx i array) (val-at-idx i array)))
(loop for i from (1+ idx) to (- (array-total-size new-array) 2)
do (assoc-array new-array (1- i) (key-at-idx i array) (val-at-idx i array)))
new-array))))
(defun insert-pair (array idx k v)
"Auxillary function to drop pairs from an array
where the pairs are packed akin to a plist, ex.
key/val/key/val....returns a new, smaller array
with the pair removed."
(error 'not-implemented)
(cond ((> idx (1- (- (array-total-size array) 2)))
(error 'index-out-of-bounds))
(t
(let* ((dimensions (incf (first (array-dimensions array)) 2))
(new-array (make-array dimensions
:element-type (array-element-type array)
:fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array))
:adjustable (adjustable-array-p array))))
(loop for i from 0 to (1- idx)
do (assoc-array new-array i (key-at-idx i array) (val-at-idx i array)))
(assoc-array new-array idx k v)
(when (< idx (1- (/ (array-total-size array) 2)))
(loop for i from idx to (1- (/ (array-total-size new-array) 2))
do (assoc-array new-array (1+ i) (key-at-idx i array) (val-at-idx i array))))
new-array))))
INode createNode(int shift , Object key1 , Object val1 , int key2hash , Object key2 , Object val2 ) {
return . EMPTY
.assoc(edit , shift , key1hash , key1 , val1 , _ )
.assoc(edit , shift , key2hash , key2 , val2 , _ )
(defun create-node (shift key1 val1 key2hash key2 val2)
"Generic function to create nodes....I need a better
explanation. Also, the box var may not be necessary.
I have to see how it's used..."
(let ((key1hash (hash key1)))
(if (= key1hash key2hash)
(->collision-node key1hash 2 (vector key1 val1 key2 val2))
(assoc (assoc (empty-indexed-node) shift key1hash key1 val1 box)
shift key2hash key2 val2 box)))))
(defun clone-and-set (arr &rest kvps)
"Aux function that clones an array and
sets the element at idx = to v, where
idx and v are drawn from the list kvps."
(let ((acc (copy-vector arr 0)))
(loop for (idx v) in (pairs kvps)
do (setf (aref acc idx) v)
finally (return acc))))
(declaim (inline bit-set?))
(defun bit-set? (bitmap i)
"Determines if the ith bit is set in bitmap."
(not (zerop (logand (>>> bitmap i) 1))))
(defun indexed-array->full-array (nodes bitmap shift hash key val addedleaf)
"Projects an indexed array, indexed by a 32-bit map, 16 (unknown)
bits of which indicate the presence of a key in an an underlying
32-element assoc array, onto an full array. The full array is
a direct mapping of a 32-bit key, projected onto a 32 element
array of nodes, by masking all but the last 5 bits. This is
basically an optimization, so that we use indexed nodes while
the node is sparse, when the keys are <= 16, then shift to a
node with no intermediate bit mapping."
create the 32 element array for the arraynode .
(j 0))
(assoc (empty-indexed-node)
(+ 5 shift) hash key val addedleaf))
(if (null (aref nodes j))
(setf (aref newnodes i) (aref nodes (1+ j)))
(assoc (empty-indexed-node)
(+ 5 shift)
(hash (aref nodes j))
(aref nodes j)
(aref nodes (1+ j))
addedleaf))
(incf j 2)))
newnodes)))
(defun indexed-node->array-node (nd shift hash key val addedleaf)
"Projects an indexed node, indexed by a 32-bit map, 16 (unknown)
bits of which indicate the presence of a key in an an underlying
32-element assoc array, onto an array node. The array node is
a direct mapping of a 32-bit key, projected onto a 32 element
array of nodes, by masking all but the last 5 bits. This is
basically an optimization, so that we use indexed nodes while
the node is sparse, when the keys are <= 16, then shift to a
node with no intermediate bit mapping."
(with-slots (bitmap nodes) nd
(->array-node (1+ (logcount bitmap))
(indexed-array->full-array nodes bitmap shift
hash key val addedleaf))))
( defmethod assoc ( ( nd indexed - node ) shift hash key addedLeaf )
( idx ( index b ) )
( exists ? ( not ( zerop ( logand bitmap b ) ) ) ) )
( let ( ( newnode ( assoc v ( + 5 shift ) hash key ) ) )
( if ( at - idx newnode )
( ->indexed - node bitmap ( clone - and - set nodes ( val - idx idx ) ) ) ) )
( val - idx idx ) ( create - node ( + 5 shift ) k v hash key ) ) ) ) )
( if ( > = ( ) + indexed - branches+ )
( indexed - node->array - node nd shift hash key )
( let ( ( newarray ( copy - vector nodes 2 ) ) )
( progn (
-between a 5 bit integer hash and an entry in the 32 element
-Type identifier for nodes that collide . Essentially , a 32
-idea of how this works using the 5 bit hashing scheme .
(defstruct collision-node hash count nodes)
(defun ->collision-node (hash count nodes)
(make-instance collision-node
:hash hash
:count count
:nodes nodes))
(defconstant +empty-pvec+ (make-pvec))
(defun empty-vec () +empty-pvec+)
(defun empty-vec? (v) (eq v +empty-pvec+))
(defgeneric vector-count (v)
(:documentation
"Fetches the count of items in the persistent vector."))
(defmethod vector-count ((v pvec))
(pvec-counter v))
(defun tail-end (n &optional (b +branches+))
"Given a count of items, n, where is the tail located in an integer
hash? Note, this assumes a 5 bit encoding for levels in an 32-way
trie. I might generalize this later..."
(if (< n b)
0
(<<< (>>> (1- n) +bit-width+) +bit-width+)))
(defun tail-off (v)
"Defines the integer index at which the tail starts."
(tail-end (pvec-counter v) +branches+))
(defun count-tail (v) (length (pvec-tail v)))
(defun find-node (rootnode shift idx)
"Given a rootnode with child nodes, a bit-shift amount, and an index,
traverses the rootnode's children for the node defined by idx."
(if (<= shift 0)
(find-node (aref rootnode (last-five-bits (>>> idx shift)))
(- shift +bit-width+) idx)))
(defun copy-path (root shift0 idx &optional (leaf-function #'identity))
"Copies the nodes from root to idx, returning a new root. If a leaf function
is provided, it will be applied to the final node. If the path does not exist,
intermediate structures WILL be created."
(labels ((walk (rootnode shift)
(if (zerop shift)
(funcall leaf-function rootnode)
(let ((childidx (last-five-bits (>>> idx shift)))
(newnode (if (null rootnode)
(make-node)
(copy-vector rootnode 0))))
(progn (setf (aref newnode childidx)
(walk (if (null rootnode)
(make-node)
(aref rootnode childidx))
(- shift +bit-width+)))
newnode)))))
(walk root shift0)))
(defun insert-path (rootnode shift idx x)
"Copies the path to the node at idx, replacing the value of the final node
on the path, the address at idx, with value x."
(copy-path rootnode shift idx
#'(lambda (node)
(progn (setf (aref node (last-five-bits idx)) x)
node))))
(defgeneric get-node (v idx)
(:documentation
"Fetches the node (an object array) at index idx, from
persistent vector v, where idx is 0-based. Currently assumes
5-bit encoding of integer keys for each level, thus 32 elements
per level."))
(defmethod get-node ((v pvec) idx)
(if (and (<= idx (pvec-counter v)) (>= idx 0))
(if (>= idx (tail-end (pvec-counter v) +branches+))
(pvec-tail v)
(find-node (pvec-root v) (pvec-shift v) idx))
(error 'index-out-of-bounds)))
(defgeneric nth-vec (v idx)
(:documentation "Returns the nth element in a persistent vector."))
(defmethod nth-vec ((v pvec) idx)
(aref (get-node v idx) (last-five-bits idx)))
(defun conj-tail (v x)
"Conjoins item x onto pvector v's tail node, returning a new pvector that
uses the new tail, along with an incremented count."
(let ((newtail (if (null (pvec-tail v))
(vector x)
(let ((growntail (copy-vector (pvec-tail v) 1)))
(progn (setf (aref growntail (1- (length growntail))) x)
growntail)))))
(make-pvec :root (pvec-root v)
:tail newtail
:shift (pvec-shift v)
:counter (1+ (pvec-counter v)))))
(defun new-path (shift node)
"Given a node and an amount of initial 'shift', recursively builds
a nested tree of nodes, currently 32-wide arrays, linked by the first element,
with node at the logical 'bottom' of the tree, where shift = 0. This allows us
to inject a node, with the required path structure, into the trie, if the path did
not exist before. Typically used for inserting the tail into the pvector."
(if (zerop shift)
node
(let ((newnode (make-node)))
(progn (setf (aref newnode 0)
(new-path (- shift +bit-width+) node))
newnode))))
|
2bdfd6fe3e0232d47ee180efcb22522a12c832919661aab6738ef43cad3f8101 | pflanze/chj-schemelib | compat.scm | Copyright 2014 by < >
;;; This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
;;; (at your option) any later version.
(require (cj-env insert-result-of))
Provide compatibility with Gambit 4.2.8 - 1.1 in Debian
(insert-result-of
(with-exception-catcher
(lambda (e)
(cond ((wrong-number-of-arguments-exception? e)
`(begin
(define warned-read-subu8vector? #f)
(define (read-subu8vector v start end #!optional port need)
(or (u8vector? v) (error "not an u8vector:" v))
(or (and (##fixnum? start) (not (negative? start))) (error "not a non-negative fixnum:" start))
(or (and (##fixnum? end) (not (negative? end))) (error "not a non-negative fixnum:" end))
(if need
(begin
;; XXX hm can we simply ignore need?
(if (not warned-read-subu8vector?)
(begin
(display "warning (compat.scm): ignoring need argument for read-subu8vector calls\n"
(current-error-port))
(set! warned-read-subu8vector? #t)))))
(if port
(begin
(or (port? port) (error "not a port:" port))
(##read-subu8vector v start end port))
(##read-subu8vector v start end)))))
((type-exception? e)
;; nothing to change
`(begin))
(else
(raise e))))
(lambda ()
(read-subu8vector #f 0 10 'port 'need))))
(insert-result-of
(with-exception-catcher
(lambda (e)
(cond ((unbound-global-exception? e)
`(begin
(define (random-u8vector len)
(let ((v (##make-u8vector len)))
(for..< (i 0 len)
(u8vector-set! v i (random-integer 256)))
v))))
(else
(raise e))))
(lambda ()
(random-u8vector 1)
`(begin))))
(insert-result-of
(with-exception-catcher
(lambda (e)
(cond ((unbound-global-exception? e)
`(begin
(define (open-output-process s)
(open-process (append (list stdout-redirection: #f
stdin-redirection: #t)
s)))))
(else
(raise e))))
(lambda ()
(eval 'open-output-process)
`(begin))))
| null | https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/compat.scm | scheme | This file is free software; you can redistribute it and/or modify
(at your option) any later version.
XXX hm can we simply ignore need?
nothing to change | Copyright 2014 by < >
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
(require (cj-env insert-result-of))
Provide compatibility with Gambit 4.2.8 - 1.1 in Debian
(insert-result-of
(with-exception-catcher
(lambda (e)
(cond ((wrong-number-of-arguments-exception? e)
`(begin
(define warned-read-subu8vector? #f)
(define (read-subu8vector v start end #!optional port need)
(or (u8vector? v) (error "not an u8vector:" v))
(or (and (##fixnum? start) (not (negative? start))) (error "not a non-negative fixnum:" start))
(or (and (##fixnum? end) (not (negative? end))) (error "not a non-negative fixnum:" end))
(if need
(begin
(if (not warned-read-subu8vector?)
(begin
(display "warning (compat.scm): ignoring need argument for read-subu8vector calls\n"
(current-error-port))
(set! warned-read-subu8vector? #t)))))
(if port
(begin
(or (port? port) (error "not a port:" port))
(##read-subu8vector v start end port))
(##read-subu8vector v start end)))))
((type-exception? e)
`(begin))
(else
(raise e))))
(lambda ()
(read-subu8vector #f 0 10 'port 'need))))
(insert-result-of
(with-exception-catcher
(lambda (e)
(cond ((unbound-global-exception? e)
`(begin
(define (random-u8vector len)
(let ((v (##make-u8vector len)))
(for..< (i 0 len)
(u8vector-set! v i (random-integer 256)))
v))))
(else
(raise e))))
(lambda ()
(random-u8vector 1)
`(begin))))
(insert-result-of
(with-exception-catcher
(lambda (e)
(cond ((unbound-global-exception? e)
`(begin
(define (open-output-process s)
(open-process (append (list stdout-redirection: #f
stdin-redirection: #t)
s)))))
(else
(raise e))))
(lambda ()
(eval 'open-output-process)
`(begin))))
|
c92ebbe7b1c4c009c9f7a9427e3d4bb812416805a1f36996354b4bab176e2313 | eslick/cl-stdutils | assoc-table.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : utils -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: assoc-table.lisp
;;;; Purpose: A generic data structure; assoc-list tables
Programmer :
Date Started : August 2005
;;;;
(in-package :stdutils.gds)
(defclass-exported assoc-table (table)
((alist :accessor alist :initarg :alist :initform nil)
(key-test :accessor key-test :initarg :key-test :initform #'eq)))
(defmethod-exported drop ((table assoc-table) key)
(assoc-del key (alist table)))
(defmethod-exported get-value ((table assoc-table) key)
(assoc-get (alist table) key))
(defmethod-exported (setf get-value) (value (table assoc-table) key)
(assoc-setf (alist table) key value 'eq)
value)
(defmethod-exported find-value ((table assoc-table) value &key all (key #'identity) (test #'eq))
(if all
(let ((list nil))
(map-elements
(lambda (pair)
(format t "~A~%" pair)
(when (funcall test value (funcall key (cdr pair)))
(push pair list)))
table)
list)
(find value (alist table) :key (lambda (pair) (funcall key (cdr pair))) :test test)))
(defmethod-exported clear ((table assoc-table))
(setf (alist table) nil))
(defmethod-exported size-of ((table assoc-table))
(length (alist table)))
(defclass-exported assoc-table-iterator (iterator)
((current :accessor current-ptr :initarg :current)
(reference :accessor reference :initarg :reference)
(last :accessor last-ptr :initform nil)
(type :accessor iter-type :initarg :type
:documentation "Type can be :key, :value or :pair")))
(defmethod-exported get-iterator ((table assoc-table) &key (type :pair))
(make-instance 'assoc-table-iterator
:reference table
:current (alist table)
:type type))
(defmethod-exported next-p ((iter assoc-table-iterator))
(not (null (current-ptr iter))))
(defun extract-assoc-type (acell type)
(ecase type
(:key (car acell))
(:value (cdr acell))
(:pair acell)))
(defmethod-exported next ((iter assoc-table-iterator))
(if (next-p iter)
(let ((acell (car (current-ptr iter))))
(setf (current-ptr iter) (cdr (current-ptr iter)))
(setf (last-ptr iter) acell)
(let ((value (extract-assoc-type acell (iter-type iter))))
(values value t)))
(progn
(clear iter)
(values nil nil))))
(defmethod-exported drop-last ((iter assoc-table-iterator))
(aif (last-ptr iter)
(progn
(drop (reference iter) (car it))
(setf (last-ptr iter) nil)
t)
nil))
(defmethod-exported reset ((iter assoc-table-iterator))
(setf (current-ptr iter) (alist (reference iter)))
t)
(defmethod-exported clear ((iter assoc-table-iterator))
"To ensure that things are released for GC"
(setf (current-ptr iter) nil)
t)
| null | https://raw.githubusercontent.com/eslick/cl-stdutils/4a4e5a4036b815318282da5dee2a22825369137b/src/assoc-table.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : utils -*-
*************************************************************************
FILE IDENTIFICATION
Name: assoc-table.lisp
Purpose: A generic data structure; assoc-list tables
| Programmer :
Date Started : August 2005
(in-package :stdutils.gds)
(defclass-exported assoc-table (table)
((alist :accessor alist :initarg :alist :initform nil)
(key-test :accessor key-test :initarg :key-test :initform #'eq)))
(defmethod-exported drop ((table assoc-table) key)
(assoc-del key (alist table)))
(defmethod-exported get-value ((table assoc-table) key)
(assoc-get (alist table) key))
(defmethod-exported (setf get-value) (value (table assoc-table) key)
(assoc-setf (alist table) key value 'eq)
value)
(defmethod-exported find-value ((table assoc-table) value &key all (key #'identity) (test #'eq))
(if all
(let ((list nil))
(map-elements
(lambda (pair)
(format t "~A~%" pair)
(when (funcall test value (funcall key (cdr pair)))
(push pair list)))
table)
list)
(find value (alist table) :key (lambda (pair) (funcall key (cdr pair))) :test test)))
(defmethod-exported clear ((table assoc-table))
(setf (alist table) nil))
(defmethod-exported size-of ((table assoc-table))
(length (alist table)))
(defclass-exported assoc-table-iterator (iterator)
((current :accessor current-ptr :initarg :current)
(reference :accessor reference :initarg :reference)
(last :accessor last-ptr :initform nil)
(type :accessor iter-type :initarg :type
:documentation "Type can be :key, :value or :pair")))
(defmethod-exported get-iterator ((table assoc-table) &key (type :pair))
(make-instance 'assoc-table-iterator
:reference table
:current (alist table)
:type type))
(defmethod-exported next-p ((iter assoc-table-iterator))
(not (null (current-ptr iter))))
(defun extract-assoc-type (acell type)
(ecase type
(:key (car acell))
(:value (cdr acell))
(:pair acell)))
(defmethod-exported next ((iter assoc-table-iterator))
(if (next-p iter)
(let ((acell (car (current-ptr iter))))
(setf (current-ptr iter) (cdr (current-ptr iter)))
(setf (last-ptr iter) acell)
(let ((value (extract-assoc-type acell (iter-type iter))))
(values value t)))
(progn
(clear iter)
(values nil nil))))
(defmethod-exported drop-last ((iter assoc-table-iterator))
(aif (last-ptr iter)
(progn
(drop (reference iter) (car it))
(setf (last-ptr iter) nil)
t)
nil))
(defmethod-exported reset ((iter assoc-table-iterator))
(setf (current-ptr iter) (alist (reference iter)))
t)
(defmethod-exported clear ((iter assoc-table-iterator))
"To ensure that things are released for GC"
(setf (current-ptr iter) nil)
t)
|
df9d655b4fc0f063ee786673be71f07e5469ffbbc298402d56a3fa9fd9b4e649 | kronkltd/jiksnu | test_helper.clj | (ns jiksnu.test-helper
(:require [ciste.runner :refer [start-application! stop-application!]]
[hiccup.core :as h]
[jiksnu.modules.core.db :as db]
[jiksnu.referrant :as r]
[midje.sweet :refer [=> =not=> fact future-fact namespace-state-changes throws]]
[net.cgrand.enlive-html :as enlive]
[slingshot.slingshot :refer [try+ throw+]]
[taoensso.timbre :as timbre])
(:import java.io.StringReader))
(defn hiccup->doc
[hiccup-seq]
(-> hiccup-seq
h/html
StringReader.
enlive/xml-resource))
(defn select-by-model
[doc model-name]
(enlive/select doc [(enlive/attr= :data-model model-name)]))
(def ^:dynamic *depth* 0)
(defmacro context
[description & body]
`(let [var-name# (str ~description)]
(print (apply str (repeat *depth* " ")))
(println var-name#)
(fact ~description
(binding [*depth* (inc *depth*)]
~@body))
(when (zero? *depth*)
(println " "))))
(defmacro future-context
[description & body]
`(let [var-name# (str ~description)]
(future-fact var-name# ~@body)))
(defn setup-testing
([] (setup-testing nil))
([modules]
(try+
(start-application! modules)
(db/drop-all!)
(dosync
(ref-set r/this {})
(ref-set r/that {}))
;; (actions.domain/current-domain)
(catch Object ex
(timbre/error "Setup Error" ex)
;; FIXME: Handle error
(throw+ ex)))))
(defn stop-testing
[]
(try+
;; (stop-application!)
(catch Object ex
;(println "error")
(timbre/error "Shutdown Error" ex)
(throw+ ex))))
(defmacro module-test
[modules]
`(namespace-state-changes
[(before :facts (setup-testing ~modules))
(after :facts (stop-testing))]))
(defmacro test-environment-fixture
[& body]
`(try+
(timbre/debug "wrapping testing fixture")
(setup-testing)
;; (fact (do ~@body) =not=> (throws))
~@body
(catch Object ex#
(throw+ ex#))
(finally
(stop-application!))))
| null | https://raw.githubusercontent.com/kronkltd/jiksnu/8c91e9b1fddcc0224b028e573f7c3ca2f227e516/test/jiksnu/test_helper.clj | clojure | (actions.domain/current-domain)
FIXME: Handle error
(stop-application!)
(println "error")
(fact (do ~@body) =not=> (throws)) | (ns jiksnu.test-helper
(:require [ciste.runner :refer [start-application! stop-application!]]
[hiccup.core :as h]
[jiksnu.modules.core.db :as db]
[jiksnu.referrant :as r]
[midje.sweet :refer [=> =not=> fact future-fact namespace-state-changes throws]]
[net.cgrand.enlive-html :as enlive]
[slingshot.slingshot :refer [try+ throw+]]
[taoensso.timbre :as timbre])
(:import java.io.StringReader))
(defn hiccup->doc
[hiccup-seq]
(-> hiccup-seq
h/html
StringReader.
enlive/xml-resource))
(defn select-by-model
[doc model-name]
(enlive/select doc [(enlive/attr= :data-model model-name)]))
(def ^:dynamic *depth* 0)
(defmacro context
[description & body]
`(let [var-name# (str ~description)]
(print (apply str (repeat *depth* " ")))
(println var-name#)
(fact ~description
(binding [*depth* (inc *depth*)]
~@body))
(when (zero? *depth*)
(println " "))))
(defmacro future-context
[description & body]
`(let [var-name# (str ~description)]
(future-fact var-name# ~@body)))
(defn setup-testing
([] (setup-testing nil))
([modules]
(try+
(start-application! modules)
(db/drop-all!)
(dosync
(ref-set r/this {})
(ref-set r/that {}))
(catch Object ex
(timbre/error "Setup Error" ex)
(throw+ ex)))))
(defn stop-testing
[]
(try+
(catch Object ex
(timbre/error "Shutdown Error" ex)
(throw+ ex))))
(defmacro module-test
[modules]
`(namespace-state-changes
[(before :facts (setup-testing ~modules))
(after :facts (stop-testing))]))
(defmacro test-environment-fixture
[& body]
`(try+
(timbre/debug "wrapping testing fixture")
(setup-testing)
~@body
(catch Object ex#
(throw+ ex#))
(finally
(stop-application!))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.