_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 |
|---|---|---|---|---|---|---|---|---|
fa767b9e337292c92bfefe6d6f05e5060ccbecd1fcc3dbafc5be0f2f9e0afec9 | baconpaul/composition-kit | scratch_pad.clj | (ns composition-kit.compositions.scratch-pad
(:require [composition-kit.music-lib.midi-util :as midi])
(:require [composition-kit.music-lib.tempo :as tempo])
(:require [composition-kit.music-lib.tonal-theory :as th])
(:require [composition-kit.music-lib.logical-sequence :as ls])
(:require [composition-kit.music-lib.logical-item :as i])
(:require [composition-kit.music-viz.render-score :as render])
(:use composition-kit.core))
;; Just a place for trying out syntax and APIS and what not.
(def instruments
(-> (midi/midi-instrument-map)
(midi/add-midi-instrument :piano (midi/midi-port 0))
))
(defn on-inst [s i] (ls/on-instrument s (i instruments)))
(def clock (tempo/constant-tempo 4 4 120))
(def scale
(lily "^inst=piano ^hold=0.05 c*20 d*90 e8*70 f ^hold=0.99 f4 g*120 r8 g c e f2" :instruments instruments :relative :c5 ))
(render/show-png (render/sequence-to-png scale))
#_(->
(>>>
(-> scale ))
(ls/with-clock clock)
(midi-play)
)
| null | https://raw.githubusercontent.com/baconpaul/composition-kit/fce0addb74a9c30ba06e051d3bca51c5a2b0ce6f/src/composition_kit/compositions/scratch_pad.clj | clojure | Just a place for trying out syntax and APIS and what not. | (ns composition-kit.compositions.scratch-pad
(:require [composition-kit.music-lib.midi-util :as midi])
(:require [composition-kit.music-lib.tempo :as tempo])
(:require [composition-kit.music-lib.tonal-theory :as th])
(:require [composition-kit.music-lib.logical-sequence :as ls])
(:require [composition-kit.music-lib.logical-item :as i])
(:require [composition-kit.music-viz.render-score :as render])
(:use composition-kit.core))
(def instruments
(-> (midi/midi-instrument-map)
(midi/add-midi-instrument :piano (midi/midi-port 0))
))
(defn on-inst [s i] (ls/on-instrument s (i instruments)))
(def clock (tempo/constant-tempo 4 4 120))
(def scale
(lily "^inst=piano ^hold=0.05 c*20 d*90 e8*70 f ^hold=0.99 f4 g*120 r8 g c e f2" :instruments instruments :relative :c5 ))
(render/show-png (render/sequence-to-png scale))
#_(->
(>>>
(-> scale ))
(ls/with-clock clock)
(midi-play)
)
|
8204276033089a8710c2dfe365c1902b0da0197cde7afd4824c39f6850c3dbc6 | probprog/anglican-infcomp-examples | hdf5.clj | (ns helpers.hdf5
(:require [clojure.core.matrix :as m]
[clj-hdf5.core :as hdf5]
[clojure.string :as str]))
(defn- array-to-mat-vec [array]
"Takes in either 1D or 2D Java array and returns either Clojure vector or matrix."
(let [temp (seq array)]
(if (number? (first temp))
(m/to-vector temp)
(m/matrix (map seq temp)))))
(defn parse-datasets-hdf5 [filename]
"Takes filename of HDF5 file containing only 1D and 2D datasets,
Returns hashmap of the same structure as the group structure with
hashmap keys being group names."
(let [h5root (hdf5/open (clojure.java.io/file filename))
datasets-and-paths (remove nil? (doall (hdf5/walk h5root #(if (hdf5/dataset? %)
{:dataset (hdf5/read %) :path (:path %)}
nil))))
result (reduce (fn [nn-params dataset-and-path]
(let [dataset (array-to-mat-vec (:dataset dataset-and-path))
path (map read-string (remove #(= % "")
(str/split (:path dataset-and-path) #"/")))]
(assoc-in nn-params path dataset)))
{}
datasets-and-paths)]
(hdf5/close h5root)
result))
;; Code for pre-generating random projection matrices
( def WIDTH 200 )
;; (def HEIGHT 50)
( def R100 ( sample ( random - projection - matrix 100 ( * WIDTH HEIGHT ) ) ) )
( def R200 ( sample ( random - projection - matrix 200 ( * WIDTH HEIGHT ) ) ) )
( def R500 ( sample ( random - projection - matrix 500 ( * WIDTH HEIGHT ) ) ) )
( def R1000 ( sample ( random - projection - matrix 1000 ( * WIDTH HEIGHT ) ) ) )
( def R2000 ( sample ( random - projection - matrix 2000 ( * WIDTH HEIGHT ) ) ) )
( def writer ( HDF5Factory / open " resources / random - projection - matrices.h5 " ) )
( .writeDoubleMatrix writer " /R100 " ( mat - vec - to - array ( vec ( map ) ) ) )
;; (.writeDoubleMatrix writer "/R200" (mat-vec-to-array (vec (map vec R200))))
;; (.writeDoubleMatrix writer "/R500" (mat-vec-to-array (vec (map vec R500))))
( .writeDoubleMatrix writer " /R1000 " ( mat - vec - to - array ( vec ( map vec R1000 ) ) ) )
;; (.writeDoubleMatrix writer "/R2000" (mat-vec-to-array (vec (map vec R2000))))
;; (.delete writer "__DATA_TYPES__")
;; (.close writer)
| null | https://raw.githubusercontent.com/probprog/anglican-infcomp-examples/63b0e0f5413b4f4d6552a90a94f57028b96dd185/src/helpers/hdf5.clj | clojure | Code for pre-generating random projection matrices
(def HEIGHT 50)
(.writeDoubleMatrix writer "/R200" (mat-vec-to-array (vec (map vec R200))))
(.writeDoubleMatrix writer "/R500" (mat-vec-to-array (vec (map vec R500))))
(.writeDoubleMatrix writer "/R2000" (mat-vec-to-array (vec (map vec R2000))))
(.delete writer "__DATA_TYPES__")
(.close writer) | (ns helpers.hdf5
(:require [clojure.core.matrix :as m]
[clj-hdf5.core :as hdf5]
[clojure.string :as str]))
(defn- array-to-mat-vec [array]
"Takes in either 1D or 2D Java array and returns either Clojure vector or matrix."
(let [temp (seq array)]
(if (number? (first temp))
(m/to-vector temp)
(m/matrix (map seq temp)))))
(defn parse-datasets-hdf5 [filename]
"Takes filename of HDF5 file containing only 1D and 2D datasets,
Returns hashmap of the same structure as the group structure with
hashmap keys being group names."
(let [h5root (hdf5/open (clojure.java.io/file filename))
datasets-and-paths (remove nil? (doall (hdf5/walk h5root #(if (hdf5/dataset? %)
{:dataset (hdf5/read %) :path (:path %)}
nil))))
result (reduce (fn [nn-params dataset-and-path]
(let [dataset (array-to-mat-vec (:dataset dataset-and-path))
path (map read-string (remove #(= % "")
(str/split (:path dataset-and-path) #"/")))]
(assoc-in nn-params path dataset)))
{}
datasets-and-paths)]
(hdf5/close h5root)
result))
( def WIDTH 200 )
( def R100 ( sample ( random - projection - matrix 100 ( * WIDTH HEIGHT ) ) ) )
( def R200 ( sample ( random - projection - matrix 200 ( * WIDTH HEIGHT ) ) ) )
( def R500 ( sample ( random - projection - matrix 500 ( * WIDTH HEIGHT ) ) ) )
( def R1000 ( sample ( random - projection - matrix 1000 ( * WIDTH HEIGHT ) ) ) )
( def R2000 ( sample ( random - projection - matrix 2000 ( * WIDTH HEIGHT ) ) ) )
( def writer ( HDF5Factory / open " resources / random - projection - matrices.h5 " ) )
( .writeDoubleMatrix writer " /R100 " ( mat - vec - to - array ( vec ( map ) ) ) )
( .writeDoubleMatrix writer " /R1000 " ( mat - vec - to - array ( vec ( map vec R1000 ) ) ) )
|
0e12f7c126718523a36dd9ad95f89fd0ca50df445a519958e2b67f44881379e5 | sophiabrandt/markdown-preview | core.cljs | (ns mdpreview.core
(:require [reagent.core :as r]
[mdpreview.views :as views]))
(defn ^:dev/after-load start
[]
(r/render [views/app]
(.getElementById js/document "app")))
(defn ^:export main
[]
(start))
| null | https://raw.githubusercontent.com/sophiabrandt/markdown-preview/bc01798289cdd6e8775b1ab472d4afe217a27580/src/mdpreview/core.cljs | clojure | (ns mdpreview.core
(:require [reagent.core :as r]
[mdpreview.views :as views]))
(defn ^:dev/after-load start
[]
(r/render [views/app]
(.getElementById js/document "app")))
(defn ^:export main
[]
(start))
| |
ed8c5e27688c39012700cdcde594cff5c3e3d696473c99da5ccc6a3d87f19ec6 | serokell/nixfmt | Pretty.hs | © 2019 < >
- © 2019 < >
-
- SPDX - License - Identifier : MPL-2.0
- © 2019 Lars Jellema <>
-
- SPDX-License-Identifier: MPL-2.0
-}
# LANGUAGE FlexibleInstances , OverloadedStrings #
module Nixfmt.Pretty where
import Prelude hiding (String)
import Data.Char (isSpace)
import Data.Maybe (fromMaybe)
import Data.Text (Text, isPrefixOf, isSuffixOf, stripPrefix)
import qualified Data.Text as Text
(dropEnd, empty, init, isInfixOf, last, null, strip, takeWhile)
import Nixfmt.Predoc
(Doc, Pretty, base, emptyline, group, hardline, hardspace, hcat, line, line',
nest, newline, pretty, sepBy, softline, softline', text, textWidth)
import Nixfmt.Types
(Ann(..), Binder(..), Expression(..), File(..), Leaf, ParamAttr(..),
Parameter(..), Selector(..), SimpleSelector(..), StringPart(..), Term(..),
Token(..), TrailingComment(..), Trivia, Trivium(..), tokenText)
import Nixfmt.Util (commonIndentation, isSpaces, replaceMultiple)
prettyCommentLine :: Text -> Doc
prettyCommentLine l
| Text.null l = emptyline
| otherwise = text l <> hardline
toLineComment :: Text -> Trivium
toLineComment c = LineComment $ fromMaybe (" " <> c) $ stripPrefix "*" c
instance Pretty TrailingComment where
pretty (TrailingComment c)
= hardspace <> text "#" <> hardspace <> text c <> hardline
instance Pretty Trivium where
pretty EmptyLine = emptyline
pretty (LineComment c) = text "#" <> pretty c <> hardline
pretty (BlockComment c)
| all ("*" `isPrefixOf`) (tail c) = hcat (map toLineComment c)
| otherwise
= base $ text "/*" <> hardspace
<> nest 3 (hcat (map prettyCommentLine c))
<> text "*/" <> hardline
instance Pretty [Trivium] where
pretty [] = mempty
pretty trivia = hardline <> hcat trivia
instance Pretty a => Pretty (Ann a) where
pretty (Ann x trailing leading)
= pretty x <> pretty trailing <> pretty leading
instance Pretty SimpleSelector where
pretty (IDSelector i) = pretty i
pretty (InterpolSelector interpol) = pretty interpol
pretty (StringSelector (Ann s trailing leading))
= prettySimpleString s <> pretty trailing <> pretty leading
instance Pretty Selector where
pretty (Selector dot sel Nothing)
= pretty dot <> pretty sel
pretty (Selector dot sel (Just (kw, def)))
= pretty dot <> pretty sel
<> hardspace <> pretty kw <> hardspace <> pretty def
instance Pretty Binder where
pretty (Inherit inherit Nothing ids semicolon)
= base $ group (pretty inherit <> softline
<> nest 2 (sepBy softline ids)) <> pretty semicolon
pretty (Inherit inherit source ids semicolon)
= base $ group (pretty inherit <> hardspace
<> pretty source <> line
<> nest 2 (sepBy softline ids)) <> pretty semicolon
pretty (Assignment selectors assign expr semicolon)
= base $ group (hcat selectors <> hardspace
<> nest 2 (pretty assign <> softline <> pretty expr))
<> pretty semicolon
-- | Pretty print a term without wrapping it in a group.
prettyTerm :: Term -> Doc
prettyTerm (Token t) = pretty t
prettyTerm (String s) = pretty s
prettyTerm (Path p) = pretty p
prettyTerm (Selection term selectors) = pretty term <> hcat selectors
prettyTerm (List (Ann paropen Nothing []) [] parclose)
= pretty paropen <> hardspace <> pretty parclose
prettyTerm (List (Ann paropen Nothing []) [item] parclose)
| isAbsorbable item
= pretty paropen <> pretty item <> pretty parclose
prettyTerm (List (Ann paropen trailing leading) items parclose)
= base $ pretty paropen <> pretty trailing <> line
<> nest 2 (pretty leading <> sepBy line (map group items)) <> line
<> pretty parclose
prettyTerm (Set Nothing (Ann paropen Nothing []) [] parclose)
= pretty paropen <> hardspace <> pretty parclose
prettyTerm (Set krec (Ann paropen trailing leading) binders parclose)
= base $ pretty (fmap ((<>hardspace) . pretty) krec)
<> pretty paropen <> pretty trailing <> line
<> nest 2 (pretty leading <> sepBy hardline binders) <> line
<> pretty parclose
prettyTerm (Parenthesized (Ann paropen trailing leading) expr parclose)
= base $ pretty paropen <> pretty trailing
<> nest 2 (pretty leading <> group expr) <> pretty parclose
instance Pretty Term where
pretty l@(List _ _ _) = group $ prettyTerm l
pretty x = prettyTerm x
toLeading :: Maybe TrailingComment -> Trivia
toLeading Nothing = []
toLeading (Just (TrailingComment c)) = [LineComment (" " <> c)]
prettyComma :: Maybe Leaf -> Doc
prettyComma Nothing = mempty
prettyComma (Just comma) = softline' <> pretty comma <> hardspace
instance Pretty ParamAttr where
pretty (ParamAttr name Nothing comma)
= pretty name <> prettyComma comma
pretty (ParamAttr name (Just (qmark, def)) comma)
= group (pretty name <> hardspace <> pretty qmark
<> absorb softline mempty (Just 2) def)
<> prettyComma comma
pretty (ParamEllipsis ellipsis)
= pretty ellipsis
instance Pretty Parameter where
pretty (IDParameter i) = pretty i
pretty (SetParameter bopen attrs bclose)
= group $ pretty bopen <> hardspace
<> hcat attrs <> softline
<> pretty bclose
pretty (ContextParameter param1 at param2)
= pretty param1 <> pretty at <> pretty param2
isAbsorbable :: Term -> Bool
isAbsorbable (String (Ann parts@(_:_:_) _ _))
= not $ isSimpleString parts
isAbsorbable (Set _ _ (_:_) _) = True
isAbsorbable (List (Ann _ Nothing []) [item] _) = isAbsorbable item
isAbsorbable (Parenthesized (Ann _ Nothing []) (Term t) _) = isAbsorbable t
isAbsorbable (List _ (_:_:_) _) = True
isAbsorbable _ = False
absorb :: Doc -> Doc -> Maybe Int -> Expression -> Doc
absorb left right _ (Term t)
| isAbsorbable t = toHardspace left <> prettyTerm t <> toHardspace right
where toHardspace x | x == mempty = mempty
| x == softline' = mempty
| x == line' = mempty
| otherwise = hardspace
absorb left right Nothing x = left <> pretty x <> right
absorb left right (Just level) x
= left <> nest level (pretty x) <> right
absorbSet :: Expression -> Doc
absorbSet = absorb line mempty Nothing
absorbThen :: Expression -> Doc
absorbThen (Term t) | isAbsorbable t = hardspace <> prettyTerm t <> hardspace
absorbThen x = line <> nest 2 (group x) <> line
absorbElse :: Expression -> Doc
absorbElse (If if_ cond then_ expr0 else_ expr1)
= hardspace <> pretty if_ <> hardspace <> group cond <> hardspace
<> pretty then_ <> absorbThen expr0
<> pretty else_ <> absorbElse expr1
absorbElse (Term t) | isAbsorbable t = hardspace <> prettyTerm t
absorbElse x = line <> nest 2 (group x)
absorbApp :: Expression -> Doc
absorbApp (Application f x) = softline <> pretty f <> absorbApp x
absorbApp (Term t) | isAbsorbable t = hardspace <> group (prettyTerm t)
absorbApp x = softline <> pretty x
instance Pretty Expression where
pretty (Term t) = pretty t
pretty (With with expr0 semicolon expr1)
= base (pretty with <> hardspace
<> nest 2 (group expr0) <> pretty semicolon)
<> absorbSet expr1
pretty (Let (Ann let_ letTrailing letLeading) binders
(Ann in_ inTrailing inLeading) expr)
= base $ group letPart <> line <> group inPart
where letPart = pretty let_ <> pretty letTrailing <> line <> letBody
inPart = pretty in_ <> hardspace <> pretty expr
letBody = nest 2 $
pretty letLeading
<> sepBy hardline binders
<> pretty (toLeading inTrailing)
<> pretty inLeading
pretty (Assert assert cond semicolon expr)
= base (pretty assert <> hardspace
<> nest 2 (group cond) <> pretty semicolon)
<> absorbSet expr
pretty (If if_ cond then_ expr0 else_ expr1)
= base $ group $
pretty if_ <> hardspace <> group cond <> hardspace
<> pretty then_ <> absorbThen expr0
<> pretty else_ <> absorbElse expr1
pretty (Abstraction (IDParameter param) colon body)
= pretty param <> pretty colon <> absorbAbs body
where absorbAbs (Abstraction (IDParameter param0) colon0 body0) =
hardspace <> pretty param0 <> pretty colon0 <> absorbAbs body0
absorbAbs x = absorbSet x
pretty (Abstraction param colon body)
= pretty param <> pretty colon <> absorbSet body
pretty (Application f x) = group $ pretty f <> absorbApp x
pretty (Operation a op b)
= pretty a <> softline
<> pretty op <> hardspace <> pretty b
pretty (MemberCheck expr qmark sel)
= pretty expr <> softline
<> pretty qmark <> hardspace <> hcat sel
pretty (Negation minus expr)
= pretty minus <> pretty expr
pretty (Inversion bang expr)
= pretty bang <> pretty expr
instance Pretty File where
pretty (File (Ann _ Nothing leading) expr)
= group $ hcat leading <> pretty expr <> hardline
pretty (File (Ann _ (Just (TrailingComment trailing)) leading) expr)
= group $ text "# " <> pretty trailing <> hardline
<> hcat leading <> pretty expr <> hardline
instance Pretty Token where
pretty = text . tokenText
instance Pretty [Token] where
pretty = hcat
-- STRINGS
isSimpleSelector :: Selector -> Bool
isSimpleSelector (Selector _ (IDSelector _) Nothing) = True
isSimpleSelector _ = False
isSimple :: Expression -> Bool
isSimple (Term (Token (Ann (Identifier _) Nothing []))) = True
isSimple (Term (Selection t selectors))
= isSimple (Term t) && all isSimpleSelector selectors
isSimple _ = False
hasQuotes :: [StringPart] -> Bool
hasQuotes [] = False
hasQuotes (TextPart x : xs) = Text.isInfixOf "\"" x || hasQuotes xs
hasQuotes (_ : xs) = hasQuotes xs
hasDualQuotes :: [StringPart] -> Bool
hasDualQuotes [] = False
hasDualQuotes (TextPart x : xs) = Text.isInfixOf "''" x || hasDualQuotes xs
hasDualQuotes (_ : xs) = hasDualQuotes xs
endsInSingleQuote :: [StringPart] -> Bool
endsInSingleQuote [] = False
endsInSingleQuote xs =
case last xs of
(TextPart x) -> x /= Text.empty && Text.last x == '\''
_ -> False
isIndented :: [[StringPart]] -> Bool
isIndented parts =
case commonIndentation inits of
Just "" -> False
_ -> True
where textInit (TextPart t : xs) = t <> textInit xs
textInit _ = ""
nonEmpty (TextPart "" : xs) = nonEmpty xs
nonEmpty [] = False
nonEmpty _ = True
inits = map textInit $ filter nonEmpty parts
| If the last line has at least one space but nothing else , it can not be
-- cleanly represented in an indented string.
lastLineIsSpaces :: [[StringPart]] -> Bool
lastLineIsSpaces [] = False
lastLineIsSpaces xs = case last xs of
[TextPart t] -> isSpaces t
_ -> False
isInvisibleLine :: [StringPart] -> Bool
isInvisibleLine [] = True
isInvisibleLine [TextPart t] = Text.null $ Text.strip t
isInvisibleLine _ = False
isSimpleString :: [[StringPart]] -> Bool
isSimpleString [parts]
| hasDualQuotes parts = True
| endsInSingleQuote parts = True
| isIndented [parts] = True
| hasQuotes parts = False
| otherwise = True
isSimpleString parts
| all isInvisibleLine parts = True
| isIndented parts = True
| lastLineIsSpaces parts = True
| otherwise = False
instance Pretty StringPart where
pretty (TextPart t) = text t
pretty (Interpolation paropen (Term t) parclose)
| isAbsorbable t
= group $ pretty paropen <> prettyTerm t <> pretty parclose
pretty (Interpolation paropen expr parclose)
| isSimple expr
= pretty paropen <> pretty expr <> pretty parclose
| otherwise
= group $ pretty paropen <> line'
<> nest 2 (pretty expr) <> line'
<> pretty parclose
instance Pretty [StringPart] where
pretty [Interpolation paropen expr parclose]
= group $ pretty paropen <> pretty expr <> pretty parclose
pretty (TextPart t : parts)
= text t <> nest indentation (hcat parts)
where indentation = textWidth $ Text.takeWhile isSpace t
pretty parts = hcat parts
instance Pretty [[StringPart]] where
pretty parts
| isSimpleString parts = prettySimpleString parts
| otherwise = prettyIndentedString parts
type UnescapeInterpol = Text -> Text
type EscapeText = Text -> Text
prettyLine :: EscapeText -> UnescapeInterpol -> [StringPart] -> Doc
prettyLine escapeText unescapeInterpol
= pretty . unescapeInterpols . map escape
where escape (TextPart t) = TextPart (escapeText t)
escape x = x
unescapeInterpols [] = []
unescapeInterpols (TextPart t : TextPart u : xs)
= unescapeInterpols (TextPart (t <> u) : xs)
unescapeInterpols (TextPart t : xs@(Interpolation _ _ _ : _))
= TextPart (unescapeInterpol t) : unescapeInterpols xs
unescapeInterpols (x : xs) = x : unescapeInterpols xs
prettySimpleString :: [[StringPart]] -> Doc
prettySimpleString parts = group $
text "\""
<> sepBy (text "\\n") (map (prettyLine escape unescapeInterpol) parts)
<> text "\""
where escape = replaceMultiple
[ ("$\\${", "$${")
, ("${", "\\${")
, ("\"", "\\\"")
, ("\r", "\\r")
, ("\\", "\\\\")
]
unescapeInterpol t
| "$" `isSuffixOf` t = Text.init t <> "\\$"
| otherwise = t
prettyIndentedString :: [[StringPart]] -> Doc
prettyIndentedString parts = group $ base $
text "''" <> line'
<> nest 2 (sepBy newline (map (prettyLine escape unescapeInterpol) parts))
<> text "''"
where escape = replaceMultiple
[ ("'${", "''\\'''${")
, ("${", "''${")
, ("''", "'''")
]
unescapeInterpol t
| Text.null t = t
| Text.last t /= '$' = t
| trailingQuotes (Text.init t) `mod` 3 == 0
= Text.init t <> "''$"
| trailingQuotes (Text.init t) `mod` 3 == 1
= Text.dropEnd 2 t <> "''\\'''$"
| otherwise
= error "should never happen after escape"
trailingQuotes t
| "'" `isSuffixOf` t = 1 + trailingQuotes (Text.init t)
| otherwise = 0 :: Int
| null | https://raw.githubusercontent.com/serokell/nixfmt/d15f5d37eda66217b42dc360cecfca03c9affce7/src/Nixfmt/Pretty.hs | haskell | | Pretty print a term without wrapping it in a group.
STRINGS
cleanly represented in an indented string. | © 2019 < >
- © 2019 < >
-
- SPDX - License - Identifier : MPL-2.0
- © 2019 Lars Jellema <>
-
- SPDX-License-Identifier: MPL-2.0
-}
# LANGUAGE FlexibleInstances , OverloadedStrings #
module Nixfmt.Pretty where
import Prelude hiding (String)
import Data.Char (isSpace)
import Data.Maybe (fromMaybe)
import Data.Text (Text, isPrefixOf, isSuffixOf, stripPrefix)
import qualified Data.Text as Text
(dropEnd, empty, init, isInfixOf, last, null, strip, takeWhile)
import Nixfmt.Predoc
(Doc, Pretty, base, emptyline, group, hardline, hardspace, hcat, line, line',
nest, newline, pretty, sepBy, softline, softline', text, textWidth)
import Nixfmt.Types
(Ann(..), Binder(..), Expression(..), File(..), Leaf, ParamAttr(..),
Parameter(..), Selector(..), SimpleSelector(..), StringPart(..), Term(..),
Token(..), TrailingComment(..), Trivia, Trivium(..), tokenText)
import Nixfmt.Util (commonIndentation, isSpaces, replaceMultiple)
prettyCommentLine :: Text -> Doc
prettyCommentLine l
| Text.null l = emptyline
| otherwise = text l <> hardline
toLineComment :: Text -> Trivium
toLineComment c = LineComment $ fromMaybe (" " <> c) $ stripPrefix "*" c
instance Pretty TrailingComment where
pretty (TrailingComment c)
= hardspace <> text "#" <> hardspace <> text c <> hardline
instance Pretty Trivium where
pretty EmptyLine = emptyline
pretty (LineComment c) = text "#" <> pretty c <> hardline
pretty (BlockComment c)
| all ("*" `isPrefixOf`) (tail c) = hcat (map toLineComment c)
| otherwise
= base $ text "/*" <> hardspace
<> nest 3 (hcat (map prettyCommentLine c))
<> text "*/" <> hardline
instance Pretty [Trivium] where
pretty [] = mempty
pretty trivia = hardline <> hcat trivia
instance Pretty a => Pretty (Ann a) where
pretty (Ann x trailing leading)
= pretty x <> pretty trailing <> pretty leading
instance Pretty SimpleSelector where
pretty (IDSelector i) = pretty i
pretty (InterpolSelector interpol) = pretty interpol
pretty (StringSelector (Ann s trailing leading))
= prettySimpleString s <> pretty trailing <> pretty leading
instance Pretty Selector where
pretty (Selector dot sel Nothing)
= pretty dot <> pretty sel
pretty (Selector dot sel (Just (kw, def)))
= pretty dot <> pretty sel
<> hardspace <> pretty kw <> hardspace <> pretty def
instance Pretty Binder where
pretty (Inherit inherit Nothing ids semicolon)
= base $ group (pretty inherit <> softline
<> nest 2 (sepBy softline ids)) <> pretty semicolon
pretty (Inherit inherit source ids semicolon)
= base $ group (pretty inherit <> hardspace
<> pretty source <> line
<> nest 2 (sepBy softline ids)) <> pretty semicolon
pretty (Assignment selectors assign expr semicolon)
= base $ group (hcat selectors <> hardspace
<> nest 2 (pretty assign <> softline <> pretty expr))
<> pretty semicolon
prettyTerm :: Term -> Doc
prettyTerm (Token t) = pretty t
prettyTerm (String s) = pretty s
prettyTerm (Path p) = pretty p
prettyTerm (Selection term selectors) = pretty term <> hcat selectors
prettyTerm (List (Ann paropen Nothing []) [] parclose)
= pretty paropen <> hardspace <> pretty parclose
prettyTerm (List (Ann paropen Nothing []) [item] parclose)
| isAbsorbable item
= pretty paropen <> pretty item <> pretty parclose
prettyTerm (List (Ann paropen trailing leading) items parclose)
= base $ pretty paropen <> pretty trailing <> line
<> nest 2 (pretty leading <> sepBy line (map group items)) <> line
<> pretty parclose
prettyTerm (Set Nothing (Ann paropen Nothing []) [] parclose)
= pretty paropen <> hardspace <> pretty parclose
prettyTerm (Set krec (Ann paropen trailing leading) binders parclose)
= base $ pretty (fmap ((<>hardspace) . pretty) krec)
<> pretty paropen <> pretty trailing <> line
<> nest 2 (pretty leading <> sepBy hardline binders) <> line
<> pretty parclose
prettyTerm (Parenthesized (Ann paropen trailing leading) expr parclose)
= base $ pretty paropen <> pretty trailing
<> nest 2 (pretty leading <> group expr) <> pretty parclose
instance Pretty Term where
pretty l@(List _ _ _) = group $ prettyTerm l
pretty x = prettyTerm x
toLeading :: Maybe TrailingComment -> Trivia
toLeading Nothing = []
toLeading (Just (TrailingComment c)) = [LineComment (" " <> c)]
prettyComma :: Maybe Leaf -> Doc
prettyComma Nothing = mempty
prettyComma (Just comma) = softline' <> pretty comma <> hardspace
instance Pretty ParamAttr where
pretty (ParamAttr name Nothing comma)
= pretty name <> prettyComma comma
pretty (ParamAttr name (Just (qmark, def)) comma)
= group (pretty name <> hardspace <> pretty qmark
<> absorb softline mempty (Just 2) def)
<> prettyComma comma
pretty (ParamEllipsis ellipsis)
= pretty ellipsis
instance Pretty Parameter where
pretty (IDParameter i) = pretty i
pretty (SetParameter bopen attrs bclose)
= group $ pretty bopen <> hardspace
<> hcat attrs <> softline
<> pretty bclose
pretty (ContextParameter param1 at param2)
= pretty param1 <> pretty at <> pretty param2
isAbsorbable :: Term -> Bool
isAbsorbable (String (Ann parts@(_:_:_) _ _))
= not $ isSimpleString parts
isAbsorbable (Set _ _ (_:_) _) = True
isAbsorbable (List (Ann _ Nothing []) [item] _) = isAbsorbable item
isAbsorbable (Parenthesized (Ann _ Nothing []) (Term t) _) = isAbsorbable t
isAbsorbable (List _ (_:_:_) _) = True
isAbsorbable _ = False
absorb :: Doc -> Doc -> Maybe Int -> Expression -> Doc
absorb left right _ (Term t)
| isAbsorbable t = toHardspace left <> prettyTerm t <> toHardspace right
where toHardspace x | x == mempty = mempty
| x == softline' = mempty
| x == line' = mempty
| otherwise = hardspace
absorb left right Nothing x = left <> pretty x <> right
absorb left right (Just level) x
= left <> nest level (pretty x) <> right
absorbSet :: Expression -> Doc
absorbSet = absorb line mempty Nothing
absorbThen :: Expression -> Doc
absorbThen (Term t) | isAbsorbable t = hardspace <> prettyTerm t <> hardspace
absorbThen x = line <> nest 2 (group x) <> line
absorbElse :: Expression -> Doc
absorbElse (If if_ cond then_ expr0 else_ expr1)
= hardspace <> pretty if_ <> hardspace <> group cond <> hardspace
<> pretty then_ <> absorbThen expr0
<> pretty else_ <> absorbElse expr1
absorbElse (Term t) | isAbsorbable t = hardspace <> prettyTerm t
absorbElse x = line <> nest 2 (group x)
absorbApp :: Expression -> Doc
absorbApp (Application f x) = softline <> pretty f <> absorbApp x
absorbApp (Term t) | isAbsorbable t = hardspace <> group (prettyTerm t)
absorbApp x = softline <> pretty x
instance Pretty Expression where
pretty (Term t) = pretty t
pretty (With with expr0 semicolon expr1)
= base (pretty with <> hardspace
<> nest 2 (group expr0) <> pretty semicolon)
<> absorbSet expr1
pretty (Let (Ann let_ letTrailing letLeading) binders
(Ann in_ inTrailing inLeading) expr)
= base $ group letPart <> line <> group inPart
where letPart = pretty let_ <> pretty letTrailing <> line <> letBody
inPart = pretty in_ <> hardspace <> pretty expr
letBody = nest 2 $
pretty letLeading
<> sepBy hardline binders
<> pretty (toLeading inTrailing)
<> pretty inLeading
pretty (Assert assert cond semicolon expr)
= base (pretty assert <> hardspace
<> nest 2 (group cond) <> pretty semicolon)
<> absorbSet expr
pretty (If if_ cond then_ expr0 else_ expr1)
= base $ group $
pretty if_ <> hardspace <> group cond <> hardspace
<> pretty then_ <> absorbThen expr0
<> pretty else_ <> absorbElse expr1
pretty (Abstraction (IDParameter param) colon body)
= pretty param <> pretty colon <> absorbAbs body
where absorbAbs (Abstraction (IDParameter param0) colon0 body0) =
hardspace <> pretty param0 <> pretty colon0 <> absorbAbs body0
absorbAbs x = absorbSet x
pretty (Abstraction param colon body)
= pretty param <> pretty colon <> absorbSet body
pretty (Application f x) = group $ pretty f <> absorbApp x
pretty (Operation a op b)
= pretty a <> softline
<> pretty op <> hardspace <> pretty b
pretty (MemberCheck expr qmark sel)
= pretty expr <> softline
<> pretty qmark <> hardspace <> hcat sel
pretty (Negation minus expr)
= pretty minus <> pretty expr
pretty (Inversion bang expr)
= pretty bang <> pretty expr
instance Pretty File where
pretty (File (Ann _ Nothing leading) expr)
= group $ hcat leading <> pretty expr <> hardline
pretty (File (Ann _ (Just (TrailingComment trailing)) leading) expr)
= group $ text "# " <> pretty trailing <> hardline
<> hcat leading <> pretty expr <> hardline
instance Pretty Token where
pretty = text . tokenText
instance Pretty [Token] where
pretty = hcat
isSimpleSelector :: Selector -> Bool
isSimpleSelector (Selector _ (IDSelector _) Nothing) = True
isSimpleSelector _ = False
isSimple :: Expression -> Bool
isSimple (Term (Token (Ann (Identifier _) Nothing []))) = True
isSimple (Term (Selection t selectors))
= isSimple (Term t) && all isSimpleSelector selectors
isSimple _ = False
hasQuotes :: [StringPart] -> Bool
hasQuotes [] = False
hasQuotes (TextPart x : xs) = Text.isInfixOf "\"" x || hasQuotes xs
hasQuotes (_ : xs) = hasQuotes xs
hasDualQuotes :: [StringPart] -> Bool
hasDualQuotes [] = False
hasDualQuotes (TextPart x : xs) = Text.isInfixOf "''" x || hasDualQuotes xs
hasDualQuotes (_ : xs) = hasDualQuotes xs
endsInSingleQuote :: [StringPart] -> Bool
endsInSingleQuote [] = False
endsInSingleQuote xs =
case last xs of
(TextPart x) -> x /= Text.empty && Text.last x == '\''
_ -> False
isIndented :: [[StringPart]] -> Bool
isIndented parts =
case commonIndentation inits of
Just "" -> False
_ -> True
where textInit (TextPart t : xs) = t <> textInit xs
textInit _ = ""
nonEmpty (TextPart "" : xs) = nonEmpty xs
nonEmpty [] = False
nonEmpty _ = True
inits = map textInit $ filter nonEmpty parts
| If the last line has at least one space but nothing else , it can not be
lastLineIsSpaces :: [[StringPart]] -> Bool
lastLineIsSpaces [] = False
lastLineIsSpaces xs = case last xs of
[TextPart t] -> isSpaces t
_ -> False
isInvisibleLine :: [StringPart] -> Bool
isInvisibleLine [] = True
isInvisibleLine [TextPart t] = Text.null $ Text.strip t
isInvisibleLine _ = False
isSimpleString :: [[StringPart]] -> Bool
isSimpleString [parts]
| hasDualQuotes parts = True
| endsInSingleQuote parts = True
| isIndented [parts] = True
| hasQuotes parts = False
| otherwise = True
isSimpleString parts
| all isInvisibleLine parts = True
| isIndented parts = True
| lastLineIsSpaces parts = True
| otherwise = False
instance Pretty StringPart where
pretty (TextPart t) = text t
pretty (Interpolation paropen (Term t) parclose)
| isAbsorbable t
= group $ pretty paropen <> prettyTerm t <> pretty parclose
pretty (Interpolation paropen expr parclose)
| isSimple expr
= pretty paropen <> pretty expr <> pretty parclose
| otherwise
= group $ pretty paropen <> line'
<> nest 2 (pretty expr) <> line'
<> pretty parclose
instance Pretty [StringPart] where
pretty [Interpolation paropen expr parclose]
= group $ pretty paropen <> pretty expr <> pretty parclose
pretty (TextPart t : parts)
= text t <> nest indentation (hcat parts)
where indentation = textWidth $ Text.takeWhile isSpace t
pretty parts = hcat parts
instance Pretty [[StringPart]] where
pretty parts
| isSimpleString parts = prettySimpleString parts
| otherwise = prettyIndentedString parts
type UnescapeInterpol = Text -> Text
type EscapeText = Text -> Text
prettyLine :: EscapeText -> UnescapeInterpol -> [StringPart] -> Doc
prettyLine escapeText unescapeInterpol
= pretty . unescapeInterpols . map escape
where escape (TextPart t) = TextPart (escapeText t)
escape x = x
unescapeInterpols [] = []
unescapeInterpols (TextPart t : TextPart u : xs)
= unescapeInterpols (TextPart (t <> u) : xs)
unescapeInterpols (TextPart t : xs@(Interpolation _ _ _ : _))
= TextPart (unescapeInterpol t) : unescapeInterpols xs
unescapeInterpols (x : xs) = x : unescapeInterpols xs
prettySimpleString :: [[StringPart]] -> Doc
prettySimpleString parts = group $
text "\""
<> sepBy (text "\\n") (map (prettyLine escape unescapeInterpol) parts)
<> text "\""
where escape = replaceMultiple
[ ("$\\${", "$${")
, ("${", "\\${")
, ("\"", "\\\"")
, ("\r", "\\r")
, ("\\", "\\\\")
]
unescapeInterpol t
| "$" `isSuffixOf` t = Text.init t <> "\\$"
| otherwise = t
prettyIndentedString :: [[StringPart]] -> Doc
prettyIndentedString parts = group $ base $
text "''" <> line'
<> nest 2 (sepBy newline (map (prettyLine escape unescapeInterpol) parts))
<> text "''"
where escape = replaceMultiple
[ ("'${", "''\\'''${")
, ("${", "''${")
, ("''", "'''")
]
unescapeInterpol t
| Text.null t = t
| Text.last t /= '$' = t
| trailingQuotes (Text.init t) `mod` 3 == 0
= Text.init t <> "''$"
| trailingQuotes (Text.init t) `mod` 3 == 1
= Text.dropEnd 2 t <> "''\\'''$"
| otherwise
= error "should never happen after escape"
trailingQuotes t
| "'" `isSuffixOf` t = 1 + trailingQuotes (Text.init t)
| otherwise = 0 :: Int
|
3a9cf1f40cd1164f5e1b577904781805f61a4735a4c9bd18818072f9f7fc5cd6 | johnswanson/tictag | about.cljs | (ns tictag.views.about
(:require [tictag.nav :refer [route-for]]))
(def tagtime-link [:a {:href "/"} "TagTime"])
(def about-content
[:div
[:h1 "About Tictag"]
[:p "Tictag is stochastic time tracking, heavily inspired by/stolen from " tagtime-link "."]
[:h2 "Okay, what's that?"]
[:p "(On average) every 45 minutes, on an unpredictable schedule, TicTag will ping you (currently via slack, or "
"a desktop client " [:a {:href ""} "available on github"] ". "
"You respond with what you're doing " [:i "right then"] ", using tags that you choose--things like " [:code "work"]
" or " [:code "eat"] " or " [:code "cook"] " or " [:code "read"] " or..."]
[:p "This random sampling of your time provides you with a statistically accurate picture of where your time actually goes."]
[:p "How much time do I spend coding? TicTag knows (you can click on the graph to see a larger version--you can see daily totals as "
"bars at the bottom, cumulative total as a green line, the actual pings as blue dots, and two daily averages calculated in slightly different ways "
"in red and black)."]
(let [coding-link ""]
[:a {:href coding-link
:target :_blank}
[:img {:width "850px"
:title "Time spent coding"
:src coding-link}]])
[:p "How much time do I spend working on this project? TicTag knows!"]
(let [ttc-link "-6uZl0NNXgEin08YfeORLoVHAgUhsWgUevG6xwY4Fe"]
[:a {:href ttc-link
:target :_blank}
[:img {:width "850px"
:title "Time spent working on TTC"
:src ttc-link}]])
[:p "Reading?"]
(let [read-link "-hG7u-Hh0fHyt8gQWrD_g2vtM-N_XQl5x03ftiRg"]
[:a {:href read-link
:target :_blank}
[:img {:width "850px"
:title "Time spent reading"
:src read-link}]])
[:p "Cooking or cleaning?"]
(let [cook-link "-w-zBuRGmWxZs7Lae8ZkPCR4y7CWoEK-THB78LHiuwRAIwOsymQQGchg6wuSMGsonPwQHWAq8yN7VJ9gSagRfacc8k_HHGjenR1PuwkhsXjx_k"]
[:a {:href cook-link
:target :_blank}
[:img {:width "850px"
:title "Time spent cooking or cleaning"
:src cook-link}]])
[:h2 "Why it's awesome"]
[:p "Three reasons. First, Tictag is 100% passive. You never have to remember to check in, you never have to start or stop a task, you never have to remember how long something took. "
"Second, Tictag is more accurate than other passive methods, that e.g. look at what program you have active to classify your time--zoning out in front of emacs should be classified as "
"zoning out, not coding. Third, Tictag provides insights into time that other tools would miss entirely. How long do you spend driving? Rescuetime doesn't know! I love that Tictag "
"gives me a window into things like that."]
[:h2 "Beeminder Integration"]
[:p "In addition to tracking your time, you might want to change how you're spending it. " [:a {:href ""} "Beeminder"] " lets you do that. You commit "
"(with actual money!) to spending " [:code "x"] " hours on " [:code "y"] ". Tictag measures how you're spending your time, and sends it along to Beeminder. If you aren't doing what you "
"said you would, Beeminder will charge you. This pulls your long-term incentives (\"I wish I read more often\") into the short-term (\"I'd rather surf Reddit than "
"read right now... oops, except then Beeminder will charge me, so nevermind\")."]
[:p "(I would just note that I absolutely love Beeminder, and it is the single service I've ever used that I would classify as having changed my life. I recommend it highly, "
"even if you don't end up using Tictag.)"]
[:h2 "Warning: Alpha Status"]
[:p "Tictag is in alpha. Things might change without warning. Things might break entirely. Be warned."]])
(defn about []
[:div {:style {:width "70%"
:margin :auto
:margin-top "3em"}}
about-content])
| null | https://raw.githubusercontent.com/johnswanson/tictag/89140b5084817690ec417b07b7d095ba7677f4e0/src/cljs/tictag/views/about.cljs | clojure | (ns tictag.views.about
(:require [tictag.nav :refer [route-for]]))
(def tagtime-link [:a {:href "/"} "TagTime"])
(def about-content
[:div
[:h1 "About Tictag"]
[:p "Tictag is stochastic time tracking, heavily inspired by/stolen from " tagtime-link "."]
[:h2 "Okay, what's that?"]
[:p "(On average) every 45 minutes, on an unpredictable schedule, TicTag will ping you (currently via slack, or "
"a desktop client " [:a {:href ""} "available on github"] ". "
"You respond with what you're doing " [:i "right then"] ", using tags that you choose--things like " [:code "work"]
" or " [:code "eat"] " or " [:code "cook"] " or " [:code "read"] " or..."]
[:p "This random sampling of your time provides you with a statistically accurate picture of where your time actually goes."]
[:p "How much time do I spend coding? TicTag knows (you can click on the graph to see a larger version--you can see daily totals as "
"bars at the bottom, cumulative total as a green line, the actual pings as blue dots, and two daily averages calculated in slightly different ways "
"in red and black)."]
(let [coding-link ""]
[:a {:href coding-link
:target :_blank}
[:img {:width "850px"
:title "Time spent coding"
:src coding-link}]])
[:p "How much time do I spend working on this project? TicTag knows!"]
(let [ttc-link "-6uZl0NNXgEin08YfeORLoVHAgUhsWgUevG6xwY4Fe"]
[:a {:href ttc-link
:target :_blank}
[:img {:width "850px"
:title "Time spent working on TTC"
:src ttc-link}]])
[:p "Reading?"]
(let [read-link "-hG7u-Hh0fHyt8gQWrD_g2vtM-N_XQl5x03ftiRg"]
[:a {:href read-link
:target :_blank}
[:img {:width "850px"
:title "Time spent reading"
:src read-link}]])
[:p "Cooking or cleaning?"]
(let [cook-link "-w-zBuRGmWxZs7Lae8ZkPCR4y7CWoEK-THB78LHiuwRAIwOsymQQGchg6wuSMGsonPwQHWAq8yN7VJ9gSagRfacc8k_HHGjenR1PuwkhsXjx_k"]
[:a {:href cook-link
:target :_blank}
[:img {:width "850px"
:title "Time spent cooking or cleaning"
:src cook-link}]])
[:h2 "Why it's awesome"]
[:p "Three reasons. First, Tictag is 100% passive. You never have to remember to check in, you never have to start or stop a task, you never have to remember how long something took. "
"Second, Tictag is more accurate than other passive methods, that e.g. look at what program you have active to classify your time--zoning out in front of emacs should be classified as "
"zoning out, not coding. Third, Tictag provides insights into time that other tools would miss entirely. How long do you spend driving? Rescuetime doesn't know! I love that Tictag "
"gives me a window into things like that."]
[:h2 "Beeminder Integration"]
[:p "In addition to tracking your time, you might want to change how you're spending it. " [:a {:href ""} "Beeminder"] " lets you do that. You commit "
"(with actual money!) to spending " [:code "x"] " hours on " [:code "y"] ". Tictag measures how you're spending your time, and sends it along to Beeminder. If you aren't doing what you "
"said you would, Beeminder will charge you. This pulls your long-term incentives (\"I wish I read more often\") into the short-term (\"I'd rather surf Reddit than "
"read right now... oops, except then Beeminder will charge me, so nevermind\")."]
[:p "(I would just note that I absolutely love Beeminder, and it is the single service I've ever used that I would classify as having changed my life. I recommend it highly, "
"even if you don't end up using Tictag.)"]
[:h2 "Warning: Alpha Status"]
[:p "Tictag is in alpha. Things might change without warning. Things might break entirely. Be warned."]])
(defn about []
[:div {:style {:width "70%"
:margin :auto
:margin-top "3em"}}
about-content])
| |
e3f7d7f76c5814f8860024111587ae73b194750114eadac437aad8c8c160774b | rd--/hsc3 | dbrown.help.hs | -- dbrown
let n = dbrownId 'α' dinf 0 15 1
x = mouseX kr 1 40 Exponential 0.1
t = impulse kr x 0
f = demand t 0 n * 30 + 340
in sinOsc ar f 0 * 0.1
-- dbrown
let n = demand (impulse kr 10 0) 0 (dbrownId 'α' dinf (-1) 1 0.05)
f = linExp n (-1) 1 64 9600
in sinOsc ar f 0 * 0.1
| null | https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/dbrown.help.hs | haskell | dbrown
dbrown | let n = dbrownId 'α' dinf 0 15 1
x = mouseX kr 1 40 Exponential 0.1
t = impulse kr x 0
f = demand t 0 n * 30 + 340
in sinOsc ar f 0 * 0.1
let n = demand (impulse kr 10 0) 0 (dbrownId 'α' dinf (-1) 1 0.05)
f = linExp n (-1) 1 64 9600
in sinOsc ar f 0 * 0.1
|
538972c52377e73a9e7db595590e70796d6b8e065d048e137223ca8865ce9082 | simonstl/introducing-erlang-2nd | drop.erl | -module(drop).
-export([fall_velocity/2]).
fall_velocity(Planemo, Distance) ->
Gravity = case Planemo of
earth -> 9.8;
moon -> 1.6;
mars -> 3.71
end, % note comma - function isn't done yet
try math:sqrt(2 * Gravity * Distance) of
Result -> Result
catch
error:Error -> {found, Error}
end. | null | https://raw.githubusercontent.com/simonstl/introducing-erlang-2nd/607e9c85fb767cf5519d331ef6ed549aee51fe61/ch09/ex2-debug/drop.erl | erlang | note comma - function isn't done yet | -module(drop).
-export([fall_velocity/2]).
fall_velocity(Planemo, Distance) ->
Gravity = case Planemo of
earth -> 9.8;
moon -> 1.6;
mars -> 3.71
try math:sqrt(2 * Gravity * Distance) of
Result -> Result
catch
error:Error -> {found, Error}
end. |
f39a15584779314d3bd5d5bf359e743300db071eb2ed42a593140e2a6dc3d5ab | ayamada/copy-of-svn.tir.jp | cgi.scm | ;;; coding: euc-jp
;;; -*- scheme -*-
;;; vim:set ft=scheme ts=8 sts=2 sw=2 et:
$ Id$
ToDo : 雑多になってきたので、モジュール名をtir03.cgi.miscにする ?
;;; ToDo: cgi-mainの内側か外側か判定可能な何かが無いかどうか確認し、
;;; 可能なら、locationは内側でも外側でも機能するように直す事。
ToDo : location時の#の扱い
;;; - location手続きは対応済み
;;; - webサーバにhoge.cgi#abc等のアクセスが来た際に、
;;; (本来はwebサーバが行うべき???)
;;; - どうしても#付きurlにリダイレクトしたい時の為に、
;;; meta http-equiv="Refresh"
でリダイレクトさせるhtml - treeを返す手続きを用意する 。
;;; -- 更に、副作用を伴う動作後に上記リダイレクトを行わせたい時の為に、
;;; locationでリダイレクト→meta http-equiv="Refresh"でリダイレクト
;;; - 今のところは必要な場面は無いので、必要な場面が出たら作る。
ToDo : test caseを用意
ToDo : text->inline - html text->block - html関数を追加する事 。
;;; ToDo: http-tree-makeを書きましょう。
(define-module tir03.cgi
(use gauche.charconv)
(use gauche.parameter)
(use srfi-1)
(use srfi-2)
(use rfc.uri)
(use text.html-lite)
(use text.tree)
(use util.list)
(use www.cgi)
(export
hes
html-tree-make
http-tree-make
cgi-tree-make
get-html-tree-keyword-symbols
get-http-tree-keyword-symbols
get-cgi-tree-keyword-symbols
cgi-metavariables->html
cgi-params->html
make-view-cgi-metavariables-thunk
append-params-to-url
completion-uri
path->url
location
self-url
self-url/path-info
self-path
self-path/path-info
make-form
cgi-on-error/stack-trace
cgi-main/jp
cgi-main/path
cgi-main/path/jp
cgi-main/jp/path
html:form/jp
get-path-info-keylist
with-reverse-proxy
))
(select-module tir03.cgi)
(define (hes . params)
(if (= 1 (length params))
(html-escape-string (car params))
(map html-escape-string params)))
(define-syntax when/null
(syntax-rules ()
((_ pred body ...) (if pred
(begin body ...)
'()))))
(define-macro (let-keywords** keywords tree-keyword-symbols body . bodies)
;; このマクロはものすごく微妙なので、あとでもっとマシな方法を考えて直す事
`(let-keywords* keywords ,(map
(lambda (x)
(list x #f))
(eval tree-keyword-symbols (current-module)))
,body . ,bodies))
(define *html-tree-keyword-symbols*
'(encoding
base-url
css-url
css-body
js-url
js-body
js
robots
title
title-format
title-format-args
body
body-header
body-footer
frame-body
))
(define (html-tree-make . keywords)
(let-keywords** keywords *html-tree-keyword-symbols*
(list
;; xml header
(if encoding
#`"<?xml version=\"1.0\" encoding=\",|encoding|\"?>\n"
"<?xml version=\"1.0\"?>\n")
;; html doctype
(html-doctype
:type (if frame-body
:xhtml-1.0-frameset
:xhtml-1.0-transitional))
;; html
(html:html
:lang "ja-JP"
:xml:lang "ja-JP"
:xmlns ""
(html:head
(when/null encoding
(html:meta :http-equiv "Content-Type"
:content #`"text/html; charset=,|encoding|"))
(when/null base-url
(html:base :href base-url))
(when/null (or css-url css-body)
(html:meta :http-equiv "Content-Style-Type"
:content "text/css"))
(when/null (or js-url js-body js)
(html:meta :http-equiv "Content-Script-Type"
:content "text/javascript"))
(when/null robots
(html:meta :name "ROBOTS"
:content robots))
;; titleの優先順位は、titleよりもtitle-formatの方を優先する
(or
(and
title-format
(guard (e (else #f))
(html:title
(hes
(apply format #f title-format title-format-args)))))
(when/null title
(html:title (hes title))))
(when/null css-url
(html:link :rel "Stylesheet"
:type "text/css"
:href css-url))
(when/null css-body
(html:style :type "text/css"
"<!--\n"
css-body
"\n-->"
))
(when/null js-url
(html:script :type "text/javascript"
:src js-url
""))
(when/null js-body
(html:script :type "text/javascript"
"<!--\n"
js-body
"\n-->"
))
)
(when/null body
(html:body
(when/null body-header body-header)
body
(when/null body-footer body-footer)
))
(when/null frame-body
frame-body)
))))
(define *http-tree-keyword-symbols*
;; まだ
'(
))
(define (http-tree-make . keywords)
;; 未実装
(error "not implemented"))
(define *cgi-tree-keyword-symbols*
'(encoding
content-type
location
http-header
http-body
body
frame-body
))
(define (cgi-tree-make . keywords)
(let-keywords** keywords *cgi-tree-keyword-symbols*
(if location
(apply
cgi-header
:pragma "no-cache"
:cache-control "no-cache"
:location location
(or http-header '()))
(let (
(content-type-is-text (and
content-type
(#/^text\// content-type)))
(content-type-has-charset (and
content-type
(string-scan content-type #\;)))
(true-content-type (or content-type "text/html"))
)
(list
(apply
cgi-header
:content-type (if content-type-has-charset
true-content-type
(if (not encoding)
true-content-type
(string-append
true-content-type
"; charset="
encoding)))
(or http-header '()))
(cond
(http-body http-body)
((or body frame-body) (apply html-tree-make keywords))
(else
(error
(string-append
"cgi-tree-make must be needed "
":location or :body or :frame-body or :http-body")))))))))
(define (uniq src-list)
;; note: 今のところ、eq?でのみ判定を行う仕様とする
(let loop ((left src-list)
(result '()))
(if (null? left)
result
(loop
(cdr left)
(if (memq (car left) result)
result
(cons (car left) result))))))
(define-syntax define-get-*-tree-keyword-symbols
(syntax-rules ()
((_ proc-name target-list)
(define proc-name
(let1 promise (delay (uniq target-list))
(lambda ()
(force promise)))))))
(define (get-html-tree-keyword-symbols)
*html-tree-keyword-symbols*)
(define-get-*-tree-keyword-symbols get-http-tree-keyword-symbols
(append
*html-tree-keyword-symbols*
*http-tree-keyword-symbols*))
(define-get-*-tree-keyword-symbols get-cgi-tree-keyword-symbols
(append
*html-tree-keyword-symbols*
*cgi-tree-keyword-symbols*))
(define (cgi-metavariables->html . opt-mv)
ToDo : 環境変数からもCGIメタ変数を取得する事 。
ToDo : tir04にバージョンを上げる際にオプショナル引数は廃止する
(let1 mv (get-optional opt-mv (cgi-metavariables))
(html:dl
(map (lambda (x)
(list
(html:dt (hes (car x)))
(html:dd (hes (cadr x)))))
(sort
(or mv '())
(lambda (x y)
(string<? (car x) (car y))))))))
(define (cgi-params->html params)
;; まず、paramsからエンコーディングを推測する
;; formにバイナリデータが入っている事は、ここでは考えない。
(let1 ces (ces-guess-from-string (tree->string params) "*JP")
(html:dl
(map
(lambda (x)
(list
(html:dt (hes (ces-convert (car x) ces)))
(map
(lambda (y)
(html:dd (hes (ces-convert (x->string y) ces))))
(cdr x))))
params))))
;; キーワード引数を与えて、CGIメタ変数をhtmlとして表示するだけの
;; CGIスクリプトthunkを生成する高階関数。
;; 通常は:css-url :robots :title :back-urlを与えれば充分。
( ※:titleに日本語を使う場合は、 :
;; 但し、現在はまだform入力の自動日本語コード変換に対応していないので、
;; :encodingは使わない方が良い)
;; 環境変数は表示しない。
ToDo : form - parameterの自動日本語コード変換機能
(define (make-view-cgi-metavariables-thunk . keywords)
(let-keywords* keywords ((encoding #f)
(on-error #f)
(content-type (if encoding
#`"text/html; charset=,|encoding|"
"text/html"))
(back-url #f)
)
(lambda ()
(cgi-main
(lambda (params)
(define back-url-html
(or
(and
back-url
(html:ul
(html:li
(html:a
:href back-url
"back"))))
'()))
(define back-url-html-separator
(if (null? back-url-html)
'()
(html:hr)))
(define (make-html-body)
(list
back-url-html
back-url-html-separator
(html:h1
:class "inline_centering"
(hes (get-keyword :title keywords "cgi-metavariables"))
)
(cgi-metavariables->html (cgi-metavariables))
back-url-html-separator
back-url-html
))
;; 結果をtext.treeとして返す
(apply
cgi-tree-make
:content-type content-type
:body (make-html-body)
keywords))
:on-error on-error))))
(define (append-params-to-url url params)
(if (null? params)
url
(receive (url-without-fragment fragment) (let1 m (#/(\#.*)/ url)
(if m
(values (m 'before) (m 1))
(values url "")))
(call-with-output-string
(lambda (p)
(letrec ((delimitee (if (#/\?/ url-without-fragment)
(lambda () "&")
(lambda ()
(set! delimitee (lambda () "&"))
"?"))))
(display url-without-fragment p)
(let loop ((left-params params))
(if (null? left-params)
(display fragment p)
(let ((key-encoded (uri-encode-string (caar left-params)))
(vals (cdar left-params))
(next-left (cdr left-params))
)
(if (pair? vals)
(for-each
(lambda (val)
(display (delimitee) p) ; "?" or "&"
(display key-encoded p)
(display "=" p)
(display (uri-encode-string (if (string? val) val "")) p))
vals)
(begin
(display (delimitee) p)
(display key-encoded p)))
(loop next-left))))))))))
(define (completion-uri uri server-name server-port https)
(receive (uri-scheme
uri-userinfo
uri-hostname
uri-port
uri-path
uri-query
uri-fragment)
(uri-parse uri)
;; uri-schemeが無い時にだけ補完する
;; 但し、server-nameが与えられていない場合は補完できないので、何もしない
(if (or uri-scheme (not server-name))
uri
(let* ((scheme (if https "https" "http"))
(default-port (if https 443 80))
)
(uri-compose
:scheme scheme
:userinfo uri-userinfo
:host server-name
:port (and
server-port
(not (eqv? default-port (x->number server-port)))
server-port)
:path uri-path
:query uri-query
:flagment uri-fragment)))))
(define (path->url path)
(if (#/^\// path)
(completion-uri
path
(cgi-get-metavariable "SERVER_NAME")
(cgi-get-metavariable "SERVER_PORT")
(cgi-get-metavariable "HTTPS"))
path))
(define (location url)
(define (chop-url-fragment url)
(or
(and-let* ((m (#/\#/ url)))
(m 'before))
url))
(cgi-header
:pragma "no-cache"
:cache-control "no-cache"
:location (chop-url-fragment (path->url url))))
(define (self-url)
(path->url (self-path)))
(define (self-url/path-info)
(path->url (self-path/path-info)))
(define (self-path)
(or (cgi-get-metavariable "SCRIPT_NAME") "/"))
(define (self-path/path-info)
;; note: PATH_INFOは既にデコードされてしまっているので使わない事
(let* ((r (or (cgi-get-metavariable "REQUEST_URI") "/"))
(m (#/\?/ r))
)
(if m
(m 'before)
r)))
(define (make-form url hidden-params html-tree . keywords)
(apply
html:form
:action url
(append
keywords
(list
:method "post"
:target "_self")
(map
(lambda (key+vals)
(let1 key (car key+vals)
(map
(lambda (val)
(html:input
:type "hidden"
:name key
:value val))
(cdr key+vals))))
hidden-params)
html-tree)))
(define (cgi-on-error/stack-trace e)
`(,(cgi-header)
,(html-doctype)
,(html:html
(html:head (html:title "Error"))
(html:body (html:h1 "Error")
(html:pre (html-escape-string
(call-with-output-string
(cut
with-error-to-port
<>
(cut report-error e)))))))))
ToDo : ファイルアップロードの際に問題が発生する可能性があるので 、
;; 更に細かくパターンを分ける必要がある。
(define (cgi-main/jp proc . keywords)
(define (reconv-params params)
(let* ((guess-string (tree->string params))
(ces (or
(ces-guess-from-string guess-string "*JP")
(cgi-output-character-encoding)))) ; fallback
(define (conv str)
(ces-convert str ces))
(map
(lambda (key+vals)
(cons
(conv (car key+vals))
(map
(lambda (val)
(if (string? val)
(conv val)
val))
(cdr key+vals))))
params)))
(apply
cgi-main
(lambda (params)
(let1 new-params (reconv-params params)
(proc new-params)))
keywords))
(define (c/p proc-cgi-main target-proc keywords)
(let ((path-info-keylist (get-path-info-keylist))
(request-method (cgi-get-metavariable "REQUEST_METHOD")))
path - info - keylistが#fなら、一旦リダイレクトを行う 。
;; 但し、メタ変数REQUEST_METHODがPOSTなら、リダイレクトは行わない。
;; (通常通り、procを実行する)
(apply
proc-cgi-main
(lambda (params)
(if (or
path-info-keylist
(equal? request-method "POST"))
(proc params path-info-keylist)
(location
(append-params-to-url (string-append (self-url) "/") params)))))))
(define (cgi-main/path proc . keywords)
(c/p cgi-main proc keywords))
(define (cgi-main/path/jp proc . keywords)
(c/p cgi-main/jp proc keywords))
(define cgi-main/jp/path cgi-main/path/jp)
(define (html:form/jp . args)
(apply
html:form
(append args
(html:input :type "hidden"
:name "_ces_identifier"
:value "日本語"))))
(define (get-path-info-keylist)
;; それぞれの場合で、以下のような値を返す。%xxのデコードは行わない。
;; (%xxのデコードを行わないのは、セキュリティ上の安全の為)
;; - /path/to/hoge.cgi => #f
;; - /path/to/hoge.cgi/ => '()
;; - /path/to/hoge.cgi/?abc=def => '()
- /path / to / hoge.cgi / abc / def = > ' ( " abc " " def " )
- /path / to / hoge.cgi / abc / def/ = > ' ( " abc " " def " )
;; - /path/to/hoge.cgi/%20 => '("%20")
;; - /path/to/hoge.cgi/a///b => '("a" "" "" "b")
;; WARN: apache2系の古いバージョンでは、PATH_INFO部分にスラッシュが複数
;; 連続して存在する場合に、SCRIPT_NAMEが壊れるというバグがあるので、
;; そういうバージョンではスラッシュが複数連続するようなアクセスが
;; 来ないようにしなくてはならない。
;; (基本的に、セキュリティ的には問題は無いと思うので、
;; 特に対策コードは入れたりはしない予定。)
;; WARN: 今のところ、「REQUEST_URIは、常にSCRIPT_NAMEをprefixとして含む」
;; という事を前提としている。
;; 「~」が「%7e」にされたり、大文字小文字を同一視するようなhttpdでは
;; 問題になるので注意する事。
;; ToDo: %7eや%7E等があっても正常に動作するようにしなくてはならない
;; ToDo: REQUEST_URIの末尾に?が無くて#があった場合の挙動対応
(define (path-info-split path)
(and-let* ((m (#/^\/(.*?)\/?$/ path))
(plain-path (m 1))) ; 先頭と末尾の/を除去
(if (string=? plain-path "")
'()
(string-split plain-path #\/))))
(and-let* ((script-name (cgi-get-metavariable "SCRIPT_NAME"))
(request-uri (cgi-get-metavariable "REQUEST_URI"))
(re (string->regexp
(string-append "^" (regexp-quote script-name))))
(m (re request-uri))
(path-info+query (m 'after))
(result (or
(and-let* ((m (#/\?/ path-info+query)))
(m 'before))
path-info+query)))
(if (string=? result "")
#f
(path-info-split result))))
(define (with-reverse-proxy server-name server-port thunk)
(parameterize ((cgi-metavariables
(list*
`("SERVER_NAME" ,(x->string server-name))
`("SERVER_PORT" ,(x->string server-port))
(remove
(lambda (key+val)
(or
(string=? (car key+val) "SERVER_NAME")
(string=? (car key+val) "SERVER_PORT")
))
(or (cgi-metavariables) '())))))
(thunk)))
(provide "tir03/cgi")
| null | https://raw.githubusercontent.com/ayamada/copy-of-svn.tir.jp/101cd00d595ee7bb96348df54f49707295e9e263/Gauche-tir/branches/Gauche-tir03/0.0.3/lib/tir03/cgi.scm | scheme | coding: euc-jp
-*- scheme -*-
vim:set ft=scheme ts=8 sts=2 sw=2 et:
ToDo: cgi-mainの内側か外側か判定可能な何かが無いかどうか確認し、
可能なら、locationは内側でも外側でも機能するように直す事。
- location手続きは対応済み
- webサーバにhoge.cgi#abc等のアクセスが来た際に、
(本来はwebサーバが行うべき???)
- どうしても#付きurlにリダイレクトしたい時の為に、
meta http-equiv="Refresh"
-- 更に、副作用を伴う動作後に上記リダイレクトを行わせたい時の為に、
locationでリダイレクト→meta http-equiv="Refresh"でリダイレクト
- 今のところは必要な場面は無いので、必要な場面が出たら作る。
ToDo: http-tree-makeを書きましょう。
このマクロはものすごく微妙なので、あとでもっとマシな方法を考えて直す事
xml header
html doctype
html
titleの優先順位は、titleよりもtitle-formatの方を優先する
まだ
未実装
)))
note: 今のところ、eq?でのみ判定を行う仕様とする
まず、paramsからエンコーディングを推測する
formにバイナリデータが入っている事は、ここでは考えない。
キーワード引数を与えて、CGIメタ変数をhtmlとして表示するだけの
CGIスクリプトthunkを生成する高階関数。
通常は:css-url :robots :title :back-urlを与えれば充分。
但し、現在はまだform入力の自動日本語コード変換に対応していないので、
:encodingは使わない方が良い)
環境変数は表示しない。
結果をtext.treeとして返す
"?" or "&"
uri-schemeが無い時にだけ補完する
但し、server-nameが与えられていない場合は補完できないので、何もしない
note: PATH_INFOは既にデコードされてしまっているので使わない事
更に細かくパターンを分ける必要がある。
fallback
但し、メタ変数REQUEST_METHODがPOSTなら、リダイレクトは行わない。
(通常通り、procを実行する)
それぞれの場合で、以下のような値を返す。%xxのデコードは行わない。
(%xxのデコードを行わないのは、セキュリティ上の安全の為)
- /path/to/hoge.cgi => #f
- /path/to/hoge.cgi/ => '()
- /path/to/hoge.cgi/?abc=def => '()
- /path/to/hoge.cgi/%20 => '("%20")
- /path/to/hoge.cgi/a///b => '("a" "" "" "b")
WARN: apache2系の古いバージョンでは、PATH_INFO部分にスラッシュが複数
連続して存在する場合に、SCRIPT_NAMEが壊れるというバグがあるので、
そういうバージョンではスラッシュが複数連続するようなアクセスが
来ないようにしなくてはならない。
(基本的に、セキュリティ的には問題は無いと思うので、
特に対策コードは入れたりはしない予定。)
WARN: 今のところ、「REQUEST_URIは、常にSCRIPT_NAMEをprefixとして含む」
という事を前提としている。
「~」が「%7e」にされたり、大文字小文字を同一視するようなhttpdでは
問題になるので注意する事。
ToDo: %7eや%7E等があっても正常に動作するようにしなくてはならない
ToDo: REQUEST_URIの末尾に?が無くて#があった場合の挙動対応
先頭と末尾の/を除去 | $ Id$
ToDo : 雑多になってきたので、モジュール名をtir03.cgi.miscにする ?
ToDo : location時の#の扱い
でリダイレクトさせるhtml - treeを返す手続きを用意する 。
ToDo : test caseを用意
ToDo : text->inline - html text->block - html関数を追加する事 。
(define-module tir03.cgi
(use gauche.charconv)
(use gauche.parameter)
(use srfi-1)
(use srfi-2)
(use rfc.uri)
(use text.html-lite)
(use text.tree)
(use util.list)
(use www.cgi)
(export
hes
html-tree-make
http-tree-make
cgi-tree-make
get-html-tree-keyword-symbols
get-http-tree-keyword-symbols
get-cgi-tree-keyword-symbols
cgi-metavariables->html
cgi-params->html
make-view-cgi-metavariables-thunk
append-params-to-url
completion-uri
path->url
location
self-url
self-url/path-info
self-path
self-path/path-info
make-form
cgi-on-error/stack-trace
cgi-main/jp
cgi-main/path
cgi-main/path/jp
cgi-main/jp/path
html:form/jp
get-path-info-keylist
with-reverse-proxy
))
(select-module tir03.cgi)
(define (hes . params)
(if (= 1 (length params))
(html-escape-string (car params))
(map html-escape-string params)))
(define-syntax when/null
(syntax-rules ()
((_ pred body ...) (if pred
(begin body ...)
'()))))
(define-macro (let-keywords** keywords tree-keyword-symbols body . bodies)
`(let-keywords* keywords ,(map
(lambda (x)
(list x #f))
(eval tree-keyword-symbols (current-module)))
,body . ,bodies))
(define *html-tree-keyword-symbols*
'(encoding
base-url
css-url
css-body
js-url
js-body
js
robots
title
title-format
title-format-args
body
body-header
body-footer
frame-body
))
(define (html-tree-make . keywords)
(let-keywords** keywords *html-tree-keyword-symbols*
(list
(if encoding
#`"<?xml version=\"1.0\" encoding=\",|encoding|\"?>\n"
"<?xml version=\"1.0\"?>\n")
(html-doctype
:type (if frame-body
:xhtml-1.0-frameset
:xhtml-1.0-transitional))
(html:html
:lang "ja-JP"
:xml:lang "ja-JP"
:xmlns ""
(html:head
(when/null encoding
(html:meta :http-equiv "Content-Type"
:content #`"text/html; charset=,|encoding|"))
(when/null base-url
(html:base :href base-url))
(when/null (or css-url css-body)
(html:meta :http-equiv "Content-Style-Type"
:content "text/css"))
(when/null (or js-url js-body js)
(html:meta :http-equiv "Content-Script-Type"
:content "text/javascript"))
(when/null robots
(html:meta :name "ROBOTS"
:content robots))
(or
(and
title-format
(guard (e (else #f))
(html:title
(hes
(apply format #f title-format title-format-args)))))
(when/null title
(html:title (hes title))))
(when/null css-url
(html:link :rel "Stylesheet"
:type "text/css"
:href css-url))
(when/null css-body
(html:style :type "text/css"
"<!--\n"
css-body
"\n-->"
))
(when/null js-url
(html:script :type "text/javascript"
:src js-url
""))
(when/null js-body
(html:script :type "text/javascript"
"<!--\n"
js-body
"\n-->"
))
)
(when/null body
(html:body
(when/null body-header body-header)
body
(when/null body-footer body-footer)
))
(when/null frame-body
frame-body)
))))
(define *http-tree-keyword-symbols*
'(
))
(define (http-tree-make . keywords)
(error "not implemented"))
(define *cgi-tree-keyword-symbols*
'(encoding
content-type
location
http-header
http-body
body
frame-body
))
(define (cgi-tree-make . keywords)
(let-keywords** keywords *cgi-tree-keyword-symbols*
(if location
(apply
cgi-header
:pragma "no-cache"
:cache-control "no-cache"
:location location
(or http-header '()))
(let (
(content-type-is-text (and
content-type
(#/^text\// content-type)))
(content-type-has-charset (and
content-type
(true-content-type (or content-type "text/html"))
)
(list
(apply
cgi-header
:content-type (if content-type-has-charset
true-content-type
(if (not encoding)
true-content-type
(string-append
true-content-type
"; charset="
encoding)))
(or http-header '()))
(cond
(http-body http-body)
((or body frame-body) (apply html-tree-make keywords))
(else
(error
(string-append
"cgi-tree-make must be needed "
":location or :body or :frame-body or :http-body")))))))))
(define (uniq src-list)
(let loop ((left src-list)
(result '()))
(if (null? left)
result
(loop
(cdr left)
(if (memq (car left) result)
result
(cons (car left) result))))))
(define-syntax define-get-*-tree-keyword-symbols
(syntax-rules ()
((_ proc-name target-list)
(define proc-name
(let1 promise (delay (uniq target-list))
(lambda ()
(force promise)))))))
(define (get-html-tree-keyword-symbols)
*html-tree-keyword-symbols*)
(define-get-*-tree-keyword-symbols get-http-tree-keyword-symbols
(append
*html-tree-keyword-symbols*
*http-tree-keyword-symbols*))
(define-get-*-tree-keyword-symbols get-cgi-tree-keyword-symbols
(append
*html-tree-keyword-symbols*
*cgi-tree-keyword-symbols*))
(define (cgi-metavariables->html . opt-mv)
ToDo : 環境変数からもCGIメタ変数を取得する事 。
ToDo : tir04にバージョンを上げる際にオプショナル引数は廃止する
(let1 mv (get-optional opt-mv (cgi-metavariables))
(html:dl
(map (lambda (x)
(list
(html:dt (hes (car x)))
(html:dd (hes (cadr x)))))
(sort
(or mv '())
(lambda (x y)
(string<? (car x) (car y))))))))
(define (cgi-params->html params)
(let1 ces (ces-guess-from-string (tree->string params) "*JP")
(html:dl
(map
(lambda (x)
(list
(html:dt (hes (ces-convert (car x) ces)))
(map
(lambda (y)
(html:dd (hes (ces-convert (x->string y) ces))))
(cdr x))))
params))))
( ※:titleに日本語を使う場合は、 :
ToDo : form - parameterの自動日本語コード変換機能
(define (make-view-cgi-metavariables-thunk . keywords)
(let-keywords* keywords ((encoding #f)
(on-error #f)
(content-type (if encoding
#`"text/html; charset=,|encoding|"
"text/html"))
(back-url #f)
)
(lambda ()
(cgi-main
(lambda (params)
(define back-url-html
(or
(and
back-url
(html:ul
(html:li
(html:a
:href back-url
"back"))))
'()))
(define back-url-html-separator
(if (null? back-url-html)
'()
(html:hr)))
(define (make-html-body)
(list
back-url-html
back-url-html-separator
(html:h1
:class "inline_centering"
(hes (get-keyword :title keywords "cgi-metavariables"))
)
(cgi-metavariables->html (cgi-metavariables))
back-url-html-separator
back-url-html
))
(apply
cgi-tree-make
:content-type content-type
:body (make-html-body)
keywords))
:on-error on-error))))
(define (append-params-to-url url params)
(if (null? params)
url
(receive (url-without-fragment fragment) (let1 m (#/(\#.*)/ url)
(if m
(values (m 'before) (m 1))
(values url "")))
(call-with-output-string
(lambda (p)
(letrec ((delimitee (if (#/\?/ url-without-fragment)
(lambda () "&")
(lambda ()
(set! delimitee (lambda () "&"))
"?"))))
(display url-without-fragment p)
(let loop ((left-params params))
(if (null? left-params)
(display fragment p)
(let ((key-encoded (uri-encode-string (caar left-params)))
(vals (cdar left-params))
(next-left (cdr left-params))
)
(if (pair? vals)
(for-each
(lambda (val)
(display key-encoded p)
(display "=" p)
(display (uri-encode-string (if (string? val) val "")) p))
vals)
(begin
(display (delimitee) p)
(display key-encoded p)))
(loop next-left))))))))))
(define (completion-uri uri server-name server-port https)
(receive (uri-scheme
uri-userinfo
uri-hostname
uri-port
uri-path
uri-query
uri-fragment)
(uri-parse uri)
(if (or uri-scheme (not server-name))
uri
(let* ((scheme (if https "https" "http"))
(default-port (if https 443 80))
)
(uri-compose
:scheme scheme
:userinfo uri-userinfo
:host server-name
:port (and
server-port
(not (eqv? default-port (x->number server-port)))
server-port)
:path uri-path
:query uri-query
:flagment uri-fragment)))))
(define (path->url path)
(if (#/^\// path)
(completion-uri
path
(cgi-get-metavariable "SERVER_NAME")
(cgi-get-metavariable "SERVER_PORT")
(cgi-get-metavariable "HTTPS"))
path))
(define (location url)
(define (chop-url-fragment url)
(or
(and-let* ((m (#/\#/ url)))
(m 'before))
url))
(cgi-header
:pragma "no-cache"
:cache-control "no-cache"
:location (chop-url-fragment (path->url url))))
(define (self-url)
(path->url (self-path)))
(define (self-url/path-info)
(path->url (self-path/path-info)))
(define (self-path)
(or (cgi-get-metavariable "SCRIPT_NAME") "/"))
(define (self-path/path-info)
(let* ((r (or (cgi-get-metavariable "REQUEST_URI") "/"))
(m (#/\?/ r))
)
(if m
(m 'before)
r)))
(define (make-form url hidden-params html-tree . keywords)
(apply
html:form
:action url
(append
keywords
(list
:method "post"
:target "_self")
(map
(lambda (key+vals)
(let1 key (car key+vals)
(map
(lambda (val)
(html:input
:type "hidden"
:name key
:value val))
(cdr key+vals))))
hidden-params)
html-tree)))
(define (cgi-on-error/stack-trace e)
`(,(cgi-header)
,(html-doctype)
,(html:html
(html:head (html:title "Error"))
(html:body (html:h1 "Error")
(html:pre (html-escape-string
(call-with-output-string
(cut
with-error-to-port
<>
(cut report-error e)))))))))
ToDo : ファイルアップロードの際に問題が発生する可能性があるので 、
(define (cgi-main/jp proc . keywords)
(define (reconv-params params)
(let* ((guess-string (tree->string params))
(ces (or
(ces-guess-from-string guess-string "*JP")
(define (conv str)
(ces-convert str ces))
(map
(lambda (key+vals)
(cons
(conv (car key+vals))
(map
(lambda (val)
(if (string? val)
(conv val)
val))
(cdr key+vals))))
params)))
(apply
cgi-main
(lambda (params)
(let1 new-params (reconv-params params)
(proc new-params)))
keywords))
(define (c/p proc-cgi-main target-proc keywords)
(let ((path-info-keylist (get-path-info-keylist))
(request-method (cgi-get-metavariable "REQUEST_METHOD")))
path - info - keylistが#fなら、一旦リダイレクトを行う 。
(apply
proc-cgi-main
(lambda (params)
(if (or
path-info-keylist
(equal? request-method "POST"))
(proc params path-info-keylist)
(location
(append-params-to-url (string-append (self-url) "/") params)))))))
(define (cgi-main/path proc . keywords)
(c/p cgi-main proc keywords))
(define (cgi-main/path/jp proc . keywords)
(c/p cgi-main/jp proc keywords))
(define cgi-main/jp/path cgi-main/path/jp)
(define (html:form/jp . args)
(apply
html:form
(append args
(html:input :type "hidden"
:name "_ces_identifier"
:value "日本語"))))
(define (get-path-info-keylist)
- /path / to / hoge.cgi / abc / def = > ' ( " abc " " def " )
- /path / to / hoge.cgi / abc / def/ = > ' ( " abc " " def " )
(define (path-info-split path)
(and-let* ((m (#/^\/(.*?)\/?$/ path))
(if (string=? plain-path "")
'()
(string-split plain-path #\/))))
(and-let* ((script-name (cgi-get-metavariable "SCRIPT_NAME"))
(request-uri (cgi-get-metavariable "REQUEST_URI"))
(re (string->regexp
(string-append "^" (regexp-quote script-name))))
(m (re request-uri))
(path-info+query (m 'after))
(result (or
(and-let* ((m (#/\?/ path-info+query)))
(m 'before))
path-info+query)))
(if (string=? result "")
#f
(path-info-split result))))
(define (with-reverse-proxy server-name server-port thunk)
(parameterize ((cgi-metavariables
(list*
`("SERVER_NAME" ,(x->string server-name))
`("SERVER_PORT" ,(x->string server-port))
(remove
(lambda (key+val)
(or
(string=? (car key+val) "SERVER_NAME")
(string=? (car key+val) "SERVER_PORT")
))
(or (cgi-metavariables) '())))))
(thunk)))
(provide "tir03/cgi")
|
631341defdaed40dbe552a78877a878536052021dadda05363beaf117555010c | MyDataFlow/ttalk-server | cow_qs.erl | Copyright ( c ) 2013 - 2014 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(cow_qs).
-export([parse_qs/1]).
-export([qs/1]).
-export([urldecode/1]).
-export([urlencode/1]).
-type qs_vals() :: [{binary(), binary() | true}].
@doc an application / x - www - form - urlencoded string .
%%
%% The percent decoding is inlined to greatly improve the performance
%% by avoiding copying binaries twice (once for extracting, once for
%% decoding) instead of just extracting the proper representation.
-spec parse_qs(binary()) -> qs_vals().
parse_qs(B) ->
parse_qs_name(B, [], <<>>).
, H , L , Rest / bits > > , Acc , Name ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
parse_qs_name(Rest, Acc, << Name/bits, C >>);
parse_qs_name(<< $+, Rest/bits >>, Acc, Name) ->
parse_qs_name(Rest, Acc, << Name/bits, " " >>);
parse_qs_name(<< $=, Rest/bits >>, Acc, Name) when Name =/= <<>> ->
parse_qs_value(Rest, Acc, Name, <<>>);
parse_qs_name(<< $&, Rest/bits >>, Acc, Name) ->
case Name of
<<>> -> parse_qs_name(Rest, Acc, <<>>);
_ -> parse_qs_name(Rest, [{Name, true}|Acc], <<>>)
end;
parse_qs_name(<< C, Rest/bits >>, Acc, Name) when C =/= $%, C =/= $= ->
parse_qs_name(Rest, Acc, << Name/bits, C >>);
parse_qs_name(<<>>, Acc, Name) ->
case Name of
<<>> -> lists:reverse(Acc);
_ -> lists:reverse([{Name, true}|Acc])
end.
, H , L , Rest / bits > > , Acc , Name , Value ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
parse_qs_value(Rest, Acc, Name, << Value/bits, C >>);
parse_qs_value(<< $+, Rest/bits >>, Acc, Name, Value) ->
parse_qs_value(Rest, Acc, Name, << Value/bits, " " >>);
parse_qs_value(<< $&, Rest/bits >>, Acc, Name, Value) ->
parse_qs_name(Rest, [{Name, Value}|Acc], <<>>);
parse_qs_value(<< C, Rest/bits >>, Acc, Name, Value) when C =/= $% ->
parse_qs_value(Rest, Acc, Name, << Value/bits, C >>);
parse_qs_value(<<>>, Acc, Name, Value) ->
lists:reverse([{Name, Value}|Acc]).
-ifdef(TEST).
parse_qs_test_() ->
Tests = [
{<<>>, []},
{<<"&">>, []},
{<<"a">>, [{<<"a">>, true}]},
{<<"a&">>, [{<<"a">>, true}]},
{<<"&a">>, [{<<"a">>, true}]},
{<<"a&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"a&&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"a&b&">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"=">>, error},
{<<"=b">>, error},
{<<"a=">>, [{<<"a">>, <<>>}]},
{<<"a=b">>, [{<<"a">>, <<"b">>}]},
{<<"a=&b=">>, [{<<"a">>, <<>>}, {<<"b">>, <<>>}]},
{<<"a=b&c&d=e">>, [{<<"a">>, <<"b">>},
{<<"c">>, true}, {<<"d">>, <<"e">>}]},
{<<"a=b=c&d=e=f&g=h=i">>, [{<<"a">>, <<"b=c">>},
{<<"d">>, <<"e=f">>}, {<<"g">>, <<"h=i">>}]},
{<<"+">>, [{<<" ">>, true}]},
{<<"+=+">>, [{<<" ">>, <<" ">>}]},
{<<"a+b=c+d">>, [{<<"a b">>, <<"c d">>}]},
{<<"+a+=+b+&+c+=+d+">>, [{<<" a ">>, <<" b ">>},
{<<" c ">>, <<" d ">>}]},
{<<"a%20b=c%20d">>, [{<<"a b">>, <<"c d">>}]},
{<<"%25%26%3D=%25%26%3D&_-.=.-_">>, [{<<"%&=">>, <<"%&=">>},
{<<"_-.">>, <<".-_">>}]},
{<<"for=extend%2Franch">>, [{<<"for">>, <<"extend/ranch">>}]}
],
[{Qs, fun() ->
E = try parse_qs(Qs) of
R -> R
catch _:_ ->
error
end
end} || {Qs, E} <- Tests].
parse_qs_identity_test_() ->
Tests = [
<<"+">>,
<<"hl=en&q=erlang+cowboy">>,
<<"direction=desc&for=extend%2Franch&sort=updated&state=open">>,
<<"i=EWiIXmPj5gl6&v=QowBp0oDLQXdd4x_GwiywA&ip=98.20.31.81&"
"la=en&pg=New8.undertonebrandsafe.com%2F698a2525065ee2"
"60c0b2f2aaad89ab82&re=&sz=1&fc=1&fr=140&br=3&bv=11.0."
"696.16&os=3&ov=&rs=vpl&k=cookies%7Csale%7Cbrowser%7Cm"
"ore%7Cprivacy%7Cstatistics%7Cactivities%7Cauction%7Ce"
"mail%7Cfree%7Cin...&t=112373&xt=5%7C61%7C0&tz=-1&ev=x"
"&tk=&za=1&ortb-za=1&zu=&zl=&ax=U&ay=U&ortb-pid=536454"
".55&ortb-sid=112373.8&seats=999&ortb-xt=IAB24&ortb-ugc=">>,
<<"i=9pQNskA&v=0ySQQd1F&ev=12345678&t=12345&sz=3&ip=67.58."
"236.89&la=en&pg=http%3A%2F%2Fwww.yahoo.com%2Fpage1.ht"
"m&re=http%3A%2F%2Fsearch.google.com&fc=1&fr=1&br=2&bv"
"=3.0.14&os=1&ov=XP&k=cars%2Cford&rs=js&xt=5%7C22%7C23"
"4&tz=%2B180&tk=key1%3Dvalue1%7Ckey2%3Dvalue2&zl=4%2C5"
"%2C6&za=4&zu=competitor.com&ua=Mozilla%2F5.0+%28Windo"
"ws%3B+U%3B+Windows+NT+6.1%3B+en-US%29+AppleWebKit%2F5"
"34.13+%28KHTML%2C+like+Gecko%29+Chrome%2F9.0.597.98+S"
"afari%2F534.13&ortb-za=1%2C6%2C13&ortb-pid=521732&ort"
"b-sid=521732&ortb-xt=IAB3&ortb-ugc=">>
],
[{V, fun() -> V = qs(parse_qs(V)) end} || V <- Tests].
-endif.
-ifdef(PERF).
horse_parse_qs_shorter() ->
horse:repeat(20000,
parse_qs(<<"hl=en&q=erlang%20cowboy">>)
).
horse_parse_qs_short() ->
horse:repeat(20000,
parse_qs(
<<"direction=desc&for=extend%2Franch&sort=updated&state=open">>)
).
horse_parse_qs_long() ->
horse:repeat(20000,
parse_qs(<<"i=EWiIXmPj5gl6&v=QowBp0oDLQXdd4x_GwiywA&ip=98.20.31.81&"
"la=en&pg=New8.undertonebrandsafe.com%2F698a2525065ee260c0b2f2a"
"aad89ab82&re=&sz=1&fc=1&fr=140&br=3&bv=11.0.696.16&os=3&ov=&rs"
"=vpl&k=cookies%7Csale%7Cbrowser%7Cmore%7Cprivacy%7Cstatistics%"
"7Cactivities%7Cauction%7Cemail%7Cfree%7Cin...&t=112373&xt=5%7C"
"61%7C0&tz=-1&ev=x&tk=&za=1&ortb-za=1&zu=&zl=&ax=U&ay=U&ortb-pi"
"d=536454.55&ortb-sid=112373.8&seats=999&ortb-xt=IAB24&ortb-ugc"
"=">>)
).
horse_parse_qs_longer() ->
horse:repeat(20000,
parse_qs(<<"i=9pQNskA&v=0ySQQd1F&ev=12345678&t=12345&sz=3&ip=67.58."
"236.89&la=en&pg=http%3A%2F%2Fwww.yahoo.com%2Fpage1.htm&re=http"
"%3A%2F%2Fsearch.google.com&fc=1&fr=1&br=2&bv=3.0.14&os=1&ov=XP"
"&k=cars%2cford&rs=js&xt=5%7c22%7c234&tz=%2b180&tk=key1%3Dvalue"
"1%7Ckey2%3Dvalue2&zl=4,5,6&za=4&zu=competitor.com&ua=Mozilla%2"
"F5.0%20(Windows%3B%20U%3B%20Windows%20NT%206.1%3B%20en-US)%20A"
"ppleWebKit%2F534.13%20(KHTML%2C%20like%20Gecko)%20Chrome%2F9.0"
".597.98%20Safari%2F534.13&ortb-za=1%2C6%2C13&ortb-pid=521732&o"
"rtb-sid=521732&ortb-xt=IAB3&ortb-ugc=">>)
).
-endif.
%% @doc Build an application/x-www-form-urlencoded string.
-spec qs(qs_vals()) -> binary().
qs([]) ->
<<>>;
qs(L) ->
qs(L, <<>>).
qs([], Acc) ->
<< $&, Qs/bits >> = Acc,
Qs;
qs([{Name, true}|Tail], Acc) ->
Acc2 = urlencode(Name, << Acc/bits, $& >>),
qs(Tail, Acc2);
qs([{Name, Value}|Tail], Acc) ->
Acc2 = urlencode(Name, << Acc/bits, $& >>),
Acc3 = urlencode(Value, << Acc2/bits, $= >>),
qs(Tail, Acc3).
-define(QS_SHORTER, [
{<<"hl">>, <<"en">>},
{<<"q">>, <<"erlang cowboy">>}
]).
-define(QS_SHORT, [
{<<"direction">>, <<"desc">>},
{<<"for">>, <<"extend/ranch">>},
{<<"sort">>, <<"updated">>},
{<<"state">>, <<"open">>}
]).
-define(QS_LONG, [
{<<"i">>, <<"EWiIXmPj5gl6">>},
{<<"v">>, <<"QowBp0oDLQXdd4x_GwiywA">>},
{<<"ip">>, <<"98.20.31.81">>},
{<<"la">>, <<"en">>},
{<<"pg">>, <<"New8.undertonebrandsafe.com/"
"698a2525065ee260c0b2f2aaad89ab82">>},
{<<"re">>, <<>>},
{<<"sz">>, <<"1">>},
{<<"fc">>, <<"1">>},
{<<"fr">>, <<"140">>},
{<<"br">>, <<"3">>},
{<<"bv">>, <<"11.0.696.16">>},
{<<"os">>, <<"3">>},
{<<"ov">>, <<>>},
{<<"rs">>, <<"vpl">>},
{<<"k">>, <<"cookies|sale|browser|more|privacy|statistics|"
"activities|auction|email|free|in...">>},
{<<"t">>, <<"112373">>},
{<<"xt">>, <<"5|61|0">>},
{<<"tz">>, <<"-1">>},
{<<"ev">>, <<"x">>},
{<<"tk">>, <<>>},
{<<"za">>, <<"1">>},
{<<"ortb-za">>, <<"1">>},
{<<"zu">>, <<>>},
{<<"zl">>, <<>>},
{<<"ax">>, <<"U">>},
{<<"ay">>, <<"U">>},
{<<"ortb-pid">>, <<"536454.55">>},
{<<"ortb-sid">>, <<"112373.8">>},
{<<"seats">>, <<"999">>},
{<<"ortb-xt">>, <<"IAB24">>},
{<<"ortb-ugc">>, <<>>}
]).
-define(QS_LONGER, [
{<<"i">>, <<"9pQNskA">>},
{<<"v">>, <<"0ySQQd1F">>},
{<<"ev">>, <<"12345678">>},
{<<"t">>, <<"12345">>},
{<<"sz">>, <<"3">>},
{<<"ip">>, <<"67.58.236.89">>},
{<<"la">>, <<"en">>},
{<<"pg">>, <<"">>},
{<<"re">>, <<"">>},
{<<"fc">>, <<"1">>},
{<<"fr">>, <<"1">>},
{<<"br">>, <<"2">>},
{<<"bv">>, <<"3.0.14">>},
{<<"os">>, <<"1">>},
{<<"ov">>, <<"XP">>},
{<<"k">>, <<"cars,ford">>},
{<<"rs">>, <<"js">>},
{<<"xt">>, <<"5|22|234">>},
{<<"tz">>, <<"+180">>},
{<<"tk">>, <<"key1=value1|key2=value2">>},
{<<"zl">>, <<"4,5,6">>},
{<<"za">>, <<"4">>},
{<<"zu">>, <<"competitor.com">>},
{<<"ua">>, <<"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) "
"AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 "
"Safari/534.13">>},
{<<"ortb-za">>, <<"1,6,13">>},
{<<"ortb-pid">>, <<"521732">>},
{<<"ortb-sid">>, <<"521732">>},
{<<"ortb-xt">>, <<"IAB3">>},
{<<"ortb-ugc">>, <<>>}
]).
-ifdef(TEST).
qs_test_() ->
Tests = [
{[<<"a">>], error},
{[{<<"a">>, <<"b">>, <<"c">>}], error},
{[], <<>>},
{[{<<"a">>, true}], <<"a">>},
{[{<<"a">>, true}, {<<"b">>, true}], <<"a&b">>},
{[{<<"a">>, <<>>}], <<"a=">>},
{[{<<"a">>, <<"b">>}], <<"a=b">>},
{[{<<"a">>, <<>>}, {<<"b">>, <<>>}], <<"a=&b=">>},
{[{<<"a">>, <<"b">>}, {<<"c">>, true}, {<<"d">>, <<"e">>}],
<<"a=b&c&d=e">>},
{[{<<"a">>, <<"b=c">>}, {<<"d">>, <<"e=f">>}, {<<"g">>, <<"h=i">>}],
<<"a=b%3Dc&d=e%3Df&g=h%3Di">>},
{[{<<" ">>, true}], <<"+">>},
{[{<<" ">>, <<" ">>}], <<"+=+">>},
{[{<<"a b">>, <<"c d">>}], <<"a+b=c+d">>},
{[{<<" a ">>, <<" b ">>}, {<<" c ">>, <<" d ">>}],
<<"+a+=+b+&+c+=+d+">>},
{[{<<"%&=">>, <<"%&=">>}, {<<"_-.">>, <<".-_">>}],
<<"%25%26%3D=%25%26%3D&_-.=.-_">>},
{[{<<"for">>, <<"extend/ranch">>}], <<"for=extend%2Franch">>}
],
[{lists:flatten(io_lib:format("~p", [Vals])), fun() ->
E = try qs(Vals) of
R -> R
catch _:_ ->
error
end
end} || {Vals, E} <- Tests].
qs_identity_test_() ->
Tests = [
[{<<"+">>, true}],
?QS_SHORTER,
?QS_SHORT,
?QS_LONG,
?QS_LONGER
],
[{lists:flatten(io_lib:format("~p", [V])), fun() ->
V = parse_qs(qs(V))
end} || V <- Tests].
-endif.
-ifdef(PERF).
horse_qs_shorter() ->
horse:repeat(20000, qs(?QS_SHORTER)).
horse_qs_short() ->
horse:repeat(20000, qs(?QS_SHORT)).
horse_qs_long() ->
horse:repeat(20000, qs(?QS_LONG)).
horse_qs_longer() ->
horse:repeat(20000, qs(?QS_LONGER)).
-endif.
%% @doc Decode a percent encoded string (x-www-form-urlencoded rules).
-spec urldecode(B) -> B when B::binary().
urldecode(B) ->
urldecode(B, <<>>).
, H , L , Rest / bits > > , Acc ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
urldecode(Rest, << Acc/bits, C >>);
urldecode(<< $+, Rest/bits >>, Acc) ->
urldecode(Rest, << Acc/bits, " " >>);
urldecode(<< C, Rest/bits >>, Acc) when C =/= $% ->
urldecode(Rest, << Acc/bits, C >>);
urldecode(<<>>, Acc) ->
Acc.
unhex($0) -> 0;
unhex($1) -> 1;
unhex($2) -> 2;
unhex($3) -> 3;
unhex($4) -> 4;
unhex($5) -> 5;
unhex($6) -> 6;
unhex($7) -> 7;
unhex($8) -> 8;
unhex($9) -> 9;
unhex($A) -> 10;
unhex($B) -> 11;
unhex($C) -> 12;
unhex($D) -> 13;
unhex($E) -> 14;
unhex($F) -> 15;
unhex($a) -> 10;
unhex($b) -> 11;
unhex($c) -> 12;
unhex($d) -> 13;
unhex($e) -> 14;
unhex($f) -> 15.
-ifdef(TEST).
urldecode_test_() ->
Tests = [
{<<"%20">>, <<" ">>},
{<<"+">>, <<" ">>},
{<<"%00">>, <<0>>},
{<<"%fF">>, <<255>>},
{<<"123">>, <<"123">>},
{<<"%i5">>, error},
{<<"%5">>, error}
],
[{Qs, fun() ->
E = try urldecode(Qs) of
R -> R
catch _:_ ->
error
end
end} || {Qs, E} <- Tests].
urldecode_identity_test_() ->
Tests = [
<<"+">>,
<<"nothingnothingnothingnothing">>,
<<"Small+fast+modular+HTTP+server">>,
<<"Small%2C+fast%2C+modular+HTTP+server.">>,
<<"%E3%83%84%E3%82%A4%E3%83%B3%E3%82%BD%E3%82%A6%E3%83"
"%AB%E3%80%9C%E8%BC%AA%E5%BB%BB%E3%81%99%E3%82%8B%E6%97%8B%E5"
"%BE%8B%E3%80%9C">>
],
[{V, fun() -> V = urlencode(urldecode(V)) end} || V <- Tests].
-endif.
-ifdef(PERF).
horse_urldecode() ->
horse:repeat(100000,
urldecode(<<"nothingnothingnothingnothing">>)
).
horse_urldecode_plus() ->
horse:repeat(100000,
urldecode(<<"Small+fast+modular+HTTP+server">>)
).
horse_urldecode_hex() ->
horse:repeat(100000,
urldecode(<<"Small%2C%20fast%2C%20modular%20HTTP%20server.">>)
).
horse_urldecode_jp_hex() ->
horse:repeat(100000,
urldecode(<<"%E3%83%84%E3%82%A4%E3%83%B3%E3%82%BD%E3%82%A6%E3%83"
"%AB%E3%80%9C%E8%BC%AA%E5%BB%BB%E3%81%99%E3%82%8B%E6%97%8B%E5"
"%BE%8B%E3%80%9C">>)
).
horse_urldecode_mix() ->
horse:repeat(100000,
urldecode(<<"Small%2C+fast%2C+modular+HTTP+server.">>)
).
-endif.
%% @doc Percent encode a string (x-www-form-urlencoded rules).
-spec urlencode(B) -> B when B::binary().
urlencode(B) ->
urlencode(B, <<>>).
urlencode(<< $\s, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $+ >>);
urlencode(<< $-, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $- >>);
urlencode(<< $., Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $. >>);
urlencode(<< $0, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $0 >>);
urlencode(<< $1, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $1 >>);
urlencode(<< $2, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $2 >>);
urlencode(<< $3, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $3 >>);
urlencode(<< $4, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $4 >>);
urlencode(<< $5, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $5 >>);
urlencode(<< $6, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $6 >>);
urlencode(<< $7, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $7 >>);
urlencode(<< $8, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $8 >>);
urlencode(<< $9, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $9 >>);
urlencode(<< $A, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $A >>);
urlencode(<< $B, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $B >>);
urlencode(<< $C, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $C >>);
urlencode(<< $D, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $D >>);
urlencode(<< $E, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $E >>);
urlencode(<< $F, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $F >>);
urlencode(<< $G, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $G >>);
urlencode(<< $H, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $H >>);
urlencode(<< $I, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $I >>);
urlencode(<< $J, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $J >>);
urlencode(<< $K, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $K >>);
urlencode(<< $L, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $L >>);
urlencode(<< $M, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $M >>);
urlencode(<< $N, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $N >>);
urlencode(<< $O, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $O >>);
urlencode(<< $P, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $P >>);
urlencode(<< $Q, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Q >>);
urlencode(<< $R, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $R >>);
urlencode(<< $S, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $S >>);
urlencode(<< $T, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $T >>);
urlencode(<< $U, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $U >>);
urlencode(<< $V, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $V >>);
urlencode(<< $W, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $W >>);
urlencode(<< $X, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $X >>);
urlencode(<< $Y, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Y >>);
urlencode(<< $Z, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Z >>);
urlencode(<< $_, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $_ >>);
urlencode(<< $a, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $a >>);
urlencode(<< $b, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $b >>);
urlencode(<< $c, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $c >>);
urlencode(<< $d, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $d >>);
urlencode(<< $e, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $e >>);
urlencode(<< $f, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $f >>);
urlencode(<< $g, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $g >>);
urlencode(<< $h, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $h >>);
urlencode(<< $i, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $i >>);
urlencode(<< $j, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $j >>);
urlencode(<< $k, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $k >>);
urlencode(<< $l, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $l >>);
urlencode(<< $m, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $m >>);
urlencode(<< $n, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $n >>);
urlencode(<< $o, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $o >>);
urlencode(<< $p, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $p >>);
urlencode(<< $q, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $q >>);
urlencode(<< $r, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $r >>);
urlencode(<< $s, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $s >>);
urlencode(<< $t, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $t >>);
urlencode(<< $u, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $u >>);
urlencode(<< $v, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $v >>);
urlencode(<< $w, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $w >>);
urlencode(<< $x, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $x >>);
urlencode(<< $y, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $y >>);
urlencode(<< $z, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $z >>);
urlencode(<< C, Rest/bits >>, Acc) ->
H = hex(C bsr 4),
L = hex(C band 16#0f),
urlencode(Rest, << Acc/bits, $%, H, L >>);
urlencode(<<>>, Acc) ->
Acc.
hex( 0) -> $0;
hex( 1) -> $1;
hex( 2) -> $2;
hex( 3) -> $3;
hex( 4) -> $4;
hex( 5) -> $5;
hex( 6) -> $6;
hex( 7) -> $7;
hex( 8) -> $8;
hex( 9) -> $9;
hex(10) -> $A;
hex(11) -> $B;
hex(12) -> $C;
hex(13) -> $D;
hex(14) -> $E;
hex(15) -> $F.
-ifdef(TEST).
urlencode_test_() ->
Tests = [
{<<255, 0>>, <<"%FF%00">>},
{<<255, " ">>, <<"%FF+">>},
{<<" ">>, <<"+">>},
{<<"aBc123">>, <<"aBc123">>},
{<<".-_">>, <<".-_">>}
],
[{V, fun() -> E = urlencode(V) end} || {V, E} <- Tests].
urlencode_identity_test_() ->
Tests = [
<<"+">>,
<<"nothingnothingnothingnothing">>,
<<"Small fast modular HTTP server">>,
<<"Small, fast, modular HTTP server.">>,
<<227,131,132,227,130,164,227,131,179,227,130,189,227,
130,166,227,131,171,227,128,156,232,188,170,229,187,187,227,
129,153,227,130,139,230,151,139,229,190,139,227,128,156>>
],
[{V, fun() -> V = urldecode(urlencode(V)) end} || V <- Tests].
-endif.
-ifdef(PERF).
horse_urlencode() ->
horse:repeat(100000,
urlencode(<<"nothingnothingnothingnothing">>)
).
horse_urlencode_plus() ->
horse:repeat(100000,
urlencode(<<"Small fast modular HTTP server">>)
).
horse_urlencode_jp() ->
horse:repeat(100000,
urlencode(<<227,131,132,227,130,164,227,131,179,227,130,189,227,
130,166,227,131,171,227,128,156,232,188,170,229,187,187,227,
129,153,227,130,139,230,151,139,229,190,139,227,128,156>>)
).
horse_urlencode_mix() ->
horse:repeat(100000,
urlencode(<<"Small, fast, modular HTTP server.">>)
).
-endif.
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/cowlib/src/cow_qs.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
The percent decoding is inlined to greatly improve the performance
by avoiding copying binaries twice (once for extracting, once for
decoding) instead of just extracting the proper representation.
, C =/= $= ->
->
@doc Build an application/x-www-form-urlencoded string.
@doc Decode a percent encoded string (x-www-form-urlencoded rules).
->
@doc Percent encode a string (x-www-form-urlencoded rules).
, H, L >>); | Copyright ( c ) 2013 - 2014 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(cow_qs).
-export([parse_qs/1]).
-export([qs/1]).
-export([urldecode/1]).
-export([urlencode/1]).
-type qs_vals() :: [{binary(), binary() | true}].
@doc an application / x - www - form - urlencoded string .
-spec parse_qs(binary()) -> qs_vals().
parse_qs(B) ->
parse_qs_name(B, [], <<>>).
, H , L , Rest / bits > > , Acc , Name ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
parse_qs_name(Rest, Acc, << Name/bits, C >>);
parse_qs_name(<< $+, Rest/bits >>, Acc, Name) ->
parse_qs_name(Rest, Acc, << Name/bits, " " >>);
parse_qs_name(<< $=, Rest/bits >>, Acc, Name) when Name =/= <<>> ->
parse_qs_value(Rest, Acc, Name, <<>>);
parse_qs_name(<< $&, Rest/bits >>, Acc, Name) ->
case Name of
<<>> -> parse_qs_name(Rest, Acc, <<>>);
_ -> parse_qs_name(Rest, [{Name, true}|Acc], <<>>)
end;
parse_qs_name(Rest, Acc, << Name/bits, C >>);
parse_qs_name(<<>>, Acc, Name) ->
case Name of
<<>> -> lists:reverse(Acc);
_ -> lists:reverse([{Name, true}|Acc])
end.
, H , L , Rest / bits > > , Acc , Name , Value ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
parse_qs_value(Rest, Acc, Name, << Value/bits, C >>);
parse_qs_value(<< $+, Rest/bits >>, Acc, Name, Value) ->
parse_qs_value(Rest, Acc, Name, << Value/bits, " " >>);
parse_qs_value(<< $&, Rest/bits >>, Acc, Name, Value) ->
parse_qs_name(Rest, [{Name, Value}|Acc], <<>>);
parse_qs_value(Rest, Acc, Name, << Value/bits, C >>);
parse_qs_value(<<>>, Acc, Name, Value) ->
lists:reverse([{Name, Value}|Acc]).
-ifdef(TEST).
parse_qs_test_() ->
Tests = [
{<<>>, []},
{<<"&">>, []},
{<<"a">>, [{<<"a">>, true}]},
{<<"a&">>, [{<<"a">>, true}]},
{<<"&a">>, [{<<"a">>, true}]},
{<<"a&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"a&&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"a&b&">>, [{<<"a">>, true}, {<<"b">>, true}]},
{<<"=">>, error},
{<<"=b">>, error},
{<<"a=">>, [{<<"a">>, <<>>}]},
{<<"a=b">>, [{<<"a">>, <<"b">>}]},
{<<"a=&b=">>, [{<<"a">>, <<>>}, {<<"b">>, <<>>}]},
{<<"a=b&c&d=e">>, [{<<"a">>, <<"b">>},
{<<"c">>, true}, {<<"d">>, <<"e">>}]},
{<<"a=b=c&d=e=f&g=h=i">>, [{<<"a">>, <<"b=c">>},
{<<"d">>, <<"e=f">>}, {<<"g">>, <<"h=i">>}]},
{<<"+">>, [{<<" ">>, true}]},
{<<"+=+">>, [{<<" ">>, <<" ">>}]},
{<<"a+b=c+d">>, [{<<"a b">>, <<"c d">>}]},
{<<"+a+=+b+&+c+=+d+">>, [{<<" a ">>, <<" b ">>},
{<<" c ">>, <<" d ">>}]},
{<<"a%20b=c%20d">>, [{<<"a b">>, <<"c d">>}]},
{<<"%25%26%3D=%25%26%3D&_-.=.-_">>, [{<<"%&=">>, <<"%&=">>},
{<<"_-.">>, <<".-_">>}]},
{<<"for=extend%2Franch">>, [{<<"for">>, <<"extend/ranch">>}]}
],
[{Qs, fun() ->
E = try parse_qs(Qs) of
R -> R
catch _:_ ->
error
end
end} || {Qs, E} <- Tests].
parse_qs_identity_test_() ->
Tests = [
<<"+">>,
<<"hl=en&q=erlang+cowboy">>,
<<"direction=desc&for=extend%2Franch&sort=updated&state=open">>,
<<"i=EWiIXmPj5gl6&v=QowBp0oDLQXdd4x_GwiywA&ip=98.20.31.81&"
"la=en&pg=New8.undertonebrandsafe.com%2F698a2525065ee2"
"60c0b2f2aaad89ab82&re=&sz=1&fc=1&fr=140&br=3&bv=11.0."
"696.16&os=3&ov=&rs=vpl&k=cookies%7Csale%7Cbrowser%7Cm"
"ore%7Cprivacy%7Cstatistics%7Cactivities%7Cauction%7Ce"
"mail%7Cfree%7Cin...&t=112373&xt=5%7C61%7C0&tz=-1&ev=x"
"&tk=&za=1&ortb-za=1&zu=&zl=&ax=U&ay=U&ortb-pid=536454"
".55&ortb-sid=112373.8&seats=999&ortb-xt=IAB24&ortb-ugc=">>,
<<"i=9pQNskA&v=0ySQQd1F&ev=12345678&t=12345&sz=3&ip=67.58."
"236.89&la=en&pg=http%3A%2F%2Fwww.yahoo.com%2Fpage1.ht"
"m&re=http%3A%2F%2Fsearch.google.com&fc=1&fr=1&br=2&bv"
"=3.0.14&os=1&ov=XP&k=cars%2Cford&rs=js&xt=5%7C22%7C23"
"4&tz=%2B180&tk=key1%3Dvalue1%7Ckey2%3Dvalue2&zl=4%2C5"
"%2C6&za=4&zu=competitor.com&ua=Mozilla%2F5.0+%28Windo"
"ws%3B+U%3B+Windows+NT+6.1%3B+en-US%29+AppleWebKit%2F5"
"34.13+%28KHTML%2C+like+Gecko%29+Chrome%2F9.0.597.98+S"
"afari%2F534.13&ortb-za=1%2C6%2C13&ortb-pid=521732&ort"
"b-sid=521732&ortb-xt=IAB3&ortb-ugc=">>
],
[{V, fun() -> V = qs(parse_qs(V)) end} || V <- Tests].
-endif.
-ifdef(PERF).
horse_parse_qs_shorter() ->
horse:repeat(20000,
parse_qs(<<"hl=en&q=erlang%20cowboy">>)
).
horse_parse_qs_short() ->
horse:repeat(20000,
parse_qs(
<<"direction=desc&for=extend%2Franch&sort=updated&state=open">>)
).
horse_parse_qs_long() ->
horse:repeat(20000,
parse_qs(<<"i=EWiIXmPj5gl6&v=QowBp0oDLQXdd4x_GwiywA&ip=98.20.31.81&"
"la=en&pg=New8.undertonebrandsafe.com%2F698a2525065ee260c0b2f2a"
"aad89ab82&re=&sz=1&fc=1&fr=140&br=3&bv=11.0.696.16&os=3&ov=&rs"
"=vpl&k=cookies%7Csale%7Cbrowser%7Cmore%7Cprivacy%7Cstatistics%"
"7Cactivities%7Cauction%7Cemail%7Cfree%7Cin...&t=112373&xt=5%7C"
"61%7C0&tz=-1&ev=x&tk=&za=1&ortb-za=1&zu=&zl=&ax=U&ay=U&ortb-pi"
"d=536454.55&ortb-sid=112373.8&seats=999&ortb-xt=IAB24&ortb-ugc"
"=">>)
).
horse_parse_qs_longer() ->
horse:repeat(20000,
parse_qs(<<"i=9pQNskA&v=0ySQQd1F&ev=12345678&t=12345&sz=3&ip=67.58."
"236.89&la=en&pg=http%3A%2F%2Fwww.yahoo.com%2Fpage1.htm&re=http"
"%3A%2F%2Fsearch.google.com&fc=1&fr=1&br=2&bv=3.0.14&os=1&ov=XP"
"&k=cars%2cford&rs=js&xt=5%7c22%7c234&tz=%2b180&tk=key1%3Dvalue"
"1%7Ckey2%3Dvalue2&zl=4,5,6&za=4&zu=competitor.com&ua=Mozilla%2"
"F5.0%20(Windows%3B%20U%3B%20Windows%20NT%206.1%3B%20en-US)%20A"
"ppleWebKit%2F534.13%20(KHTML%2C%20like%20Gecko)%20Chrome%2F9.0"
".597.98%20Safari%2F534.13&ortb-za=1%2C6%2C13&ortb-pid=521732&o"
"rtb-sid=521732&ortb-xt=IAB3&ortb-ugc=">>)
).
-endif.
-spec qs(qs_vals()) -> binary().
qs([]) ->
<<>>;
qs(L) ->
qs(L, <<>>).
qs([], Acc) ->
<< $&, Qs/bits >> = Acc,
Qs;
qs([{Name, true}|Tail], Acc) ->
Acc2 = urlencode(Name, << Acc/bits, $& >>),
qs(Tail, Acc2);
qs([{Name, Value}|Tail], Acc) ->
Acc2 = urlencode(Name, << Acc/bits, $& >>),
Acc3 = urlencode(Value, << Acc2/bits, $= >>),
qs(Tail, Acc3).
-define(QS_SHORTER, [
{<<"hl">>, <<"en">>},
{<<"q">>, <<"erlang cowboy">>}
]).
-define(QS_SHORT, [
{<<"direction">>, <<"desc">>},
{<<"for">>, <<"extend/ranch">>},
{<<"sort">>, <<"updated">>},
{<<"state">>, <<"open">>}
]).
-define(QS_LONG, [
{<<"i">>, <<"EWiIXmPj5gl6">>},
{<<"v">>, <<"QowBp0oDLQXdd4x_GwiywA">>},
{<<"ip">>, <<"98.20.31.81">>},
{<<"la">>, <<"en">>},
{<<"pg">>, <<"New8.undertonebrandsafe.com/"
"698a2525065ee260c0b2f2aaad89ab82">>},
{<<"re">>, <<>>},
{<<"sz">>, <<"1">>},
{<<"fc">>, <<"1">>},
{<<"fr">>, <<"140">>},
{<<"br">>, <<"3">>},
{<<"bv">>, <<"11.0.696.16">>},
{<<"os">>, <<"3">>},
{<<"ov">>, <<>>},
{<<"rs">>, <<"vpl">>},
{<<"k">>, <<"cookies|sale|browser|more|privacy|statistics|"
"activities|auction|email|free|in...">>},
{<<"t">>, <<"112373">>},
{<<"xt">>, <<"5|61|0">>},
{<<"tz">>, <<"-1">>},
{<<"ev">>, <<"x">>},
{<<"tk">>, <<>>},
{<<"za">>, <<"1">>},
{<<"ortb-za">>, <<"1">>},
{<<"zu">>, <<>>},
{<<"zl">>, <<>>},
{<<"ax">>, <<"U">>},
{<<"ay">>, <<"U">>},
{<<"ortb-pid">>, <<"536454.55">>},
{<<"ortb-sid">>, <<"112373.8">>},
{<<"seats">>, <<"999">>},
{<<"ortb-xt">>, <<"IAB24">>},
{<<"ortb-ugc">>, <<>>}
]).
-define(QS_LONGER, [
{<<"i">>, <<"9pQNskA">>},
{<<"v">>, <<"0ySQQd1F">>},
{<<"ev">>, <<"12345678">>},
{<<"t">>, <<"12345">>},
{<<"sz">>, <<"3">>},
{<<"ip">>, <<"67.58.236.89">>},
{<<"la">>, <<"en">>},
{<<"pg">>, <<"">>},
{<<"re">>, <<"">>},
{<<"fc">>, <<"1">>},
{<<"fr">>, <<"1">>},
{<<"br">>, <<"2">>},
{<<"bv">>, <<"3.0.14">>},
{<<"os">>, <<"1">>},
{<<"ov">>, <<"XP">>},
{<<"k">>, <<"cars,ford">>},
{<<"rs">>, <<"js">>},
{<<"xt">>, <<"5|22|234">>},
{<<"tz">>, <<"+180">>},
{<<"tk">>, <<"key1=value1|key2=value2">>},
{<<"zl">>, <<"4,5,6">>},
{<<"za">>, <<"4">>},
{<<"zu">>, <<"competitor.com">>},
{<<"ua">>, <<"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) "
"AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 "
"Safari/534.13">>},
{<<"ortb-za">>, <<"1,6,13">>},
{<<"ortb-pid">>, <<"521732">>},
{<<"ortb-sid">>, <<"521732">>},
{<<"ortb-xt">>, <<"IAB3">>},
{<<"ortb-ugc">>, <<>>}
]).
-ifdef(TEST).
qs_test_() ->
Tests = [
{[<<"a">>], error},
{[{<<"a">>, <<"b">>, <<"c">>}], error},
{[], <<>>},
{[{<<"a">>, true}], <<"a">>},
{[{<<"a">>, true}, {<<"b">>, true}], <<"a&b">>},
{[{<<"a">>, <<>>}], <<"a=">>},
{[{<<"a">>, <<"b">>}], <<"a=b">>},
{[{<<"a">>, <<>>}, {<<"b">>, <<>>}], <<"a=&b=">>},
{[{<<"a">>, <<"b">>}, {<<"c">>, true}, {<<"d">>, <<"e">>}],
<<"a=b&c&d=e">>},
{[{<<"a">>, <<"b=c">>}, {<<"d">>, <<"e=f">>}, {<<"g">>, <<"h=i">>}],
<<"a=b%3Dc&d=e%3Df&g=h%3Di">>},
{[{<<" ">>, true}], <<"+">>},
{[{<<" ">>, <<" ">>}], <<"+=+">>},
{[{<<"a b">>, <<"c d">>}], <<"a+b=c+d">>},
{[{<<" a ">>, <<" b ">>}, {<<" c ">>, <<" d ">>}],
<<"+a+=+b+&+c+=+d+">>},
{[{<<"%&=">>, <<"%&=">>}, {<<"_-.">>, <<".-_">>}],
<<"%25%26%3D=%25%26%3D&_-.=.-_">>},
{[{<<"for">>, <<"extend/ranch">>}], <<"for=extend%2Franch">>}
],
[{lists:flatten(io_lib:format("~p", [Vals])), fun() ->
E = try qs(Vals) of
R -> R
catch _:_ ->
error
end
end} || {Vals, E} <- Tests].
qs_identity_test_() ->
Tests = [
[{<<"+">>, true}],
?QS_SHORTER,
?QS_SHORT,
?QS_LONG,
?QS_LONGER
],
[{lists:flatten(io_lib:format("~p", [V])), fun() ->
V = parse_qs(qs(V))
end} || V <- Tests].
-endif.
-ifdef(PERF).
horse_qs_shorter() ->
horse:repeat(20000, qs(?QS_SHORTER)).
horse_qs_short() ->
horse:repeat(20000, qs(?QS_SHORT)).
horse_qs_long() ->
horse:repeat(20000, qs(?QS_LONG)).
horse_qs_longer() ->
horse:repeat(20000, qs(?QS_LONGER)).
-endif.
-spec urldecode(B) -> B when B::binary().
urldecode(B) ->
urldecode(B, <<>>).
, H , L , Rest / bits > > , Acc ) - >
C = (unhex(H) bsl 4 bor unhex(L)),
urldecode(Rest, << Acc/bits, C >>);
urldecode(<< $+, Rest/bits >>, Acc) ->
urldecode(Rest, << Acc/bits, " " >>);
urldecode(Rest, << Acc/bits, C >>);
urldecode(<<>>, Acc) ->
Acc.
unhex($0) -> 0;
unhex($1) -> 1;
unhex($2) -> 2;
unhex($3) -> 3;
unhex($4) -> 4;
unhex($5) -> 5;
unhex($6) -> 6;
unhex($7) -> 7;
unhex($8) -> 8;
unhex($9) -> 9;
unhex($A) -> 10;
unhex($B) -> 11;
unhex($C) -> 12;
unhex($D) -> 13;
unhex($E) -> 14;
unhex($F) -> 15;
unhex($a) -> 10;
unhex($b) -> 11;
unhex($c) -> 12;
unhex($d) -> 13;
unhex($e) -> 14;
unhex($f) -> 15.
-ifdef(TEST).
urldecode_test_() ->
Tests = [
{<<"%20">>, <<" ">>},
{<<"+">>, <<" ">>},
{<<"%00">>, <<0>>},
{<<"%fF">>, <<255>>},
{<<"123">>, <<"123">>},
{<<"%i5">>, error},
{<<"%5">>, error}
],
[{Qs, fun() ->
E = try urldecode(Qs) of
R -> R
catch _:_ ->
error
end
end} || {Qs, E} <- Tests].
urldecode_identity_test_() ->
Tests = [
<<"+">>,
<<"nothingnothingnothingnothing">>,
<<"Small+fast+modular+HTTP+server">>,
<<"Small%2C+fast%2C+modular+HTTP+server.">>,
<<"%E3%83%84%E3%82%A4%E3%83%B3%E3%82%BD%E3%82%A6%E3%83"
"%AB%E3%80%9C%E8%BC%AA%E5%BB%BB%E3%81%99%E3%82%8B%E6%97%8B%E5"
"%BE%8B%E3%80%9C">>
],
[{V, fun() -> V = urlencode(urldecode(V)) end} || V <- Tests].
-endif.
-ifdef(PERF).
horse_urldecode() ->
horse:repeat(100000,
urldecode(<<"nothingnothingnothingnothing">>)
).
horse_urldecode_plus() ->
horse:repeat(100000,
urldecode(<<"Small+fast+modular+HTTP+server">>)
).
horse_urldecode_hex() ->
horse:repeat(100000,
urldecode(<<"Small%2C%20fast%2C%20modular%20HTTP%20server.">>)
).
horse_urldecode_jp_hex() ->
horse:repeat(100000,
urldecode(<<"%E3%83%84%E3%82%A4%E3%83%B3%E3%82%BD%E3%82%A6%E3%83"
"%AB%E3%80%9C%E8%BC%AA%E5%BB%BB%E3%81%99%E3%82%8B%E6%97%8B%E5"
"%BE%8B%E3%80%9C">>)
).
horse_urldecode_mix() ->
horse:repeat(100000,
urldecode(<<"Small%2C+fast%2C+modular+HTTP+server.">>)
).
-endif.
-spec urlencode(B) -> B when B::binary().
urlencode(B) ->
urlencode(B, <<>>).
urlencode(<< $\s, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $+ >>);
urlencode(<< $-, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $- >>);
urlencode(<< $., Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $. >>);
urlencode(<< $0, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $0 >>);
urlencode(<< $1, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $1 >>);
urlencode(<< $2, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $2 >>);
urlencode(<< $3, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $3 >>);
urlencode(<< $4, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $4 >>);
urlencode(<< $5, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $5 >>);
urlencode(<< $6, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $6 >>);
urlencode(<< $7, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $7 >>);
urlencode(<< $8, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $8 >>);
urlencode(<< $9, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $9 >>);
urlencode(<< $A, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $A >>);
urlencode(<< $B, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $B >>);
urlencode(<< $C, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $C >>);
urlencode(<< $D, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $D >>);
urlencode(<< $E, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $E >>);
urlencode(<< $F, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $F >>);
urlencode(<< $G, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $G >>);
urlencode(<< $H, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $H >>);
urlencode(<< $I, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $I >>);
urlencode(<< $J, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $J >>);
urlencode(<< $K, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $K >>);
urlencode(<< $L, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $L >>);
urlencode(<< $M, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $M >>);
urlencode(<< $N, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $N >>);
urlencode(<< $O, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $O >>);
urlencode(<< $P, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $P >>);
urlencode(<< $Q, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Q >>);
urlencode(<< $R, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $R >>);
urlencode(<< $S, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $S >>);
urlencode(<< $T, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $T >>);
urlencode(<< $U, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $U >>);
urlencode(<< $V, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $V >>);
urlencode(<< $W, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $W >>);
urlencode(<< $X, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $X >>);
urlencode(<< $Y, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Y >>);
urlencode(<< $Z, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $Z >>);
urlencode(<< $_, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $_ >>);
urlencode(<< $a, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $a >>);
urlencode(<< $b, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $b >>);
urlencode(<< $c, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $c >>);
urlencode(<< $d, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $d >>);
urlencode(<< $e, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $e >>);
urlencode(<< $f, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $f >>);
urlencode(<< $g, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $g >>);
urlencode(<< $h, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $h >>);
urlencode(<< $i, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $i >>);
urlencode(<< $j, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $j >>);
urlencode(<< $k, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $k >>);
urlencode(<< $l, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $l >>);
urlencode(<< $m, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $m >>);
urlencode(<< $n, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $n >>);
urlencode(<< $o, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $o >>);
urlencode(<< $p, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $p >>);
urlencode(<< $q, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $q >>);
urlencode(<< $r, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $r >>);
urlencode(<< $s, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $s >>);
urlencode(<< $t, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $t >>);
urlencode(<< $u, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $u >>);
urlencode(<< $v, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $v >>);
urlencode(<< $w, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $w >>);
urlencode(<< $x, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $x >>);
urlencode(<< $y, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $y >>);
urlencode(<< $z, Rest/bits >>, Acc) -> urlencode(Rest, << Acc/bits, $z >>);
urlencode(<< C, Rest/bits >>, Acc) ->
H = hex(C bsr 4),
L = hex(C band 16#0f),
urlencode(<<>>, Acc) ->
Acc.
hex( 0) -> $0;
hex( 1) -> $1;
hex( 2) -> $2;
hex( 3) -> $3;
hex( 4) -> $4;
hex( 5) -> $5;
hex( 6) -> $6;
hex( 7) -> $7;
hex( 8) -> $8;
hex( 9) -> $9;
hex(10) -> $A;
hex(11) -> $B;
hex(12) -> $C;
hex(13) -> $D;
hex(14) -> $E;
hex(15) -> $F.
-ifdef(TEST).
urlencode_test_() ->
Tests = [
{<<255, 0>>, <<"%FF%00">>},
{<<255, " ">>, <<"%FF+">>},
{<<" ">>, <<"+">>},
{<<"aBc123">>, <<"aBc123">>},
{<<".-_">>, <<".-_">>}
],
[{V, fun() -> E = urlencode(V) end} || {V, E} <- Tests].
urlencode_identity_test_() ->
Tests = [
<<"+">>,
<<"nothingnothingnothingnothing">>,
<<"Small fast modular HTTP server">>,
<<"Small, fast, modular HTTP server.">>,
<<227,131,132,227,130,164,227,131,179,227,130,189,227,
130,166,227,131,171,227,128,156,232,188,170,229,187,187,227,
129,153,227,130,139,230,151,139,229,190,139,227,128,156>>
],
[{V, fun() -> V = urldecode(urlencode(V)) end} || V <- Tests].
-endif.
-ifdef(PERF).
horse_urlencode() ->
horse:repeat(100000,
urlencode(<<"nothingnothingnothingnothing">>)
).
horse_urlencode_plus() ->
horse:repeat(100000,
urlencode(<<"Small fast modular HTTP server">>)
).
horse_urlencode_jp() ->
horse:repeat(100000,
urlencode(<<227,131,132,227,130,164,227,131,179,227,130,189,227,
130,166,227,131,171,227,128,156,232,188,170,229,187,187,227,
129,153,227,130,139,230,151,139,229,190,139,227,128,156>>)
).
horse_urlencode_mix() ->
horse:repeat(100000,
urlencode(<<"Small, fast, modular HTTP server.">>)
).
-endif.
|
c8a6fb4539ae8d63f85d9350881d7889d93f40be6d0a9b042bba638a390b4189 | startalkIM/ejabberd | luerl.erl | Copyright ( c ) 2013
%%
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.
%% File : luerl.erl
Authors : ,
Purpose : Basic LUA 5.2 interface .
-module(luerl).
-include("luerl.hrl").
-export([eval/1,eval/2,evalfile/1,evalfile/2,
do/1,do/2,dofile/1,dofile/2,
load/1,load/2,loadfile/1,loadfile/2,path_loadfile/2,path_loadfile/3,
load_module/3,load_module1/3,
call/2,call/3,call_chunk/2,call_chunk/3,
call_function/2,call_function/3,call_function1/3,function_list/2,
get_table/2,get_table1/2,set_table/3,set_table1/3,set_table1/4,
call_method/2,call_method/3,call_method1/3,method_list/2,
init/0,stop/1,gc/1,
encode/2,encode_list/2,decode/2,decode_list/2]).
%% luerl:eval(String|Binary|Form[, State]) -> Result.
eval(Chunk) ->
eval(Chunk, init()).
eval(Chunk, St0) ->
try do(Chunk, St0) of
{Ret,St1} -> {ok, decode_list(Ret, St1)}
catch
_E:R -> {error, R} % {error, {E, R}} ? <- todo: decide
end.
luerl : evalfile(Path [ , State ] ) - > { ok , Result } | { error , Reason } .
evalfile(Path) ->
evalfile(Path, init()).
evalfile(Path, St0) ->
try dofile(Path, St0) of
{Ret,St1} -> {ok, decode_list(Ret, St1)}
catch
_E:R -> {error, R} % {error, {E, R}} ? <- todo: decide
end.
luerl : do(String|Binary|Form [ , State ] ) - > { Result , NewState }
do(SBC) -> do(SBC, init()).
do(S, St0) when is_binary(S); is_list(S) ->
{ok,Func,St1} = load(S, St0),
luerl_emul:call(Func, St1);
do(Func, St) ->
luerl_emul:call(Func, St).
luerl : dofile(Path [ , State ] ) - > { Result , NewState } .
dofile(Path) ->
dofile(Path, init()).
dofile(Path, St0) ->
{ok,Func,St1} = loadfile(Path, St0),
luerl_emul:call(Func, St1).
%% load(String|Binary) -> {ok,Function,NewState}.
load(Str) -> load(Str, init()).
load(Bin, St) when is_binary(Bin) ->
load(binary_to_list(Bin), St);
load(Str, St0) when is_list(Str) ->
case luerl_comp:string(Str) of
{ok,Chunk} ->
{Func,St1} = luerl_emul:load_chunk(Chunk, St0),
{ok,Func,St1};
{error,_,_}=E -> E
end.
%% loadfile(FileName) -> {ok,Function,NewState}.
loadfile(FileName , State ) - > { ok , Function , NewState } .
loadfile(Name) -> loadfile(Name, init()).
loadfile(Name, St0) ->
case luerl_comp:file(Name) of
{ok,Chunk} ->
{Func,St1} = luerl_emul:load_chunk(Chunk, St0),
{ok,Func,St1};
{error,_,_}=E -> E
end.
path_loadfile(FileName , State ) - > { ok , Function , FullName , State } .
path_loadfile(Path , FileName , State ) - > { ok , Function , FullName , State } .
%% We manually step down the path to get the correct handling of
%% filenames by the compiler.
path_loadfile(Name, St) ->
Path = case os:getenv("LUA_LOAD_PATH") of
false -> []; %You get what you asked for
Env ->
%% Get path separator depending on os type.
Sep = case os:type() of
{win32,_} -> ";";
_ -> ":" %Unix
end,
string:tokens(Env, Sep) %Split into path list
end,
path_loadfile(Path, Name, St).
path_loadfile([Dir|Dirs], Name, St0) ->
Full = filename:join(Dir, Name),
case loadfile(Full, St0) of
{ok,Func,St1} ->
{ok,Func,Full,St1};
{error,[{_,_,enoent}],_} -> %Couldn't find the file
path_loadfile(Dirs, Name, St0);
Error -> Error
end;
path_loadfile([], _, _) ->
{error,[{none,file,enoent}],[]}.
load_module(TablePath , ModuleName , State ) - > State .
load_module1(LuaTablePath , ModuleName , State ) - > State .
%% Load module and add module table to the path.
load_module(Fp, Mod, St0) when is_list(Fp) ->
{Lfp,St1} = encode_list(Fp, St0),
load_module1(Lfp, Mod, St1);
load_module(_, _,_) -> error(badarg).
load_module1(Lfp, Mod, St0) ->
{Tab,St1} = Mod:install(St0),
luerl_emul:set_table_keys(Lfp, Tab, St1).
%% init() -> State.
init() -> luerl_emul:init().
call(Chunk , , State ) - > { Result , State }
call(C, As) -> call_chunk(C, As).
call(C, As, St) -> call_chunk(C, As, St).
call_chunk(C, As) -> call_chunk(C, As, init()).
call_chunk(C, As, St0) ->
{Las,St1} = encode_list(As, St0),
{Lrs,St2} = luerl_emul:call(C, Las, St1),
Rs = decode_list(Lrs, St2),
{Rs,St2}.
call_function(Table , ) - > { Result , State } .
call_function(TablePath , , State ) - > { Result , State } .
call_function1(LuaTablePath | Func , LuaArgs , State ) - > { LuaResult , State } .
call_function(Fp, As) ->
call_function(Fp, As, init()).
call_function(Fp, As, St0) ->
%% Encode the input arguments.
{Lfp,St1} = encode_list(Fp, St0),
{Las,St2} = encode_list(As, St1),
%% Find the function definition and call function.
{Lrs,St3} = call_function1(Lfp, Las, St2),
Rs = decode_list(Lrs, St3),
{Rs,St3}.
call_function1(Lfp, Las, St0) when is_list(Lfp) ->
{F,St1} = luerl_emul:get_table_keys(Lfp, St0),
luerl_emul:functioncall(F, Las, St1);
call_function1(F, Las, St) ->
luerl_emul:functioncall(F, Las, St).
function_list(Keys , State ) - > { V , State } .
%% Go down a list of keys and return final value.
function_list(Ks, St) -> luerl_emul:get_table_keys(Ks, St).
call_method(FuncPath , ) - > { Result , State } .
call_method(FuncPath , , State ) - > { Result , State } .
call_method1(FuncPath | FuncPath , Args , State ) - > { Result , State } .
call_method(Fp, As) ->
call_method(Fp, As, init()).
call_method(Fp, As, St0) ->
%% Encode the input arguments.
{Lfp,St1} = encode_list(Fp, St0),
{Las,St2} = encode_list(As, St1),
%% Find the object and method definition and call method.
{O,M,St3} = method_list(Lfp, St2),
{Lrs,St4} = luerl_emul:functioncall(M, [O|Las], St3),
Rs = decode_list(Lrs, St4),
{Rs,St4}.
call_method1(Fp, Las, St0) ->
%% Find the object and method definition and call method.
{O,M,St1} = method_list(Fp, St0),
luerl_emul:functioncall(M, [O|Las], St1).
method_list([G|Ks], St0) ->
{First,St1} = luerl_emul:get_global_key(G, St0),
method_list(First, Ks, St1).
method_list(Tab, [K], St0) ->
{Func,St1} = luerl_emul:get_table_key(Tab, K, St0),
{Tab,Func,St1};
method_list(Tab, [K|Ks], St0) ->
{Next,St1} = luerl_emul:get_table_key(Tab, K, St0),
method_list(Next, Ks, St1);
method_list(_, _, _) -> error(badarg).
get_table(TablePath , State ) - > { Result , State } .
%% Go down a list of keys and return decoded final value.
get_table(Fp, St0) when is_list(Fp) ->
{Lfp,St1} = encode_list(Fp, St0),
{V,St2} = luerl_emul:get_table_keys(Lfp, St1),
Vd = decode(V, St2),
{Vd,St2};
get_table(_,_) -> error(badarg).
get_table1(LuaTablePath , State ) - > { LuaResult , State } .
get_table1(Fp, St) when is_list(Fp) ->
luerl_emul:get_table_keys(Fp, St);
get_table1(_,_) -> error(badarg).
set_table(TablePath , Value , State ) - > State .
%% Go down a list of keys and set final key to Value.
set_table(Fp, V, St0) when is_list(Fp) ->
{Lfp,St1} = encode_list(Fp, St0),
{Lv, St2} = encode(V, St1),
set_table1(Lfp, Lv, St2);
set_table(_,_,_) -> error(badarg).
set_table1(LuaTablePath , Value , State ) - > State .
%% Must explicitly read table key to get
set_table1(Lfp, Lv, St) ->
luerl_emul:set_table_keys(Lfp, Lv, St).
set_table1(Table , Key , Value , State ) - > State .
%% Must explicitly read table key to get
set_table1(Tab, Key, Lv, St) ->
luerl_emul:set_table_key(Tab, Key, Lv, St).
%% stop(State) -> GCedState.
stop(St) ->
luerl_emul:gc(St).
%% gc(State) -> State.
gc(St) -> luerl_emul:gc(St).
encode_list([Term ] , State ) - > { [ LuerlTerm],State } .
encode(Term , State ) - > { LuerlTerm , State } .
encode_list(Ts, St) ->
lists:mapfoldl(fun encode/2, St, Ts).
encode(nil, St) -> {nil,St};
encode(false, St) -> {false,St};
encode(true, St) -> {true,St};
encode(B, St) when is_binary(B) -> {B,St};
encode(A, St) when is_atom(A) -> {atom_to_binary(A, latin1),St};
encode(I, St) when is_integer(I) -> {float(I),St};
encode(F, St) when is_float(F) -> {F,St};
encode(L, St0) when is_list(L) ->
{Es,{_,St1}} = lists:mapfoldl(fun ({K0,V0}, {I,S0}) ->
{K1,S1} = encode(K0, S0),
{V1,S2} = encode(V0, S1),
{{K1,V1},{I,S2}};
(V0, {I,S0}) ->
{V1,S1} = encode(V0, S0),
{{I,V1},{I+1,S1}}
end, {1.0,St0}, L),
{T,St2} = luerl_emul:alloc_table(Es, St1),
{T,St2}; %No more to do for now
encode(F, St) when is_function(F, 2) ->
F1 = fun(Args, State) ->
Args1 = decode_list(Args, State),
{Res, State1} = F(Args1, State),
encode_list(Res, State1)
end,
{{function, F1}, St};
encode(F, St) when is_function(F, 1) ->
F1 = fun(Args, State) ->
Args1 = decode_list(Args, State),
Res = F(Args1),
encode_list(Res, State)
end,
{{function, F1}, St};
encode(_, _) -> error(badarg). %Can't encode anything else
decode_list([LuerlTerm ] , State ) - > [ Term ] .
decode(LuerlTerm , State ) - > Term .
%% In decode we track of which tables we have seen to detect
%% recursive references and generate an error when that occurs.
decode_list(Lts, St) ->
lists:map(fun (Lt) -> decode(Lt, St) end, Lts).
decode(LT, St) ->
%% Catch errors to clean up call stack.
try decode(LT, St, [])
catch
error:E ->
erlang:raise(error, E, [{?MODULE,decode,2}])
end.
decode(nil, _, _) -> nil;
decode(false, _, _) -> false;
decode(true, _, _) -> true;
decode(B, _, _) when is_binary(B) -> B;
decode(N, _, _) when is_number(N) -> N;
decode(#tref{i=N}, St, In) ->
decode_table(N, St, In);
decode({function,Fun}, _, _) -> {function,Fun};
decode(#function{}=Fun, State, _) ->
F = fun(Args) ->
{Args1, State1} = encode_list(Args, State),
{Ret, State2} = luerl_emul:functioncall(Fun, Args1, State1),
decode_list(Ret, State2)
end,
{function, F};
decode(_, _, _) -> error(badarg). %Shouldn't have anything else
decode_table(N, St, In0) ->
case lists:member(N, In0) of
true -> error(recursive_data); %Been here before
false ->
In1 = [N|In0], %We are in this as well
case ?GET_TABLE(N, St#luerl.ttab) of
#table{a=Arr,t=Tab} ->
Fun = fun (K, V, Acc) ->
[{decode(K, St, In1),decode(V, St, In1)}|Acc]
end,
Ts = ttdict:fold(Fun, [], Tab),
array:sparse_foldr(Fun, Ts, Arr);
_Undefined -> error(badarg)
end
end.
| null | https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/deps/luerl/src/luerl.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.
File : luerl.erl
luerl:eval(String|Binary|Form[, State]) -> Result.
{error, {E, R}} ? <- todo: decide
{error, {E, R}} ? <- todo: decide
load(String|Binary) -> {ok,Function,NewState}.
loadfile(FileName) -> {ok,Function,NewState}.
We manually step down the path to get the correct handling of
filenames by the compiler.
You get what you asked for
Get path separator depending on os type.
Unix
Split into path list
Couldn't find the file
Load module and add module table to the path.
init() -> State.
Encode the input arguments.
Find the function definition and call function.
Go down a list of keys and return final value.
Encode the input arguments.
Find the object and method definition and call method.
Find the object and method definition and call method.
Go down a list of keys and return decoded final value.
Go down a list of keys and set final key to Value.
Must explicitly read table key to get
Must explicitly read table key to get
stop(State) -> GCedState.
gc(State) -> State.
No more to do for now
Can't encode anything else
In decode we track of which tables we have seen to detect
recursive references and generate an error when that occurs.
Catch errors to clean up call stack.
Shouldn't have anything else
Been here before
We are in this as well | Copyright ( c ) 2013
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
Authors : ,
Purpose : Basic LUA 5.2 interface .
-module(luerl).
-include("luerl.hrl").
-export([eval/1,eval/2,evalfile/1,evalfile/2,
do/1,do/2,dofile/1,dofile/2,
load/1,load/2,loadfile/1,loadfile/2,path_loadfile/2,path_loadfile/3,
load_module/3,load_module1/3,
call/2,call/3,call_chunk/2,call_chunk/3,
call_function/2,call_function/3,call_function1/3,function_list/2,
get_table/2,get_table1/2,set_table/3,set_table1/3,set_table1/4,
call_method/2,call_method/3,call_method1/3,method_list/2,
init/0,stop/1,gc/1,
encode/2,encode_list/2,decode/2,decode_list/2]).
eval(Chunk) ->
eval(Chunk, init()).
eval(Chunk, St0) ->
try do(Chunk, St0) of
{Ret,St1} -> {ok, decode_list(Ret, St1)}
catch
end.
luerl : evalfile(Path [ , State ] ) - > { ok , Result } | { error , Reason } .
evalfile(Path) ->
evalfile(Path, init()).
evalfile(Path, St0) ->
try dofile(Path, St0) of
{Ret,St1} -> {ok, decode_list(Ret, St1)}
catch
end.
luerl : do(String|Binary|Form [ , State ] ) - > { Result , NewState }
do(SBC) -> do(SBC, init()).
do(S, St0) when is_binary(S); is_list(S) ->
{ok,Func,St1} = load(S, St0),
luerl_emul:call(Func, St1);
do(Func, St) ->
luerl_emul:call(Func, St).
luerl : dofile(Path [ , State ] ) - > { Result , NewState } .
dofile(Path) ->
dofile(Path, init()).
dofile(Path, St0) ->
{ok,Func,St1} = loadfile(Path, St0),
luerl_emul:call(Func, St1).
load(Str) -> load(Str, init()).
load(Bin, St) when is_binary(Bin) ->
load(binary_to_list(Bin), St);
load(Str, St0) when is_list(Str) ->
case luerl_comp:string(Str) of
{ok,Chunk} ->
{Func,St1} = luerl_emul:load_chunk(Chunk, St0),
{ok,Func,St1};
{error,_,_}=E -> E
end.
loadfile(FileName , State ) - > { ok , Function , NewState } .
loadfile(Name) -> loadfile(Name, init()).
loadfile(Name, St0) ->
case luerl_comp:file(Name) of
{ok,Chunk} ->
{Func,St1} = luerl_emul:load_chunk(Chunk, St0),
{ok,Func,St1};
{error,_,_}=E -> E
end.
path_loadfile(FileName , State ) - > { ok , Function , FullName , State } .
path_loadfile(Path , FileName , State ) - > { ok , Function , FullName , State } .
path_loadfile(Name, St) ->
Path = case os:getenv("LUA_LOAD_PATH") of
Env ->
Sep = case os:type() of
{win32,_} -> ";";
end,
end,
path_loadfile(Path, Name, St).
path_loadfile([Dir|Dirs], Name, St0) ->
Full = filename:join(Dir, Name),
case loadfile(Full, St0) of
{ok,Func,St1} ->
{ok,Func,Full,St1};
path_loadfile(Dirs, Name, St0);
Error -> Error
end;
path_loadfile([], _, _) ->
{error,[{none,file,enoent}],[]}.
load_module(TablePath , ModuleName , State ) - > State .
load_module1(LuaTablePath , ModuleName , State ) - > State .
load_module(Fp, Mod, St0) when is_list(Fp) ->
{Lfp,St1} = encode_list(Fp, St0),
load_module1(Lfp, Mod, St1);
load_module(_, _,_) -> error(badarg).
load_module1(Lfp, Mod, St0) ->
{Tab,St1} = Mod:install(St0),
luerl_emul:set_table_keys(Lfp, Tab, St1).
init() -> luerl_emul:init().
call(Chunk , , State ) - > { Result , State }
call(C, As) -> call_chunk(C, As).
call(C, As, St) -> call_chunk(C, As, St).
call_chunk(C, As) -> call_chunk(C, As, init()).
call_chunk(C, As, St0) ->
{Las,St1} = encode_list(As, St0),
{Lrs,St2} = luerl_emul:call(C, Las, St1),
Rs = decode_list(Lrs, St2),
{Rs,St2}.
call_function(Table , ) - > { Result , State } .
call_function(TablePath , , State ) - > { Result , State } .
call_function1(LuaTablePath | Func , LuaArgs , State ) - > { LuaResult , State } .
call_function(Fp, As) ->
call_function(Fp, As, init()).
call_function(Fp, As, St0) ->
{Lfp,St1} = encode_list(Fp, St0),
{Las,St2} = encode_list(As, St1),
{Lrs,St3} = call_function1(Lfp, Las, St2),
Rs = decode_list(Lrs, St3),
{Rs,St3}.
call_function1(Lfp, Las, St0) when is_list(Lfp) ->
{F,St1} = luerl_emul:get_table_keys(Lfp, St0),
luerl_emul:functioncall(F, Las, St1);
call_function1(F, Las, St) ->
luerl_emul:functioncall(F, Las, St).
function_list(Keys , State ) - > { V , State } .
function_list(Ks, St) -> luerl_emul:get_table_keys(Ks, St).
call_method(FuncPath , ) - > { Result , State } .
call_method(FuncPath , , State ) - > { Result , State } .
call_method1(FuncPath | FuncPath , Args , State ) - > { Result , State } .
call_method(Fp, As) ->
call_method(Fp, As, init()).
call_method(Fp, As, St0) ->
{Lfp,St1} = encode_list(Fp, St0),
{Las,St2} = encode_list(As, St1),
{O,M,St3} = method_list(Lfp, St2),
{Lrs,St4} = luerl_emul:functioncall(M, [O|Las], St3),
Rs = decode_list(Lrs, St4),
{Rs,St4}.
call_method1(Fp, Las, St0) ->
{O,M,St1} = method_list(Fp, St0),
luerl_emul:functioncall(M, [O|Las], St1).
method_list([G|Ks], St0) ->
{First,St1} = luerl_emul:get_global_key(G, St0),
method_list(First, Ks, St1).
method_list(Tab, [K], St0) ->
{Func,St1} = luerl_emul:get_table_key(Tab, K, St0),
{Tab,Func,St1};
method_list(Tab, [K|Ks], St0) ->
{Next,St1} = luerl_emul:get_table_key(Tab, K, St0),
method_list(Next, Ks, St1);
method_list(_, _, _) -> error(badarg).
get_table(TablePath , State ) - > { Result , State } .
get_table(Fp, St0) when is_list(Fp) ->
{Lfp,St1} = encode_list(Fp, St0),
{V,St2} = luerl_emul:get_table_keys(Lfp, St1),
Vd = decode(V, St2),
{Vd,St2};
get_table(_,_) -> error(badarg).
get_table1(LuaTablePath , State ) - > { LuaResult , State } .
get_table1(Fp, St) when is_list(Fp) ->
luerl_emul:get_table_keys(Fp, St);
get_table1(_,_) -> error(badarg).
set_table(TablePath , Value , State ) - > State .
set_table(Fp, V, St0) when is_list(Fp) ->
{Lfp,St1} = encode_list(Fp, St0),
{Lv, St2} = encode(V, St1),
set_table1(Lfp, Lv, St2);
set_table(_,_,_) -> error(badarg).
set_table1(LuaTablePath , Value , State ) - > State .
set_table1(Lfp, Lv, St) ->
luerl_emul:set_table_keys(Lfp, Lv, St).
set_table1(Table , Key , Value , State ) - > State .
set_table1(Tab, Key, Lv, St) ->
luerl_emul:set_table_key(Tab, Key, Lv, St).
stop(St) ->
luerl_emul:gc(St).
gc(St) -> luerl_emul:gc(St).
encode_list([Term ] , State ) - > { [ LuerlTerm],State } .
encode(Term , State ) - > { LuerlTerm , State } .
encode_list(Ts, St) ->
lists:mapfoldl(fun encode/2, St, Ts).
encode(nil, St) -> {nil,St};
encode(false, St) -> {false,St};
encode(true, St) -> {true,St};
encode(B, St) when is_binary(B) -> {B,St};
encode(A, St) when is_atom(A) -> {atom_to_binary(A, latin1),St};
encode(I, St) when is_integer(I) -> {float(I),St};
encode(F, St) when is_float(F) -> {F,St};
encode(L, St0) when is_list(L) ->
{Es,{_,St1}} = lists:mapfoldl(fun ({K0,V0}, {I,S0}) ->
{K1,S1} = encode(K0, S0),
{V1,S2} = encode(V0, S1),
{{K1,V1},{I,S2}};
(V0, {I,S0}) ->
{V1,S1} = encode(V0, S0),
{{I,V1},{I+1,S1}}
end, {1.0,St0}, L),
{T,St2} = luerl_emul:alloc_table(Es, St1),
encode(F, St) when is_function(F, 2) ->
F1 = fun(Args, State) ->
Args1 = decode_list(Args, State),
{Res, State1} = F(Args1, State),
encode_list(Res, State1)
end,
{{function, F1}, St};
encode(F, St) when is_function(F, 1) ->
F1 = fun(Args, State) ->
Args1 = decode_list(Args, State),
Res = F(Args1),
encode_list(Res, State)
end,
{{function, F1}, St};
decode_list([LuerlTerm ] , State ) - > [ Term ] .
decode(LuerlTerm , State ) - > Term .
decode_list(Lts, St) ->
lists:map(fun (Lt) -> decode(Lt, St) end, Lts).
decode(LT, St) ->
try decode(LT, St, [])
catch
error:E ->
erlang:raise(error, E, [{?MODULE,decode,2}])
end.
decode(nil, _, _) -> nil;
decode(false, _, _) -> false;
decode(true, _, _) -> true;
decode(B, _, _) when is_binary(B) -> B;
decode(N, _, _) when is_number(N) -> N;
decode(#tref{i=N}, St, In) ->
decode_table(N, St, In);
decode({function,Fun}, _, _) -> {function,Fun};
decode(#function{}=Fun, State, _) ->
F = fun(Args) ->
{Args1, State1} = encode_list(Args, State),
{Ret, State2} = luerl_emul:functioncall(Fun, Args1, State1),
decode_list(Ret, State2)
end,
{function, F};
decode_table(N, St, In0) ->
case lists:member(N, In0) of
false ->
case ?GET_TABLE(N, St#luerl.ttab) of
#table{a=Arr,t=Tab} ->
Fun = fun (K, V, Acc) ->
[{decode(K, St, In1),decode(V, St, In1)}|Acc]
end,
Ts = ttdict:fold(Fun, [], Tab),
array:sparse_foldr(Fun, Ts, Arr);
_Undefined -> error(badarg)
end
end.
|
6d0eb0992df9dfb7b8bf4aa2937de37d71374549cc8041438c2c8c9c1c228a09 | casperschipper/ocaml-cisp | tablepath2.ml | let max = 512
let noise = Cisp.sineseg max |> Array.of_seq
let steps =
Array.init max (fun idx -> let next = ((idx + 1) mod max) in Infseq.repeat next)
let get_table arr idx =
if idx > Array.length arr || (idx < 0) then
None
else
Some (arr.(idx))
let play_index_table arr =
let rec aux arr idx () =
match get_table arr idx with
| Some stream ->
(match stream () with
| Infseq.InfCons(nextIdx,tail) -> Array.set arr idx tail ;Infseq.InfCons(idx,aux arr nextIdx))
| None ->
Infseq.InfCons(0,aux arr 0)
in
aux arr 0
let write_split () =
let idx = Toolkit.rvi 1 (max - 1) in
let a = Toolkit.rvi 1 (max - 1) in
let b = Toolkit.rvi 1 (max - 1) in
let o = Toolkit.rvi 10 11 in
let stream =
if Toolkit.rvi 0 30 > 28 then
Cisp.ch [|a;b|] |> Cisp.hold (Cisp.st o) |> Infseq.cycleSq
else
Cisp.seq [a;b] |> Cisp.hold (Cisp.st o) |> Infseq.cycleSq
in
steps.(idx) <- stream
let write_normal idx =
let next = Infseq.repeat (idx + 1) in
steps.(idx) <- next
let () =
let open Cisp in
let chaos = timed (fractRandTimer (ch [|0.5;1.0;2.0;3.0;4.0|])) (st write_split |> Seq.map (fun x -> x ()) ) in
let peace = timed (fractRandTimer (ch [|0.001;0.1;0.5;1.0;2.0|])) (countTill (max-1) |> Seq.map write_normal) in
let eff = effect_lst masterClock [chaos;peace] in
let signal () = play_index_table steps |> Infseq.index noise |> Infseq.to_seq |> Cisp.blpf_static 60.0 0.9 |> Seq.map (fun x -> x *. 40000.0 |> sin) in
let channels = rangei 0 14 |> Seq.map (fun _ -> signal ()) |> List.of_seq in
Jack.playSeqs 0 Process.sample_rate ((effect eff (signal ())) :: channels)
| null | https://raw.githubusercontent.com/casperschipper/ocaml-cisp/571ffb8e508c5427d01e407ba5e91ff2a4604f40/examples/tablepath2.ml | ocaml | let max = 512
let noise = Cisp.sineseg max |> Array.of_seq
let steps =
Array.init max (fun idx -> let next = ((idx + 1) mod max) in Infseq.repeat next)
let get_table arr idx =
if idx > Array.length arr || (idx < 0) then
None
else
Some (arr.(idx))
let play_index_table arr =
let rec aux arr idx () =
match get_table arr idx with
| Some stream ->
(match stream () with
| Infseq.InfCons(nextIdx,tail) -> Array.set arr idx tail ;Infseq.InfCons(idx,aux arr nextIdx))
| None ->
Infseq.InfCons(0,aux arr 0)
in
aux arr 0
let write_split () =
let idx = Toolkit.rvi 1 (max - 1) in
let a = Toolkit.rvi 1 (max - 1) in
let b = Toolkit.rvi 1 (max - 1) in
let o = Toolkit.rvi 10 11 in
let stream =
if Toolkit.rvi 0 30 > 28 then
Cisp.ch [|a;b|] |> Cisp.hold (Cisp.st o) |> Infseq.cycleSq
else
Cisp.seq [a;b] |> Cisp.hold (Cisp.st o) |> Infseq.cycleSq
in
steps.(idx) <- stream
let write_normal idx =
let next = Infseq.repeat (idx + 1) in
steps.(idx) <- next
let () =
let open Cisp in
let chaos = timed (fractRandTimer (ch [|0.5;1.0;2.0;3.0;4.0|])) (st write_split |> Seq.map (fun x -> x ()) ) in
let peace = timed (fractRandTimer (ch [|0.001;0.1;0.5;1.0;2.0|])) (countTill (max-1) |> Seq.map write_normal) in
let eff = effect_lst masterClock [chaos;peace] in
let signal () = play_index_table steps |> Infseq.index noise |> Infseq.to_seq |> Cisp.blpf_static 60.0 0.9 |> Seq.map (fun x -> x *. 40000.0 |> sin) in
let channels = rangei 0 14 |> Seq.map (fun _ -> signal ()) |> List.of_seq in
Jack.playSeqs 0 Process.sample_rate ((effect eff (signal ())) :: channels)
| |
d0ed315eda058f9dad0baa20da0d039997e72319dc7cc48e6c4cb0ed9e6e224c | froydnj/ironclad | rsa.lisp | ;;;; -*- mode: lisp; indent-tabs-mode: nil -*-
rsa.lisp -- implementation of the RSA public key algorithm
(in-package :crypto)
;;; class definitions
(defclass rsa-key ()
((n :initarg :n :reader rsa-key-modulus :type integer)))
(defclass rsa-public-key (rsa-key)
((e :initarg :e :reader rsa-key-exponent :type integer)))
(defclass rsa-private-key (rsa-key)
((d :initarg :d :reader rsa-key-exponent :type integer)))
;;; function definitions
(defmethod make-public-key ((kind (eql :rsa))
&key e n &allow-other-keys)
(unless (and e n)
(error "Must specify public exponent and modulus"))
(make-instance 'rsa-public-key :e e :n n))
(defmethod make-private-key ((kind (eql :rsa))
&key d n &allow-other-keys)
(unless (and d n)
(error "Must specify private exponent and modulus"))
(make-instance 'rsa-private-key :d d :n n))
(defmethod generate-key-pair ((kind (eql :rsa)) &key num-bits &allow-other-keys)
(let* ((prng (or *prng* (make-prng :fortuna :seed :random)))
(l (floor num-bits 2))
p q n)
(loop
for a = (generate-safe-prime (- num-bits l) prng)
for b = (generate-safe-prime l prng)
for c = (* a b)
until (and (/= a b) (= num-bits (integer-length c)))
finally (setf p a
q b
n c))
(let* ((phi (* (1- p) (1- q)))
(e (loop
for e = (+ 2 (strong-random (- phi 2) prng))
until (= 1 (gcd e phi))
finally (return e)))
(d (modular-inverse e phi)))
(values (make-private-key :rsa :d d :n n)
(make-public-key :rsa :e e :n n)))))
(defun rsa-core (msg exponent modulus)
(assert (< msg modulus))
(expt-mod msg exponent modulus))
(defmethod encrypt-message ((key rsa-public-key) msg &key (start 0) end oaep &allow-other-keys)
(let ((nbits (integer-length (rsa-key-modulus key)))
(m (subseq msg start end)))
(when oaep
(setf m (oaep-encode :sha1 m (/ nbits 8))))
(setf m (octets-to-integer m))
(integer-to-octets
(rsa-core m (rsa-key-exponent key) (rsa-key-modulus key))
:n-bits nbits)))
(defmethod decrypt-message ((key rsa-private-key) msg &key (start 0) end oaep &allow-other-keys)
(let ((nbits (integer-length (rsa-key-modulus key)))
(m (octets-to-integer msg :start start :end end)))
(if oaep
(oaep-decode :sha1 (integer-to-octets
(rsa-core m (rsa-key-exponent key) (rsa-key-modulus key))
:n-bits nbits))
(integer-to-octets
(rsa-core m (rsa-key-exponent key) (rsa-key-modulus key))))))
(defmethod sign-message ((key rsa-private-key) msg &key (start 0) end pss &allow-other-keys)
(let ((nbits (integer-length (rsa-key-modulus key)))
(m (subseq msg start end)))
(when pss
(setf m (pss-encode :sha1 m (/ nbits 8))))
(setf m (octets-to-integer m))
(integer-to-octets
(rsa-core m (rsa-key-exponent key) (rsa-key-modulus key))
:n-bits nbits)))
(defmethod verify-signature ((key rsa-public-key) msg signature &key (start 0) end pss &allow-other-keys)
(let ((nbits (integer-length (rsa-key-modulus key))))
(unless (= (* 8 (length signature)) nbits)
(error "Bad signature length"))
(if pss
(let ((s (integer-to-octets (rsa-core (octets-to-integer signature)
(rsa-key-exponent key) (rsa-key-modulus key))
:n-bits nbits)))
(pss-verify :sha1 (subseq msg start end) s))
(let ((s (integer-to-octets (rsa-core (octets-to-integer signature)
(rsa-key-exponent key) (rsa-key-modulus key)))))
(equalp s (subseq msg start end))))))
| null | https://raw.githubusercontent.com/froydnj/ironclad/fe88483bba68eac4db3b48bb4a5a40035965fc84/src/public-key/rsa.lisp | lisp | -*- mode: lisp; indent-tabs-mode: nil -*-
class definitions
function definitions | rsa.lisp -- implementation of the RSA public key algorithm
(in-package :crypto)
(defclass rsa-key ()
((n :initarg :n :reader rsa-key-modulus :type integer)))
(defclass rsa-public-key (rsa-key)
((e :initarg :e :reader rsa-key-exponent :type integer)))
(defclass rsa-private-key (rsa-key)
((d :initarg :d :reader rsa-key-exponent :type integer)))
(defmethod make-public-key ((kind (eql :rsa))
&key e n &allow-other-keys)
(unless (and e n)
(error "Must specify public exponent and modulus"))
(make-instance 'rsa-public-key :e e :n n))
(defmethod make-private-key ((kind (eql :rsa))
&key d n &allow-other-keys)
(unless (and d n)
(error "Must specify private exponent and modulus"))
(make-instance 'rsa-private-key :d d :n n))
(defmethod generate-key-pair ((kind (eql :rsa)) &key num-bits &allow-other-keys)
(let* ((prng (or *prng* (make-prng :fortuna :seed :random)))
(l (floor num-bits 2))
p q n)
(loop
for a = (generate-safe-prime (- num-bits l) prng)
for b = (generate-safe-prime l prng)
for c = (* a b)
until (and (/= a b) (= num-bits (integer-length c)))
finally (setf p a
q b
n c))
(let* ((phi (* (1- p) (1- q)))
(e (loop
for e = (+ 2 (strong-random (- phi 2) prng))
until (= 1 (gcd e phi))
finally (return e)))
(d (modular-inverse e phi)))
(values (make-private-key :rsa :d d :n n)
(make-public-key :rsa :e e :n n)))))
(defun rsa-core (msg exponent modulus)
(assert (< msg modulus))
(expt-mod msg exponent modulus))
(defmethod encrypt-message ((key rsa-public-key) msg &key (start 0) end oaep &allow-other-keys)
(let ((nbits (integer-length (rsa-key-modulus key)))
(m (subseq msg start end)))
(when oaep
(setf m (oaep-encode :sha1 m (/ nbits 8))))
(setf m (octets-to-integer m))
(integer-to-octets
(rsa-core m (rsa-key-exponent key) (rsa-key-modulus key))
:n-bits nbits)))
(defmethod decrypt-message ((key rsa-private-key) msg &key (start 0) end oaep &allow-other-keys)
(let ((nbits (integer-length (rsa-key-modulus key)))
(m (octets-to-integer msg :start start :end end)))
(if oaep
(oaep-decode :sha1 (integer-to-octets
(rsa-core m (rsa-key-exponent key) (rsa-key-modulus key))
:n-bits nbits))
(integer-to-octets
(rsa-core m (rsa-key-exponent key) (rsa-key-modulus key))))))
(defmethod sign-message ((key rsa-private-key) msg &key (start 0) end pss &allow-other-keys)
(let ((nbits (integer-length (rsa-key-modulus key)))
(m (subseq msg start end)))
(when pss
(setf m (pss-encode :sha1 m (/ nbits 8))))
(setf m (octets-to-integer m))
(integer-to-octets
(rsa-core m (rsa-key-exponent key) (rsa-key-modulus key))
:n-bits nbits)))
(defmethod verify-signature ((key rsa-public-key) msg signature &key (start 0) end pss &allow-other-keys)
(let ((nbits (integer-length (rsa-key-modulus key))))
(unless (= (* 8 (length signature)) nbits)
(error "Bad signature length"))
(if pss
(let ((s (integer-to-octets (rsa-core (octets-to-integer signature)
(rsa-key-exponent key) (rsa-key-modulus key))
:n-bits nbits)))
(pss-verify :sha1 (subseq msg start end) s))
(let ((s (integer-to-octets (rsa-core (octets-to-integer signature)
(rsa-key-exponent key) (rsa-key-modulus key)))))
(equalp s (subseq msg start end))))))
|
a75c17456aabbd4ce49022dd8f62a71f0904ea4acccebe8784ea0ef42741a599 | jimweirich/sicp-study | ex2_20.scm | Exercise 2.20 . The procedures + , * , and list take arbitrary
numbers of arguments . One way to define such procedures is to use
;; define with dotted-tail notation. In a procedure definition, a
;; parameter list that has a dot before the last parameter name
;; indicates that, when the procedure is called, the initial
;; parameters (if any) will have as values the initial arguments, as
;; usual, but the final parameter's value will be a list of any
;; remaining arguments. For instance, given the definition
;; (define (f x y . z) <body>)
the procedure f can be called with two or more arguments . If we
;; evaluate
;; (f 1 2 3 4 5 6)
then in the body of f , x will be 1 , y will be 2 , and z will be the
list ( 3 4 5 6 ) . Given the definition
;; (define (g . w) <body>)
the procedure g can be called with zero or more arguments . If we
;; evaluate
;; (g 1 2 3 4 5 6)
then in the body of g , w will be the list ( 1 2 3 4 5 6).11
Use this notation to write a procedure same - parity that takes one
;; or more integers and returns a list of all the arguments that have
the same even - odd parity as the first argument . For example ,
( same - parity 1 2 3 4 5 6 7 )
;; (1 3 5 7)
( same - parity 2 3 4 5 6 7 )
( 2 4 6 )
;; ANSWER ------------------------------------------------------------
(define (same-parity sample . rest)
(let ((m (remainder sample 2)))
(define (choose rest result)
(cond ((null? rest) result)
((= m (remainder (car rest) 2))
(choose (cdr rest) (cons (car rest) result)))
(else
(choose (cdr rest) result))))
(reverse (choose rest (list sample)))))
| null | https://raw.githubusercontent.com/jimweirich/sicp-study/bc5190e04ed6ae321107ed6149241f26efc1b8c8/scheme/chapter2/ex2_20.scm | scheme | define with dotted-tail notation. In a procedure definition, a
parameter list that has a dot before the last parameter name
indicates that, when the procedure is called, the initial
parameters (if any) will have as values the initial arguments, as
usual, but the final parameter's value will be a list of any
remaining arguments. For instance, given the definition
(define (f x y . z) <body>)
evaluate
(f 1 2 3 4 5 6)
(define (g . w) <body>)
evaluate
(g 1 2 3 4 5 6)
or more integers and returns a list of all the arguments that have
(1 3 5 7)
ANSWER ------------------------------------------------------------ | Exercise 2.20 . The procedures + , * , and list take arbitrary
numbers of arguments . One way to define such procedures is to use
the procedure f can be called with two or more arguments . If we
then in the body of f , x will be 1 , y will be 2 , and z will be the
list ( 3 4 5 6 ) . Given the definition
the procedure g can be called with zero or more arguments . If we
then in the body of g , w will be the list ( 1 2 3 4 5 6).11
Use this notation to write a procedure same - parity that takes one
the same even - odd parity as the first argument . For example ,
( same - parity 1 2 3 4 5 6 7 )
( same - parity 2 3 4 5 6 7 )
( 2 4 6 )
(define (same-parity sample . rest)
(let ((m (remainder sample 2)))
(define (choose rest result)
(cond ((null? rest) result)
((= m (remainder (car rest) 2))
(choose (cdr rest) (cons (car rest) result)))
(else
(choose (cdr rest) result))))
(reverse (choose rest (list sample)))))
|
d54d95d47a6f94cb431d29593e0354bf0f4274f081bb3448ec1e7cd34f04eb18 | ericclack/racket-examples | asteroids4.rkt | #lang racket
#|
Asteroids - (go) to run.
Left / right to rotate
Up / down to speed up, slow down
Space to fire.
DONE:
- Score
TODO:
- Lives
|#
(require 2htdp/universe 2htdp/image)
(require "util.rkt")
(struct world (asteroids ship bullets score) #:transparent)
(struct pos (x y) #:transparent)
(struct ship (pos direction speed) #:transparent)
(struct asteroid (pos direction speed size) #:transparent)
(struct bullet (pos direction speed) #:transparent)
(define BIG-ASTEROID 60)
(define NUM-ASTEROIDS 5)
(define BULLET-SPEED 5)
(define SHIP-SIZE 30)
(define TICK-RATE 1/30)
(define WIDTH 800)
(define HEIGHT 600)
;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(define (new-asteroid)
(asteroid (pos (random WIDTH) (random HEIGHT))
(random 360) (+ 1 (random 2)) BIG-ASTEROID))
(define (move-pos a-pos a-direction a-speed)
(define r (degrees->radians a-direction))
(pos (+ (pos-x a-pos) (* a-speed (cos r)))
(+ (pos-y a-pos) (* a-speed (sin r)))))
(define (wrap-pos a-pos a-size)
(define x (pos-x a-pos))
(define y (pos-y a-pos))
(pos (cond
[(> x (+ WIDTH a-size)) (- 0 a-size)]
[(< x (- 0 a-size)) (+ WIDTH a-size)]
[else x])
(cond
[(> y (+ HEIGHT a-size)) (- 0 a-size)]
[(< y (- 0 a-size)) (+ HEIGHT a-size)]
[else y])))
(define (inside-circle circle-pos radius a-pos)
(define distance
(sqrt (+ (expt (- (pos-x a-pos) (pos-x circle-pos)) 2)
(expt (- (pos-y a-pos) (pos-y circle-pos)) 2))))
(<= distance radius))
(define (bullet-in-range a-bullet)
(define x (pos-x (bullet-pos a-bullet)))
(define y (pos-y (bullet-pos a-bullet)))
(and (> x 0) (< x WIDTH) (> y 0) (< y HEIGHT)))
(define (move-asteroid a)
(asteroid (wrap-pos
(move-pos (asteroid-pos a) (asteroid-direction a) (asteroid-speed a))
(asteroid-size a))
(asteroid-direction a)
(asteroid-speed a)
(asteroid-size a)))
(define (new-bullet a-ship)
(bullet (ship-pos a-ship)
(ship-direction a-ship)
(+ (ship-speed a-ship) BULLET-SPEED)))
(define (move-bullet b)
(bullet (move-pos (bullet-pos b) (bullet-direction b) (bullet-speed b))
(bullet-direction b)
(bullet-speed b)))
(define (hit-asteroids asteroids bullets)
If any asteroids have been hit , split them in half .
;; Asteroids that are too small are deleted.
;; A list like this (a a a a a) will result in a list
;; like this (a a (a a) a a) on hit, we use flatten
;; to return the right thing.
(define (hit-asteroid? a bullets)
;; Has this asteroid been hit by any of the bullets?
(cond
[(empty? bullets) #f]
[(inside-circle (asteroid-pos a) (asteroid-size a)
(bullet-pos (car bullets))) #t]
[else
(hit-asteroid? a (cdr bullets))]))
(define (split-asteroid a)
(list (asteroid (asteroid-pos a) (- (asteroid-direction a) 90)
(asteroid-speed a) (/ (asteroid-size a) 2))
(asteroid (asteroid-pos a) (+ (asteroid-direction a) 90)
(asteroid-speed a) (/ (asteroid-size a) 2))))
(define (bullets-hit-asteroid a)
(if (hit-asteroid? a bullets)
(split-asteroid a)
a))
(define (big-enough a)
(> (asteroid-size a) 5))
(filter big-enough (flatten (map bullets-hit-asteroid asteroids))))
(define (asteroids-diff prev-asteroids next-asteroids)
;; +1 point each time the number of asteroids decreases
;; regardless of size
(define diff (- (length prev-asteroids)
(length next-asteroids)))
(if (> diff 0) diff 0))
(define (live-bullets asteroids bullets)
;; Like hit-asteroids, but returns only bullets that
;; have not hit an asteroid
(define (bullet-hit? b asteroids)
(cond
[(empty? asteroids) #f]
[(inside-circle (asteroid-pos (car asteroids))
(asteroid-size (car asteroids))
(bullet-pos b)) #t]
[else (bullet-hit? b (cdr asteroids))]))
(define (bullet-hit-no-asteroids b)
(not (bullet-hit? b asteroids)))
(filter bullet-hit-no-asteroids bullets))
(define (move-ship a-ship)
(ship (wrap-pos
(move-pos (ship-pos a-ship) (ship-direction a-ship) (ship-speed a-ship))
SHIP-SIZE)
(ship-direction a-ship)
(ship-speed a-ship)))
(define (next-world w)
(define next-asteroids (hit-asteroids (world-asteroids w) (world-bullets w)))
(define next-bullets (live-bullets (world-asteroids w) (world-bullets w)))
(define add-score (asteroids-diff (world-asteroids w) next-asteroids))
(world (map move-asteroid next-asteroids)
(move-ship (world-ship w))
(filter bullet-in-range (map move-bullet next-bullets))
(+ add-score (world-score w))))
;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;; Rendering
(define (img+scene pos img scene)
(place-image img (pos-x pos) (pos-y pos) scene))
(define (ship-img a-direction)
(rotate (- 270 a-direction)
(overlay/offset (triangle SHIP-SIZE "solid" "white") 0 8
(triangle SHIP-SIZE "solid" "white"))))
(define (ship+scene a-ship scene)
(img+scene (ship-pos a-ship)
(ship-img (ship-direction a-ship))
scene))
(define (asteroids+scene asteroids scene)
(foldl (λ (a scene)
(img+scene (asteroid-pos a)
(circle (asteroid-size a) "solid" "gray")
scene))
scene asteroids))
(define (bullets+scene bullets scene)
(foldl (λ (b scene)
(img+scene (bullet-pos b)
(circle 2 "solid" "yellow")
scene))
scene bullets))
(define (score+scene score scene)
(place-image (text (string-append "Score: "
(number->string score))
24 "white") 55 20 scene))
(define (render-world w)
(score+scene (world-score w)
(ship+scene (world-ship w)
(asteroids+scene (world-asteroids w)
(bullets+scene (world-bullets w)
(empty-scene WIDTH HEIGHT "black"))))))
;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(define (direct-ship w a-key)
(define a-ship (world-ship w))
(define a-direction
(+ (ship-direction a-ship)
(cond
[(key=? a-key "left") -5]
[(key=? a-key "right") 5]
[else 0])))
(define a-speed
(+ (ship-speed a-ship)
(cond
[(key=? a-key "up") 1]
[(key=? a-key "down") -1]
[else 0])))
(define bullets
(cond
[(key=? a-key " ") (cons (new-bullet a-ship) (world-bullets w))]
[else (world-bullets w)]))
(world (world-asteroids w)
(ship (ship-pos a-ship) a-direction a-speed)
bullets
(world-score w)))
(define (ship-crashed? w)
(define a-ship (world-ship w))
(define (ship-hit-asteroids? asteroids)
(cond
[(empty? asteroids) #f]
[(inside-circle (asteroid-pos (car asteroids))
(+ (asteroid-size (car asteroids))
(/ SHIP-SIZE 2))
(ship-pos a-ship)) #t]
[else (ship-hit-asteroids? (cdr asteroids))]))
(ship-hit-asteroids? (world-asteroids w)))
(define (new-world)
;; Produce a world in which the ship has not just crashed
(define asteroids (times-repeat NUM-ASTEROIDS (new-asteroid)))
(define a-ship (ship (pos (/ WIDTH 2) (/ HEIGHT 2)) 0 0))
(define a-world
(world asteroids a-ship '() 0))
(if (ship-crashed? a-world)
(new-world)
a-world))
(define (go)
(big-bang (new-world)
(on-tick next-world TICK-RATE)
(on-key direct-ship)
(to-draw render-world)
(stop-when ship-crashed?)))
| null | https://raw.githubusercontent.com/ericclack/racket-examples/ee858daac3577ead0c8463b9701a8653220039de/asteroids4.rkt | racket |
Asteroids - (go) to run.
Left / right to rotate
Up / down to speed up, slow down
Space to fire.
DONE:
- Score
TODO:
- Lives
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Asteroids that are too small are deleted.
A list like this (a a a a a) will result in a list
like this (a a (a a) a a) on hit, we use flatten
to return the right thing.
Has this asteroid been hit by any of the bullets?
+1 point each time the number of asteroids decreases
regardless of size
Like hit-asteroids, but returns only bullets that
have not hit an asteroid
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Rendering
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Produce a world in which the ship has not just crashed | #lang racket
(require 2htdp/universe 2htdp/image)
(require "util.rkt")
(struct world (asteroids ship bullets score) #:transparent)
(struct pos (x y) #:transparent)
(struct ship (pos direction speed) #:transparent)
(struct asteroid (pos direction speed size) #:transparent)
(struct bullet (pos direction speed) #:transparent)
(define BIG-ASTEROID 60)
(define NUM-ASTEROIDS 5)
(define BULLET-SPEED 5)
(define SHIP-SIZE 30)
(define TICK-RATE 1/30)
(define WIDTH 800)
(define HEIGHT 600)
(define (new-asteroid)
(asteroid (pos (random WIDTH) (random HEIGHT))
(random 360) (+ 1 (random 2)) BIG-ASTEROID))
(define (move-pos a-pos a-direction a-speed)
(define r (degrees->radians a-direction))
(pos (+ (pos-x a-pos) (* a-speed (cos r)))
(+ (pos-y a-pos) (* a-speed (sin r)))))
(define (wrap-pos a-pos a-size)
(define x (pos-x a-pos))
(define y (pos-y a-pos))
(pos (cond
[(> x (+ WIDTH a-size)) (- 0 a-size)]
[(< x (- 0 a-size)) (+ WIDTH a-size)]
[else x])
(cond
[(> y (+ HEIGHT a-size)) (- 0 a-size)]
[(< y (- 0 a-size)) (+ HEIGHT a-size)]
[else y])))
(define (inside-circle circle-pos radius a-pos)
(define distance
(sqrt (+ (expt (- (pos-x a-pos) (pos-x circle-pos)) 2)
(expt (- (pos-y a-pos) (pos-y circle-pos)) 2))))
(<= distance radius))
(define (bullet-in-range a-bullet)
(define x (pos-x (bullet-pos a-bullet)))
(define y (pos-y (bullet-pos a-bullet)))
(and (> x 0) (< x WIDTH) (> y 0) (< y HEIGHT)))
(define (move-asteroid a)
(asteroid (wrap-pos
(move-pos (asteroid-pos a) (asteroid-direction a) (asteroid-speed a))
(asteroid-size a))
(asteroid-direction a)
(asteroid-speed a)
(asteroid-size a)))
(define (new-bullet a-ship)
(bullet (ship-pos a-ship)
(ship-direction a-ship)
(+ (ship-speed a-ship) BULLET-SPEED)))
(define (move-bullet b)
(bullet (move-pos (bullet-pos b) (bullet-direction b) (bullet-speed b))
(bullet-direction b)
(bullet-speed b)))
(define (hit-asteroids asteroids bullets)
If any asteroids have been hit , split them in half .
(define (hit-asteroid? a bullets)
(cond
[(empty? bullets) #f]
[(inside-circle (asteroid-pos a) (asteroid-size a)
(bullet-pos (car bullets))) #t]
[else
(hit-asteroid? a (cdr bullets))]))
(define (split-asteroid a)
(list (asteroid (asteroid-pos a) (- (asteroid-direction a) 90)
(asteroid-speed a) (/ (asteroid-size a) 2))
(asteroid (asteroid-pos a) (+ (asteroid-direction a) 90)
(asteroid-speed a) (/ (asteroid-size a) 2))))
(define (bullets-hit-asteroid a)
(if (hit-asteroid? a bullets)
(split-asteroid a)
a))
(define (big-enough a)
(> (asteroid-size a) 5))
(filter big-enough (flatten (map bullets-hit-asteroid asteroids))))
(define (asteroids-diff prev-asteroids next-asteroids)
(define diff (- (length prev-asteroids)
(length next-asteroids)))
(if (> diff 0) diff 0))
(define (live-bullets asteroids bullets)
(define (bullet-hit? b asteroids)
(cond
[(empty? asteroids) #f]
[(inside-circle (asteroid-pos (car asteroids))
(asteroid-size (car asteroids))
(bullet-pos b)) #t]
[else (bullet-hit? b (cdr asteroids))]))
(define (bullet-hit-no-asteroids b)
(not (bullet-hit? b asteroids)))
(filter bullet-hit-no-asteroids bullets))
(define (move-ship a-ship)
(ship (wrap-pos
(move-pos (ship-pos a-ship) (ship-direction a-ship) (ship-speed a-ship))
SHIP-SIZE)
(ship-direction a-ship)
(ship-speed a-ship)))
(define (next-world w)
(define next-asteroids (hit-asteroids (world-asteroids w) (world-bullets w)))
(define next-bullets (live-bullets (world-asteroids w) (world-bullets w)))
(define add-score (asteroids-diff (world-asteroids w) next-asteroids))
(world (map move-asteroid next-asteroids)
(move-ship (world-ship w))
(filter bullet-in-range (map move-bullet next-bullets))
(+ add-score (world-score w))))
(define (img+scene pos img scene)
(place-image img (pos-x pos) (pos-y pos) scene))
(define (ship-img a-direction)
(rotate (- 270 a-direction)
(overlay/offset (triangle SHIP-SIZE "solid" "white") 0 8
(triangle SHIP-SIZE "solid" "white"))))
(define (ship+scene a-ship scene)
(img+scene (ship-pos a-ship)
(ship-img (ship-direction a-ship))
scene))
(define (asteroids+scene asteroids scene)
(foldl (λ (a scene)
(img+scene (asteroid-pos a)
(circle (asteroid-size a) "solid" "gray")
scene))
scene asteroids))
(define (bullets+scene bullets scene)
(foldl (λ (b scene)
(img+scene (bullet-pos b)
(circle 2 "solid" "yellow")
scene))
scene bullets))
(define (score+scene score scene)
(place-image (text (string-append "Score: "
(number->string score))
24 "white") 55 20 scene))
(define (render-world w)
(score+scene (world-score w)
(ship+scene (world-ship w)
(asteroids+scene (world-asteroids w)
(bullets+scene (world-bullets w)
(empty-scene WIDTH HEIGHT "black"))))))
(define (direct-ship w a-key)
(define a-ship (world-ship w))
(define a-direction
(+ (ship-direction a-ship)
(cond
[(key=? a-key "left") -5]
[(key=? a-key "right") 5]
[else 0])))
(define a-speed
(+ (ship-speed a-ship)
(cond
[(key=? a-key "up") 1]
[(key=? a-key "down") -1]
[else 0])))
(define bullets
(cond
[(key=? a-key " ") (cons (new-bullet a-ship) (world-bullets w))]
[else (world-bullets w)]))
(world (world-asteroids w)
(ship (ship-pos a-ship) a-direction a-speed)
bullets
(world-score w)))
(define (ship-crashed? w)
(define a-ship (world-ship w))
(define (ship-hit-asteroids? asteroids)
(cond
[(empty? asteroids) #f]
[(inside-circle (asteroid-pos (car asteroids))
(+ (asteroid-size (car asteroids))
(/ SHIP-SIZE 2))
(ship-pos a-ship)) #t]
[else (ship-hit-asteroids? (cdr asteroids))]))
(ship-hit-asteroids? (world-asteroids w)))
(define (new-world)
(define asteroids (times-repeat NUM-ASTEROIDS (new-asteroid)))
(define a-ship (ship (pos (/ WIDTH 2) (/ HEIGHT 2)) 0 0))
(define a-world
(world asteroids a-ship '() 0))
(if (ship-crashed? a-world)
(new-world)
a-world))
(define (go)
(big-bang (new-world)
(on-tick next-world TICK-RATE)
(on-key direct-ship)
(to-draw render-world)
(stop-when ship-crashed?)))
|
deefaee6152a2fd2fbf85e962688f55943d0ace1e7f5569b27750b47353c0229 | thheller/shadow-cljs | deps.cljs | {:externs
["foo/externs.js"]
:foreign-libs
[{:file "file.js"
:file-min "file-min.js"
:externs ["file-externs.js"]
:provides ["file"]}]}
| null | https://raw.githubusercontent.com/thheller/shadow-cljs/ba0a02aec050c6bc8db1932916009400f99d3cce/test/resource-dir/deps.cljs | clojure | {:externs
["foo/externs.js"]
:foreign-libs
[{:file "file.js"
:file-min "file-min.js"
:externs ["file-externs.js"]
:provides ["file"]}]}
| |
7ad82252f080e8dc6629d8d4084959b1bbcc4157d78116c4751e3a26b7df9747 | TheLortex/mirage-monorepo | integer_interface.ml | module type S = sig
type t
val zero : t
(** Integer 0. *)
val one : t
(** Integer 1. *)
val minus_one : t
(** Integer (-1). *)
val neg : t -> t
(** Unary negation. *)
val add : t -> t -> t
(** Addition. *)
val sub : t -> t -> t
(** Subtraction. *)
val mul : t -> t -> t
(** Mulitplication. *)
val div : t -> t -> t
* Integer division . Raise [ Division_by_zero ] if the second argument is zero .
This division rounds the real quotient of its arguments towrds zero .
This division rounds the real quotient of its arguments towrds zero. *)
val rem : t -> t -> t
* Integer remainder . If [ y ] is not zero , the result of [ rem x y ] satisfies
the following property : [ x = add ( mul ( div x y ) y ) ( rem x y ) ] . if [ y = 0 ] ,
[ rem x y ] raises [ Division_by_zero ] .
the following property: [x = add (mul (div x y) y) (rem x y)]. if [y = 0],
[rem x y] raises [Division_by_zero]. *)
val succ : t -> t
(** Successor. [succ x] is [add x one]. *)
val pred : t -> t
(** Predecessor. [pred x] is [sub x one]. *)
val abs : t -> t
(** Return the absolute value its argument. *)
val max_int : t
(** The greatest representable integer. *)
val min_int : t
(** The smallest representable integer. *)
val logand : t -> t -> t
(** Bitwise logical and. *)
val logor : t -> t -> t
(** Bitwise logical or. *)
val logxor : t -> t -> t
(** Bitwise logical exclusive or. *)
val lognot : t -> t
(** Bitwise logical negation. *)
val shift_left : t -> int -> t
* [ shift_left x y ] shifts [ x ] to the left by [ y ] bits . The result is
unspecified if [ y < 0 ] or [ y > = ( 32 || 63 ) ] .
unspecified if [y < 0] or [y >= (32 || 63)]. *)
val shift_right : t -> int -> t
* [ shift_right x y ] shifts [ x ] to the right by [ y ] bits . This is an
arithmetic shift : the sign bit of [ x ] is replicated and inserted in the
vacated bits . The result is unspecified if [ y < 0 ] or [ y > = ( 32 || 63 ) ] .
arithmetic shift: the sign bit of [x] is replicated and inserted in the
vacated bits. The result is unspecified if [y < 0] or [y >= (32 || 63)]. *)
val shift_right_logical : t -> int -> t
* [ shift_right_logical x y ] shifts [ x ] to the right by [ y ] bits . This is a
logical shift : zeroes are inserted in the vacated bits regardless of the
sign of [ x ] / The result is unspecified if [ y < 0 ] or [ y > = ( 32 || 63 ) ] .
logical shift: zeroes are inserted in the vacated bits regardless of the
sign of [x] / The result is unspecified if [y < 0] or [y >= (32 || 63)]. *)
val of_int : int -> t
(** Convert the given integer (type [int] ) to {!t}. It's an unsafe function
whose semantic is different from architecture. *)
val to_int : t -> int
* Convert the given { ! t } integer to an integer ( type [ int ] ) . On 64 - bit
platforms , the conversion is exact . On 32 - bit platforms , the 32 - bit
integer is taken modulo 2 { ^ 31 } , i.e. the high - order bit is lost during
the conversion .
platforms, the conversion is exact. On 32-bit platforms, the 32-bit
integer is taken modulo 2 {^ 31}, i.e. the high-order bit is lost during
the conversion. *)
val of_int32 : int32 -> t
* Convert the given 32 - bit integer ( type [ int32 ] ) to { ! t } integer . It 's an
unsafe function whose semantic is different from architecture .
unsafe function whose semantic is different from architecture. *)
val to_int32 : t -> int32
* Convert the given { ! t } integer to a 32 - bit integer .
val of_int64 : int64 -> t
* Convert the given 64 - bit integer ( type [ int64 ] ) to { ! t } integer .
val to_int64 : t -> int64
* Covert the given { ! t } integer to a 64 - bit integer .
val of_float : float -> t
(** Convert the given floating-point number to a {!t} integer, discarding the
fractional part (truncate towards 0). The result of the conversion is
undefined if, after truncation, the number is outside the range
{!min_int}, {!max_int}. *)
val to_float : t -> float
(** Convert the given {!t} integer to a floating-point number. *)
val of_string : string -> t
* Convert the given string to a { ! t } integer . The string is read in decimal
( by default , or if the string begins with [ 0u ] ) or in hexadecimal , octal
or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ] respectively .
The [ 0u ] prefix reads the input as an unsigned integer in the range
[ \[0 , 2 * max_int + 1\ ] ] . If the input exceeds { ! max_int } it is converted
to the signed integer [ min_int + input - max_int - 1 ] .
The [ _ ] ( underscore ) character can appear anywhere in the string is
ignored . Raise [ Failure _ ] if the given string is not a valid
representation of an integer , or if the integer represented exceeds the
range of integer , or if the integer represented exceeds the range of
integers representable in type { ! t } .
(by default, or if the string begins with [0u]) or in hexadecimal, octal
or binary if the string begins with [0x], [0o] or [0b] respectively.
The [0u] prefix reads the input as an unsigned integer in the range
[\[0, 2 * max_int + 1\]]. If the input exceeds {!max_int} it is converted
to the signed integer [min_int + input - max_int - 1].
The [_] (underscore) character can appear anywhere in the string is
ignored. Raise [Failure _] if the given string is not a valid
representation of an integer, or if the integer represented exceeds the
range of integer, or if the integer represented exceeds the range of
integers representable in type {!t}. *)
val of_string_opt : string -> t option
(** Same as [of_string], but return [None] instead of raising. *)
val to_string : t -> string
(** Return the string representation of its argument, in decimal. *)
val compare : t -> t -> int
(** The comparison function for {!t} integers, with the same specification as
{!Stdlib.compare}. Along with the type [t], this function [compare] allows
the module [Optint] to be passed as argument to the functors {!Set.Make}
and {!Map.Make}. *)
val equal : t -> t -> bool
(** The equal function for {!t}. *)
val pp : Format.formatter -> t -> unit
(** The pretty-printer for {!t}. *)
(** {2 Encoding functions}
Efficient fixed-length big-endian encoding functions for {!t} integers: *)
val encode : bytes -> off:int -> t -> unit
val decode : string -> off:int -> t
val encoded_size : int
(** The number of bytes in the {{!encode} encoded} form of {!t}. *)
val to_unsigned_int32 : t -> int32
val of_unsigned_int32 : int32 -> t
val to_unsigned_int : t -> int
val of_unsigned_int : int -> t
module Infix : sig
val ( + ) : t -> t -> t
val ( - ) : t -> t -> t
val ( * ) : t -> t -> t
val ( % ) : t -> t -> t
val ( / ) : t -> t -> t
val ( && ) : t -> t -> t
val ( || ) : t -> t -> t
val ( >> ) : t -> int -> t
val ( << ) : t -> int -> t
end
end
| null | https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/optint/src/integer_interface.ml | ocaml | * Integer 0.
* Integer 1.
* Integer (-1).
* Unary negation.
* Addition.
* Subtraction.
* Mulitplication.
* Successor. [succ x] is [add x one].
* Predecessor. [pred x] is [sub x one].
* Return the absolute value its argument.
* The greatest representable integer.
* The smallest representable integer.
* Bitwise logical and.
* Bitwise logical or.
* Bitwise logical exclusive or.
* Bitwise logical negation.
* Convert the given integer (type [int] ) to {!t}. It's an unsafe function
whose semantic is different from architecture.
* Convert the given floating-point number to a {!t} integer, discarding the
fractional part (truncate towards 0). The result of the conversion is
undefined if, after truncation, the number is outside the range
{!min_int}, {!max_int}.
* Convert the given {!t} integer to a floating-point number.
* Same as [of_string], but return [None] instead of raising.
* Return the string representation of its argument, in decimal.
* The comparison function for {!t} integers, with the same specification as
{!Stdlib.compare}. Along with the type [t], this function [compare] allows
the module [Optint] to be passed as argument to the functors {!Set.Make}
and {!Map.Make}.
* The equal function for {!t}.
* The pretty-printer for {!t}.
* {2 Encoding functions}
Efficient fixed-length big-endian encoding functions for {!t} integers:
* The number of bytes in the {{!encode} encoded} form of {!t}. | module type S = sig
type t
val zero : t
val one : t
val minus_one : t
val neg : t -> t
val add : t -> t -> t
val sub : t -> t -> t
val mul : t -> t -> t
val div : t -> t -> t
* Integer division . Raise [ Division_by_zero ] if the second argument is zero .
This division rounds the real quotient of its arguments towrds zero .
This division rounds the real quotient of its arguments towrds zero. *)
val rem : t -> t -> t
* Integer remainder . If [ y ] is not zero , the result of [ rem x y ] satisfies
the following property : [ x = add ( mul ( div x y ) y ) ( rem x y ) ] . if [ y = 0 ] ,
[ rem x y ] raises [ Division_by_zero ] .
the following property: [x = add (mul (div x y) y) (rem x y)]. if [y = 0],
[rem x y] raises [Division_by_zero]. *)
val succ : t -> t
val pred : t -> t
val abs : t -> t
val max_int : t
val min_int : t
val logand : t -> t -> t
val logor : t -> t -> t
val logxor : t -> t -> t
val lognot : t -> t
val shift_left : t -> int -> t
* [ shift_left x y ] shifts [ x ] to the left by [ y ] bits . The result is
unspecified if [ y < 0 ] or [ y > = ( 32 || 63 ) ] .
unspecified if [y < 0] or [y >= (32 || 63)]. *)
val shift_right : t -> int -> t
* [ shift_right x y ] shifts [ x ] to the right by [ y ] bits . This is an
arithmetic shift : the sign bit of [ x ] is replicated and inserted in the
vacated bits . The result is unspecified if [ y < 0 ] or [ y > = ( 32 || 63 ) ] .
arithmetic shift: the sign bit of [x] is replicated and inserted in the
vacated bits. The result is unspecified if [y < 0] or [y >= (32 || 63)]. *)
val shift_right_logical : t -> int -> t
* [ shift_right_logical x y ] shifts [ x ] to the right by [ y ] bits . This is a
logical shift : zeroes are inserted in the vacated bits regardless of the
sign of [ x ] / The result is unspecified if [ y < 0 ] or [ y > = ( 32 || 63 ) ] .
logical shift: zeroes are inserted in the vacated bits regardless of the
sign of [x] / The result is unspecified if [y < 0] or [y >= (32 || 63)]. *)
val of_int : int -> t
val to_int : t -> int
* Convert the given { ! t } integer to an integer ( type [ int ] ) . On 64 - bit
platforms , the conversion is exact . On 32 - bit platforms , the 32 - bit
integer is taken modulo 2 { ^ 31 } , i.e. the high - order bit is lost during
the conversion .
platforms, the conversion is exact. On 32-bit platforms, the 32-bit
integer is taken modulo 2 {^ 31}, i.e. the high-order bit is lost during
the conversion. *)
val of_int32 : int32 -> t
* Convert the given 32 - bit integer ( type [ int32 ] ) to { ! t } integer . It 's an
unsafe function whose semantic is different from architecture .
unsafe function whose semantic is different from architecture. *)
val to_int32 : t -> int32
* Convert the given { ! t } integer to a 32 - bit integer .
val of_int64 : int64 -> t
* Convert the given 64 - bit integer ( type [ int64 ] ) to { ! t } integer .
val to_int64 : t -> int64
* Covert the given { ! t } integer to a 64 - bit integer .
val of_float : float -> t
val to_float : t -> float
val of_string : string -> t
* Convert the given string to a { ! t } integer . The string is read in decimal
( by default , or if the string begins with [ 0u ] ) or in hexadecimal , octal
or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ] respectively .
The [ 0u ] prefix reads the input as an unsigned integer in the range
[ \[0 , 2 * max_int + 1\ ] ] . If the input exceeds { ! max_int } it is converted
to the signed integer [ min_int + input - max_int - 1 ] .
The [ _ ] ( underscore ) character can appear anywhere in the string is
ignored . Raise [ Failure _ ] if the given string is not a valid
representation of an integer , or if the integer represented exceeds the
range of integer , or if the integer represented exceeds the range of
integers representable in type { ! t } .
(by default, or if the string begins with [0u]) or in hexadecimal, octal
or binary if the string begins with [0x], [0o] or [0b] respectively.
The [0u] prefix reads the input as an unsigned integer in the range
[\[0, 2 * max_int + 1\]]. If the input exceeds {!max_int} it is converted
to the signed integer [min_int + input - max_int - 1].
The [_] (underscore) character can appear anywhere in the string is
ignored. Raise [Failure _] if the given string is not a valid
representation of an integer, or if the integer represented exceeds the
range of integer, or if the integer represented exceeds the range of
integers representable in type {!t}. *)
val of_string_opt : string -> t option
val to_string : t -> string
val compare : t -> t -> int
val equal : t -> t -> bool
val pp : Format.formatter -> t -> unit
val encode : bytes -> off:int -> t -> unit
val decode : string -> off:int -> t
val encoded_size : int
val to_unsigned_int32 : t -> int32
val of_unsigned_int32 : int32 -> t
val to_unsigned_int : t -> int
val of_unsigned_int : int -> t
module Infix : sig
val ( + ) : t -> t -> t
val ( - ) : t -> t -> t
val ( * ) : t -> t -> t
val ( % ) : t -> t -> t
val ( / ) : t -> t -> t
val ( && ) : t -> t -> t
val ( || ) : t -> t -> t
val ( >> ) : t -> int -> t
val ( << ) : t -> int -> t
end
end
|
5bb92a1f7d7b0744904e2566b35c1001e9805d03c8a63df77956c8f2725bbe71 | carotene/carotene | carotene_subscriber_sup.erl | -module(carotene_subscriber_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
-export([start_child/1]).
%% Supervisor callbacks
-export([init/1]).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
start_child(Args) ->
supervisor:start_child(?MODULE, Args).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init([]) ->
{ok, { {simple_one_for_one, 5, 10}, [
{carotene_subscriber,
{carotene_subscriber, start_link, []},
temporary,
infinity,
worker,
[carotene_subscriber]
} ]} }.
| null | https://raw.githubusercontent.com/carotene/carotene/963ecad344ec1c318c173ad828a5af3c000ddbfc/src/carotene_subscriber_sup.erl | erlang | API
Supervisor callbacks
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
=================================================================== | -module(carotene_subscriber_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([start_child/1]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
start_child(Args) ->
supervisor:start_child(?MODULE, Args).
init([]) ->
{ok, { {simple_one_for_one, 5, 10}, [
{carotene_subscriber,
{carotene_subscriber, start_link, []},
temporary,
infinity,
worker,
[carotene_subscriber]
} ]} }.
|
0656d62a63413af2edb23737be15246a439310fd940cc7a5ecaa3081cf7eb6be | WickedShell/clj-mavlink | core.clj | (ns mavlink.core
(:require [clojure.core.async :as async]
[mavlink.checksum :refer :all]
[mavlink.type :refer [byte-to-long]]
[mavlink.mavlink_xml :refer :all])
(:import [java.io InputStream OutputStream DataOutputStream IOException]
[java.nio ByteBuffer ByteOrder]
[java.security MessageDigest]
[java.lang System]))
(defonce ^:const INCOMPAT-FLAG-SIGNED 0x01)
(defonce ^:const MAVLINK1-START-VALUE 254)
(defonce MAVLINK1-START-BYTE (.byteValue (new Long MAVLINK1-START-VALUE)))
(defonce ^:const MAVLINK1-HDR-SIZE 6)
(defonce ^:const MAVLINK1-HDR-CRC-SIZE 8)
(defonce ^:const MAVLINK2-START-VALUE 253)
(defonce MAVLINK2-START-BYTE (.byteValue (new Long MAVLINK2-START-VALUE)))
(defonce ^:const MAVLINK2-HDR-SIZE 10)
(defonce ^:const MAVLINK2-HDR-CRC-SIZE 12)
(defonce ^:const MAVLINK2-HDR-CRC-SIGN-SIZE 25)
(defonce ^:const MAVLINK2-SIGN-SIZE 13)
(defonce ^:const SIGN-PACKETS-FLAG 0x1)
(defonce ^:const BUFFER-SIZE (+ MAVLINK2-HDR-CRC-SIGN-SIZE 256))
(defonce ^:const ONE-MINUTE 6000000)
(defonce ^:const start-bytes #{MAVLINK1-START-BYTE MAVLINK2-START-BYTE})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Telemetry Log functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro write-tlog
"Write timestamp and packet to DataOutputStream."
[tlog packet length timestamp]
`(do
(.writeLong ~tlog (or ~timestamp (quot (System/nanoTime) 1000)))
(.write ~tlog ~packet 0 ~length)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Encode support functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- encode-mavlink1
"Encodes a MAVLink1 message.
channel - the internal channel map
sequence-id - the sequence id to use in the message
message - the message map as received from the application
message-info - the mavlink message information
"
^bytes [{:keys [mavlink system-id component-id]}
^long sequence-id
message
{:keys [encode-fns ^long payload-size crc-seed
^long msg-id]}]
mavlink 1.0 only
(instance? Long system-id)
(instance? Long component-id)
]}
(let [^long sys-id (or (:system'id message) system-id)
^long comp-id (or (:component'id message) component-id)
payload (let [byte-buffer (ByteBuffer/allocate payload-size)]
(.order byte-buffer ByteOrder/LITTLE_ENDIAN)
byte-buffer)
packed (byte-array (+ MAVLINK1-HDR-SIZE payload-size 2))]
(aset-byte packed 0 MAVLINK1-START-BYTE)
(aset-byte packed 1 (.byteValue (new Long payload-size)))
(aset-byte packed 2 (.byteValue (new Long sequence-id)))
(aset-byte packed 3 (.byteValue (new Long sys-id)))
(aset-byte packed 4 (.byteValue (new Long comp-id)))
(aset-byte packed 5 (.byteValue (new Long msg-id)))
(doseq [encode-fn encode-fns]
(encode-fn mavlink payload message))
; now copy the array from the payload to the packed array.
(System/arraycopy
(.array payload) 0 packed MAVLINK1-HDR-SIZE (.position payload))
finally calculate and put the checksum in , lsb first .
(let [checksum (compute-checksum packed 1 (+ MAVLINK1-HDR-SIZE payload-size)
crc-seed)]
(aset-byte packed (+ MAVLINK1-HDR-SIZE payload-size)
(.byteValue (new Long (bit-and checksum 0xff))))
(aset-byte packed (+ 1 MAVLINK1-HDR-SIZE payload-size)
(.byteValue
(new Long (bit-and (bit-shift-right checksum 8) 0xff)))))
packed))
(defn- sign-packet
"Sign the packet, it is assumed there is a secret-key and
that the packet array has room for the 13 bytes of the signature:
the link-id, the 6 bytes of timestamp and the 6 bytes of the signature.
The timestamp is determined from the system time, if the new
timestamp is the same as the old, then add add 1. Timestamps are
in units of 10 microseconds.
The link id and the first 6 bytes of the timestamp are appended to the
packet starting at the signature-idx. Then the signature is calculated
using SHA256 implemeneted by java.securty.MessageDigest.
signature = sha256(secret_key + header + payload + CRC + link-ID + timestamp)
encode-timestamp - the encode timestamp atom
packet - the bytes of the packet (with uninitialized signing bytes)
secret-key - the secret-key to sign the packet with
encodesha256 - the MessageDigest for signing the packet
signature-start-idx - the index of the start of the signature in the packet
link-id - the link id to use in the signature
"
[encode-timestamp
^bytes packet
secret-key
^MessageDigest encode-sha256
signature-start-idx
link-id]
(let [curr-timestamp (quot (System/nanoTime) 10000) ; get the current timestamp
sha256-start-idx (+ signature-start-idx 7) ; the packet plus the
; link id and timestamp
timestamp-array (let [bb (ByteBuffer/allocate 8)]
(.order bb ByteOrder/LITTLE_ENDIAN)
(if (> curr-timestamp @encode-timestamp)
(reset! encode-timestamp curr-timestamp)
(swap! encode-timestamp inc))
(.putLong bb ^long @encode-timestamp)
(.array bb))]
; add link ID to the packet
(aset-byte packet signature-start-idx link-id)
; add the timestamp to the packet
(System/arraycopy timestamp-array 0 packet (inc signature-start-idx) 6)
; calculate the sha256 from the secret-key and the packet
(.reset encode-sha256)
(.update encode-sha256 secret-key 0 32)
(.update encode-sha256 packet 0 sha256-start-idx)
(let [sha256-bytes ^bytes (.digest encode-sha256)]
add the first 6 bytes of the sha256 to the packet
(System/arraycopy sha256-bytes 0 packet sha256-start-idx 6))))
(defn- encode-mavlink2
"Encodes a MAVLink 2.0 message. The caller determines whether the message
is to be signed. If the message is not to be signed, the secret-key should
be nil. If the message is to be signed, the secret-key is not nil, then
the link-id must be specified in the message map, otherwise the default
value 0 is used.
channel - the internal channel map
sequence-id - the sequence id to use in the message
secret-key - the secret-key holding the key to sign the packets with
encode-sha256 - the MessageDigest for signing encoded messages
message - the message map as received from the application
message-info - the mavlink message information
"
^bytes [{:keys [mavlink system-id component-id
link-id encode-timestamp]}
sequence-id
secret-key
^MessageDigest encode-sha256
message
{:keys [encode-fns extension-encode-fns ^long extension-payload-size
crc-seed ^long msg-id]}]
{:pre [(<= 0 msg-id 16777215)
(instance? Long system-id)
(instance? Long component-id)
]}
(let [^long sys-id (or (:system'id message) system-id)
^long comp-id (or (:component'id message) component-id)
^long link-id (or (:link'id message) link-id)
payload (let [byte-buffer (ByteBuffer/allocate extension-payload-size)]
(.order byte-buffer ByteOrder/LITTLE_ENDIAN)
byte-buffer)
incompat-flags (if secret-key
only one possible flag ,
; so no or'ing necessary
0)
compat-flags 0]
; encode the payload
(doseq [encode-fn (concat encode-fns extension-encode-fns)]
(encode-fn mavlink payload message))
; trim the message and fix the payload size
(while (and (pos? (.position payload))
(zero? (.get payload (dec (.position payload)))))
(.position payload (dec (.position payload))))
; size of byte array now known, so can create it and fill it in
(let [trimmed-payload-size (.position payload)
packed (byte-array (+ trimmed-payload-size
(if secret-key
MAVLINK2-HDR-CRC-SIGN-SIZE
MAVLINK2-HDR-CRC-SIZE)))]
(aset-byte packed 0 MAVLINK2-START-BYTE)
(aset-byte packed 1 (.byteValue (new Long trimmed-payload-size)))
(aset-byte packed 2 (.byteValue (new Long incompat-flags)))
(aset-byte packed 3 (.byteValue (new Long compat-flags)))
(aset-byte packed 4 (.byteValue (new Long ^long sequence-id)))
(aset-byte packed 5 (.byteValue (new Long sys-id)))
(aset-byte packed 6 (.byteValue (new Long comp-id)))
(aset-byte packed 7 (.byteValue (new Long (bit-and msg-id 0xff))))
(aset-byte packed 8
(.byteValue
(new Long (bit-and (bit-shift-right msg-id 8) 0xff))))
(aset-byte packed 9
(.byteValue
(new Long (bit-and (bit-shift-right msg-id 16) 0xff))))
; now copy the array from the payload to the packed array.
(when (pos? trimmed-payload-size)
(System/arraycopy (.array payload) 0 packed
MAVLINK2-HDR-SIZE trimmed-payload-size))
finally calculate and put the checksum in , lsb first .
(let [checksum (compute-checksum packed 1
(+ MAVLINK2-HDR-SIZE trimmed-payload-size)
crc-seed)]
(aset-byte packed (+ MAVLINK2-HDR-SIZE trimmed-payload-size)
(.byteValue (new Long (bit-and checksum 0xff))))
(aset-byte packed (+ 1 MAVLINK2-HDR-SIZE trimmed-payload-size)
(.byteValue
(new Long (bit-and (bit-shift-right checksum 8) 0xff)))))
; the packet is ready to go, if there is a secret-key, then the message should be signed
(when secret-key
(sign-packet encode-timestamp
packed
secret-key
encode-sha256
(+ MAVLINK2-HDR-CRC-SIZE trimmed-payload-size)
link-id))
packed)))
(defn- encode-messages
"Encodes messages received from the input-channel.
The system-id, component-id and sequence-id may all be specified in the
message; if specified in the message, the values will override the default
values. If the the sequence-id is specified, in addition to overriding
the default sequence-id, the volatile used to generate the default
sequence-id is set to this value. Loops continuously until the channel
is closed (a nil is returned from the channel).
Encoded messages will be written to the output link; if the output link is
a stream the bytes will be writtenn to the stream, otherwise it is assumed
the link is a channel and the byte array will be written to the channel.
Note, the value of the protocol atom and secret-key are set by the
application in the open-channel function and are then updated by the
decode thread.
Once the protocol is MAVlink 2 signed, all outgoing messages are encoded
as signed MAVlink2 messages. To change back to an earlier protocol, the
channel must be closed and reopened.
channel - the internal channel map
input-channel - a clojure channel to take messages from
output-link - the stream to write the encoded bytes to or
a clojue channel to put the messages to
"
^bytes [{:keys [mavlink continue protocol report-error
signing-options statistics ^DataOutputStream tlog-stream] :as channel}
input-channel
output-link]
{:pre [(instance? clojure.lang.Atom statistics)
]}
(let [link-is-stream (instance? OutputStream output-link)
encode-sha256 (MessageDigest/getInstance "SHA-256")
{:keys [secret-key]} signing-options
sequence-id (volatile! 0)]
(loop [message (async/<!! input-channel)]
; return normally if continue
(when @continue
(when message
(if (= (:message'id message) :clj-mavlink)
(when-let [{new-protocol :protocol} message]
(case new-protocol
:mavlink2 (reset! protocol :mavlink2)
:mavlink1 (when (= @protocol :mavlink2)
(when report-error
(report-error (ex-info "clj-mavlink cannot go from protocol MAVLink 2 to MAVLink1"
{:cause :bad-protocol
:error :clj-mavlink-protocol
:message message}))))
(when report-error
(report-error (ex-info "clj-mavlink message specified unknown protocol"
{:cause :bad-protocol
:error :clj-mavlink-protocol
:message message})))))
; not shutting down and message to encode received
; look up the message-info based on the :message'id of the message
(if-let [message-info ((:message'id message)
(:messages-by-keyword mavlink))]
(try
; calculate the sequence id then encode the message
; don't update the mavlink sequence id until after message is sent
(let [msg-seq-id (:sequence'id message)
new-seq-id (if msg-seq-id
(mod msg-seq-id 256)
(mod (inc @sequence-id) 256))]
(if-let [packet (case (or (:protocol' message)
@protocol)
:mavlink1
(if (>= (:msg-id message-info) 256)
(do
(swap! statistics update-in
[:bad-protocol] inc)
(throw (ex-info "MAVlink 2 message id, current protocol is MAVLink 1"
{:cause :bad-protocol
:error :encode-failed
:message message})))
(encode-mavlink1 channel new-seq-id
message message-info))
:mavlink2
(encode-mavlink2 channel new-seq-id
@secret-key encode-sha256
message message-info)
)]
; message successfully encoded,
(do
; write the packet out
(if link-is-stream
(do
(.write ^OutputStream output-link ^bytes packet)
(.flush ^OutputStream output-link))
(async/>!! output-link packet))
;
;update the statistics
(swap! statistics update-in [:messages-encoded] inc)
;
; write the tlog
(when tlog-stream
(locking tlog-stream
(write-tlog tlog-stream packet (count ^bytes packet) nil)))
;
; now update mavlink sequence id
(vreset! sequence-id new-seq-id))
; message failed to encode due to error in encode function
(do
(swap! statistics update-in [:encode-failed] inc)
(when report-error
(report-error (ex-info "Encoding failed"
{:cause :encode-failed
:message message}))))))
(catch Exception e (if report-error
(report-error (if (ex-data e)
e
(ex-info "Encoding exception."
{:cause :encode-failed
:message message
:exception e})))
(throw e))))
; message failed to encode because invalid :message'id
(do
(swap! statistics update-in [:encode-failed] inc)
(when report-error
(report-error (ex-info "Encoding failed."
{:cause :invalid-message-id
:error :encode-failed
:message message}))))))
(recur (async/<!! input-channel)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Decode state machine support functions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare start-state)
(defn update-decode-statistics
[^long system-id ^long sequence-id statistics]
(let [{:keys [^longs last-seq-ids ^longs messages-decoded ^longs messages-skipped]} @statistics
last-sys-seq-id (aget last-seq-ids system-id)
last-sys-decoded (aget messages-decoded system-id)
last-sys-skipped (aget messages-skipped system-id)
difference (- sequence-id (mod (inc last-sys-seq-id) 256))
skipped (if (neg? last-sys-seq-id)
0
(if (neg? difference)
(+ difference 255)
difference))]
(aset last-seq-ids system-id sequence-id)
(aset messages-decoded system-id (inc last-sys-decoded))
(aset messages-skipped system-id (long (+ last-sys-skipped skipped)))))
(defn- decode-mavlink1
"Decode a MAVLink 1.0 message in the channel's buffer Return a message
map of the decoded message.
Message-info - the mavlink message information to use to decode the message
buffer - the buffer to decode
statistics - the statistics atom
"
[{:keys [system'id sequence'id] :as message}
decode-fns
^ByteBuffer buffer
statistics]
; position the buffer to the start of the payload
(.position buffer MAVLINK1-HDR-SIZE)
; decode the message, restart the decode state machine, then
; save the message and return it!
(let [message (persistent!
(reduce (fn [message decode-fn] (decode-fn buffer message))
(transient message)
decode-fns))]
(update-decode-statistics system'id sequence'id statistics)
message))
(defn- decode-mavlink2
"Decode a MAVLink 2.0 message in the channel's input buffer. If there is a
signature, it is assumed the signature has been verified and the link id
extracted from the signature and passed in. This is because if the message
was trimmed of trailing zeroes, the zeroes will be written on to the end
of the message, possibly/probably overwriting the checksum and signature
bytes before decoding the payload of the message.
It is assumed that the buffer is large enough to hold the bytes the trailing
zero bytes of the message when it was encoded. The bytes are added back
before decoding begins.
Message-info - the mavlink message information to use to decode the message
buffer - the buffer to decode
msg-payload-sie - the payload size of the message
statistics - the statistics atom
"
[{:keys [system'id sequence'id] :as message}
message-info
^ByteBuffer buffer
msg-payload-size
statistics
]
(let [{:keys [extension-payload-size decode-fns extension-decode-fns]}
message-info]
; replace trimmed bytes
(when (> extension-payload-size msg-payload-size)
(.position buffer (int (+ MAVLINK2-HDR-SIZE msg-payload-size)))
(dotimes [_ (- extension-payload-size msg-payload-size)]
(.put buffer (byte 0))))
; position the buffer at the start of the payload
(.position buffer MAVLINK2-HDR-SIZE)
; decode the message, and return it!
(let [message (persistent! (reduce (fn [message decode-fn]
(decode-fn buffer message))
(transient message)
(concat decode-fns
extension-decode-fns)))]
(update-decode-statistics system'id sequence'id statistics)
message)))
(defn- try-secret-key
"The try to match the signature with the given secret-key, return true if it
matches or return nil if it doesn't match.
decode-sha256 - The MessageDigest to use to try decrypting a the packet's
signature
secret-key - the key to try to use to decrypt the signature
packet - the packet with the signature to try
start-sha256-idx - the start index of the sha256 bytes in the signature
"
^Boolean [^MessageDigest decode-sha256
secret-key
^bytes packet
start-sha256-idx]
reset the MessageDigest
(.reset decode-sha256)
(.update decode-sha256 secret-key 0 32)
(.update decode-sha256 packet 0 start-sha256-idx) ; The link-id and timestamps
; bytes are included
(let [sha256-bytes ^bytes (.digest decode-sha256)]
(loop [idx start-sha256-idx
sidx 0]
(if (>= sidx 6)
if we got through the first 6 bytes , it 's valid
true
(if (not= (aget packet idx) (aget sha256-bytes sidx))
; if any byte is invalid immediately return false
false
; otherwise go to the next index
(recur (inc idx)
(inc sidx)))))))
(defn- verify-signature
"Verify the signature of the MVLink 2.0 message in the buffer.
The start-signature-idx is the index of the first byte of the signature.
Verify the signature of the packet by making sure the timetamp is valid
(at least one higher than the last timestamp for the signing tuple and
within one minute of the last timestamp)
and that the first 6 bytes of the sha256 of the packet matches the sha256
bytes in the packet.
If the timestamp and the signature are valid, the signing tuple timestamp
is updated and true is returned. Otherwise the statistics are updated and
false is returned.
channel - internal mavlink channel map
buffer - buffer holding bytes of the message
payload-size - the size of the payload of the message in the buffer
unsigned-packets-handler - handler for unsigned packets, returns true if
packet should be accepted.
start-signature-idx - the start of the signature of the message in the buffer
statistics - the statistics
"
^Boolean
[secret-key secret-keyset
signing-tuples
^MessageDigest decode-sha256
encode-timestamp
^ByteBuffer buffer payload-size
start-signature-idx
message-info
statistics]
(let [packet (.array buffer)
tuple (sequence [(.get buffer 5) ; system id
(.get buffer 6) ; component id
(.get buffer ^long start-signature-idx)]) ; link id
tuple-timestamp (get @signing-tuples tuple)
timestamp (let [bb (ByteBuffer/allocate 8)]
(.order bb ByteOrder/LITTLE_ENDIAN)
(System/arraycopy packet
(inc start-signature-idx)
(.array bb) 0 6)
(.put bb 6 (byte 0))
(.put bb 7 (byte 0))
(.getLong bb))
start-sha256-idx (+ start-signature-idx 7)]
(if (or (nil? tuple-timestamp)
(< tuple-timestamp timestamp (+ tuple-timestamp ONE-MINUTE)))
(let [valid-signature? (or (and @secret-key
(try-secret-key decode-sha256
@secret-key
packet
start-sha256-idx))
(loop [key-to-try (first secret-keyset)
rest-keys (rest secret-keyset)]
(when key-to-try
(if (try-secret-key decode-sha256
key-to-try
packet
start-sha256-idx)
(do
(reset! secret-key key-to-try)
true)
(recur (first rest-keys)
(rest rest-keys))))))]
(if valid-signature?
(do ; housekeeping stuff
(swap! signing-tuples assoc tuple timestamp)
(if (> timestamp @encode-timestamp)
(reset! encode-timestamp timestamp)
(swap! encode-timestamp inc))
true)
(do ; bad signature, update statistics
(swap! statistics update-in [:bad-signatures] inc)
false)))
(do
(swap! statistics update-in [:bad-timestamps] inc)
false))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; decode state machine state functions. (started via trampoline in open-channel)
;; Each state will return a function to handle the next state or
;; nil if the state machine should stop normally.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- read-bytes
"Read the indicated number of bytes from the stream into the indicated buffer.
Returns true is the number of bytes requested were added to the buffer.
If the InputStream read operation throws an excception, that exception will
be caught by the open channel decode thread call (i.e. see open-channel for
exception handling).
statistics - the statistics
input-stream - the stream to read the btes from
buffer - the buffer to place the bytes (the position must be correct before
the call) num-bytes - the number of bytes to read
"
^Boolean [statistics
^InputStream input-stream
^ByteBuffer buffer
num-bytes]
(let [buffer-array (.array buffer)
num-bytes-read (.read input-stream
buffer-array
(.position buffer)
num-bytes)]
(if (neg? num-bytes-read) ; end of stream has been reached
false
(do
(swap! statistics update-in [:bytes-read] #(+ num-bytes-read %))
(.position buffer (+ (.position buffer) num-bytes-read))
(if (>= num-bytes-read num-bytes)
true
(recur statistics input-stream buffer (- num-bytes num-bytes-read)))))))
(defn- verify-checksum
"Given a buffer, the crc seed, and the position of lsb of checksum in the
buffer, extract the lsb and msb of the checksum, compute the checksum on
the buffer and return whether the checksum matches. The msb of the checksum
always follows the lsb of the checksum.
buffer - buffer to check CRC bytes
crc-seed - CRC seed for calculating the checksum
(specific to the message type)
lsb-idx - the index of the LSB of the CRC (the MSB follows the LSB)
"
^Boolean [^ByteBuffer buffer crc-seed ^long lsb-idx]
(let [checksum-lsb (byte-to-long (new Long (.get buffer lsb-idx)))
checksum-msb (byte-to-long (new Long (.get buffer (inc lsb-idx))))
checksum (bit-or (bit-and checksum-lsb 0xff)
(bit-and (bit-shift-left checksum-msb 8) 0xff00))
checksum-calc (compute-checksum buffer 1 lsb-idx crc-seed)]
(== checksum checksum-calc)))
(defn- mavlink2-payload-state
"Decode Mavlink 2 payload state, get the Mavlink2 payload bytes and CRC bytes.
Verify the CRC. If the message is signed, then get and verify the signature.
Then decode the message and put the decoded message into output channel.
When the stream is closed, just return nil which stops the decoding
state machine.
channel - internal mavlink channel
buffer - buffer holding message to decode
payload-size - the payload size
input-stream - stream to get bytes to decode from
output-channel - the clojure channel to write the decoded message to
message-info - mavlink message information for message in buffer
statistics - statistics
"
[{:keys [encode-timestamp signing-options protocol ^DataOutputStream tlog-stream] :as channel}
^ByteBuffer buffer
payload-size
^InputStream input-stream
output-channel
message
message-info
statistics]
(let [{:keys [accept-message-handler decode-sha256 secret-key
secret-keyset signing-tuples]} signing-options
signed-message (not
(zero? (bit-and (.get buffer 2) INCOMPAT-FLAG-SIGNED)))
bytes-to-read (if signed-message
read payload , CRC , and the signature
(+ payload-size 2 MAVLINK2-SIGN-SIZE)
read only the payload and CRC
(+ payload-size 2))
bytes-in-message (+ MAVLINK2-HDR-SIZE bytes-to-read)
]
(when (read-bytes statistics input-stream buffer bytes-to-read)
(if (verify-checksum buffer
(:crc-seed message-info)
; compute the checksum LSB
(+ MAVLINK2-HDR-SIZE payload-size))
(let [signature-verified (when signed-message
; verify-signature counts bad signatures,
; updates the secret-key if it changes, and
; returns whether the signature verified
(or (verify-signature secret-key secret-keyset
signing-tuples
decode-sha256
encode-timestamp
buffer payload-size
(+ MAVLINK2-HDR-CRC-SIZE
payload-size)
message-info statistics)
(when accept-message-handler
(accept-message-handler
(assoc message
:signed'message signed-message
:current'protocol @protocol)))))
okay-to-decode (case @protocol
:mavlink1
(when (or (not signed-message)
(and signed-message
signature-verified))
(reset! protocol :mavlink2))
:mavlink2
(if signed-message
signature-verified ; signed and verified?
(or (not @secret-key) ; okay to not be signed
(do ; should be signed not okay
(swap! statistics update-in
[:unsigned-messages] inc)
false))))]
; if okay to decode
(when okay-to-decode
write telemetry log first ( because decode - mavlink2 will replace the
trimmed zero bytes in the buffer , overwriting the packet as received .
(when tlog-stream
(locking tlog-stream
(write-tlog tlog-stream (.array ^ByteBuffer buffer) bytes-in-message (:timestamp' message))))
;
; decode and output the message
(async/>!! output-channel
(decode-mavlink2 (assoc message
:signed'message signed-message)
message-info
buffer
payload-size
statistics))
;
; update statistics
(swap! statistics update-in [:bytes-decoded] #(+ bytes-in-message %))))
; update statistics on messages dropped due to bad checksums
(swap! statistics update-in [:bad-checksums] inc)))
; regardless of what happened, go to the start state
#(start-state channel buffer input-stream output-channel statistics)))
(defn- mavlink2-header-state
"Decode Mavlink 2 header state, get the Mavlink2 header bytes, then verify the
bytes are appropriate for a Mavlink2 header, and return the function to
execute next.
When the stream is closed, just return nil which stops the decoding
state machine.
Header bytes are [start-byte
payload-size
incompat-flags
compat-flags
seq id
system id
component id
msg id byte1
msg id byte2
msg id byte3]
channel - internal mavlink channel
buffer - buffer to hold message to decode
input-stream - stream to get bytes to decode
output-channel - channel to write decoded messages to
statistics statistics
"
[{:keys [mavlink] :as channel}
^ByteBuffer buffer
^InputStream input-stream
output-channel
statistics timestamp]
(when (read-bytes statistics input-stream buffer (dec MAVLINK2-HDR-SIZE))
; now verify the header bytes
(let [low-byte (byte-to-long (new Long (.get buffer 7)))
middle-byte (byte-to-long (new Long (.get buffer 8)))
high-byte (byte-to-long (new Long (.get buffer 9)))
msg-id (+ (bit-and (bit-shift-left high-byte 16) 0xff0000)
(bit-and (bit-shift-left middle-byte 8) 0xff00)
(bit-and low-byte 0xff))
message-info (get (:messages-by-id mavlink) msg-id)]
; select and then return function to execute the next state
(if message-info
#(mavlink2-payload-state channel
buffer
(byte-to-long (new Long (.get buffer 1)))
input-stream
output-channel
{:timestamp' timestamp
:message'id (:msg-key message-info)
:protocol' :mavlink2
:sequence'id
(byte-to-long (new Long (.get buffer 4)))
:system'id
(byte-to-long (new Long (.get buffer 5)))
:component'id
(byte-to-long (new Long (.get buffer 6)))}
message-info
statistics)
#(start-state channel buffer input-stream output-channel statistics)))))
(defn- mavlink1-payload-state
"Decode Mavlink 1 payload state, get the Mavlink1 payload bytes and CRC bytes.
Verify the CRC, decode the message and put the decoded message into output
channel. When the stream is closed, just return nil which stops the decoding
state machine.
channel - internal mavlink channel
buffer - buffer holding message to decode
payload-size - the payload size
input-stream - stream to get bytes to decode from
output-channel - the clojure channel to write the decoded message to
message-info - mavlink message information for message in buffer
statistics - statistics
"
[{:keys [protocol ^DataOutputStream tlog-stream] :as channel}
^ByteBuffer buffer
payload-size
^InputStream input-stream
output-channel
message
message-info
statistics]
(let [bytes-to-read (+ payload-size 2)]
(when (read-bytes statistics input-stream buffer bytes-to-read)
(if (verify-checksum buffer
(:crc-seed message-info)
; compute checksum LSB
(+ MAVLINK1-HDR-SIZE payload-size))
(if (or (= @protocol :mavlink1)
(and (= @protocol :mavlink2)
(when-let [accept-message-handler (:accept-message-handler (:signing-options channel))]
(accept-message-handler (assoc message :current'protocol @protocol)))))
(do
; write telemetry log
(when tlog-stream
(locking tlog-stream
(write-tlog tlog-stream
(.array ^ByteBuffer buffer)
(+ MAVLINK1-HDR-CRC-SIZE payload-size)
(:timestamp' message))))
; decode and output the message
(async/>!! output-channel
(decode-mavlink1 message
(:decode-fns message-info)
buffer
statistics))
; update statistics
(swap! statistics update-in
[:bytes-decoded] #(+ % MAVLINK1-HDR-SIZE bytes-to-read)))
(swap! statistics update-in [:bad-protocol] inc))
(swap! statistics update-in [:bad-checksums] inc))))
; always return function to execute start-state
#(start-state channel buffer input-stream output-channel statistics))
(defn- mavlink1-header-state
"Decode Mavlink 1 header state, get the Mavlink1 header bytes (remember the
start-byte has already been read), then verify the bytes are appropriate
for a Mavlink1 header, and return the function to execute next.
When the stream is closed, just return nil which stops the decoding
state machine.
Header bytes are [start-byte
payload-size
seq id
system id
component id
msg id]
channel - internal mavlink channel
buffer - buffer to hold message to decode
input-stream - stream to get bytes to decode
output-channel - channel to write decoded messages to
statistics statistics
"
[{:keys [mavlink] :as channel}
^ByteBuffer buffer
^InputStream input-stream
output-channel
statistics timestamp]
(when (read-bytes statistics input-stream buffer (dec MAVLINK1-HDR-SIZE))
; now verify the header bytes
(let [msg-id (byte-to-long (new Long (.get buffer 5)))
msg-payload-size (byte-to-long (new Long (.get buffer 1)))
{:keys [messages-by-id]} mavlink
message-info (get messages-by-id msg-id)]
; select state to execute next and return function to execute the state
(if (and message-info
(<= msg-payload-size (:payload-size message-info)))
#(mavlink1-payload-state channel
buffer
msg-payload-size
input-stream
output-channel
{:timestamp' timestamp
:message'id (:msg-key message-info)
:protocol' :mavlink1
:sequence'id
(byte-to-long (new Long (.get buffer 2)))
:system'id
(byte-to-long (new Long (.get buffer 3)))
:component'id
(byte-to-long (new Long (.get buffer 4)))}
message-info
statistics)
#(start-state channel buffer input-stream output-channel statistics)))))
(defn- start-state
"Decode start state, looking for start byte for either MAVlink 1 or MAVlink 2.
Ignore every other byte. Continue getting bytes until either a nil byte
is returned, which indicates the stream was closed, or a start-byte is
returned. When the stream is closed, just return nil which stops the decoding
state machine. Otherwise, return a function to execute the function to get
the header of the message (see clojure trampline documentation).
Timestamp every decoded message with the system time, unless the input stream
is a tlog, in which case get the timestamp from the tlog.
channel - internal mavlink channel
buffer - buffer to hold message to decode
input-stream - stream to get bytes to decode
output-channel - channel to write decoded messages to
statistics statistics
"
[{:keys [continue input-is-tlog?] :as channel}
^ByteBuffer buffer
^InputStream input-stream
output-channel
statistics]
(.clear buffer)
(when-let [timestamp (or
(when input-is-tlog? ; read timestamp and start byte
(when (read-bytes statistics input-stream buffer (inc (Long/BYTES)))
(loop []
(let [sb (.get buffer (Long/BYTES))]
(if (contains? start-bytes sb)
; get the timestamp to return, clear the buffer,
; then put back the start byte
(let [ts (do
(.position buffer 0)
(Long/reverseBytes (.getLong buffer)))]
(.clear buffer)
(.put buffer sb)
ts)
; didn't get the a start byte, so the timestamp isn't right either
; shift the buffer and read another byte
(do
(doseq [i (range (Long/BYTES))]
(.put buffer (int i) (.get buffer ^long (inc i))))
(.position buffer (Long/BYTES))
(when (read-bytes statistics input-stream buffer 1)
(recur))))))))
(loop [] ; just find the start byte
(.position buffer 0)
(when (read-bytes statistics input-stream buffer 1)
(if (contains? start-bytes (.get buffer 0))
(quot (System/nanoTime) 1000)
(recur)))))]
; return nil and stop the decode state machine "normally"
(when (and @continue
timestamp)
; return function to select and execute the header state
(condp = (.get buffer 0)
MAVLINK1-START-BYTE #(mavlink1-header-state channel buffer
input-stream output-channel statistics timestamp)
MAVLINK2-START-BYTE #(mavlink2-header-state channel buffer
input-stream output-channel statistics timestamp)
(when-let [report-error (:report-error channel)]
(report-error (ex-info "clj-mavlink internal error decoding"
{:cause :decode-failed
:error :start-byte-not-found
:message "Could not find start of a MAVLink message"}))
nil)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End decode state machine state functions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-description
"Return the description, only useful if descriptions were saved.
Otherwise nil is returned."
[{:keys [descriptions]} msg-key]
(when descriptions
(msg-key descriptions)))
(defn parse
"Given a map with the specifications for a mavlink instance, return a
map of the mavlink instance.
The map should contain the following bindings:
:descriptions - true or false indicating whether to save descriptions
:xml-sources - either a vector of 1 or more maps holding the XML sources:
[{:xml-file - holds the filename of the XML file
:xml-source - An XML source suitable for clojure.data.xml/parse
}]
or a vector of 1 or more XML sources
For example: {:xml-sources [{:xml-file test-parse.xml
:xml-source (-> test/resources/test-parse.xml
io/input-stream)}]
:descriptions true}
Possible :cause failures from ExceptionInfo exceptions:
:bad-checksum - obviously a bad checksum
:enum-conflicts - there is a name conflict in the enumerated types
:message-id-conflicts - there is a conflict with the message id values
in an XML file
:message-name-conflicts - there is a conflict witht he message names in
an XML file
:missing-xml-include - an XML file is included, but no source was
identified for this file
:missing-xml-file-id - an XML source is missing an XML file indicator
:no-read-fn - the type is missing a read function
:no-write-fn - the type is missing a write function
:null-pointer - obviously a null pointer
:string-not-number - string conversion to a number failed usually
due to non numeric characters
:undefined-enum - A message value uses an unidentified
enumerated value
:unknown-type - unknown type specifier in an XML file
"
[{:keys [xml-sources] :as options}]
{:pre [(pos? (count xml-sources))]}
(let [parsed (get-xml-zippers xml-sources)
mavlink
(reduce #(add-mavlink-enums %1 (get-mavlink-enums %2))
{} parsed)]
The mavlink map holds the merged enum data of all the XML sources
now add on all the message information from the XML sources
(reduce
#(add-mavlink-messages %1 (get-mavlink-messages %2 options mavlink))
mavlink parsed)))
(defn open-channel
"Given a mavlink (the result of parse), and the open channel options
an encode and a decode thread are started. A map is returned with
the following bindings:
:statistics - the atom the encode/decode threads will update with
encoding/decoding statistics
:close-channel-fn - a function with no arguments to call to close
the channel, in other words to stop the encoding/decoding
threads.
A note about MAVlink message protocol.
Messages are (en/de)coded based on the current protocol and the value
of the secret-key.
If the protocol is :mavlink1 then messages are encoded MAVlink 1 and
all received messages are expected to be MAVlink 1, until a MAVlink 2
message is received. If the message is successfully decoded,
this will change the protocol to :mavlink2.
If the protocol is :mavlink2, then all messages will be encoded MAVlink 2.
Whether the message is signed or not is controlled by the secret key in the
signing options. If the key is not nil, the message is signed.
Once the secret key is set it is never cleared, and only updated when a
signed MAVlink 2 message's signature is successfully decrypted using a
different key, then the secret key is updated to the key used to decrypt
the signature.
Thus, the MAVlink protocol is either :mavlink1, :mavlink2 without
signing (because the secret key is nil) or :mavlink2 with signing
(because the secret key is set). And the protocol can only move forward
through those 'states'. Thus the application can start using MAVlink 1
MAVlink 2 signed or unsigned by setting the procotol and secret-key.
Once running, the decoding process itself will update the protocol
based on the decoding process.
The accept-message-handler provides a method for the application to
indicate whether or not to accept a message that is MAVlink 1 when the
current protocol is MAVlink 2. Or the message is unsigned when it should
be signed. Of it is signed and no key was found to decode it. The handler
is called with one argument, a message map with the following fields:
:message'id - from the message
:sequence'id - from the message
:system'id - from the message
:component'id - from the message
:current'protocol - :mavlink1 or :mavlink2
:signed'message - true or false
The handler should return true if the message should be accepted,
false otherwise.
mavlink - is the mavlink map returned by a call to parse.
options - is a hashmap of channel options
accept-message-handler- a function to all to ask the application whether
to accept a message that it would otherwise drop.
component-id - the encode component id
decode-input-stream - the stream to read bytes to decode from
decode-output-channel - the channel to write decoded messages to
encode-input-channel - the channel to receive messages to decode on
encode-output-link - either an output stream to write the encoded bytes to
or a channel to write the encoded byte array to
(anything else will cause an exception)
exception-handler - exception handler function,
if nil the exception is thrown
otherwise this function is called with the exception
as the sole argument. Exception's generally will
be an IException, the ex-data map will have :cause,
:message (if the message is known), and :exception.
link-id - the encode link id, if not given and protocol
is :mavlink2, then 0 is used
protocol - the encode protocol to use
:mavlink1 - decode mavlink1 ignore mavlink2 messages
:mavlink2 - decode mavlink2 using signing options
report-error - function to report non-fatal errors and exceptions,
particularly encoding errors, it is passed an IException
(see exception -handler for a description of the error
data message map bindings.
signing-options {
secret-key - The current secret-key to use to encode, the
first key to try when decoding signed messages.
The secret-key can be set on open-channel.
When signed messages are decoded, the secret-key
is set to the key that was used to validate the
signature. If signed message cannot be validated
with any keys, then the secret-key is not updated.
secret-keyset - a sequable collection of valid keys
while decoding, if the currnet secret-key fails to
validate the message, all the keys will be tried in
order. If no valid key is found the secret-key is
not updated, if a valid key is found the secret-key is updated.
accept-message-handler - a function to all if the message header
indicates the message is not of the expected
protocol.
}
system-id - the encode system id
tlog-stream - OutputStream to write telemetry log to. Should be nil if
no telemetry log is desired.
For encodingMAVLink 2.0:
The system-id and component-id are taken from the channel, but maybe
provided in the encode message-map. Note that if signing is active
(i.e. the secret-key has a value) then the link-id must be given in the
message-map, otherwise the default value will be used for the link id
(see the encode function.)
Timestamps just indicate forward progression (once a timestamp is seen,
ignore anything earlier). So, the initial values of the encoding timestamp
is 0. See the sign-packet function for timestamping for encoding.
"
[mavlink {:keys [component-id
input-is-tlog?
decode-input-stream
decode-output-channel
encode-input-channel
encode-output-link
exception-handler
link-id
protocol
report-error
signing-options
system-id
tlog-stream]}]
{:pre [(instance? Long system-id)
(instance? Long component-id)
(instance? InputStream decode-input-stream)
(or (instance? OutputStream encode-output-link)
encode-output-link)
decode-output-channel
encode-input-channel
(map? mavlink)
(keyword? protocol)
(map? (:messages-by-keyword mavlink))
(map? (:messages-by-id mavlink))
(or (nil? tlog-stream)
(instance? java.io.OutputStream tlog-stream))
]}
; start with a buffer size bigger then is possible
(let [buffer (ByteBuffer/allocate BUFFER-SIZE)
statistics (atom {:bytes-read 0
:bytes-decoded 0
:messages-decoded (long-array 256 0)
:last-seq-ids (long-array 256 -1)
:messages-skipped (long-array 256 0)
:messages-encoded 0
:encode-failed 0
:bad-checksums 0
:bad-protocol 0
:bad-signatures 0
:unsigned-messages 0
:bad-timestamps 0
:bad-mavlink2 0})
signing-options-map {:accept-message-handler
(:accept-message-handler signing-options)
:decode-sha256
(MessageDigest/getInstance "SHA-256")
:secret-key (atom (:secret-key signing-options))
:secret-keyset (:secret-keyset signing-options)
:signing-tuples (atom {})
}
continue (atom true)
channel {:component-id component-id
:input-is-tlog? input-is-tlog?
MAVLInk 2.0 encoding and decoding
MAVLink 2.0 , encoding only
:mavlink mavlink ; returned by parse
:protocol (atom protocol)
:report-error report-error ; function to call to report errors
:continue continue ; encode/decode thread continue flag
:signing-options signing-options-map
:statistics statistics
:system-id system-id
:tlog-stream (when tlog-stream
(DataOutputStream. tlog-stream))
}
shutdown-fn (fn[e]
; This function can be called by the application
; or internally by the channel threads in case of an error
; or internally or when a thread's input source closes
; this function sets the shutdown flag to true;
; the threads ; will stop when they poll the continue flag
; NOTE the application is responsible for managing the
; input and output sources. Thus it is not enough to
; call the returned close function, the applicaiton
; must also close the input/output sources.
(reset! continue false)
(when e
(if exception-handler
(exception-handler e)
(throw e))))
]
(.order buffer ByteOrder/LITTLE_ENDIAN)
(async/thread ; decoding thread
(.setName (Thread/currentThread) "Mavlink decoding")
(try
; start the decoding state machine
(trampoline start-state channel
buffer
decode-input-stream
decode-output-channel
statistics)
; when the state machine stops, output the state of the signing tuples
(async/>!! decode-output-channel
{:message'id :SigningTuples
:signing-tuples (:signing-tuples channel)})
; shutdown the encode thread normally
(shutdown-fn nil)
(catch IOException e (shutdown-fn (ex-info "clj-mavlink IOException occurred, probably due to shutdown of the link."
{:cause :io-exception
:thread "Mavlink Decode"
:exception e})))
(catch Exception e (shutdown-fn (ex-info "clj-mavlink decode thread Exception"
{:cause :decode
:exception e})))))
(async/thread ; encoding thread
(.setName (Thread/currentThread) "Mavlink encoding")
(try
; start encoding messages
(encode-messages channel
encode-input-channel
encode-output-link)
; shutdown the decode thread normally
(shutdown-fn nil)
(catch IOException e (shutdown-fn (ex-info "clj-mavlink IOException occurred, probably due to shutdown of the link."
{:cause :io-exception
:thread "Mavlink Encode"
:exception e})))
(catch Exception e (shutdown-fn (ex-info "clj-mavlink encode thread Exception"
{:cause :encode
:exception e})))))
; Return a map holding the statistics atom and the close-channel function
{:statistics statistics
:close-channel-fn #(shutdown-fn nil)}))
(defn get-enum
"Look up value in an enum group and return the enum-key for that value.
nil in case of error."
[mavlink group-id v]
(get-in mavlink [:enums-by-group group-id v]))
(defn get-enum-group
"Given a group id, return the map of key/values for that group."
[mavlink group-id]
(group-id (:enums-by-group mavlink)))
| null | https://raw.githubusercontent.com/WickedShell/clj-mavlink/21d79d07f862e3fb6d9a75be8e65151e2ab4952b/src/mavlink/core.clj | clojure |
Encode support functions
now copy the array from the payload to the packed array.
get the current timestamp
the packet plus the
link id and timestamp
add link ID to the packet
add the timestamp to the packet
calculate the sha256 from the secret-key and the packet
so no or'ing necessary
encode the payload
trim the message and fix the payload size
size of byte array now known, so can create it and fill it in
now copy the array from the payload to the packed array.
the packet is ready to go, if there is a secret-key, then the message should be signed
if specified in the message, the values will override the default
if the output link is
return normally if continue
not shutting down and message to encode received
look up the message-info based on the :message'id of the message
calculate the sequence id then encode the message
don't update the mavlink sequence id until after message is sent
message successfully encoded,
write the packet out
update the statistics
write the tlog
now update mavlink sequence id
message failed to encode due to error in encode function
message failed to encode because invalid :message'id
Decode state machine support functions.
position the buffer to the start of the payload
decode the message, restart the decode state machine, then
save the message and return it!
replace trimmed bytes
position the buffer at the start of the payload
decode the message, and return it!
The link-id and timestamps
bytes are included
if any byte is invalid immediately return false
otherwise go to the next index
system id
component id
link id
housekeeping stuff
bad signature, update statistics
decode state machine state functions. (started via trampoline in open-channel)
Each state will return a function to handle the next state or
nil if the state machine should stop normally.
end of stream has been reached
compute the checksum LSB
verify-signature counts bad signatures,
updates the secret-key if it changes, and
returns whether the signature verified
signed and verified?
okay to not be signed
should be signed not okay
if okay to decode
decode and output the message
update statistics
update statistics on messages dropped due to bad checksums
regardless of what happened, go to the start state
now verify the header bytes
select and then return function to execute the next state
compute checksum LSB
write telemetry log
decode and output the message
update statistics
always return function to execute start-state
now verify the header bytes
select state to execute next and return function to execute the state
read timestamp and start byte
get the timestamp to return, clear the buffer,
then put back the start byte
didn't get the a start byte, so the timestamp isn't right either
shift the buffer and read another byte
just find the start byte
return nil and stop the decode state machine "normally"
return function to select and execute the header state
End decode state machine state functions.
Public functions
start with a buffer size bigger then is possible
returned by parse
function to call to report errors
encode/decode thread continue flag
This function can be called by the application
or internally by the channel threads in case of an error
or internally or when a thread's input source closes
this function sets the shutdown flag to true;
the threads ; will stop when they poll the continue flag
NOTE the application is responsible for managing the
input and output sources. Thus it is not enough to
call the returned close function, the applicaiton
must also close the input/output sources.
decoding thread
start the decoding state machine
when the state machine stops, output the state of the signing tuples
shutdown the encode thread normally
encoding thread
start encoding messages
shutdown the decode thread normally
Return a map holding the statistics atom and the close-channel function | (ns mavlink.core
(:require [clojure.core.async :as async]
[mavlink.checksum :refer :all]
[mavlink.type :refer [byte-to-long]]
[mavlink.mavlink_xml :refer :all])
(:import [java.io InputStream OutputStream DataOutputStream IOException]
[java.nio ByteBuffer ByteOrder]
[java.security MessageDigest]
[java.lang System]))
(defonce ^:const INCOMPAT-FLAG-SIGNED 0x01)
(defonce ^:const MAVLINK1-START-VALUE 254)
(defonce MAVLINK1-START-BYTE (.byteValue (new Long MAVLINK1-START-VALUE)))
(defonce ^:const MAVLINK1-HDR-SIZE 6)
(defonce ^:const MAVLINK1-HDR-CRC-SIZE 8)
(defonce ^:const MAVLINK2-START-VALUE 253)
(defonce MAVLINK2-START-BYTE (.byteValue (new Long MAVLINK2-START-VALUE)))
(defonce ^:const MAVLINK2-HDR-SIZE 10)
(defonce ^:const MAVLINK2-HDR-CRC-SIZE 12)
(defonce ^:const MAVLINK2-HDR-CRC-SIGN-SIZE 25)
(defonce ^:const MAVLINK2-SIGN-SIZE 13)
(defonce ^:const SIGN-PACKETS-FLAG 0x1)
(defonce ^:const BUFFER-SIZE (+ MAVLINK2-HDR-CRC-SIGN-SIZE 256))
(defonce ^:const ONE-MINUTE 6000000)
(defonce ^:const start-bytes #{MAVLINK1-START-BYTE MAVLINK2-START-BYTE})
Telemetry Log functions
(defmacro write-tlog
"Write timestamp and packet to DataOutputStream."
[tlog packet length timestamp]
`(do
(.writeLong ~tlog (or ~timestamp (quot (System/nanoTime) 1000)))
(.write ~tlog ~packet 0 ~length)))
(defn- encode-mavlink1
"Encodes a MAVLink1 message.
channel - the internal channel map
sequence-id - the sequence id to use in the message
message - the message map as received from the application
message-info - the mavlink message information
"
^bytes [{:keys [mavlink system-id component-id]}
^long sequence-id
message
{:keys [encode-fns ^long payload-size crc-seed
^long msg-id]}]
mavlink 1.0 only
(instance? Long system-id)
(instance? Long component-id)
]}
(let [^long sys-id (or (:system'id message) system-id)
^long comp-id (or (:component'id message) component-id)
payload (let [byte-buffer (ByteBuffer/allocate payload-size)]
(.order byte-buffer ByteOrder/LITTLE_ENDIAN)
byte-buffer)
packed (byte-array (+ MAVLINK1-HDR-SIZE payload-size 2))]
(aset-byte packed 0 MAVLINK1-START-BYTE)
(aset-byte packed 1 (.byteValue (new Long payload-size)))
(aset-byte packed 2 (.byteValue (new Long sequence-id)))
(aset-byte packed 3 (.byteValue (new Long sys-id)))
(aset-byte packed 4 (.byteValue (new Long comp-id)))
(aset-byte packed 5 (.byteValue (new Long msg-id)))
(doseq [encode-fn encode-fns]
(encode-fn mavlink payload message))
(System/arraycopy
(.array payload) 0 packed MAVLINK1-HDR-SIZE (.position payload))
finally calculate and put the checksum in , lsb first .
(let [checksum (compute-checksum packed 1 (+ MAVLINK1-HDR-SIZE payload-size)
crc-seed)]
(aset-byte packed (+ MAVLINK1-HDR-SIZE payload-size)
(.byteValue (new Long (bit-and checksum 0xff))))
(aset-byte packed (+ 1 MAVLINK1-HDR-SIZE payload-size)
(.byteValue
(new Long (bit-and (bit-shift-right checksum 8) 0xff)))))
packed))
(defn- sign-packet
"Sign the packet, it is assumed there is a secret-key and
that the packet array has room for the 13 bytes of the signature:
the link-id, the 6 bytes of timestamp and the 6 bytes of the signature.
The timestamp is determined from the system time, if the new
timestamp is the same as the old, then add add 1. Timestamps are
in units of 10 microseconds.
The link id and the first 6 bytes of the timestamp are appended to the
packet starting at the signature-idx. Then the signature is calculated
using SHA256 implemeneted by java.securty.MessageDigest.
signature = sha256(secret_key + header + payload + CRC + link-ID + timestamp)
encode-timestamp - the encode timestamp atom
packet - the bytes of the packet (with uninitialized signing bytes)
secret-key - the secret-key to sign the packet with
encodesha256 - the MessageDigest for signing the packet
signature-start-idx - the index of the start of the signature in the packet
link-id - the link id to use in the signature
"
[encode-timestamp
^bytes packet
secret-key
^MessageDigest encode-sha256
signature-start-idx
link-id]
timestamp-array (let [bb (ByteBuffer/allocate 8)]
(.order bb ByteOrder/LITTLE_ENDIAN)
(if (> curr-timestamp @encode-timestamp)
(reset! encode-timestamp curr-timestamp)
(swap! encode-timestamp inc))
(.putLong bb ^long @encode-timestamp)
(.array bb))]
(aset-byte packet signature-start-idx link-id)
(System/arraycopy timestamp-array 0 packet (inc signature-start-idx) 6)
(.reset encode-sha256)
(.update encode-sha256 secret-key 0 32)
(.update encode-sha256 packet 0 sha256-start-idx)
(let [sha256-bytes ^bytes (.digest encode-sha256)]
add the first 6 bytes of the sha256 to the packet
(System/arraycopy sha256-bytes 0 packet sha256-start-idx 6))))
(defn- encode-mavlink2
"Encodes a MAVLink 2.0 message. The caller determines whether the message
is to be signed. If the message is not to be signed, the secret-key should
be nil. If the message is to be signed, the secret-key is not nil, then
the link-id must be specified in the message map, otherwise the default
value 0 is used.
channel - the internal channel map
sequence-id - the sequence id to use in the message
secret-key - the secret-key holding the key to sign the packets with
encode-sha256 - the MessageDigest for signing encoded messages
message - the message map as received from the application
message-info - the mavlink message information
"
^bytes [{:keys [mavlink system-id component-id
link-id encode-timestamp]}
sequence-id
secret-key
^MessageDigest encode-sha256
message
{:keys [encode-fns extension-encode-fns ^long extension-payload-size
crc-seed ^long msg-id]}]
{:pre [(<= 0 msg-id 16777215)
(instance? Long system-id)
(instance? Long component-id)
]}
(let [^long sys-id (or (:system'id message) system-id)
^long comp-id (or (:component'id message) component-id)
^long link-id (or (:link'id message) link-id)
payload (let [byte-buffer (ByteBuffer/allocate extension-payload-size)]
(.order byte-buffer ByteOrder/LITTLE_ENDIAN)
byte-buffer)
incompat-flags (if secret-key
only one possible flag ,
0)
compat-flags 0]
(doseq [encode-fn (concat encode-fns extension-encode-fns)]
(encode-fn mavlink payload message))
(while (and (pos? (.position payload))
(zero? (.get payload (dec (.position payload)))))
(.position payload (dec (.position payload))))
(let [trimmed-payload-size (.position payload)
packed (byte-array (+ trimmed-payload-size
(if secret-key
MAVLINK2-HDR-CRC-SIGN-SIZE
MAVLINK2-HDR-CRC-SIZE)))]
(aset-byte packed 0 MAVLINK2-START-BYTE)
(aset-byte packed 1 (.byteValue (new Long trimmed-payload-size)))
(aset-byte packed 2 (.byteValue (new Long incompat-flags)))
(aset-byte packed 3 (.byteValue (new Long compat-flags)))
(aset-byte packed 4 (.byteValue (new Long ^long sequence-id)))
(aset-byte packed 5 (.byteValue (new Long sys-id)))
(aset-byte packed 6 (.byteValue (new Long comp-id)))
(aset-byte packed 7 (.byteValue (new Long (bit-and msg-id 0xff))))
(aset-byte packed 8
(.byteValue
(new Long (bit-and (bit-shift-right msg-id 8) 0xff))))
(aset-byte packed 9
(.byteValue
(new Long (bit-and (bit-shift-right msg-id 16) 0xff))))
(when (pos? trimmed-payload-size)
(System/arraycopy (.array payload) 0 packed
MAVLINK2-HDR-SIZE trimmed-payload-size))
finally calculate and put the checksum in , lsb first .
(let [checksum (compute-checksum packed 1
(+ MAVLINK2-HDR-SIZE trimmed-payload-size)
crc-seed)]
(aset-byte packed (+ MAVLINK2-HDR-SIZE trimmed-payload-size)
(.byteValue (new Long (bit-and checksum 0xff))))
(aset-byte packed (+ 1 MAVLINK2-HDR-SIZE trimmed-payload-size)
(.byteValue
(new Long (bit-and (bit-shift-right checksum 8) 0xff)))))
(when secret-key
(sign-packet encode-timestamp
packed
secret-key
encode-sha256
(+ MAVLINK2-HDR-CRC-SIZE trimmed-payload-size)
link-id))
packed)))
(defn- encode-messages
"Encodes messages received from the input-channel.
The system-id, component-id and sequence-id may all be specified in the
values. If the the sequence-id is specified, in addition to overriding
the default sequence-id, the volatile used to generate the default
sequence-id is set to this value. Loops continuously until the channel
is closed (a nil is returned from the channel).
a stream the bytes will be writtenn to the stream, otherwise it is assumed
the link is a channel and the byte array will be written to the channel.
Note, the value of the protocol atom and secret-key are set by the
application in the open-channel function and are then updated by the
decode thread.
Once the protocol is MAVlink 2 signed, all outgoing messages are encoded
as signed MAVlink2 messages. To change back to an earlier protocol, the
channel must be closed and reopened.
channel - the internal channel map
input-channel - a clojure channel to take messages from
output-link - the stream to write the encoded bytes to or
a clojue channel to put the messages to
"
^bytes [{:keys [mavlink continue protocol report-error
signing-options statistics ^DataOutputStream tlog-stream] :as channel}
input-channel
output-link]
{:pre [(instance? clojure.lang.Atom statistics)
]}
(let [link-is-stream (instance? OutputStream output-link)
encode-sha256 (MessageDigest/getInstance "SHA-256")
{:keys [secret-key]} signing-options
sequence-id (volatile! 0)]
(loop [message (async/<!! input-channel)]
(when @continue
(when message
(if (= (:message'id message) :clj-mavlink)
(when-let [{new-protocol :protocol} message]
(case new-protocol
:mavlink2 (reset! protocol :mavlink2)
:mavlink1 (when (= @protocol :mavlink2)
(when report-error
(report-error (ex-info "clj-mavlink cannot go from protocol MAVLink 2 to MAVLink1"
{:cause :bad-protocol
:error :clj-mavlink-protocol
:message message}))))
(when report-error
(report-error (ex-info "clj-mavlink message specified unknown protocol"
{:cause :bad-protocol
:error :clj-mavlink-protocol
:message message})))))
(if-let [message-info ((:message'id message)
(:messages-by-keyword mavlink))]
(try
(let [msg-seq-id (:sequence'id message)
new-seq-id (if msg-seq-id
(mod msg-seq-id 256)
(mod (inc @sequence-id) 256))]
(if-let [packet (case (or (:protocol' message)
@protocol)
:mavlink1
(if (>= (:msg-id message-info) 256)
(do
(swap! statistics update-in
[:bad-protocol] inc)
(throw (ex-info "MAVlink 2 message id, current protocol is MAVLink 1"
{:cause :bad-protocol
:error :encode-failed
:message message})))
(encode-mavlink1 channel new-seq-id
message message-info))
:mavlink2
(encode-mavlink2 channel new-seq-id
@secret-key encode-sha256
message message-info)
)]
(do
(if link-is-stream
(do
(.write ^OutputStream output-link ^bytes packet)
(.flush ^OutputStream output-link))
(async/>!! output-link packet))
(swap! statistics update-in [:messages-encoded] inc)
(when tlog-stream
(locking tlog-stream
(write-tlog tlog-stream packet (count ^bytes packet) nil)))
(vreset! sequence-id new-seq-id))
(do
(swap! statistics update-in [:encode-failed] inc)
(when report-error
(report-error (ex-info "Encoding failed"
{:cause :encode-failed
:message message}))))))
(catch Exception e (if report-error
(report-error (if (ex-data e)
e
(ex-info "Encoding exception."
{:cause :encode-failed
:message message
:exception e})))
(throw e))))
(do
(swap! statistics update-in [:encode-failed] inc)
(when report-error
(report-error (ex-info "Encoding failed."
{:cause :invalid-message-id
:error :encode-failed
:message message}))))))
(recur (async/<!! input-channel)))))))
(declare start-state)
(defn update-decode-statistics
[^long system-id ^long sequence-id statistics]
(let [{:keys [^longs last-seq-ids ^longs messages-decoded ^longs messages-skipped]} @statistics
last-sys-seq-id (aget last-seq-ids system-id)
last-sys-decoded (aget messages-decoded system-id)
last-sys-skipped (aget messages-skipped system-id)
difference (- sequence-id (mod (inc last-sys-seq-id) 256))
skipped (if (neg? last-sys-seq-id)
0
(if (neg? difference)
(+ difference 255)
difference))]
(aset last-seq-ids system-id sequence-id)
(aset messages-decoded system-id (inc last-sys-decoded))
(aset messages-skipped system-id (long (+ last-sys-skipped skipped)))))
(defn- decode-mavlink1
"Decode a MAVLink 1.0 message in the channel's buffer Return a message
map of the decoded message.
Message-info - the mavlink message information to use to decode the message
buffer - the buffer to decode
statistics - the statistics atom
"
[{:keys [system'id sequence'id] :as message}
decode-fns
^ByteBuffer buffer
statistics]
(.position buffer MAVLINK1-HDR-SIZE)
(let [message (persistent!
(reduce (fn [message decode-fn] (decode-fn buffer message))
(transient message)
decode-fns))]
(update-decode-statistics system'id sequence'id statistics)
message))
(defn- decode-mavlink2
"Decode a MAVLink 2.0 message in the channel's input buffer. If there is a
signature, it is assumed the signature has been verified and the link id
extracted from the signature and passed in. This is because if the message
was trimmed of trailing zeroes, the zeroes will be written on to the end
of the message, possibly/probably overwriting the checksum and signature
bytes before decoding the payload of the message.
It is assumed that the buffer is large enough to hold the bytes the trailing
zero bytes of the message when it was encoded. The bytes are added back
before decoding begins.
Message-info - the mavlink message information to use to decode the message
buffer - the buffer to decode
msg-payload-sie - the payload size of the message
statistics - the statistics atom
"
[{:keys [system'id sequence'id] :as message}
message-info
^ByteBuffer buffer
msg-payload-size
statistics
]
(let [{:keys [extension-payload-size decode-fns extension-decode-fns]}
message-info]
(when (> extension-payload-size msg-payload-size)
(.position buffer (int (+ MAVLINK2-HDR-SIZE msg-payload-size)))
(dotimes [_ (- extension-payload-size msg-payload-size)]
(.put buffer (byte 0))))
(.position buffer MAVLINK2-HDR-SIZE)
(let [message (persistent! (reduce (fn [message decode-fn]
(decode-fn buffer message))
(transient message)
(concat decode-fns
extension-decode-fns)))]
(update-decode-statistics system'id sequence'id statistics)
message)))
(defn- try-secret-key
"The try to match the signature with the given secret-key, return true if it
matches or return nil if it doesn't match.
decode-sha256 - The MessageDigest to use to try decrypting a the packet's
signature
secret-key - the key to try to use to decrypt the signature
packet - the packet with the signature to try
start-sha256-idx - the start index of the sha256 bytes in the signature
"
^Boolean [^MessageDigest decode-sha256
secret-key
^bytes packet
start-sha256-idx]
reset the MessageDigest
(.reset decode-sha256)
(.update decode-sha256 secret-key 0 32)
(let [sha256-bytes ^bytes (.digest decode-sha256)]
(loop [idx start-sha256-idx
sidx 0]
(if (>= sidx 6)
if we got through the first 6 bytes , it 's valid
true
(if (not= (aget packet idx) (aget sha256-bytes sidx))
false
(recur (inc idx)
(inc sidx)))))))
(defn- verify-signature
"Verify the signature of the MVLink 2.0 message in the buffer.
The start-signature-idx is the index of the first byte of the signature.
Verify the signature of the packet by making sure the timetamp is valid
(at least one higher than the last timestamp for the signing tuple and
within one minute of the last timestamp)
and that the first 6 bytes of the sha256 of the packet matches the sha256
bytes in the packet.
If the timestamp and the signature are valid, the signing tuple timestamp
is updated and true is returned. Otherwise the statistics are updated and
false is returned.
channel - internal mavlink channel map
buffer - buffer holding bytes of the message
payload-size - the size of the payload of the message in the buffer
unsigned-packets-handler - handler for unsigned packets, returns true if
packet should be accepted.
start-signature-idx - the start of the signature of the message in the buffer
statistics - the statistics
"
^Boolean
[secret-key secret-keyset
signing-tuples
^MessageDigest decode-sha256
encode-timestamp
^ByteBuffer buffer payload-size
start-signature-idx
message-info
statistics]
(let [packet (.array buffer)
tuple-timestamp (get @signing-tuples tuple)
timestamp (let [bb (ByteBuffer/allocate 8)]
(.order bb ByteOrder/LITTLE_ENDIAN)
(System/arraycopy packet
(inc start-signature-idx)
(.array bb) 0 6)
(.put bb 6 (byte 0))
(.put bb 7 (byte 0))
(.getLong bb))
start-sha256-idx (+ start-signature-idx 7)]
(if (or (nil? tuple-timestamp)
(< tuple-timestamp timestamp (+ tuple-timestamp ONE-MINUTE)))
(let [valid-signature? (or (and @secret-key
(try-secret-key decode-sha256
@secret-key
packet
start-sha256-idx))
(loop [key-to-try (first secret-keyset)
rest-keys (rest secret-keyset)]
(when key-to-try
(if (try-secret-key decode-sha256
key-to-try
packet
start-sha256-idx)
(do
(reset! secret-key key-to-try)
true)
(recur (first rest-keys)
(rest rest-keys))))))]
(if valid-signature?
(swap! signing-tuples assoc tuple timestamp)
(if (> timestamp @encode-timestamp)
(reset! encode-timestamp timestamp)
(swap! encode-timestamp inc))
true)
(swap! statistics update-in [:bad-signatures] inc)
false)))
(do
(swap! statistics update-in [:bad-timestamps] inc)
false))))
(defn- read-bytes
"Read the indicated number of bytes from the stream into the indicated buffer.
Returns true is the number of bytes requested were added to the buffer.
If the InputStream read operation throws an excception, that exception will
be caught by the open channel decode thread call (i.e. see open-channel for
exception handling).
statistics - the statistics
input-stream - the stream to read the btes from
buffer - the buffer to place the bytes (the position must be correct before
the call) num-bytes - the number of bytes to read
"
^Boolean [statistics
^InputStream input-stream
^ByteBuffer buffer
num-bytes]
(let [buffer-array (.array buffer)
num-bytes-read (.read input-stream
buffer-array
(.position buffer)
num-bytes)]
false
(do
(swap! statistics update-in [:bytes-read] #(+ num-bytes-read %))
(.position buffer (+ (.position buffer) num-bytes-read))
(if (>= num-bytes-read num-bytes)
true
(recur statistics input-stream buffer (- num-bytes num-bytes-read)))))))
(defn- verify-checksum
"Given a buffer, the crc seed, and the position of lsb of checksum in the
buffer, extract the lsb and msb of the checksum, compute the checksum on
the buffer and return whether the checksum matches. The msb of the checksum
always follows the lsb of the checksum.
buffer - buffer to check CRC bytes
crc-seed - CRC seed for calculating the checksum
(specific to the message type)
lsb-idx - the index of the LSB of the CRC (the MSB follows the LSB)
"
^Boolean [^ByteBuffer buffer crc-seed ^long lsb-idx]
(let [checksum-lsb (byte-to-long (new Long (.get buffer lsb-idx)))
checksum-msb (byte-to-long (new Long (.get buffer (inc lsb-idx))))
checksum (bit-or (bit-and checksum-lsb 0xff)
(bit-and (bit-shift-left checksum-msb 8) 0xff00))
checksum-calc (compute-checksum buffer 1 lsb-idx crc-seed)]
(== checksum checksum-calc)))
(defn- mavlink2-payload-state
"Decode Mavlink 2 payload state, get the Mavlink2 payload bytes and CRC bytes.
Verify the CRC. If the message is signed, then get and verify the signature.
Then decode the message and put the decoded message into output channel.
When the stream is closed, just return nil which stops the decoding
state machine.
channel - internal mavlink channel
buffer - buffer holding message to decode
payload-size - the payload size
input-stream - stream to get bytes to decode from
output-channel - the clojure channel to write the decoded message to
message-info - mavlink message information for message in buffer
statistics - statistics
"
[{:keys [encode-timestamp signing-options protocol ^DataOutputStream tlog-stream] :as channel}
^ByteBuffer buffer
payload-size
^InputStream input-stream
output-channel
message
message-info
statistics]
(let [{:keys [accept-message-handler decode-sha256 secret-key
secret-keyset signing-tuples]} signing-options
signed-message (not
(zero? (bit-and (.get buffer 2) INCOMPAT-FLAG-SIGNED)))
bytes-to-read (if signed-message
read payload , CRC , and the signature
(+ payload-size 2 MAVLINK2-SIGN-SIZE)
read only the payload and CRC
(+ payload-size 2))
bytes-in-message (+ MAVLINK2-HDR-SIZE bytes-to-read)
]
(when (read-bytes statistics input-stream buffer bytes-to-read)
(if (verify-checksum buffer
(:crc-seed message-info)
(+ MAVLINK2-HDR-SIZE payload-size))
(let [signature-verified (when signed-message
(or (verify-signature secret-key secret-keyset
signing-tuples
decode-sha256
encode-timestamp
buffer payload-size
(+ MAVLINK2-HDR-CRC-SIZE
payload-size)
message-info statistics)
(when accept-message-handler
(accept-message-handler
(assoc message
:signed'message signed-message
:current'protocol @protocol)))))
okay-to-decode (case @protocol
:mavlink1
(when (or (not signed-message)
(and signed-message
signature-verified))
(reset! protocol :mavlink2))
:mavlink2
(if signed-message
(swap! statistics update-in
[:unsigned-messages] inc)
false))))]
(when okay-to-decode
write telemetry log first ( because decode - mavlink2 will replace the
trimmed zero bytes in the buffer , overwriting the packet as received .
(when tlog-stream
(locking tlog-stream
(write-tlog tlog-stream (.array ^ByteBuffer buffer) bytes-in-message (:timestamp' message))))
(async/>!! output-channel
(decode-mavlink2 (assoc message
:signed'message signed-message)
message-info
buffer
payload-size
statistics))
(swap! statistics update-in [:bytes-decoded] #(+ bytes-in-message %))))
(swap! statistics update-in [:bad-checksums] inc)))
#(start-state channel buffer input-stream output-channel statistics)))
(defn- mavlink2-header-state
"Decode Mavlink 2 header state, get the Mavlink2 header bytes, then verify the
bytes are appropriate for a Mavlink2 header, and return the function to
execute next.
When the stream is closed, just return nil which stops the decoding
state machine.
Header bytes are [start-byte
payload-size
incompat-flags
compat-flags
seq id
system id
component id
msg id byte1
msg id byte2
msg id byte3]
channel - internal mavlink channel
buffer - buffer to hold message to decode
input-stream - stream to get bytes to decode
output-channel - channel to write decoded messages to
statistics statistics
"
[{:keys [mavlink] :as channel}
^ByteBuffer buffer
^InputStream input-stream
output-channel
statistics timestamp]
(when (read-bytes statistics input-stream buffer (dec MAVLINK2-HDR-SIZE))
(let [low-byte (byte-to-long (new Long (.get buffer 7)))
middle-byte (byte-to-long (new Long (.get buffer 8)))
high-byte (byte-to-long (new Long (.get buffer 9)))
msg-id (+ (bit-and (bit-shift-left high-byte 16) 0xff0000)
(bit-and (bit-shift-left middle-byte 8) 0xff00)
(bit-and low-byte 0xff))
message-info (get (:messages-by-id mavlink) msg-id)]
(if message-info
#(mavlink2-payload-state channel
buffer
(byte-to-long (new Long (.get buffer 1)))
input-stream
output-channel
{:timestamp' timestamp
:message'id (:msg-key message-info)
:protocol' :mavlink2
:sequence'id
(byte-to-long (new Long (.get buffer 4)))
:system'id
(byte-to-long (new Long (.get buffer 5)))
:component'id
(byte-to-long (new Long (.get buffer 6)))}
message-info
statistics)
#(start-state channel buffer input-stream output-channel statistics)))))
(defn- mavlink1-payload-state
"Decode Mavlink 1 payload state, get the Mavlink1 payload bytes and CRC bytes.
Verify the CRC, decode the message and put the decoded message into output
channel. When the stream is closed, just return nil which stops the decoding
state machine.
channel - internal mavlink channel
buffer - buffer holding message to decode
payload-size - the payload size
input-stream - stream to get bytes to decode from
output-channel - the clojure channel to write the decoded message to
message-info - mavlink message information for message in buffer
statistics - statistics
"
[{:keys [protocol ^DataOutputStream tlog-stream] :as channel}
^ByteBuffer buffer
payload-size
^InputStream input-stream
output-channel
message
message-info
statistics]
(let [bytes-to-read (+ payload-size 2)]
(when (read-bytes statistics input-stream buffer bytes-to-read)
(if (verify-checksum buffer
(:crc-seed message-info)
(+ MAVLINK1-HDR-SIZE payload-size))
(if (or (= @protocol :mavlink1)
(and (= @protocol :mavlink2)
(when-let [accept-message-handler (:accept-message-handler (:signing-options channel))]
(accept-message-handler (assoc message :current'protocol @protocol)))))
(do
(when tlog-stream
(locking tlog-stream
(write-tlog tlog-stream
(.array ^ByteBuffer buffer)
(+ MAVLINK1-HDR-CRC-SIZE payload-size)
(:timestamp' message))))
(async/>!! output-channel
(decode-mavlink1 message
(:decode-fns message-info)
buffer
statistics))
(swap! statistics update-in
[:bytes-decoded] #(+ % MAVLINK1-HDR-SIZE bytes-to-read)))
(swap! statistics update-in [:bad-protocol] inc))
(swap! statistics update-in [:bad-checksums] inc))))
#(start-state channel buffer input-stream output-channel statistics))
(defn- mavlink1-header-state
"Decode Mavlink 1 header state, get the Mavlink1 header bytes (remember the
start-byte has already been read), then verify the bytes are appropriate
for a Mavlink1 header, and return the function to execute next.
When the stream is closed, just return nil which stops the decoding
state machine.
Header bytes are [start-byte
payload-size
seq id
system id
component id
msg id]
channel - internal mavlink channel
buffer - buffer to hold message to decode
input-stream - stream to get bytes to decode
output-channel - channel to write decoded messages to
statistics statistics
"
[{:keys [mavlink] :as channel}
^ByteBuffer buffer
^InputStream input-stream
output-channel
statistics timestamp]
(when (read-bytes statistics input-stream buffer (dec MAVLINK1-HDR-SIZE))
(let [msg-id (byte-to-long (new Long (.get buffer 5)))
msg-payload-size (byte-to-long (new Long (.get buffer 1)))
{:keys [messages-by-id]} mavlink
message-info (get messages-by-id msg-id)]
(if (and message-info
(<= msg-payload-size (:payload-size message-info)))
#(mavlink1-payload-state channel
buffer
msg-payload-size
input-stream
output-channel
{:timestamp' timestamp
:message'id (:msg-key message-info)
:protocol' :mavlink1
:sequence'id
(byte-to-long (new Long (.get buffer 2)))
:system'id
(byte-to-long (new Long (.get buffer 3)))
:component'id
(byte-to-long (new Long (.get buffer 4)))}
message-info
statistics)
#(start-state channel buffer input-stream output-channel statistics)))))
(defn- start-state
"Decode start state, looking for start byte for either MAVlink 1 or MAVlink 2.
Ignore every other byte. Continue getting bytes until either a nil byte
is returned, which indicates the stream was closed, or a start-byte is
returned. When the stream is closed, just return nil which stops the decoding
state machine. Otherwise, return a function to execute the function to get
the header of the message (see clojure trampline documentation).
Timestamp every decoded message with the system time, unless the input stream
is a tlog, in which case get the timestamp from the tlog.
channel - internal mavlink channel
buffer - buffer to hold message to decode
input-stream - stream to get bytes to decode
output-channel - channel to write decoded messages to
statistics statistics
"
[{:keys [continue input-is-tlog?] :as channel}
^ByteBuffer buffer
^InputStream input-stream
output-channel
statistics]
(.clear buffer)
(when-let [timestamp (or
(when (read-bytes statistics input-stream buffer (inc (Long/BYTES)))
(loop []
(let [sb (.get buffer (Long/BYTES))]
(if (contains? start-bytes sb)
(let [ts (do
(.position buffer 0)
(Long/reverseBytes (.getLong buffer)))]
(.clear buffer)
(.put buffer sb)
ts)
(do
(doseq [i (range (Long/BYTES))]
(.put buffer (int i) (.get buffer ^long (inc i))))
(.position buffer (Long/BYTES))
(when (read-bytes statistics input-stream buffer 1)
(recur))))))))
(.position buffer 0)
(when (read-bytes statistics input-stream buffer 1)
(if (contains? start-bytes (.get buffer 0))
(quot (System/nanoTime) 1000)
(recur)))))]
(when (and @continue
timestamp)
(condp = (.get buffer 0)
MAVLINK1-START-BYTE #(mavlink1-header-state channel buffer
input-stream output-channel statistics timestamp)
MAVLINK2-START-BYTE #(mavlink2-header-state channel buffer
input-stream output-channel statistics timestamp)
(when-let [report-error (:report-error channel)]
(report-error (ex-info "clj-mavlink internal error decoding"
{:cause :decode-failed
:error :start-byte-not-found
:message "Could not find start of a MAVLink message"}))
nil)))))
(defn get-description
"Return the description, only useful if descriptions were saved.
Otherwise nil is returned."
[{:keys [descriptions]} msg-key]
(when descriptions
(msg-key descriptions)))
(defn parse
"Given a map with the specifications for a mavlink instance, return a
map of the mavlink instance.
The map should contain the following bindings:
:descriptions - true or false indicating whether to save descriptions
:xml-sources - either a vector of 1 or more maps holding the XML sources:
[{:xml-file - holds the filename of the XML file
:xml-source - An XML source suitable for clojure.data.xml/parse
}]
or a vector of 1 or more XML sources
For example: {:xml-sources [{:xml-file test-parse.xml
:xml-source (-> test/resources/test-parse.xml
io/input-stream)}]
:descriptions true}
Possible :cause failures from ExceptionInfo exceptions:
:bad-checksum - obviously a bad checksum
:enum-conflicts - there is a name conflict in the enumerated types
:message-id-conflicts - there is a conflict with the message id values
in an XML file
:message-name-conflicts - there is a conflict witht he message names in
an XML file
:missing-xml-include - an XML file is included, but no source was
identified for this file
:missing-xml-file-id - an XML source is missing an XML file indicator
:no-read-fn - the type is missing a read function
:no-write-fn - the type is missing a write function
:null-pointer - obviously a null pointer
:string-not-number - string conversion to a number failed usually
due to non numeric characters
:undefined-enum - A message value uses an unidentified
enumerated value
:unknown-type - unknown type specifier in an XML file
"
[{:keys [xml-sources] :as options}]
{:pre [(pos? (count xml-sources))]}
(let [parsed (get-xml-zippers xml-sources)
mavlink
(reduce #(add-mavlink-enums %1 (get-mavlink-enums %2))
{} parsed)]
The mavlink map holds the merged enum data of all the XML sources
now add on all the message information from the XML sources
(reduce
#(add-mavlink-messages %1 (get-mavlink-messages %2 options mavlink))
mavlink parsed)))
(defn open-channel
"Given a mavlink (the result of parse), and the open channel options
an encode and a decode thread are started. A map is returned with
the following bindings:
:statistics - the atom the encode/decode threads will update with
encoding/decoding statistics
:close-channel-fn - a function with no arguments to call to close
the channel, in other words to stop the encoding/decoding
threads.
A note about MAVlink message protocol.
Messages are (en/de)coded based on the current protocol and the value
of the secret-key.
If the protocol is :mavlink1 then messages are encoded MAVlink 1 and
all received messages are expected to be MAVlink 1, until a MAVlink 2
message is received. If the message is successfully decoded,
this will change the protocol to :mavlink2.
If the protocol is :mavlink2, then all messages will be encoded MAVlink 2.
Whether the message is signed or not is controlled by the secret key in the
signing options. If the key is not nil, the message is signed.
Once the secret key is set it is never cleared, and only updated when a
signed MAVlink 2 message's signature is successfully decrypted using a
different key, then the secret key is updated to the key used to decrypt
the signature.
Thus, the MAVlink protocol is either :mavlink1, :mavlink2 without
signing (because the secret key is nil) or :mavlink2 with signing
(because the secret key is set). And the protocol can only move forward
through those 'states'. Thus the application can start using MAVlink 1
MAVlink 2 signed or unsigned by setting the procotol and secret-key.
Once running, the decoding process itself will update the protocol
based on the decoding process.
The accept-message-handler provides a method for the application to
indicate whether or not to accept a message that is MAVlink 1 when the
current protocol is MAVlink 2. Or the message is unsigned when it should
be signed. Of it is signed and no key was found to decode it. The handler
is called with one argument, a message map with the following fields:
:message'id - from the message
:sequence'id - from the message
:system'id - from the message
:component'id - from the message
:current'protocol - :mavlink1 or :mavlink2
:signed'message - true or false
The handler should return true if the message should be accepted,
false otherwise.
mavlink - is the mavlink map returned by a call to parse.
options - is a hashmap of channel options
accept-message-handler- a function to all to ask the application whether
to accept a message that it would otherwise drop.
component-id - the encode component id
decode-input-stream - the stream to read bytes to decode from
decode-output-channel - the channel to write decoded messages to
encode-input-channel - the channel to receive messages to decode on
encode-output-link - either an output stream to write the encoded bytes to
or a channel to write the encoded byte array to
(anything else will cause an exception)
exception-handler - exception handler function,
if nil the exception is thrown
otherwise this function is called with the exception
as the sole argument. Exception's generally will
be an IException, the ex-data map will have :cause,
:message (if the message is known), and :exception.
link-id - the encode link id, if not given and protocol
is :mavlink2, then 0 is used
protocol - the encode protocol to use
:mavlink1 - decode mavlink1 ignore mavlink2 messages
:mavlink2 - decode mavlink2 using signing options
report-error - function to report non-fatal errors and exceptions,
particularly encoding errors, it is passed an IException
(see exception -handler for a description of the error
data message map bindings.
signing-options {
secret-key - The current secret-key to use to encode, the
first key to try when decoding signed messages.
The secret-key can be set on open-channel.
When signed messages are decoded, the secret-key
is set to the key that was used to validate the
signature. If signed message cannot be validated
with any keys, then the secret-key is not updated.
secret-keyset - a sequable collection of valid keys
while decoding, if the currnet secret-key fails to
validate the message, all the keys will be tried in
order. If no valid key is found the secret-key is
not updated, if a valid key is found the secret-key is updated.
accept-message-handler - a function to all if the message header
indicates the message is not of the expected
protocol.
}
system-id - the encode system id
tlog-stream - OutputStream to write telemetry log to. Should be nil if
no telemetry log is desired.
For encodingMAVLink 2.0:
The system-id and component-id are taken from the channel, but maybe
provided in the encode message-map. Note that if signing is active
(i.e. the secret-key has a value) then the link-id must be given in the
message-map, otherwise the default value will be used for the link id
(see the encode function.)
Timestamps just indicate forward progression (once a timestamp is seen,
ignore anything earlier). So, the initial values of the encoding timestamp
is 0. See the sign-packet function for timestamping for encoding.
"
[mavlink {:keys [component-id
input-is-tlog?
decode-input-stream
decode-output-channel
encode-input-channel
encode-output-link
exception-handler
link-id
protocol
report-error
signing-options
system-id
tlog-stream]}]
{:pre [(instance? Long system-id)
(instance? Long component-id)
(instance? InputStream decode-input-stream)
(or (instance? OutputStream encode-output-link)
encode-output-link)
decode-output-channel
encode-input-channel
(map? mavlink)
(keyword? protocol)
(map? (:messages-by-keyword mavlink))
(map? (:messages-by-id mavlink))
(or (nil? tlog-stream)
(instance? java.io.OutputStream tlog-stream))
]}
(let [buffer (ByteBuffer/allocate BUFFER-SIZE)
statistics (atom {:bytes-read 0
:bytes-decoded 0
:messages-decoded (long-array 256 0)
:last-seq-ids (long-array 256 -1)
:messages-skipped (long-array 256 0)
:messages-encoded 0
:encode-failed 0
:bad-checksums 0
:bad-protocol 0
:bad-signatures 0
:unsigned-messages 0
:bad-timestamps 0
:bad-mavlink2 0})
signing-options-map {:accept-message-handler
(:accept-message-handler signing-options)
:decode-sha256
(MessageDigest/getInstance "SHA-256")
:secret-key (atom (:secret-key signing-options))
:secret-keyset (:secret-keyset signing-options)
:signing-tuples (atom {})
}
continue (atom true)
channel {:component-id component-id
:input-is-tlog? input-is-tlog?
MAVLInk 2.0 encoding and decoding
MAVLink 2.0 , encoding only
:protocol (atom protocol)
:signing-options signing-options-map
:statistics statistics
:system-id system-id
:tlog-stream (when tlog-stream
(DataOutputStream. tlog-stream))
}
shutdown-fn (fn[e]
(reset! continue false)
(when e
(if exception-handler
(exception-handler e)
(throw e))))
]
(.order buffer ByteOrder/LITTLE_ENDIAN)
(.setName (Thread/currentThread) "Mavlink decoding")
(try
(trampoline start-state channel
buffer
decode-input-stream
decode-output-channel
statistics)
(async/>!! decode-output-channel
{:message'id :SigningTuples
:signing-tuples (:signing-tuples channel)})
(shutdown-fn nil)
(catch IOException e (shutdown-fn (ex-info "clj-mavlink IOException occurred, probably due to shutdown of the link."
{:cause :io-exception
:thread "Mavlink Decode"
:exception e})))
(catch Exception e (shutdown-fn (ex-info "clj-mavlink decode thread Exception"
{:cause :decode
:exception e})))))
(.setName (Thread/currentThread) "Mavlink encoding")
(try
(encode-messages channel
encode-input-channel
encode-output-link)
(shutdown-fn nil)
(catch IOException e (shutdown-fn (ex-info "clj-mavlink IOException occurred, probably due to shutdown of the link."
{:cause :io-exception
:thread "Mavlink Encode"
:exception e})))
(catch Exception e (shutdown-fn (ex-info "clj-mavlink encode thread Exception"
{:cause :encode
:exception e})))))
{:statistics statistics
:close-channel-fn #(shutdown-fn nil)}))
(defn get-enum
"Look up value in an enum group and return the enum-key for that value.
nil in case of error."
[mavlink group-id v]
(get-in mavlink [:enums-by-group group-id v]))
(defn get-enum-group
"Given a group id, return the map of key/values for that group."
[mavlink group-id]
(group-id (:enums-by-group mavlink)))
|
60c704046f10275976bd350b8decef073e7a00f40b516b49bc25190f0858180a | oshyshko/adventofcode | AXY.hs | module Geom.AXY where
import Imports
data XY a = XY a a deriving (Show, Functor, Foldable)
data Line a = Line (XY a) (XY a) deriving (Show, Functor, Foldable)
instance Applicative XY where
pure a = XY a a
liftA2 f (XY x0 y0) (XY x1 y1) = XY (f x0 x1) (f y0 y1)
| null | https://raw.githubusercontent.com/oshyshko/adventofcode/95b6bb4d514cf02680ba1a62de5a5dca2bf9e92d/src/Geom/AXY.hs | haskell | module Geom.AXY where
import Imports
data XY a = XY a a deriving (Show, Functor, Foldable)
data Line a = Line (XY a) (XY a) deriving (Show, Functor, Foldable)
instance Applicative XY where
pure a = XY a a
liftA2 f (XY x0 y0) (XY x1 y1) = XY (f x0 x1) (f y0 y1)
| |
83c4cd3a67ea1828176448b06b7f3fcf802d9ca3ce7c430f8eaff6f655cef637 | wjrforcyber/SystemT | Tests.hs | # LANGUAGE ScopedTypeVariables #
module Lang.L3.Tests (propertyTests) where
import Data.Maybe
import qualified Lang.L3.Eval.EEval as E
import Lang.L3.Syntax.Extrinsic
import Lang.L3.Typecheck
import Test.Tasty
import Test.Tasty.QuickCheck as QC
propertyTests :: TestTree
propertyTests = testGroup "L3 Property tests" [tcL3Props, evalL3Props]
tcL3Props :: TestTree
tcL3Props =
testGroup
"Bidi-typecheck"
[ QC.testProperty "if a type can be checked with nat, then it will also be inferred to nat" $
\(e :: Exp) ->
tccheck e TNat /= return () || (tcinfer e == return TNat),
QC.testProperty "if a type can be checked with bool, then it will also be inferred to bool" $
\(e :: Exp) ->
tccheck e TBool /= return () || (tcinfer e == return TBool),
QC.testProperty "every well-typed expression can be inferred" $
\(e :: TcTyExp) ->
tcisSuccess (tcinfer (tcgetExp e)),
QC.testProperty "every well-typed expression can be checked for its type" $
\(e :: TcTyExp) ->
case runTC (tcinfer (tcgetExp e)) of
Right ty -> tcisSuccess $ tccheck (tcgetExp e) ty
Left _ -> error $ "This cannot happen because" ++ show e ++ " is well-typed"
]
evalL3Props :: TestTree
evalL3Props =
testGroup
"eval"
[ QC.testProperty "1-Well-typed expressions reduced to a value" $
\(e :: TcTyExp) ->
isJust (E.eval (tcgetExp e))
]
| null | https://raw.githubusercontent.com/wjrforcyber/SystemT/0b402e5a9a335e28e8a19ba0274f1b8e40c08eaf/tests/Lang/L3/Tests.hs | haskell | # LANGUAGE ScopedTypeVariables #
module Lang.L3.Tests (propertyTests) where
import Data.Maybe
import qualified Lang.L3.Eval.EEval as E
import Lang.L3.Syntax.Extrinsic
import Lang.L3.Typecheck
import Test.Tasty
import Test.Tasty.QuickCheck as QC
propertyTests :: TestTree
propertyTests = testGroup "L3 Property tests" [tcL3Props, evalL3Props]
tcL3Props :: TestTree
tcL3Props =
testGroup
"Bidi-typecheck"
[ QC.testProperty "if a type can be checked with nat, then it will also be inferred to nat" $
\(e :: Exp) ->
tccheck e TNat /= return () || (tcinfer e == return TNat),
QC.testProperty "if a type can be checked with bool, then it will also be inferred to bool" $
\(e :: Exp) ->
tccheck e TBool /= return () || (tcinfer e == return TBool),
QC.testProperty "every well-typed expression can be inferred" $
\(e :: TcTyExp) ->
tcisSuccess (tcinfer (tcgetExp e)),
QC.testProperty "every well-typed expression can be checked for its type" $
\(e :: TcTyExp) ->
case runTC (tcinfer (tcgetExp e)) of
Right ty -> tcisSuccess $ tccheck (tcgetExp e) ty
Left _ -> error $ "This cannot happen because" ++ show e ++ " is well-typed"
]
evalL3Props :: TestTree
evalL3Props =
testGroup
"eval"
[ QC.testProperty "1-Well-typed expressions reduced to a value" $
\(e :: TcTyExp) ->
isJust (E.eval (tcgetExp e))
]
| |
a8df1d6c08dda5750fa618735f8d731bf841b17caf414b5817c507926b5f14fa | facebook/pyre-check | typeVariableTest.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
open IntegrationTest
let test_check_bounded_variables context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import TypeVar, Callable
TFun = TypeVar("TFun", bound=Callable[[int], None])
def foo(x: TFun) -> None:
x(7)
|}
[];
assert_type_errors
{|
from typing import TypeVar, Callable
TFun = TypeVar("TFun", bound=Callable[[int], None])
def foo(x: TFun) -> None:
x("7")
|}
[
"Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \
`int` but got `str`.";
];
assert_type_errors
{|
from typing import TypeVar, Callable, Union
T1 = TypeVar("T1", bound=Union[Callable[[], str], Callable[[], int]])
def foo(x: T1) -> None:
y = x()
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Union[int, str]`."];
assert_type_errors
{|
from typing import TypeVar, Callable, Union
T1 = TypeVar("T1", bound=Union[Callable[[], str], Callable[[], str]])
def foo(x: T1) -> None:
y = x()
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `str`."];
assert_type_errors
{|
from typing import TypeVar
class CallableClass:
def __call__(self, x:int) -> str:
return "A"
T2 = TypeVar("T2", bound=CallableClass)
def foo(x: T2) -> None:
y = x(5)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `str`."];
assert_type_errors
{|
from typing import TypeVar
class CallableClass:
def __call__(self, x:int) -> str:
return "A"
T2 = TypeVar("T2", bound=CallableClass)
def foo(x: T2) -> None:
y = x(2)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `str`."];
assert_type_errors
{|
from typing import Type, TypeVar
class Constructable:
def __init__(self, x:int) -> None:
return
T3 = TypeVar("T3", bound=Type[Constructable])
def foo(x: T3) -> None:
x(5)
|}
[];
assert_type_errors
{|
from typing import TypeVar, Generic, List
S = TypeVar('S', bound=List[float])
def bar(x: List[float]) -> None:
pass
def foo(x: S) -> S:
bar(x)
return x
|}
[];
assert_type_errors
{|
from typing import TypeVar, Generic
T = TypeVar('T', covariant=True)
S = TypeVar('S', bound="Foo[float]")
class Foo(Generic[T]):
def a(self, x: S) -> S:
return x
def b(self, x: S) -> None:
self.a(x)
def foo(a: Foo[int]) -> Foo[float]:
return a
|}
[];
assert_type_errors
{|
from typing import TypeVar, List, Tuple, Optional, Callable
T = TypeVar("T", int, str)
def f(x: Callable[[T], None]) -> None:
y = g(x)
def g(x: Callable[[T], None]) -> None:
...
|}
[];
assert_type_errors
{|
from typing import TypeVar, List, Tuple, Optional, Callable
T = TypeVar("T", int, str)
def f(x: Optional[Callable[[Optional[T]], None]]) -> None:
y = g(x)
def g(x: Optional[Callable[[Optional[T]], None]]) -> None:
...
|}
[];
assert_type_errors
{|
from typing import *
T = TypeVar("T", Callable[[], str], Callable[[], int])
def foo(f: T) -> None:
f()
|}
[];
(* Test strict mode bounds with explicit Any types *)
assert_type_errors
{|
from typing import Any, List, TypeVar
T = TypeVar("T", bound=List[Any])
|}
["Prohibited any [33]: Type variable `T` cannot have a bound containing `Any`."];
assert_type_errors
{|
from typing import Any, TypeVar
T = TypeVar("T", bound=Any)
|}
["Prohibited any [33]: Type variable `T` cannot have `Any` as a bound."];
()
let test_check_unbounded_variables context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def expects_any(input: object) -> None: ...
def expects_string(inut: str) -> None: ...
def foo(input: T) -> None:
expects_any(input)
expects_string(input)
|}
[
"Incompatible parameter type [6]: In call `expects_string`, for 1st positional argument, \
expected `str` but got `Variable[T]`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def foo(input: T) -> typing.Any:
return input
|}
["Missing return annotation [3]: Returning `Variable[T]` but type `Any` is specified."];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def foo(input: T) -> int:
return input
|}
["Incompatible return type [7]: Expected `int` but got `Variable[T]`."];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def mapping_get(k: str, default: typing.Union[int, T]) -> typing.Union[int, T]: ...
def foo() -> None:
reveal_type(mapping_get("A", "A"))
reveal_type(mapping_get("A", 7))
|}
[
"Revealed type [-1]: Revealed type for `test.mapping_get(\"A\", \"A\")` is "
^ "`typing.Union[typing_extensions.Literal['A'], int]`.";
"Revealed type [-1]: Revealed type for `test.mapping_get(\"A\", 7)` is `int`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def foo(input: T) -> None:
input.impossible()
|}
["Undefined attribute [16]: `Variable[T]` has no attribute `impossible`."];
assert_type_errors
{|
import typing
X = typing.TypeVar("X")
class Foo(typing.Generic[X]): pass
reveal_type(Foo[float])
reveal_type(Foo[float]())
reveal_type(Foo[str]())
Foo["str"]()
|}
[
"Revealed type [-1]: Revealed type for `test.Foo[float]` is `typing.Type[Foo[float]]`.";
"Revealed type [-1]: Revealed type for `test.Foo[float]()` is `Foo[float]`.";
"Revealed type [-1]: Revealed type for `test.Foo[str]()` is `Foo[str]`.";
"Incompatible parameter type [6]: In call `typing.GenericMeta.__getitem__`, for 1st \
positional argument, expected `Type[Variable[X]]` but got `str`.";
];
assert_type_errors
{|
import typing
X = typing.TypeVar("X")
class Foo(typing.Generic[X]):
def __init__(self, x: X) -> None: ...
def one() -> Foo[int]:
return Foo[int](1)
def two() -> Foo[int]:
return Foo[int](1.2)
|}
[
"Incompatible parameter type [6]: In call `Foo.__init__`, for 1st positional argument, \
expected `int` but got `float`.";
];
assert_type_errors
{|
from typing import overload, TypeVar, List, Callable, Tuple, Union
@overload
def overloaded(x: int) -> str: ...
@overload
def overloaded(x: bool) -> float: ...
@overload
def overloaded(x: float) -> bool: ...
@overload
def overloaded(x: str) -> int: ...
def overloaded(x: Union[int, bool, float, str]) -> Union[int, bool, float, str]: ...
T1 = TypeVar("T1")
T2 = TypeVar("T2")
def generic(x: Callable[[T1], T2], y: List[T1], z: List[T2]) -> Tuple[T1, T2]: ...
def foo() -> None:
reveal_type(generic(overloaded, [1], ["1"]))
reveal_type(generic(overloaded, [True], [1.0]))
reveal_type(generic(overloaded, [1.0], [False]))
reveal_type(generic(overloaded, ["1"], [7]))
generic(overloaded, [1], [7])
|}
[
"Revealed type [-1]: Revealed type for `test.generic(test.overloaded, [1], [\"1\"])` is \
`Tuple[int, str]`.";
"Revealed type [-1]: Revealed type for `test.generic(test.overloaded, [True], [1.000000])` \
is `Tuple[bool, float]`.";
"Revealed type [-1]: Revealed type for `test.generic(test.overloaded, [1.000000], [False])` \
is `Tuple[float, bool]`.";
"Revealed type [-1]: Revealed type for `test.generic(test.overloaded, [\"1\"], [7])` is \
`Tuple[str, int]`.";
"Incompatible parameter type [6]: In call `generic`, for 3rd positional argument, expected \
`List[Variable[T2]]` but got `List[int]`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def foo(input: T, b: bool) -> typing.Optional[T]:
x = None
if b:
x = input
reveal_type(x)
return x
|}
["Revealed type [-1]: Revealed type for `x` is `typing.Optional[Variable[T]]`."];
assert_type_errors
{|
from typing import TypeVar, Generic, Optional
T1 = TypeVar("T1")
class Lol(Generic[T1]):
def bar(self, x: Optional[T1]) -> None:
if x is not None and self.bop(x):
return
def bop(self, x: T1) -> bool:
return True
|}
[];
assert_type_errors
{|
from typing import TypeVar, Union, List
T = TypeVar("T")
def foo(x: Union[T, List[T]]) -> None: ...
def bar(x: Union[T, List[T]]) -> None:
foo(x)
|}
[];
assert_type_errors
{|
from builtins import identity
from typing import Union, Tuple
SeparatedUnion = Union[
Tuple[int, bool],
Tuple[str, None],
]
def foo(x: SeparatedUnion) -> SeparatedUnion:
i = identity(x)
reveal_type(i)
return i
|}
["Revealed type [-1]: Revealed type for `i` is `Union[Tuple[int, bool], Tuple[str, None]]`."];
assert_type_errors
{|
from typing import Callable, TypeVar
T = TypeVar("T")
class CallMe:
def __call__(self, x: int) -> str:
return "A"
def foo(f: Callable[[int], T]) -> T:
return f(1)
def bar() -> None:
x = foo(CallMe())
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `str`."];
(* Type variables in the nesting function is correctly captured *)
assert_type_errors
{|
from typing import TypeVar, Callable
T = TypeVar('T')
def foo(x: T) -> Callable[[], T]:
def bar() -> T:
return x
return bar
|}
[];
(* Type variables in the parent class is correctly captured *)
assert_type_errors
{|
from typing import TypeVar, Generic, Callable
T = TypeVar('T')
class A(Generic[T]):
def foo(self, x: T) -> T:
return x
|}
[];
(* Type variables in the parent class of nesting function is correctly captured *)
assert_type_errors
{|
from typing import TypeVar, Generic, Callable
T = TypeVar('T')
class A(Generic[T]):
def foo(self, x: T) -> Callable[[T], int]:
def bar(x: T) -> int:
return 42
return bar
|}
[];
(* Correctly mark the boundness of nested function type variables when there're recursive calls *)
assert_type_errors
{|
from typing import TypeVar, Dict, Any, Union
def loads(obj: object) -> Dict[str, Any]: ...
T = TypeVar('T')
def foo() -> None:
def bar(obj: T, *, top_level: bool = True) -> Union[str, T]:
if isinstance(obj, dict):
return "dict"
else:
loaded = loads(obj)
modified = bar(loaded, top_level = False)
return str(modified)
|}
[];
assert_type_errors
{|
from typing import TypeVar, List, Generic
T_bound_int = TypeVar('T_bound_int', bound=int)
class G(Generic[T_bound_int]):
pass
T = TypeVar('T')
def foo(a: G[List[T]]) -> T: ...
|}
[
"Invalid type parameters [24]: Type parameter `List[Variable[T]]` violates constraints on \
`Variable[T_bound_int (bound to int)]` in generic type `G`.";
];
assert_type_errors
{|
from typing import TypeVar, List, Generic
T_Con = TypeVar('T_Con', contravariant=True)
class G(Generic[T_Con]):
pass
def foo(a: G[str], b: G[int]) -> None:
l: List[G[object]] = [a, b]
|}
[
"Incompatible variable type [9]: l is declared to have type `List[G[object]]` but is used as \
type `List[Union[G[int], G[str]]]`.";
];
assert_type_errors
{|
from typing import Generic, Optional, TypeVar
_T = TypeVar('_T')
class ContextVar(Generic[_T]):
def __init__(self, name: str, *, default: _T = ...) -> None: ...
def foo() -> None:
x: ContextVar[Optional[int]] = ContextVar[Optional[int]]("var1", default=None)
|}
[];
()
let test_check_variable_bindings context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from builtins import str_to_int
import typing
T = typing.TypeVar('T', bound=int)
def foo(t: T) -> None:
str_to_int(t)
|}
[
"Incompatible parameter type [6]: In call `str_to_int`, for 1st positional argument, \
expected `str` but got `Variable[T (bound to int)]`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T', bound=int)
def foo() -> T:
return 1.0
|}
[
"Invalid type variable [34]: The type variable `Variable[T (bound to int)]` isn't present in \
the function's parameters.";
"Incompatible return type [7]: Expected `Variable[T (bound to int)]` but got `float`.";
];
assert_type_errors
{|
from builtins import int_to_str
import typing
T = typing.TypeVar('T', bound=int)
def foo(t: T) -> None:
int_to_str(t)
def bar(x: str) -> None:
foo(x)
|}
[
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`Variable[T (bound to int)]` but got `str`.";
];
assert_type_errors
{|
import typing
class C():
def baz(self) -> int:
return 7
T = typing.TypeVar('T', bound=C)
def foo(t: T) -> int:
return t.baz()
|}
[];
assert_type_errors
{|
from typing import TypeVar
T = TypeVar("T", bound=int)
def f(x: T, y: int) -> T:
return x
def buggy(n: None) -> None:
return f(2, n)
|}
[
"Incompatible return type [7]: Expected `None` but got `int`.";
"Incompatible parameter type [6]: In call `f`, for 2nd positional argument, expected `int` \
but got `None`.";
];
assert_type_errors
{|
import typing
class C: pass
T = typing.TypeVar('T', bound=C)
def foo(input: typing.Type[T]) -> T:
v = input()
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `Variable[T (bound to C)]`."];
assert_type_errors
{|
import typing
_T = typing.TypeVar("T", bound=int)
class Foo:
def foo(self, x: int) -> int:
return x
class Bar(Foo):
def foo(self, x: _T) -> _T:
return x
|}
[];
assert_type_errors
{|
import typing
_T = typing.TypeVar("T", bound=float)
class Foo:
def foo(self, x: int) -> int:
return x
class Bar(Foo):
def foo(self, x: _T) -> _T:
return x
|}
[
"Inconsistent override [15]: `test.Bar.foo` overrides method defined in `Foo` inconsistently. "
^ "Returned type `Variable[_T (bound to float)]` is not a subtype of the overridden return "
^ "`int`.";
];
assert_type_errors
{|
import typing
_T = typing.TypeVar("T", bound=float)
class Foo:
def foo(self, x: _T) -> _T:
return x
class Bar(Foo):
def foo(self, x: int) -> int:
return x
|}
[
"Inconsistent override [14]: `test.Bar.foo` overrides method defined in `Foo` inconsistently. "
^ "Parameter of type `int` is not a supertype of the overridden parameter "
^ "`Variable[_T (bound to float)]`.";
];
assert_type_errors
{|
from typing import TypeVar
_SelfT = TypeVar("SelfT", bound=C)
class C():
def clone(self: _SelfT) -> _SelfT: ...
def foo(self: _SelfT) -> _SelfT:
x = self.clone()
reveal_type(x)
return x
|}
["Revealed type [-1]: Revealed type for `x` is `Variable[_SelfT (bound to C)]`."];
assert_type_errors
{|
from typing import TypeVar, Type
_SelfT = TypeVar("SelfT", bound=C)
class C():
@classmethod
def clone(cls: Type[_SelfT]) -> _SelfT: ...
@classmethod
def foop(cls: Type[_SelfT]) -> _SelfT:
x = cls.clone()
reveal_type(x)
return x
|}
["Revealed type [-1]: Revealed type for `x` is `Variable[_SelfT (bound to C)]`."];
assert_type_errors
{|
import typing
X = typing.TypeVar("X", bound=C)
class Foo(typing.Generic[X]): pass
class C(): pass
class D(C): pass
reveal_type(Foo[C])
reveal_type(Foo[C]())
reveal_type(Foo[D]())
Foo[int]()
|}
[
"Revealed type [-1]: Revealed type for `test.Foo[test.C]` is `typing.Type[Foo[C]]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.C]()` is `Foo[C]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.D]()` is `Foo[D]`.";
"Incompatible parameter type [6]: In call `typing.GenericMeta.__getitem__`, for 1st \
positional argument, expected `Type[Variable[X (bound to C)]]` but got `Type[int]`.";
];
assert_type_errors
{|
import typing
X = typing.TypeVar("X", Mineral, Animal)
class Foo(typing.Generic[X]): pass
class Mineral(): pass
class Animal(): pass
class Fish(Animal): pass
reveal_type(Foo[Animal])
reveal_type(Foo[Animal]())
reveal_type(Foo[Mineral]())
reveal_type(Foo[Fish]())
Foo[int]()
|}
[
"Revealed type [-1]: Revealed type for `test.Foo[test.Animal]` is "
^ "`typing.Type[Foo[Animal]]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.Animal]()` is `Foo[Animal]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.Mineral]()` is `Foo[Mineral]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.Fish]()` is `Foo[Animal]`.";
"Incompatible parameter type [6]: In call `typing.GenericMeta.__getitem__`, for 1st \
positional argument, expected `Type[Variable[X <: [Mineral, Animal]]]` but got `Type[int]`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T', bound=int)
class ConstrainedBase(typing.Generic[T]): pass
class BadChild(ConstrainedBase[str]): pass
|}
[
"Invalid type parameters [24]: Type parameter `str` violates constraints on "
^ "`Variable[T (bound to int)]` in generic type `ConstrainedBase`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T', bound=int)
class ConstrainedBase(typing.Generic[T]): pass
class AnyChild(ConstrainedBase[typing.Any]): pass
|}
[];
assert_type_errors
{|
from typing import TypeVar, Generic
T = TypeVar('T', bound="G")
class G(Generic[T]):
pass
|}
["Invalid type parameters [24]: Generic type `G` expects 1 type parameter."];
(* Test for a common misuse of variable bounds. *)
assert_type_errors
{|
from typing import TypeVar, Generic
TSelf = TypeVar("TSelf", bound="G")
T = TypeVar("T")
class G(Generic[T]):
# This method restricts the inputs to be less than `G[Any]` but does
# not enforce that the two inputs are of the same type.
def expect_self(self: TSelf, other: TSelf) -> TSelf: ...
x: G[int]
y: G[str]
x.expect_self(y)
reveal_type(x.expect_self(y))
z: bool
x.expect_self(z)
|}
[
"Invalid type parameters [24]: Generic type `G` expects 1 type parameter.";
"Revealed type [-1]: Revealed type for `x.expect_self(y)` is `typing.Union[G[int], G[str]]`.";
"Incompatible parameter type [6]: In call `G.expect_self`, for 1st positional argument, \
expected `Variable[TSelf (bound to G[typing.Any])]` but got `bool`.";
];
(* Same test as above but without an explicit type for `self`. *)
assert_type_errors
{|
from typing import TypeVar, Generic
TSelf = TypeVar("TSelf", bound="G")
T = TypeVar("T")
class G(Generic[T]):
# This method restricts the inputs to be less than `G[Any]` but does
# not enforce that the two inputs are of the same type.
def expect_self(self, other: TSelf) -> TSelf: ...
x: G[int]
y: G[str]
x.expect_self(y)
reveal_type(x.expect_self(y))
z: bool
x.expect_self(z)
|}
[
"Invalid type parameters [24]: Generic type `G` expects 1 type parameter.";
"Revealed type [-1]: Revealed type for `x.expect_self(y)` is `G[str]`.";
"Incompatible parameter type [6]: In call `G.expect_self`, for 1st positional argument, \
expected `Variable[TSelf (bound to G[typing.Any])]` but got `bool`.";
];
(* This actually requires the input to be of the same type as `self`. *)
assert_type_errors
{|
from typing import TypeVar, Generic
TSelf = TypeVar("TSelf", bound="G")
T = TypeVar("T")
class G(Generic[T]):
def expect_same_type(self: G[T], other: G[T]) -> G[T]: ...
x: G[int]
y: G[str]
x.expect_same_type(y)
reveal_type(x.expect_same_type(y))
z: bool
x.expect_same_type(z)
|}
[
"Invalid type parameters [24]: Generic type `G` expects 1 type parameter.";
"Incompatible parameter type [6]: In call `G.expect_same_type`, for 1st positional argument, \
expected `G[int]` but got `G[str]`.";
"Revealed type [-1]: Revealed type for `x.expect_same_type(y)` is `G[int]`.";
"Incompatible parameter type [6]: In call `G.expect_same_type`, for 1st positional argument, \
expected `G[int]` but got `bool`.";
];
Setting the bound as a parameter - less generic class ` INode ` replaces the parameters with Any .
This is equivalent to writing ` bound = INode[Any ] ` .
This is equivalent to writing `bound=INode[Any]`. *)
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
T = TypeVar("T")
class INode(Generic[T]): ...
TBoundToINode = TypeVar("TNodeGetResult", bound=INode)
TResult = TypeVar("TResult")
class Query(Generic[TResult]):
def get_result(self) -> TResult: ...
class NodeGetQuery(Query[TBoundToINode]): ...
y: NodeGetQuery[int]
z: NodeGetQuery[INode[str]]
z3: NodeGetQuery[INode[int]]
|}
[
"Invalid type parameters [24]: Generic type `INode` expects 1 type parameter.";
"Invalid type parameters [24]: Type parameter `int` violates constraints on \
`Variable[TBoundToINode (bound to test.INode)]` in generic type `NodeGetQuery`.";
];
(* Bug fix: Solve Optional[T (bound)] vs Optional[T (free)]. *)
assert_type_errors
{|
from typing import Generic, Optional, TypeVar
T = TypeVar("T")
class Foo(Generic[T]): ...
def create(x: Optional[T]) -> Foo[T]: ...
def main(x: T) -> Foo[T]:
return create(x)
|}
[];
()
let test_unbound_variables context =
let assert_type_errors = assert_type_errors ~context in
let assert_default_type_errors = assert_default_type_errors ~context in
assert_type_errors
{|
def foo() -> None:
x = []
|}
[
"Incomplete type [37]: Type `typing.List[Variable[_T]]` inferred for `x` is incomplete, "
^ "add an explicit annotation.";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.List[int] = []
|}
[];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Sequence[int] = []
|}
[];
assert_type_errors
{|
def foo() -> None:
x: int = []
|}
[
"Incompatible variable type [9]: x is declared to have type `int` but is used as type \
`List[Variable[_T]]`.";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Optional[typing.List[int]]
x = []
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is `typing.Optional[typing.List[int]]` (inferred: \
`typing.List[int]`).";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Dict[str, typing.List[int]] = { "A" : [] }
|}
[];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.List[int] = {}
|}
[
"Incompatible variable type [9]: x is declared to have type `List[int]` but is used as type \
`Dict[Variable[_KT], Variable[_VT]]`.";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Dict[int, str] = []
|}
[
"Incompatible variable type [9]: x is declared to have type `Dict[int, str]` but is used as \
type `List[Variable[_T]]`.";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Dict[int, typing.List[int]] = { "A" : [] }
|}
[
"Incompatible variable type [9]: x is declared to have type `Dict[int, List[int]]` but is \
used as type `Dict[str, List[int]]`.";
];
assert_type_errors
{|
import typing
def foo() -> typing.List[int]:
return []
|}
[];
assert_type_errors
{|
import typing
def bar(x: typing.List[int]) -> None:
pass
def foo() -> None:
bar([])
|}
[];
(* TODO(T42360946): Probably want a better error here *)
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
def bar(x: typing.List[T]) -> T:
return x[0]
def foo() -> None:
x = bar([])
|}
["Incomplete type [37]: Type inferred for `x` is incomplete, add an explicit annotation."];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[int]:
return G()
|}
[];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[int]:
g = G()
reveal_type(g)
return g
|}
[
"Incomplete type [37]: Type `G[Variable[T_Explicit <: [int, str]]]` inferred for `g` is "
^ "incomplete, add an explicit annotation.";
"Revealed type [-1]: Revealed type for `g` is `G[typing.Any]`.";
];
assert_default_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[int]:
g = G()
reveal_type(g)
return g
|}
["Revealed type [-1]: Revealed type for `g` is `G[typing.Any]`."];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[int]:
g: G[int] = G()
reveal_type(g)
return g
|}
["Revealed type [-1]: Revealed type for `g` is `G[int]`."];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[bool]:
g: G[bool] = G()
reveal_type(g)
return g
|}
[
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Revealed type [-1]: Revealed type for `g` is `G[typing.Any]`.";
];
assert_default_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[bool]:
g: G[bool] = G()
reveal_type(g)
return g
|}
[
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Revealed type [-1]: Revealed type for `g` is `G[typing.Any]`.";
];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
T = typing.TypeVar("T")
class G(typing.Generic[T_Explicit, T]):
def __init__(self) -> None:
pass
def bar(g: G[bool, bool]) -> None:
reveal_type(g)
|}
[
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Revealed type [-1]: Revealed type for `g` is `G[typing.Any, bool]`.";
];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def foo(self) -> int:
return 7
def bar() -> int:
return G().foo()
|}
[
"Incomplete type [37]: Type `G[Variable[T_Explicit <: [int, str]]]` inferred for `test.G()` "
^ "is incomplete, so attribute `foo` cannot be accessed. Separate the expression into an "
^ "assignment and give it an explicit annotation.";
];
assert_type_errors
{|
def bar() -> None:
for x in []:
pass
|}
[
"Incomplete type [37]: Type `typing.List[Variable[_T]]` inferred for `[]` is incomplete, so \
attribute `__iter__` cannot be accessed. Separate the expression into an assignment and \
give it an explicit annotation.";
];
assert_type_errors
{|
import typing
import collections
def foo() -> None:
x: typing.Dict[int, typing.Dict[int, str]] = collections.defaultdict(dict)
|}
[];
assert_type_errors
{|
import typing
import collections
def foo() -> None:
x: typing.Dict[int, str] = collections.defaultdict(dict)
|}
[
"Incompatible variable type [9]: x is declared to have type `Dict[int, str]` but is used as \
type `DefaultDict[Variable[collections._KT], Dict[Variable[_KT], Variable[_VT]]]`.";
];
assert_type_errors
{|
import typing
def foo() -> typing.Tuple[typing.List[int], typing.List[str]]:
return [], []
|}
[];
(* This could cause an infinite loop due to mismatching errors if we didn't make the error set
namespace insensitive *)
assert_type_errors
{|
def foo(x: int) -> None: pass
def bar() -> None:
for x in [1, 2, 3]:
foo([])
|}
[
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected `int` \
but got `List[Variable[_T]]`.";
];
assert_type_errors
{|
import typing
def bar(
a: typing.Optional[typing.List[int]], b: typing.Optional[typing.List[str]]
) -> typing.Tuple[typing.List[int], typing.List[str]]:
return a or [], b or []
|}
[];
assert_type_errors
{|
from typing import Generic, TypeVar, Any
T = TypeVar('T')
class G(Generic[T]):
prop: T
def __init__(self, prop: T) -> None:
self.prop = prop
class C(G[int]):
def foo(self) -> None:
reveal_type(self.prop)
|}
["Revealed type [-1]: Revealed type for `self.prop` is `int`."];
()
let test_distinguish context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
import typing
_T1 = typing.TypeVar("_T1")
_T2 = typing.TypeVar("_T2")
class C(typing.Generic[_T1]):
def pair(self, a: _T1, b: _T2) -> typing.Tuple[_T1, _T2]:
return (a, b)
def foo(q: C[_T2], x: _T2, y:_T1) -> typing.Tuple[_T2, _T1]:
A = q.pair(x, y)
reveal_type(A)
return A
|}
["Revealed type [-1]: Revealed type for `A` is `typing.Tuple[Variable[_T2], Variable[_T1]]`."];
assert_type_errors
{|
import typing
_T1 = typing.TypeVar("_T1")
_T2 = typing.TypeVar("_T2")
def foo(f: typing.Callable[[_T1], _T2], p: _T1) -> _T2:
v = f(p)
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `Variable[_T2]`."];
assert_type_errors
{|
import typing
_T1 = typing.TypeVar("_T1")
_T2 = typing.TypeVar("_T2")
def foo(f: typing.Callable[[_T1], _T2], p: _T1) -> _T2:
return f(1)
|}
[
"Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \
`Variable[_T1]` but got `int`.";
];
assert_type_errors
{|
import typing
_T1 = typing.TypeVar("_T1")
_T2 = typing.TypeVar("_T2")
class B: pass
class C(B): pass
def foo(f: typing.Callable[[typing.List[typing.Tuple[_T1, B]]], _T2], p: _T1) -> _T2:
v = f([(p, C())])
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `Variable[_T2]`."];
assert_type_errors
{|
import typing
class C():
def __init__(self, x: int) -> None:
pass
def foo() -> typing.Iterator[C]:
v = map(C, [1, 2, 3])
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `map[C]`."];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
class C(typing.Generic[T]):
def __init__(self, x: T) -> None:
pass
def foo() -> typing.Iterator[C[int]]:
v = map(C, [1, 2, 3])
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `map[C[int]]`."];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
class C(typing.Generic[T]):
def __init__(self, x: T) -> None:
pass
def foo(x: typing.List[T]) -> typing.Iterator[C[T]]:
v = map(C, x)
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `map[C[Variable[T]]]`."];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
def foo(x: T) -> typing.List[T]:
return [x]
T1 = typing.TypeVar("T1")
def bar(x: typing.Callable[[T1], T1]) -> None:
pass
def baz() -> None:
bar(foo)
|}
[
"Mutually recursive type variables [36]: Solving type variables for call `bar` "
^ "led to infinite recursion.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
def foo(x: T) -> T:
return x
T1 = typing.TypeVar("T1")
T2 = typing.TypeVar("T2")
def bar(x: typing.Callable[[T1], T2], y: typing.Callable[[T2], T1]) -> typing.Tuple[T1, T2]:
...
def baz() -> None:
x = bar(foo, foo)
|}
[
"Incomplete type [37]: Type `typing.Tuple[Variable[T1], Variable[T1]]` inferred for `x"
^ "` is incomplete, add an explicit annotation.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
def identity(x: T) -> T:
return x
def f() -> None:
reveal_type(map(identity, [1, 2, 3]))
|}
["Revealed type [-1]: Revealed type for `map(test.identity, [1, 2, 3])` is `map[int]`."];
()
let test_integer_variables context =
assert_type_errors
~context
{|
import typing_extensions
T = typing_extensions.IntVar("T")
X = typing_extensions.IntVar("X")
def baz(x: X) -> X:
return x
def bop(x: int) -> None:
pass
def foo(x: T) -> T:
y = x.__add__(5)
z = baz(x)
bop(x)
return z
def bar() -> None:
x = foo(1)
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `typing_extensions.Literal[1]`."];
assert_type_errors
~context
{|
import typing_extensions
X = typing_extensions.IntVar("X")
def baz(x: X) -> X:
return x
def bar(y: int) -> None:
baz(y)
|}
[
"Incompatible parameter type [6]: In call `baz`, for 1st positional argument, expected \
`IntegerVariable[X]` but got `int`.";
];
()
let test_nested_variable_error context =
assert_type_errors
~context
{|
import typing
T1 = typing.TypeVar("T1")
T2 = typing.TypeVar("T2", typing.List[T1], typing.Dict[str, T1])
|}
[
"Invalid type [31]: Expression `Variable[T2 <: [typing.List[Variable[test.T1]], "
^ "typing.Dict[str, Variable[test.T1]]]]` is not a valid type. Type variables cannot contain "
^ "other type variables in their constraints.";
];
()
let test_single_explicit_error context =
assert_type_errors
~context
{|
import typing
T1 = typing.TypeVar("T1", int)
|}
[
"Invalid type [31]: TypeVar can't have a single explicit constraint. Did you mean `bound=int`?";
];
()
let test_callable_parameter_variadics context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Callable, List
import pyre_extensions
V = pyre_extensions.ParameterSpecification("V")
def f(x: Callable[V, int]) -> Callable[V, List[int]]: ...
def foo(x: int) -> int:
return 7
def bar(x: int, y: str) -> int:
return 7
def g() -> None:
reveal_type(f(foo))
reveal_type(f(bar))
|}
[
"Revealed type [-1]: Revealed type for `test.f(test.foo)` is `typing.Callable[[Named(x, \
int)], "
^ "List[int]]`.";
"Revealed type [-1]: Revealed type for `test.f(test.bar)` is `typing.Callable[[Named(x, \
int), "
^ "Named(y, str)], List[int]]`.";
];
assert_type_errors
{|
import typing
import pyre_extensions
V = pyre_extensions.ParameterSpecification("V")
class Propagating(typing.List[typing.Callable[V, int]]):
def foo(self) -> int: ...
|}
[];
assert_type_errors
~handle:"qualifier.py"
{|
from typing import Callable, List
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import PositionalArgumentsOf, KeywordArgumentsOf
V = ParameterSpecification("V")
def f(x: Callable[V, int]) -> Callable[V, List[int]]:
def decorated( *args: V.args, **kwargs: V.kwargs) -> List[int]:
return [x( *args, **kwargs)]
return decorated
|}
[];
assert_type_errors
{|
from typing import Callable
from pyre_extensions import ParameterSpecification
TParams = ParameterSpecification("TParams")
def eek(x: Callable[TParams, int]) -> Callable[TParams, float]:
return x
|}
[];
assert_type_errors
{|
from typing import Protocol, Callable, TypeVar
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def call_this_function(__f: Callable[TParams, TReturn], *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
return __f( *args, **kwargs)
def int_to_string(i: int) -> str:
return "A"
def foo() -> None:
x = call_this_function(int_to_string, 1)
reveal_type(x)
y = call_this_function(int_to_string, i=1)
reveal_type(y)
call_this_function(int_to_string, "A")
call_this_function(int_to_string, i="A")
|}
[
"Revealed type [-1]: Revealed type for `x` is `str`.";
"Revealed type [-1]: Revealed type for `y` is `str`.";
"Incompatible parameter type [6]: In call `call_this_function`, for 2nd positional argument, \
expected `int` but got `str`.";
"Incompatible parameter type [6]: In call `call_this_function`, for argument `i`, expected \
`int` but got `str`.";
];
(* Interaction with overloads *)
assert_type_errors
{|
from typing import Protocol, Callable, TypeVar, overload, Union
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def call_this_function(__f: Callable[TParams, TReturn], *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
return __f( *args, **kwargs)
@overload
def overloaded(x: int) -> str:...
@overload
def overloaded(x: str) -> int:...
def overloaded(x: Union[int, str]) -> Union[int, str]:
if isinstance(x, int):
return "A"
else:
return 1
def foo() -> None:
x = call_this_function(overloaded, 1)
reveal_type(x)
y = call_this_function(overloaded, "A")
reveal_type(y)
call_this_function(overloaded, 1.0)
|}
[
"Revealed type [-1]: Revealed type for `x` is `str`.";
"Revealed type [-1]: Revealed type for `y` is `int`.";
"Incompatible parameter type [6]: In call `call_this_function`, for 2nd positional argument, \
expected `int` but got `float`.";
];
(* Example from PEP *)
assert_type_errors
{|
from typing import Protocol, Callable, TypeVar
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def call_n_times(
__f: Callable[TParams, None],
__n: int,
*args: TParams.args,
**kwargs: TParams.kwargs,
) -> None:
for x in range(__n):
__f( *args, **kwargs)
def valid(x: int, y: str) -> None: ...
def invalid(x: int, y: str) -> int: ...
def foo() -> None:
call_n_times(valid, 75, 1, "A")
# invalid first argument
call_n_times(invalid, 75, 1, "A")
# missing second argument
call_n_times(valid, y="A", x=1)
|}
[
"Incompatible parameter type [6]: In call `call_n_times`, for 1st positional argument, \
expected `typing.Callable[test.TParams, None]` but got `typing.Callable(invalid)[[Named(x, \
int), Named(y, str)], int]`.";
"Missing argument [20]: Call `call_n_times` expects argument in position 1.";
];
(* Decorator to supply an argument to a method. *)
assert_type_errors
{|
from typing import *
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import Concatenate
P = ParameterSpecification("P")
R = TypeVar("R")
class Client: ...
def with_client(
f: Callable[Concatenate["Foo", Client, P], R]
) -> Callable[Concatenate["Foo", P], R]:
def inner(__self: "Foo", *args: P.args, **kwargs: P.kwargs) -> R:
return f(__self, Client(), *args, **kwargs)
return inner
class Foo:
@with_client
def takes_int_str(self, client: Client, x: int, y: str) -> int:
# Use `client` here.
return x + 7
reveal_type(with_client)
x: Foo
reveal_type(x.takes_int_str)
x.takes_int_str(1, "A") # Accepted
x.takes_int_str("B", 2) # Correctly rejected by the type checker
|}
[
"Revealed type [-1]: Revealed type for `test.with_client` is \
`typing.Callable(with_client)[[Named(f, \
typing.Callable[pyre_extensions.type_variable_operators.Concatenate[Foo, Client, test.P], \
Variable[R]])], typing.Callable[pyre_extensions.type_variable_operators.Concatenate[Foo, \
test.P], Variable[R]]]`.";
"Revealed type [-1]: Revealed type for `x.takes_int_str` is \
`BoundMethod[typing.Callable[[Foo, Named(x, int), Named(y, str)], int], Foo]`.";
"Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \
`int` but got `str`.";
"Incompatible parameter type [6]: In anonymous call, for 2nd positional argument, expected \
`str` but got `int`.";
];
PyTorch style delegation pattern
assert_type_errors
{|
from abc import ABCMeta
from typing import Protocol, Callable, TypeVar
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
class HasForward(Protocol[TParams, TReturn]):
forward: Callable[TParams, TReturn]
class Model(metaclass=ABCMeta):
forward: Callable[..., object]
def __call__(__self: HasForward[TParams, TReturn], *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
# do some common stuff
return_value = __self.forward( *args, **kwargs)
# do some more stuff
return return_value
class AModel(Model):
def forward(self, x: int, y: str) -> bool:
...
class BModel(Model):
def forward(self, x: bool, *args: int) -> str:
...
def foo() -> None:
# Correct usages
x = AModel()(1, "A")
reveal_type(x)
y = AModel()(y="A", x=5)
reveal_type(y)
# Incorrect second argument
AModel()(1, 1)
# Different model
z = BModel()(True, 1, 4, 5)
reveal_type(z)
|}
[
"Revealed type [-1]: Revealed type for `x` is `bool`.";
"Revealed type [-1]: Revealed type for `y` is `bool`.";
"Incompatible parameter type [6]: In call `Model.__call__`, for 2nd positional argument, \
expected `str` but got `int`.";
"Revealed type [-1]: Revealed type for `z` is `str`.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import Generic
P = ParameterSpecification("P")
class H(Generic[P]):
def f(self, /, *args: P.args, **kwargs: P.kwargs) -> int:
return 5
def foo(x: H[int, str]) -> None:
reveal_type(x.f.__call__)
# incorrect
x.f()
x.f("A", 1)
# correct
x.f(1, "A")
|}
[
"Revealed type [-1]: Revealed type for `x.f.__call__` is `typing.Callable[[int, str], int]`.";
"Missing argument [20]: Call `H.f` expects argument in position 1.";
"Incompatible parameter type [6]: In call `H.f`, for 1st positional argument, expected `int` \
but got `str`.";
"Incompatible parameter type [6]: In call `H.f`, for 2nd positional argument, expected `str` \
but got `int`.";
];
assert_type_errors
{|
from typing import Callable
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
def outer(f: Callable[TParams, int]) -> None:
def foo(x: int, *args: TParams.args, **kwargs: TParams.kwargs) -> None:
pass
def bar(__x: int, *args: TParams.args, **kwargs: TParams.kwargs) -> None:
pass
def baz(x: int, /, *args: TParams.args, **kwargs: TParams.kwargs) -> None:
pass
reveal_type(foo)
reveal_type(bar)
reveal_type(baz)
|}
[
"Revealed type [-1]: Revealed type for `foo` is \
`typing.Callable[pyre_extensions.type_variable_operators.Concatenate[int, test.TParams], \
None]`.";
"Revealed type [-1]: Revealed type for `bar` is \
`typing.Callable[pyre_extensions.type_variable_operators.Concatenate[int, test.TParams], \
None]`.";
"Revealed type [-1]: Revealed type for `baz` is \
`typing.Callable[pyre_extensions.type_variable_operators.Concatenate[int, test.TParams], \
None]`.";
];
assert_type_errors
{|
from typing import Callable
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
def outer(f: Callable[TParams, int]) -> Callable[TParams, None]:
def foo(x: int, *args: TParams.args, **kwargs: TParams.kwargs) -> None:
f( *args, **kwargs)
def bar( *args: TParams.args, **kwargs: TParams.kwargs) -> None:
foo(1, *args, **kwargs) # Accepted
foo(x=1, *args, **kwargs) # Rejected
return bar
|}
["Unexpected keyword [28]: Unexpected keyword argument `x` to anonymous call."];
assert_type_errors
{|
from typing import Protocol, Callable, TypeVar, overload, Union
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
def doesnt_care_positional( *args: object) -> None:
pass
def doesnt_care_keywords( **kwargs: object) -> None:
pass
def does_care_positional( *args: int) -> None:
pass
def does_care_keywords( **kwargs: int) -> None:
pass
def outer(f: Callable[TParams, int]) -> Callable[TParams, None]:
def foo( *args: TParams.args, **kwargs: TParams.kwargs) -> None:
doesnt_care_positional( *args)
doesnt_care_keywords( **kwargs)
does_care_positional( *args)
does_care_keywords( **kwargs)
f( *args, **kwargs)
return foo
|}
[
"Incompatible parameter type [6]: In call `does_care_positional`, for 1st positional \
argument, expected `int` but got `object`.";
"Incompatible parameter type [6]: In call `does_care_keywords`, for 1st positional argument, \
expected `int` but got `object`.";
];
()
let test_user_defined_parameter_specification_classes context =
let assert_type_errors = assert_type_errors ~context in
Make sure ` typing . ParamSpec ` works .
assert_type_errors
{|
from typing import Callable, ParamSpec
TParams = ParamSpec("TParams")
def client(f: Callable[TParams, int]) -> None:
def inner( *args: TParams.args, **kwargs: TParams.kwargs) -> int:
return f( *args, **kwargs)
|}
[];
Make sure ` typing_extensions . ParamSpec ` works .
assert_type_errors
{|
from typing import Callable
from typing_extensions import ParamSpec
TParams = ParamSpec("TParams")
def client(f: Callable[TParams, int]) -> None:
def inner( *args: TParams.args, **kwargs: TParams.kwargs) -> int:
return f( *args, **kwargs)
|}
[];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def function(param: str) -> str:
...
class MyClass(Generic[TParams, TReturn]):
f: Callable[TParams, TReturn]
def __init__(self, f: Callable[TParams, TReturn]) -> None:
self.f = f
def call(__self, *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
f = __self.f
# do some logging or something
return f( *args, **kwargs)
def client(f: Callable[TParams, TReturn]) -> MyClass[TParams, TReturn]:
return MyClass(f)
def foo() -> None:
x = client(function).call(param="")
reveal_type(x)
client(function).call(parm="")
|}
[
"Revealed type [-1]: Revealed type for `x` is `str`.";
"Unexpected keyword [28]: Unexpected keyword argument `parm` to call `MyClass.call`.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def client(f: Callable[TParams, TReturn]) -> None:
def inner(__x: int, *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
return f( *args, **kwargs)
reveal_type(inner)
|}
[
"Revealed type [-1]: Revealed type for `inner` is \
`typing.Callable[pyre_extensions.type_variable_operators.Concatenate[int, test.TParams], \
Variable[TReturn]]`.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable, Protocol
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
class CallableReturningInt(Protocol[TParams]):
def __call__(__self, __f: int, *args: TParams.args, **kwargs: TParams.kwargs) -> int:
...
def remove_int_argument(f: CallableReturningInt[TParams]) -> Callable[TParams, int]: ...
def goof(x: int, y: str) -> int:
return x
def foo() -> None:
f = remove_int_argument(goof)
reveal_type(f)
|}
["Revealed type [-1]: Revealed type for `f` is `typing.Callable[[Named(y, str)], int]`."];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import Concatenate
from typing import TypeVar, Generic, Callable, Protocol
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def remove_int_argument(f: Callable[Concatenate[int, TParams], str]) -> Callable[TParams, int]:
def inner( *args: TParams.args, **kwargs: TParams.kwargs) -> int:
s = f(75, *args, **kwargs)
return int(s)
return inner
def goof(x: int, y: str) -> str:
return str(x)
def foo() -> None:
f = remove_int_argument(goof)
reveal_type(f)
|}
["Revealed type [-1]: Revealed type for `f` is `typing.Callable[[Named(y, str)], int]`."];
assert_type_errors
{|
from typing import Protocol
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
TSelf = TypeVar("TSelf")
class ObjectMethod(Protocol[TSelf, TParams, TReturn]):
def __call__(__self, __other_self: TSelf, *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn: ...
def track_assertion(
assertion: ObjectMethod["TestCommand", TParams, None]
) -> ObjectMethod["TestCommand", TParams, int]:
def assert_test(
__self: "TestCommand",
*args: TParams.args,
**kwargs: TParams.kwargs
) -> int:
assertion(__self, *args, **kwargs)
return 7
return assert_test
class TestCommand:
@track_assertion
def method(self: "TestCommand", x: int) -> None:
pass
def foo() -> None:
m = TestCommand().method
reveal_type(m)
|}
[
"Revealed type [-1]: Revealed type for `m` is `ObjectMethod[TestCommand, [Named(x, int)], \
int]`.";
];
assert_type_errors
{|
from typing import Protocol
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import Concatenate
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
TSelf = TypeVar("TSelf")
def track_assertion(
assertion: Callable[Concatenate["TestCommand", TParams], None]
) -> Callable[Concatenate["TestCommand", TParams], int]:
def assert_test(
__self: "TestCommand",
*args: TParams.args,
**kwargs: TParams.kwargs
) -> int:
assertion(__self, *args, **kwargs)
return 7
return assert_test
class TestCommand:
@track_assertion
def method(self: "TestCommand", x: int) -> None:
pass
def foo() -> None:
m = TestCommand().method
reveal_type(m)
|}
[
"Revealed type [-1]: Revealed type for `m` is `BoundMethod[typing.Callable[[TestCommand, \
Named(x, int)], int], TestCommand]`.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import Concatenate
from typing import TypeVar, Generic, Callable, Protocol
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def add_on_argument(f: Callable[TParams, str]) -> Callable[Concatenate[str, TParams], int]:
def inner(first: str, /, *args: TParams.args, **kwargs: TParams.kwargs) -> int:
s = f( *args, **kwargs)
return int(s)
return inner
def goof(x: int) -> str:
return str(x)
def foo() -> None:
f = add_on_argument(goof)
reveal_type(f)
|}
["Revealed type [-1]: Revealed type for `f` is `typing.Callable[[str, Named(x, int)], int]`."];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
class MyClass(Generic[TParams]):
def __call__(__self, *args: TParams.args, **kwargs: TParams.kwargs) -> bool: ...
IntStrParamSpec = MyClass[int, str]
def foo() -> None:
f: IntStrParamSpec
reveal_type(f)
f(1, "hello")
f("invalid")
|}
[
"Revealed type [-1]: Revealed type for `f` is `MyClass[[int, str]]`.";
"Missing argument [20]: Call `MyClass.__call__` expects argument in position 2.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable, Protocol
TParams = ParameterSpecification("TParams")
class PrependIntProtocol(Protocol[TParams]):
def __call__(__self, __f: int, *args: TParams.args, **kwargs: TParams.kwargs) -> int: ...
IntBoolStrParamSpec = PrependIntProtocol[bool, str]
def foo() -> None:
f: IntBoolStrParamSpec
reveal_type(f)
f(1, True, "hello")
f("invalid")
|}
[
"Revealed type [-1]: Revealed type for `f` is `PrependIntProtocol[[bool, str]]`.";
"Missing argument [20]: Call `PrependIntProtocol.__call__` expects argument in position 2.";
];
()
let test_duplicate_type_variables context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import TypeVar, Generic
T = TypeVar("T")
S = TypeVar("S")
class A(Generic[T, S, T]):
pass
|}
["Duplicate type variables [59]: Duplicate type variable `T` in Generic[...]."];
assert_type_errors
{|
from typing import TypeVar, Protocol
T = TypeVar("T")
class A(Protocol[T, T, T]):
pass
|}
["Duplicate type variables [59]: Duplicate type variable `T` in Protocol[...]."];
assert_type_errors
{|
from typing import Generic
from pyre_extensions import ParameterSpecification
P = ParameterSpecification("P")
class A(Generic[P, P]):
pass
|}
["Duplicate type variables [59]: Duplicate type variable `P` in Generic[...]."];
()
let test_generic_aliases context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import List
MyList = List[int]
x: MyList
reveal_type(x)
reveal_type(x[0])
|}
[
"Revealed type [-1]: Revealed type for `x` is `List[int]`.";
"Revealed type [-1]: Revealed type for `x[0]` is `int`.";
];
assert_type_errors
{|
from typing import Tuple, TypeVar
T = TypeVar("T")
Pair = Tuple[T, T]
x: Pair[str]
reveal_type(x)
reveal_type(x[0])
|}
[
"Revealed type [-1]: Revealed type for `x` is `Tuple[str, str]`.";
"Revealed type [-1]: Revealed type for `x[0]` is `str`.";
];
assert_type_errors
{|
from typing import TypeVar, Union
T = TypeVar("T")
UnionWithInt = Union[T, int]
x: UnionWithInt[str]
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `Union[int, str]`."];
assert_type_errors
{|
from typing import List, Tuple, TypeVar, Union
T = TypeVar("T")
Alias1 = Union[T, int]
Alias2 = Tuple[T, Alias1[T]]
Alias3 = List[Alias2[T]]
x: Alias3[str]
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `List[Tuple[str, Union[int, str]]]`."];
(* `MyList3` resolves to `List[int]`. So, it ignores the extra `str` argument. *)
assert_type_errors
{|
from typing import *
T = TypeVar("T")
MyList1 = List[T]
MyList2 = MyList1[int]
MyList3 = MyList2
xs: MyList3[str]
reveal_type(xs)
|}
["Revealed type [-1]: Revealed type for `xs` is `typing.List[int]`."];
let sources_exporting_generic_classes =
[
{
Test.handle = "foo.py";
source =
{|
from typing import Generic, TypeVar
T= TypeVar("T")
class SomeGenericClass(Generic[T]): ...
|};
};
{
handle = "baz.py";
source =
{|
from typing import Dict, Generic, Iterable, Optional, Sequence, Union, TypeVar
from foo import SomeGenericClass
|};
};
]
in
(* `Optional` is imported as `foo.bar.baz.Optional`, which is an alias we resolve to
`typing.Optional`. *)
assert_type_errors
~update_environment_with:sources_exporting_generic_classes
{|
from baz import *
from typing import List as MyList
reveal_type(Optional)
reveal_type(Union)
reveal_type(MyList)
reveal_type(Iterable)
reveal_type(SomeGenericClass)
|}
[
"Revealed type [-1]: Revealed type for `baz.Optional` is `typing.Type[typing.Optional]`.";
"Revealed type [-1]: Revealed type for `baz.Union` is `typing.Type[typing.Union]`.";
"Revealed type [-1]: Revealed type for `typing.List` is `typing.Type[list]`.";
"Revealed type [-1]: Revealed type for `baz.Iterable` is `typing.Type[typing.Iterable]`.";
"Revealed type [-1]: Revealed type for `baz.SomeGenericClass` is \
`typing.Type[foo.SomeGenericClass]`.";
];
assert_type_errors
~update_environment_with:sources_exporting_generic_classes
{|
from baz import *
from typing import List as MyList, TypeVar
z: MyList[int] = ["hello"]
z2: Iterable[int] = ["hello"]
z3: SomeGenericClass[int] = ["hello"]
|}
[
"Incompatible variable type [9]: z is declared to have type `MyList[int]` but is used as \
type `MyList[str]`.";
"Incompatible variable type [9]: z2 is declared to have type `Iterable[int]` but is used as \
type `Iterable[str]`.";
"Incompatible variable type [9]: z3 is declared to have type `SomeGenericClass[int]` but is \
used as type `MyList[str]`.";
];
(* We should correctly resolve nested generic aliases like `baz.Dict`. *)
assert_type_errors
~update_environment_with:sources_exporting_generic_classes
{|
from baz import *
x: Optional[Dict[str, int]]
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `typing.Optional[typing.Dict[str, int]]`."];
let sources_exporting_generic_classes =
[
{
Test.handle = "bar/baz.py";
source = {|
from typing import Callable
|};
};
]
in
assert_type_errors
~update_environment_with:sources_exporting_generic_classes
{|
from bar.baz import Callable
def foo() -> None:
reveal_type(Callable)
f: Callable[[int], str]
y = f(1)
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `bar.baz.Callable` is `typing.Type[typing.Callable]`.";
"Revealed type [-1]: Revealed type for `y` is `str`.";
];
assert_type_errors
{|
from typing import Callable
C = Callable
def foo() -> None:
f: C[[int], str]
reveal_type(f)
|}
[
(* TODO(T78935633): Probably shouldn't error here. *)
"Invalid type parameters [24]: Generic type `Callable` expects 2 type parameters.";
"Revealed type [-1]: Revealed type for `f` is `typing.Callable[[int], str]`.";
];
assert_type_errors
{|
from typing import Callable, Iterable, Iterator, TypeVar
T = TypeVar("T")
Predicate = Callable[[T], int]
def dropwhile(predicate: Predicate[T], iterable: Iterable[T]) -> Iterator[T]: ...
def foo() -> None:
reveal_type(dropwhile)
|}
[
"Revealed type [-1]: Revealed type for `test.dropwhile` is \
`typing.Callable(dropwhile)[[Named(predicate, typing.Callable[[Variable[T]], int]), \
Named(iterable, Iterable[Variable[T]])], Iterator[Variable[T]]]`.";
];
Generic alias for a class respects variance .
assert_type_errors
{|
from typing import TypeVar, Iterable as MyIterable, List as MyList
T = TypeVar("T")
class Base: ...
class Child(Base): ...
xs: MyIterable[Child]
# No error, since Iterable is covariant.
ys: MyIterable[Base] = xs
xs: MyList[Child]
# Error because List is invariant.
ys: MyList[Base] = xs
|}
[
"Incompatible variable type [9]: ys is declared to have type `MyList[Base]` but is used as \
type `MyList[Child]`.";
];
(* Error messages. *)
Zero type parameters provided .
assert_type_errors
{|
from typing import Tuple, TypeVar
T = TypeVar("T")
Pair = Tuple[T, T]
y: Pair
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Tuple[typing.Any, typing.Any]`."];
(* Extra type parameters provided. *)
assert_type_errors
{|
from typing import Tuple, TypeVar
T = TypeVar("T")
Pair = Tuple[T, T]
y: Pair[int, str]
reveal_type(y)
|}
[
(* TODO(T78935633): Raise clearer error. *)
"Invalid type variable [34]: The type variable `Variable[T]` can only be used to annotate \
generic classes or functions.";
"Revealed type [-1]: Revealed type for `y` is `typing.Any`.";
];
More than one free variable in the alias body .
assert_type_errors
{|
from typing import Tuple, TypeVar
T1 = TypeVar("T1")
T2 = TypeVar("T2")
Pair = Tuple[T1, T2]
y: Pair[int]
reveal_type(y)
y: Pair[int, str]
reveal_type(y)
|}
[
(* TODO(T78935633): Raise clearer error. *)
"Invalid type variable [34]: The type variable `Variable[T1]` can only be used to annotate \
generic classes or functions.";
"Invalid type variable [34]: The type variable `Variable[T2]` can only be used to annotate \
generic classes or functions.";
"Revealed type [-1]: Revealed type for `y` is `typing.Any`.";
"Revealed type [-1]: Revealed type for `y` is `Tuple[int, str]`.";
];
(* No free variables in the alias body. *)
assert_type_errors
{|
from typing import Any, Tuple, TypeVar
T = TypeVar("T")
Pair = Tuple[str, int]
y: Pair
reveal_type(y)
y: Pair[str]
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[str, int]`.";
(* TODO(T78935633): Raise error about extra parameter. *)
"Revealed type [-1]: Revealed type for `y` is `Tuple[str, int]`.";
];
TODO(T78935633 ): We should error on the naked and treat it as ] .
assert_type_errors
{|
from typing import *
T = TypeVar("T")
MyList = List[T]
def foo(x: T, y: MyList) -> MyList:
return y
foo(1, ['hello'])
foo('some', ['hello'])
reveal_type(foo(1, ['hello']))
|}
[
"Revealed type [-1]: Revealed type for `test.foo(1, [\"hello\"])` is \
`typing.List[typing.Any]`.";
];
assert_type_errors
{|
from typing import *
MyList = List
def foo(x: MyList) -> MyList: ...
reveal_type(foo)
reveal_type(foo(['hello']))
|}
[
"Invalid type parameters [24]: Generic type `list` expects 1 type parameter, use \
`typing.List[<element type>]` to avoid runtime subscripting errors.";
"Revealed type [-1]: Revealed type for `test.foo` is `typing.Callable(foo)[[Named(x, \
typing.List[typing.Any])], typing.List[typing.Any]]`.";
"Revealed type [-1]: Revealed type for `test.foo([\"hello\"])` is `typing.List[typing.Any]`.";
];
(* This confusing behavior is the downside of allowing multiple type variables. *)
assert_type_errors
{|
from typing import List, Tuple, TypeVar, Union
T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")
Alias2Before3 = Tuple[T1, Union[T2, T3], T2]
Alias3Before2 = Tuple[T1, Union[T3, T2], T2]
x: Alias2Before3[int, str, bool]
reveal_type(x)
y: Alias3Before2[int, str, bool]
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `x` is `Tuple[int, Union[bool, str], str]`.";
"Revealed type [-1]: Revealed type for `y` is `Tuple[int, Union[bool, str], str]`.";
];
()
let test_recursive_aliases context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is `test.Tree (resolves to Union[Tuple[Tree, \
Tree], int])`.";
];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
some_int: int
x = some_int
tuple_int: Tuple[int, int]
x = tuple_int
tuple_tuple_int: Tuple[Tuple[int, int], int]
x = tuple_tuple_int
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
x = 1
x = (2, 3)
x = ((4, 5), (6, 7))
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
some_str: str
x = some_str
tuple_int_str: Tuple[int, str]
x = tuple_int_str
|}
[
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `str`.";
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `Tuple[int, str]`.";
];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
x = "hello"
x = (1, "hello")
x = ((2, 3), (4, "hello"))
|}
[
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `str`.";
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `Tuple[int, str]`.";
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `Tuple[Tuple[int, int], Tuple[int, \
str]]`.";
];
assert_type_errors
{|
from typing import Mapping, Union
StringDict = Union[str, Mapping[str, "StringDict"]]
valid: StringDict = {"hello": {"world": "from here"}}
contains_int: StringDict = {"hello": {"world": 1}}
|}
[
"Incompatible variable type [9]: contains_int is declared to have type `test.StringDict \
(resolves to Union[Mapping[str, StringDict], str])` but is used as type `Dict[str, \
Dict[str, int]]`.";
];
assert_type_errors
{|
from typing import List, Tuple
Tree = Tuple[str, List["Tree"]]
tree: Tree = ("foo", [])
tree2: Tree = ("foo", [("branch1", [("leaf1", [])]), ("leaf2", [])])
|}
[];
(* Useless but valid recursive alias. *)
assert_type_errors
{|
from typing import List, Union
X = List["X"]
def foo() -> None:
x: X = [[], [[], []], []]
|}
[];
assert_type_errors
{|
from typing import Mapping, Union
StringMapping = Union[str, Mapping[str, "StringMapping"]]
d: Mapping[str, str]
d2: StringMapping = d
|}
[];
Incompatible because is invariant .
assert_type_errors
{|
from typing import Dict, Union
StringDict = Union[str, Dict[str, "StringDict"]]
d: Dict[str, str]
d2: StringDict = d
|}
[
"Incompatible variable type [9]: d2 is declared to have type `test.StringDict (resolves to \
Union[Dict[str, StringDict], str])` but is used as type `Dict[str, str]`.";
];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
Y = Union[int, Tuple[int, "Y"]]
x: X
y: Y = x
y2: Y
x2: X = y2
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
NotQuiteIsomorphicToX = Union[int, Tuple[str, "NotQuiteIsomorphicToX"]]
x: X
not_quite_isomorphic: NotQuiteIsomorphicToX = x
not_quite_isomorphic2: NotQuiteIsomorphicToX
x2: X = not_quite_isomorphic2
|}
[
"Incompatible variable type [9]: not_quite_isomorphic is declared to have type \
`test.NotQuiteIsomorphicToX (resolves to Union[Tuple[str, NotQuiteIsomorphicToX], int])` \
but is used as type `test.X (resolves to Union[Tuple[int, X], int])`.";
"Incompatible variable type [9]: x2 is declared to have type `test.X (resolves to \
Union[Tuple[int, X], int])` but is used as type `test.NotQuiteIsomorphicToX (resolves to \
Union[Tuple[str, NotQuiteIsomorphicToX], int])`.";
];
(* Unrolling an equirecursive type still makes it equivalent to the original recursive type. *)
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
unrolled: Tuple[int, X]
x: X = unrolled
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
unrolled: Tuple[int, X]
unrolled2: Tuple[int, X] = unrolled
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
unrolled_union: Union[int, Tuple[int, X]]
x: X = unrolled_union
x2: X
unrolled_union2: Union[int, Tuple[int, X]] = x2
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
x: X
unrolled_multiple_times: Union[int, Tuple[int, Union[int, Tuple[int, X]]]] = x
unrolled_multiple_times2: Union[int, Tuple[int, Union[int, Tuple[int, X]]]]
x2: X = unrolled_multiple_times2
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
unrolled_once: Union[int, Tuple[int, X]]
unrolled_multiple_times: Union[int, Tuple[int, Union[int, Tuple[int, X]]]]
unrolled_once = unrolled_multiple_times
unrolled_once2: Union[int, Tuple[int, X]]
unrolled_multiple_times2: Union[int, Tuple[int, Union[int, Tuple[int, X]]]]
unrolled_multiple_times2 = unrolled_once2
|}
[];
(* Cannot assign a recursive type to a concrete type *)
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
x: X
y: Union[int, Tuple[int, int]] = x
|}
[
"Incompatible variable type [9]: y is declared to have type `Union[Tuple[int, int], int]` \
but is used as type `test.X (resolves to Union[Tuple[int, X], int])`.";
];
Fixpoint should not blow up on a loop that constructs a recursive type .
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
def foo(x: X, n: int) -> X:
result = x
for i in range(n):
result = (i, result)
reveal_type(result)
reveal_type(result)
return result
|}
[
"Revealed type [-1]: Revealed type for `result` is `Tuple[int, test.X (resolves to \
Union[Tuple[int, X], int])]`.";
"Revealed type [-1]: Revealed type for `result` is `test.X (resolves to Union[Tuple[int, X], \
int])`.";
];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
def foo(tree: Tree, some_bool: bool) -> Tree:
if some_bool:
x = 42
else:
x = (1, (2, tree))
return x
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
Unrolled = Union[int, Tuple[Union[int, Tuple["Unrolled", "Unrolled"]], "Unrolled"]]
def foo(some_bool: bool) -> Tree:
tree: Tree
unrolled_tree: Unrolled
if some_bool:
x = tree
else:
x = unrolled_tree
return x
|}
[];
Type.RecursiveType.Namespace.reset ();
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
# str instead of int.
Wrong = Union[int, Tuple[Union[str, Tuple["Wrong", "Wrong"]], "Wrong"]]
def foo(some_bool: bool) -> Tree:
tree: Tree
wrong_unrolled_tree: Wrong
if some_bool:
x = tree
else:
x = wrong_unrolled_tree
return x
|}
[
"Incompatible return type [7]: Expected `test.Tree (resolves to Union[Tuple[Tree, Tree], \
int])` but got `$RecursiveType1 (resolves to Union[Tuple[Union[Tuple[$RecursiveType1, \
$RecursiveType1], str], $RecursiveType1], Tuple[$RecursiveType1, $RecursiveType1], int])`.";
];
assert_type_errors
{|
from typing import Final
from typing_extensions import Literal
x: Final[str] = "x"
y: Literal["y"] = "y"
reveal_type(x)
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `x` is `str` (inferred: \
`typing_extensions.Literal['x']`, final).";
"Revealed type [-1]: Revealed type for `y` is `typing_extensions.Literal['y']`.";
];
assert_type_errors
{|
x: str = "x"
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is `str` (inferred: \
`typing_extensions.Literal['x']`).";
];
assert_type_errors
{|
from typing_extensions import TypeAlias
MyInt = int
X: TypeAlias = "MyInt"
y: X
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `int`."];
assert_type_errors
{|
from typing import List, Union
X = List[Union[int, "X"]]
def foo() -> None:
x: X
y = x[0]
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Union[int, test.X (resolves to List[Union[X, \
int]])]`.";
];
assert_type_errors
{|
from typing import Dict, Union
D = Dict[str, Union[str, "D"]]
def foo(d: D) -> None:
y = d["hello"]
reveal_type(y)
if isinstance(y, str):
reveal_type(y)
else:
z = y["world"]
reveal_type(z)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Union[str, test.D (resolves to Dict[str, \
Union[D, str]])]`.";
"Revealed type [-1]: Revealed type for `y` is `str`.";
"Revealed type [-1]: Revealed type for `z` is `Union[str, test.D (resolves to Dict[str, \
Union[D, str]])]`.";
];
(* Forbid directly-recursive aliases. *)
assert_type_errors
{|
from typing import Union
D = Union[int, "D"]
D2 = Union[int, "D2"]
def foo() -> None:
d: D
reveal_type(d)
d2: D2
d = d2
|}
[
"Missing global annotation [5]: Globally accessible variable `D` has no type specified.";
"Missing global annotation [5]: Globally accessible variable `D2` has no type specified.";
"Undefined or invalid type [11]: Annotation `D` is not defined as a type.";
"Revealed type [-1]: Revealed type for `d` is `typing.Any`.";
"Undefined or invalid type [11]: Annotation `D2` is not defined as a type.";
];
assert_type_errors
{|
from typing import List, Union
NestedList = List[Union[int, "NestedList"]]
def pass_spurious_parameter(x: NestedList[int]) -> None:
reveal_type(x)
|}
(* TODO(T78935633): We should raise an error on parameters to non-generic recursive alias. *)
[
"Revealed type [-1]: Revealed type for `x` is `test.NestedList (resolves to \
List[Union[NestedList, int]])`.";
];
(* TODO(T82613757): Generic recursive aliases are unsupported as of now. *)
assert_type_errors
{|
from typing import Tuple, TypeVar, Union
T = TypeVar("T")
GenericTree = Union[T, Tuple["GenericTree[T]", "GenericTree[T]"]]
def foo(x: GenericTree[int]) -> None:
reveal_type(x)
|}
[
"Missing global annotation [5]: Globally accessible variable `GenericTree` has no type \
specified.";
"Undefined or invalid type [11]: Annotation `GenericTree` is not defined as a type.";
"Revealed type [-1]: Revealed type for `x` is `unknown`.";
];
(* Aliases that refer to recursive aliases. *)
assert_type_errors
{|
from typing import List, Union
X = List["X"]
Y = Union[int, X]
def foo() -> None:
y: Y
y == y
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Union[int, test.X (resolves to List[X])]`."];
assert_type_errors
{|
from typing import List, Sequence, Union
class Foo: ...
X = Union[
Sequence["X"],
List["X"]
]
Y = Union[Foo, X]
def foo() -> None:
y: Y
y == y
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Union[Foo, test.X (resolves to Union[List[X], \
Sequence[X]])]`.";
];
assert_type_errors
{|
from typing import List, Sequence, Union
class Foo: ...
X = Union[
Sequence["X"],
List["X"]
]
Y = Union[Foo, X]
Z = List[Y]
def foo() -> None:
z: Z
reveal_type(z)
|}
[
"Revealed type [-1]: Revealed type for `z` is `List[Union[Foo, test.X (resolves to \
Union[List[X], Sequence[X]])]]`.";
];
()
let test_variadic_tuples context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def foo(x: Tuple[int, Unpack[Ts]]) -> Tuple[bool, Unpack[Ts]]: ...
def bar() -> None:
x: Tuple[int, str, bool]
y = foo(x)
reveal_type(y)
x2: Tuple[int]
y2 = foo(x2)
reveal_type(y2)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[bool, str, bool]`.";
"Revealed type [-1]: Revealed type for `y2` is `Tuple[bool]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def foo(x: Tuple[int, Unpack[Ts], str]) -> Tuple[bool, Unpack[Ts]]: ...
def bar() -> None:
x: Tuple[int]
foo(x)
|}
[
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`typing.Tuple[int, *test.Ts, str]` but got `Tuple[int]`.";
];
(* We should be able to typecheck the body of a generic variadic function. *)
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def add_int(xs: Tuple[Unpack[Ts]]) -> Tuple[int, Unpack[Ts]]: ...
def remove_int(xs: Tuple[int, Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def generic_function(xs: Tuple[Unpack[Ts]]) -> None:
y = remove_int(add_int(xs))
reveal_type(y)
add_int(remove_int(xs))
|}
[
"Revealed type [-1]: Revealed type for `y` is `typing.Tuple[*test.Ts]`.";
"Incompatible parameter type [6]: In call `remove_int`, for 1st positional argument, \
expected `typing.Tuple[int, *test.Ts]` but got `typing.Tuple[*test.Ts]`.";
];
We should not infer Tuple[int|bool , str|bool ] for Ts . That would surprise most users who would
expect that the Ts was bound to at least one of the concrete types they specified .
expect that the Ts was bound to at least one of the concrete types they specified. *)
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def expects_same_tuples(x: Tuple[Unpack[Ts]], y: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def bar() -> None:
tuple1: Tuple[int, str]
tuple2: Tuple[bool, bool]
expects_same_tuples(tuple1, tuple2)
|}
[
"Incompatible parameter type [6]: In call `expects_same_tuples`, for 2nd positional \
argument, expected `typing.Tuple[*test.Ts]` but got `Tuple[bool, bool]`.";
];
(* Length mismatch. *)
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def expects_same_tuples(x: Tuple[Unpack[Ts]], y: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def bar() -> None:
tuple1: Tuple[int, str]
shorter_tuple: Tuple[bool]
expects_same_tuples(tuple1, shorter_tuple)
|}
[
"Incompatible parameter type [6]: In call `expects_same_tuples`, for 2nd positional \
argument, expected `typing.Tuple[*test.Ts]` but got `Tuple[bool]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def expects_same_tuples(x: Tuple[Unpack[Ts]], y: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def bar() -> None:
tuple1: Tuple[int, str]
shorter_tuple: Tuple[bool]
expects_same_tuples(tuple1, shorter_tuple)
|}
[
"Incompatible parameter type [6]: In call `expects_same_tuples`, for 2nd positional \
argument, expected `typing.Tuple[*test.Ts]` but got `Tuple[bool]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def add_int(xs: Tuple[Unpack[Tuple[str, ...]]]) -> Tuple[int, Unpack[Tuple[str, ...]]]: ...
def foo() -> None:
xs: Tuple[str, str]
y = add_int(xs)
reveal_type(y)
invalid: Tuple[int, str]
add_int(invalid)
|}
[
"Revealed type [-1]: Revealed type for `y` is `typing.Tuple[int, *Tuple[str, ...]]`.";
"Incompatible parameter type [6]: In call `add_int`, for 1st positional argument, expected \
`typing.Tuple[str, ...]` but got `Tuple[int, str]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def foo(xs: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def baz() -> None:
unbounded_tuple: Tuple[int, ...]
y = foo(unbounded_tuple)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `typing.Tuple[int, ...]`."];
assert_type_errors
{|
from typing import Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
def foo(xs: Tuple[T, Unpack[Tuple[str, ...]]]) -> T: ...
def baz() -> None:
some_tuple: Tuple[int, str, str]
y = foo(some_tuple)
reveal_type(y)
invalid_tuple: Tuple[int, str, int]
foo(invalid_tuple)
|}
[
"Revealed type [-1]: Revealed type for `y` is `int`.";
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`typing.Tuple[Variable[T], *Tuple[str, ...]]` but got `Tuple[int, str, int]`.";
];
assert_type_errors
{|
from typing import Any, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
N = TypeVar("N", bound=int)
def foo(x: Tuple[N, Unpack[Ts]]) -> Tuple[Unpack[Ts], N]: ...
def bar() -> None:
x: Tuple[Any, ...]
y = foo(x)
reveal_type(y)
x2: Tuple[int, ...]
y2 = foo(x2)
reveal_type(y2)
|}
[
"Prohibited any [33]: Explicit annotation for `x` cannot contain `Any`.";
"Revealed type [-1]: Revealed type for `y` is `typing.Tuple[*Tuple[typing.Any, ...], \
typing.Any]`.";
"Revealed type [-1]: Revealed type for `y2` is `typing.Tuple[*Tuple[int, ...], int]`.";
];
assert_type_errors
{|
from typing import Any, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
N = TypeVar("N", bound=int)
def foo(x: Tuple[N, Unpack[Ts]]) -> Tuple[Unpack[Ts], N]: ...
def bar() -> None:
x_error: Tuple[str, ...]
y_error = foo(x_error)
reveal_type(y_error)
|}
[
"Incomplete type [37]: Type `typing.Tuple[*test.Ts, Variable[N (bound to int)]]` inferred \
for `y_error` is incomplete, add an explicit annotation.";
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`typing.Tuple[Variable[N (bound to int)], *test.Ts]` but got `typing.Tuple[str, ...]`.";
"Revealed type [-1]: Revealed type for `y_error` is `typing.Tuple[*Tuple[typing.Any, ...], \
typing.Any]`.";
];
assert_type_errors
{|
from typing import Any, Tuple, TypeVar
N = TypeVar("N", bound=int)
def foo(x: Tuple[N]) -> Tuple[N]: ...
def bar() -> None:
x: Tuple[int, ...]
y = foo(x)
reveal_type(y)
x_error: Tuple[str, ...]
foo(x_error)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[int]`.";
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`Tuple[Variable[N (bound to int)]]` but got `typing.Tuple[str, ...]`.";
];
()
let test_variadic_classes context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Generic
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]): ...
def add_bool(x: Tensor[int, Unpack[Ts], str]) -> Tensor[bool, Unpack[Ts]]: ...
def foo() -> None:
x: Tensor[int, bool, str]
y = add_bool(x)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Tensor[bool, bool]`."];
Expect the same Tensor type for both parameters . We do n't infer ` Ts = Tuple[int | bool , str |
bool ] ` even though it is sound , because it is unintuitive .
bool]` even though it is sound, because it is unintuitive. *)
assert_type_errors
{|
from typing import Generic
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]): ...
def expects_same_tensors(x: Tensor[Unpack[Ts]], y: Tensor[Unpack[Ts]]) -> Tensor[Unpack[Ts]]: ...
def bar() -> None:
tensor: Tensor[int, str]
tensor2: Tensor[bool, bool]
y = expects_same_tensors(tensor, tensor2)
reveal_type(y)
|}
[
"Incompatible parameter type [6]: In call `expects_same_tensors`, for 2nd positional \
argument, expected `Tensor[*test.Ts]` but got `Tensor[bool, bool]`.";
"Revealed type [-1]: Revealed type for `y` is `Tensor[int, str]`.";
];
(* Length mismatch. *)
assert_type_errors
{|
from typing import Generic
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]): ...
def expects_same_length(xs: Tensor[Unpack[Ts]], ys: Tensor[Unpack[Ts]]) -> Tensor[Unpack[Ts]]: ...
def bar() -> None:
xs: Tensor[int, str]
ys: Tensor[bool]
expects_same_length(xs, ys)
|}
[
"Incompatible parameter type [6]: In call `expects_same_length`, for 2nd positional \
argument, expected `Tensor[*test.Ts]` but got `Tensor[bool]`.";
];
(* Tensor is covariant in its shape, since the shape is immutable. However, it is invariant in the
unary datatype. *)
assert_type_errors
{|
from typing import Generic, List, Protocol, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
class Base: ...
class Child(Base): ...
def foo(x: Tensor[float, Base, Base]) -> None: ...
def bar() -> None:
child: Tensor[float, Child, Child]
foo(child)
int_tensor: Tensor[int, Base, Base]
foo(int_tensor)
|}
[
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`Tensor[float, Base, Base]` but got `Tensor[int, Base, Base]`.";
];
assert_type_errors
{|
from typing import Generic, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
Ts = TypeVarTuple("Ts")
Tin = TypeVar("Tin")
Tout = TypeVar("Tout")
class Tensor(Generic[Unpack[Ts]]): ...
class Linear(Generic[Tin, Tout]):
"""Transform the last dimension from Tin to Tout."""
def __init__(self, in_dimension: Tin, out_dimension: Tout) -> None:
self.in_dimension = in_dimension
self.out_dimension = out_dimension
def __call__(self, x: Tensor[Unpack[Ts], Tin]) -> Tensor[Unpack[Ts], Tout]: ...
def bar() -> None:
x: Tensor[L[10], L[20]]
layer1 = Linear(20, 30)
layer2 = Linear(30, 40)
layer3 = Linear(40, 50)
y = layer3(layer2(layer1(x)))
reveal_type(y)
shape_mismatch = (10, 21)
layer1(shape_mismatch)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tensor[typing_extensions.Literal[10], \
typing_extensions.Literal[50]]`.";
"Incompatible parameter type [6]: In call `Linear.__call__`, for 1st positional argument, \
expected `Tensor[*test.Ts, typing_extensions.Literal[20]]` but got \
`Tuple[typing_extensions.Literal[10], typing_extensions.Literal[21]]`.";
];
assert_type_errors
{|
from typing import Generic
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]):
def some_method(self, x: Tensor[Unpack[Ts]]) -> None: ...
def bar() -> None:
xs: Tensor[int, str]
xs.some_method(xs)
|}
[];
assert_type_errors
{|
from typing import Generic, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
def bar() -> None:
x = Tensor.__getitem__
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is \
`BoundMethod[typing.Callable(typing.GenericMeta.__getitem__)[[Named(self, unknown), \
typing.Tuple[typing.Type[Variable[T]], typing.Any]], typing.Type[Tensor[Variable[T], \
typing.Any]]], typing.Type[Tensor]]`.";
];
assert_type_errors
{|
from typing import Generic, List, Protocol, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class VariadicProtocol(Protocol[T, Unpack[Ts]]):
def foo(self, x: Tuple[T, Unpack[Ts]]) -> None: ...
class Tensor(Generic[Unpack[Ts]]):
"""This implements VariadicProtocol with T = List[int] and Ts = Tuple[Unpack[Ts]]."""
def foo(self, x: Tuple[List[int], Unpack[Ts]]) -> None:...
def accepts_variadic_protocol(x: VariadicProtocol[T, Unpack[Ts]]) -> VariadicProtocol[T, Unpack[Ts]]: ...
def bar() -> None:
x: Tensor[int, str]
y = accepts_variadic_protocol(x)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `VariadicProtocol[List[int], int, str]`."];
TODO(T84553937 ): While Tensor is indeed invariant , we should have inferred ` Tensor[int , Base ,
Base ] ` below .
Base]` below. *)
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]):
def __init__(self, default: T, shape: Tuple[Unpack[Ts]]) -> None: ...
class Base: ...
class Child(Base): ...
def expects_base(t: Tensor[int, Base, Base]) -> None: ...
def bar() -> None:
expects_base(Tensor(1, (Child(), Child())))
|}
[
"Incompatible parameter type [6]: In call `expects_base`, for 1st positional argument, \
expected `Tensor[int, Base, Base]` but got `Tensor[int, Child, Child]`.";
];
assert_type_errors
{|
from typing import Generic, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
FloatTensor = Tensor[float, Unpack[Ts]]
def bar() -> None:
x: FloatTensor[L[10], L[20]]
reveal_type(x)
y: FloatTensor
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `x` is `Tensor[float, typing_extensions.Literal[10], \
typing_extensions.Literal[20]]`.";
"Revealed type [-1]: Revealed type for `y` is `Tensor[float, *Tuple[typing.Any, ...]]`.";
];
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
def get_last_type(t: Tensor[float, Unpack[Tuple[int, ...]], T]) -> T: ...
def bar() -> None:
x: Tensor[float, L[10], L[20]]
y = get_last_type(x)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `typing_extensions.Literal[20]`."];
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
# pyre-ignore[24]: Generic type `Tensor` expects at least 1 type parameter.
def accept_arbitrary_tensor(t: Tensor) -> Tensor: ...
def bar() -> None:
x: Tensor[float, L[10], L[20]]
y = accept_arbitrary_tensor(x)
reveal_type(y)
# pyre-ignore[24]: Generic type `Tensor` expects at least 1 type parameter.
no_parameters: Tensor
accept_arbitrary_tensor(no_parameters)
|}
["Revealed type [-1]: Revealed type for `y` is `Tensor[typing.Any, *Tuple[typing.Any, ...]]`."];
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
def strip_last(x: Tensor[int, Unpack[Ts], int]) -> Tensor[int, Unpack[Ts]]: ...
def bar() -> None:
invalid: Tensor[int, L[10], str]
y = strip_last(invalid)
reveal_type(y)
|}
[
"Incomplete type [37]: Type `Tensor[int, *test.Ts]` inferred for `y` is incomplete, add an \
explicit annotation.";
"Incompatible parameter type [6]: In call `strip_last`, for 1st positional argument, \
expected `Tensor[int, *test.Ts, int]` but got `Tensor[int, int, str]`.";
"Revealed type [-1]: Revealed type for `y` is `Tensor[int, *Tuple[typing.Any, ...]]`.";
];
assert_type_errors
{|
from typing import Callable, Generic, Tuple, TypeVar
from pyre_extensions import ParameterSpecification, TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
TParams = ParameterSpecification("TParams")
class Tensor(Generic[T, TParams, Unpack[Ts]]):
def __init__(self, f: Callable[TParams, T], shape: Tuple[Unpack[Ts]]) -> None:
self.f = f
self.shape = shape
def bar() -> None:
tensor: Tensor[float, [int, str], int, str]
y = tensor.f( *tensor.shape)
reveal_type(y)
tensor.f("wrong argument")
|}
[
"Revealed type [-1]: Revealed type for `y` is `float`.";
"Missing argument [20]: PositionalOnly call expects argument in position 1.";
];
()
let test_variadic_callables context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Callable, Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def make_tuple(leave_this_out: int, *args: Unpack[Ts], message: str) -> Tuple[Unpack[Ts], bool]: ...
def foo() -> None:
y = make_tuple(1, 2, 3, message="hello")
reveal_type(y)
y2 = make_tuple(1, message="hello")
reveal_type(y2)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[typing_extensions.Literal[2], \
typing_extensions.Literal[3], bool]`.";
"Revealed type [-1]: Revealed type for `y2` is `Tuple[bool]`.";
];
assert_type_errors
{|
from typing import Callable, Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def make_tuple(leave_this_out: int, *args: Unpack[Tuple[int, Unpack[Ts], str]], message: str) -> Tuple[int, Unpack[Ts], str]:
return args
def foo() -> None:
y = make_tuple(1, 2, 3, "has to end with a string", message="hello")
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[int, typing_extensions.Literal[3], str]`.";
];
Unpack an unbounded tuple .
assert_type_errors
{|
from typing import Callable, Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def make_tuple( *args: Unpack[Tuple[int, Unpack[Ts], str]]) -> None: ...
def foo(x: Tuple[Unpack[Ts]]) -> None:
unbounded_tuple: Tuple[int, ...]
make_tuple(1, *unbounded_tuple, "foo")
make_tuple( *unbounded_tuple, "foo")
unbounded_str_tuple: Tuple[str, ...]
make_tuple( *unbounded_str_tuple, "foo")
|}
[
"Invalid argument [32]: Argument types `*Tuple[str, ...], typing_extensions.Literal['foo']` \
are not compatible with expected variadic elements `int, *test.Ts, str`.";
];
assert_type_errors
{|
from typing import Callable, Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def make_tuple( *args: Unpack[Tuple[int, Unpack[Ts], str]]) -> None: ...
def foo(x: Tuple[Unpack[Ts]]) -> None:
make_tuple(1, 2)
make_tuple(1, *x, *x, "foo")
|}
[
"Invalid argument [32]: Argument types `typing_extensions.Literal[1], \
typing_extensions.Literal[2]` are not compatible with expected variadic elements `int, \
*test.Ts, str`.";
"Invalid argument [32]: Variadic type variable `int, *test.Ts, str` cannot be made to \
contain `typing_extensions.Literal[1], *test.Ts, *test.Ts, \
typing_extensions.Literal['foo']`; concatenation of multiple variadic type variables is not \
yet implemented.";
];
assert_type_errors
{|
from typing import Callable, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def strip_int_parameter(f: Callable[[int, Unpack[Ts]], None]) -> Callable[[Unpack[Ts]], None]: ...
def foo(x: int, y: str, z: bool) -> None: ...
def baz() -> None:
f = strip_int_parameter(foo)
reveal_type(f)
# Valid
f("hello", True)
# Error
f("hello")
|}
[
"Revealed type [-1]: Revealed type for `f` is `typing.Callable[[str, bool], None]`.";
"Missing argument [20]: PositionalOnly call expects argument in position 1.";
];
assert_type_errors
{|
from typing import Callable, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def strip_int_parameter(f: Callable[[int, Unpack[Ts]], None]) -> Callable[[Unpack[Ts]], None]: ...
def no_leading_int(y: str, z: bool) -> None: ...
def foo() -> None:
strip_int_parameter(no_leading_int)
|}
[
"Incompatible parameter type [6]: In call `strip_int_parameter`, for 1st positional \
argument, expected `typing.Callable[[Variable(int, *test.Ts)], None]` but got \
`typing.Callable(no_leading_int)[[Named(y, str), Named(z, bool)], None]`.";
];
assert_type_errors
{|
from typing import Callable, Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]):
def some_method(self, *args: Unpack[Ts]) -> Tuple[Unpack[Ts]]: ...
def bar() -> None:
x: Tensor[int, str]
y = x.some_method(1, "hello")
reveal_type(y)
x.some_method("invalid")
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[int, str]`.";
"Missing argument [20]: Call `Tensor.some_method` expects argument in position 2.";
];
assert_type_errors
{|
from typing import Callable, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
T = TypeVar("T")
def apply(f: Callable[[Unpack[Ts]], T], *args: Unpack[Ts]) -> T: ...
def foo(x: int, y: str, z: bool) -> str: ...
def bar(a: int, b: str, c: bool) -> None:
y = apply(foo, a, b, c)
reveal_type(y)
apply(foo, a, b)
|}
[
"Revealed type [-1]: Revealed type for `y` is `str`.";
"Invalid argument [32]: Argument types `int, str` are not compatible with expected variadic \
elements `*test.Ts`.";
];
(* It should be fine to pass a subclass to a function expecting the base class. *)
assert_type_errors
{|
from typing import Callable, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
T = TypeVar("T")
def apply(f: Callable[[Unpack[Ts]], T], *args: Unpack[Ts]) -> T: ...
class Base: ...
class Child(Base): ...
def expects_base(x: int, y: str, z: Base) -> str: ...
def expects_child(x: int, y: str, z: Child) -> str: ...
def bar() -> None:
child: Child
apply(expects_base, 1, "hello", child)
base: Base
apply(expects_child, 1, "hello", base)
|}
[
"Invalid argument [32]: Argument types `typing_extensions.Literal[1], \
typing_extensions.Literal['hello'], test.Base` are not compatible with expected variadic \
elements `*test.Ts`.";
];
()
let test_self_type context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing_extensions import Self
class Shape:
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
def set_scale(self, scale: float) -> Self:
reveal_type(self)
self.scale = scale
return self
class Circle(Shape):
def __init__(self, scale: float = 0.0, radius: float = 0.0) -> None:
super(Circle, self).__init__(scale)
self.radius = radius
def set_radius(self, radius: float) -> Self:
self.radius = radius
return self
def foo() -> None:
circle: Circle
y = circle.set_scale(0.5).set_radius(2.7)
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_Shape__ (bound to \
Shape)]`.";
"Revealed type [-1]: Revealed type for `y` is `Circle`.";
];
(* Same example but with protocols. *)
assert_type_errors
{|
from typing_extensions import Self
from typing import Protocol
class ShapeProtocol(Protocol):
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
def set_scale(self, scale: float) -> Self:
reveal_type(self)
self.scale = scale
return self
class CircleProtocol(ShapeProtocol, Protocol):
def __init__(self, scale: float = 0.0, radius: float = 0.0) -> None:
super(CircleProtocol, self).__init__(scale)
self.radius = radius
def set_radius(self, radius: float) -> Self:
self.radius = radius
return self
def foo() -> None:
circle: CircleProtocol
y = circle.set_scale(0.5).set_radius(2.7)
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_ShapeProtocol__ (bound \
to ShapeProtocol)]`.";
"Revealed type [-1]: Revealed type for `y` is `CircleProtocol`.";
];
assert_type_errors
{|
from typing_extensions import Self
from typing import Protocol
class ShapeProtocol(Protocol):
def set_scale(self, scale: float) -> Self: ...
class ReturnSelf:
scale: float = 1.0
def set_scale(self, scale: float) -> Self:
self.scale = scale
return self
class ReturnConcreteShape:
scale: float = 1.0
def set_scale(self, scale: float) -> ReturnConcreteShape:
self.scale = scale
return self
class BadReturnType:
scale: float = 1.0
def set_scale(self, scale: float) -> int:
self.scale = scale
return 42
def foo(shape: ShapeProtocol) -> None:
y = shape.set_scale(0.5)
reveal_type(y)
def main() -> None:
return_self_shape: ReturnSelf
return_concrete_shape: ReturnConcreteShape
bad_return_type: BadReturnType
foo(return_self_shape)
foo(return_concrete_shape)
foo(bad_return_type)
|}
[
"Revealed type [-1]: Revealed type for `y` is `ShapeProtocol`.";
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`ShapeProtocol` but got `BadReturnType`.";
];
assert_type_errors
{|
from typing_extensions import Self
class Shape:
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
def set_scale(self, scale: float) -> Self:
self.scale = scale
return self
class Circle(Shape):
def set_scale(self, scale: float) -> Self:
self.scale = scale + 1.0
return self
class CircleArc(Circle):
def set_scale(self, scale: float) -> Self:
self.scale = scale * 3.14
return self
|}
[];
assert_type_errors
{|
from typing_extensions import Self
class Shape:
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
@classmethod
def with_scale(cls, scale: float) -> Self:
return cls(scale)
class Circle(Shape):
@classmethod
def with_scale(cls, scale: float) -> Self:
return cls(scale + 1.0)
class CircleArc(Circle):
@classmethod
def with_scale(cls, scale: float) -> Self:
return cls(scale * 3.14)
|}
[];
Generic class .
assert_type_errors
{|
from typing_extensions import Self
from typing import Generic, TypeVar
T = TypeVar("T")
class Container(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def set_value(self, value: T) -> Self:
reveal_type(self)
self.value = value
return self
class ChildContainer(Container[T]): ...
class ConcreteContainer(ChildContainer[int]): ...
def foo() -> None:
child: ChildContainer[str]
y = child.set_value("hello")
reveal_type(y)
child.set_value(42)
concrete: ConcreteContainer
y2 = concrete.set_value(42)
reveal_type(y2)
concrete.set_value("bad")
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_Container__ (bound to \
Container[typing.Any])]`.";
"Revealed type [-1]: Revealed type for `y` is `ChildContainer[str]`.";
"Incompatible parameter type [6]: In call `Container.set_value`, for 1st positional \
argument, expected `str` but got `int`.";
"Revealed type [-1]: Revealed type for `y2` is `ConcreteContainer`.";
"Incompatible parameter type [6]: In call `Container.set_value`, for 1st positional \
argument, expected `int` but got `str`.";
];
(* Nested class using Self. *)
assert_type_errors
{|
from typing_extensions import Self
class Outer:
class Shape:
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
def set_scale(self, scale: float) -> Self:
self.scale = scale
return self
class Circle(Shape): ...
def foo() -> None:
circle: Outer.Circle
y = circle.set_scale(0.5)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Outer.Circle`."];
assert_type_errors
{|
from typing_extensions import Self
class Shape:
def __init__(self, scale: float) -> None: ...
@classmethod
def from_config(cls, config: dict[str, float]) -> Self:
reveal_type(cls)
return cls(config["scale"])
class Circle(Shape): ...
def foo() -> None:
circle = Circle.from_config({"scale": 7.0})
reveal_type(circle)
|}
[
"Revealed type [-1]: Revealed type for `cls` is `typing.Type[Variable[_Self_test_Shape__ \
(bound to Shape)]]`.";
"Revealed type [-1]: Revealed type for `circle` is `Circle`.";
];
assert_type_errors
{|
from typing_extensions import Self
class IsMergeable:
def can_merge(self, other: Self) -> bool:
reveal_type(self)
reveal_type(other)
return True
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_IsMergeable__ (bound \
to IsMergeable)]`.";
"Revealed type [-1]: Revealed type for `other` is `Variable[_Self_test_IsMergeable__ (bound \
to IsMergeable)]`.";
];
assert_type_errors
{|
from typing_extensions import Self
class Merger:
def merge(self, other: Self) -> Self:
reveal_type(self)
reveal_type(other)
return self
class ChildMerger(Merger):
pass
class BadOverriddenMerger(Merger):
def merge(self, other: Self) -> Self:
return self
class GoodOverriddenMerger(Merger):
def merge(self, other: Merger) -> Self:
return self
Merger().merge(Merger())
ChildMerger().merge(ChildMerger())
ChildMerger().merge(123)
Merger().merge(123)
# Classes do NOT need to match exactly, parent/children are allowed:
ChildMerger().merge(Merger())
Merger().merge(ChildMerger())
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_Merger__ (bound to \
Merger)]`.";
"Revealed type [-1]: Revealed type for `other` is `Variable[_Self_test_Merger__ (bound to \
Merger)]`.";
"Inconsistent override [14]: `test.BadOverriddenMerger.merge` overrides method defined in \
`Merger` inconsistently. Parameter of type `Variable[_Self_test_BadOverriddenMerger__ \
(bound to BadOverriddenMerger)]` is not a supertype of the overridden parameter \
`Variable[_Self_test_Merger__ (bound to Merger)]`.";
"Incompatible parameter type [6]: In call `Merger.merge`, for 1st positional argument, \
expected `Variable[_Self_test_Merger__ (bound to Merger)]` but got `int`.";
"Incompatible parameter type [6]: In call `Merger.merge`, for 1st positional argument, \
expected `Variable[_Self_test_Merger__ (bound to Merger)]` but got `int`.";
];
()
let () =
"typeVariable"
>::: [
"check_bounded_variables" >:: test_check_bounded_variables;
"check_unbounded_variables" >:: test_check_unbounded_variables;
"check_variable_bindings" >:: test_check_variable_bindings;
"unbound_variables" >:: test_unbound_variables;
"distinguish" >:: test_distinguish;
"integer_variables" >:: test_integer_variables;
"nested_variable_error" >:: test_nested_variable_error;
"single_explicit_error" >:: test_single_explicit_error;
"callable_parameter_variadics" >:: test_callable_parameter_variadics;
"user_defined_parameter_variadics" >:: test_user_defined_parameter_specification_classes;
"duplicate_type_variables" >:: test_duplicate_type_variables;
"generic_aliases" >:: test_generic_aliases;
"recursive_aliases" >:: test_recursive_aliases;
"variadic_tuples" >:: test_variadic_tuples;
"variadic_classes" >:: test_variadic_classes;
"variadic_callables" >:: test_variadic_callables;
"self_type" >:: test_self_type;
]
|> Test.run
| null | https://raw.githubusercontent.com/facebook/pyre-check/518f5ef44d7079c68b273ff8bcbfd4a8bdd985d6/source/analysis/test/integration/typeVariableTest.ml | ocaml | Test strict mode bounds with explicit Any types
Type variables in the nesting function is correctly captured
Type variables in the parent class is correctly captured
Type variables in the parent class of nesting function is correctly captured
Correctly mark the boundness of nested function type variables when there're recursive calls
Test for a common misuse of variable bounds.
Same test as above but without an explicit type for `self`.
This actually requires the input to be of the same type as `self`.
Bug fix: Solve Optional[T (bound)] vs Optional[T (free)].
TODO(T42360946): Probably want a better error here
This could cause an infinite loop due to mismatching errors if we didn't make the error set
namespace insensitive
Interaction with overloads
Example from PEP
Decorator to supply an argument to a method.
`MyList3` resolves to `List[int]`. So, it ignores the extra `str` argument.
`Optional` is imported as `foo.bar.baz.Optional`, which is an alias we resolve to
`typing.Optional`.
We should correctly resolve nested generic aliases like `baz.Dict`.
TODO(T78935633): Probably shouldn't error here.
Error messages.
Extra type parameters provided.
TODO(T78935633): Raise clearer error.
TODO(T78935633): Raise clearer error.
No free variables in the alias body.
TODO(T78935633): Raise error about extra parameter.
This confusing behavior is the downside of allowing multiple type variables.
Useless but valid recursive alias.
Unrolling an equirecursive type still makes it equivalent to the original recursive type.
Cannot assign a recursive type to a concrete type
Forbid directly-recursive aliases.
TODO(T78935633): We should raise an error on parameters to non-generic recursive alias.
TODO(T82613757): Generic recursive aliases are unsupported as of now.
Aliases that refer to recursive aliases.
We should be able to typecheck the body of a generic variadic function.
Length mismatch.
Length mismatch.
Tensor is covariant in its shape, since the shape is immutable. However, it is invariant in the
unary datatype.
It should be fine to pass a subclass to a function expecting the base class.
Same example but with protocols.
Nested class using Self. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
open IntegrationTest
let test_check_bounded_variables context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import TypeVar, Callable
TFun = TypeVar("TFun", bound=Callable[[int], None])
def foo(x: TFun) -> None:
x(7)
|}
[];
assert_type_errors
{|
from typing import TypeVar, Callable
TFun = TypeVar("TFun", bound=Callable[[int], None])
def foo(x: TFun) -> None:
x("7")
|}
[
"Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \
`int` but got `str`.";
];
assert_type_errors
{|
from typing import TypeVar, Callable, Union
T1 = TypeVar("T1", bound=Union[Callable[[], str], Callable[[], int]])
def foo(x: T1) -> None:
y = x()
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Union[int, str]`."];
assert_type_errors
{|
from typing import TypeVar, Callable, Union
T1 = TypeVar("T1", bound=Union[Callable[[], str], Callable[[], str]])
def foo(x: T1) -> None:
y = x()
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `str`."];
assert_type_errors
{|
from typing import TypeVar
class CallableClass:
def __call__(self, x:int) -> str:
return "A"
T2 = TypeVar("T2", bound=CallableClass)
def foo(x: T2) -> None:
y = x(5)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `str`."];
assert_type_errors
{|
from typing import TypeVar
class CallableClass:
def __call__(self, x:int) -> str:
return "A"
T2 = TypeVar("T2", bound=CallableClass)
def foo(x: T2) -> None:
y = x(2)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `str`."];
assert_type_errors
{|
from typing import Type, TypeVar
class Constructable:
def __init__(self, x:int) -> None:
return
T3 = TypeVar("T3", bound=Type[Constructable])
def foo(x: T3) -> None:
x(5)
|}
[];
assert_type_errors
{|
from typing import TypeVar, Generic, List
S = TypeVar('S', bound=List[float])
def bar(x: List[float]) -> None:
pass
def foo(x: S) -> S:
bar(x)
return x
|}
[];
assert_type_errors
{|
from typing import TypeVar, Generic
T = TypeVar('T', covariant=True)
S = TypeVar('S', bound="Foo[float]")
class Foo(Generic[T]):
def a(self, x: S) -> S:
return x
def b(self, x: S) -> None:
self.a(x)
def foo(a: Foo[int]) -> Foo[float]:
return a
|}
[];
assert_type_errors
{|
from typing import TypeVar, List, Tuple, Optional, Callable
T = TypeVar("T", int, str)
def f(x: Callable[[T], None]) -> None:
y = g(x)
def g(x: Callable[[T], None]) -> None:
...
|}
[];
assert_type_errors
{|
from typing import TypeVar, List, Tuple, Optional, Callable
T = TypeVar("T", int, str)
def f(x: Optional[Callable[[Optional[T]], None]]) -> None:
y = g(x)
def g(x: Optional[Callable[[Optional[T]], None]]) -> None:
...
|}
[];
assert_type_errors
{|
from typing import *
T = TypeVar("T", Callable[[], str], Callable[[], int])
def foo(f: T) -> None:
f()
|}
[];
assert_type_errors
{|
from typing import Any, List, TypeVar
T = TypeVar("T", bound=List[Any])
|}
["Prohibited any [33]: Type variable `T` cannot have a bound containing `Any`."];
assert_type_errors
{|
from typing import Any, TypeVar
T = TypeVar("T", bound=Any)
|}
["Prohibited any [33]: Type variable `T` cannot have `Any` as a bound."];
()
let test_check_unbounded_variables context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def expects_any(input: object) -> None: ...
def expects_string(inut: str) -> None: ...
def foo(input: T) -> None:
expects_any(input)
expects_string(input)
|}
[
"Incompatible parameter type [6]: In call `expects_string`, for 1st positional argument, \
expected `str` but got `Variable[T]`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def foo(input: T) -> typing.Any:
return input
|}
["Missing return annotation [3]: Returning `Variable[T]` but type `Any` is specified."];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def foo(input: T) -> int:
return input
|}
["Incompatible return type [7]: Expected `int` but got `Variable[T]`."];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def mapping_get(k: str, default: typing.Union[int, T]) -> typing.Union[int, T]: ...
def foo() -> None:
reveal_type(mapping_get("A", "A"))
reveal_type(mapping_get("A", 7))
|}
[
"Revealed type [-1]: Revealed type for `test.mapping_get(\"A\", \"A\")` is "
^ "`typing.Union[typing_extensions.Literal['A'], int]`.";
"Revealed type [-1]: Revealed type for `test.mapping_get(\"A\", 7)` is `int`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def foo(input: T) -> None:
input.impossible()
|}
["Undefined attribute [16]: `Variable[T]` has no attribute `impossible`."];
assert_type_errors
{|
import typing
X = typing.TypeVar("X")
class Foo(typing.Generic[X]): pass
reveal_type(Foo[float])
reveal_type(Foo[float]())
reveal_type(Foo[str]())
Foo["str"]()
|}
[
"Revealed type [-1]: Revealed type for `test.Foo[float]` is `typing.Type[Foo[float]]`.";
"Revealed type [-1]: Revealed type for `test.Foo[float]()` is `Foo[float]`.";
"Revealed type [-1]: Revealed type for `test.Foo[str]()` is `Foo[str]`.";
"Incompatible parameter type [6]: In call `typing.GenericMeta.__getitem__`, for 1st \
positional argument, expected `Type[Variable[X]]` but got `str`.";
];
assert_type_errors
{|
import typing
X = typing.TypeVar("X")
class Foo(typing.Generic[X]):
def __init__(self, x: X) -> None: ...
def one() -> Foo[int]:
return Foo[int](1)
def two() -> Foo[int]:
return Foo[int](1.2)
|}
[
"Incompatible parameter type [6]: In call `Foo.__init__`, for 1st positional argument, \
expected `int` but got `float`.";
];
assert_type_errors
{|
from typing import overload, TypeVar, List, Callable, Tuple, Union
@overload
def overloaded(x: int) -> str: ...
@overload
def overloaded(x: bool) -> float: ...
@overload
def overloaded(x: float) -> bool: ...
@overload
def overloaded(x: str) -> int: ...
def overloaded(x: Union[int, bool, float, str]) -> Union[int, bool, float, str]: ...
T1 = TypeVar("T1")
T2 = TypeVar("T2")
def generic(x: Callable[[T1], T2], y: List[T1], z: List[T2]) -> Tuple[T1, T2]: ...
def foo() -> None:
reveal_type(generic(overloaded, [1], ["1"]))
reveal_type(generic(overloaded, [True], [1.0]))
reveal_type(generic(overloaded, [1.0], [False]))
reveal_type(generic(overloaded, ["1"], [7]))
generic(overloaded, [1], [7])
|}
[
"Revealed type [-1]: Revealed type for `test.generic(test.overloaded, [1], [\"1\"])` is \
`Tuple[int, str]`.";
"Revealed type [-1]: Revealed type for `test.generic(test.overloaded, [True], [1.000000])` \
is `Tuple[bool, float]`.";
"Revealed type [-1]: Revealed type for `test.generic(test.overloaded, [1.000000], [False])` \
is `Tuple[float, bool]`.";
"Revealed type [-1]: Revealed type for `test.generic(test.overloaded, [\"1\"], [7])` is \
`Tuple[str, int]`.";
"Incompatible parameter type [6]: In call `generic`, for 3rd positional argument, expected \
`List[Variable[T2]]` but got `List[int]`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T')
def foo(input: T, b: bool) -> typing.Optional[T]:
x = None
if b:
x = input
reveal_type(x)
return x
|}
["Revealed type [-1]: Revealed type for `x` is `typing.Optional[Variable[T]]`."];
assert_type_errors
{|
from typing import TypeVar, Generic, Optional
T1 = TypeVar("T1")
class Lol(Generic[T1]):
def bar(self, x: Optional[T1]) -> None:
if x is not None and self.bop(x):
return
def bop(self, x: T1) -> bool:
return True
|}
[];
assert_type_errors
{|
from typing import TypeVar, Union, List
T = TypeVar("T")
def foo(x: Union[T, List[T]]) -> None: ...
def bar(x: Union[T, List[T]]) -> None:
foo(x)
|}
[];
assert_type_errors
{|
from builtins import identity
from typing import Union, Tuple
SeparatedUnion = Union[
Tuple[int, bool],
Tuple[str, None],
]
def foo(x: SeparatedUnion) -> SeparatedUnion:
i = identity(x)
reveal_type(i)
return i
|}
["Revealed type [-1]: Revealed type for `i` is `Union[Tuple[int, bool], Tuple[str, None]]`."];
assert_type_errors
{|
from typing import Callable, TypeVar
T = TypeVar("T")
class CallMe:
def __call__(self, x: int) -> str:
return "A"
def foo(f: Callable[[int], T]) -> T:
return f(1)
def bar() -> None:
x = foo(CallMe())
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `str`."];
assert_type_errors
{|
from typing import TypeVar, Callable
T = TypeVar('T')
def foo(x: T) -> Callable[[], T]:
def bar() -> T:
return x
return bar
|}
[];
assert_type_errors
{|
from typing import TypeVar, Generic, Callable
T = TypeVar('T')
class A(Generic[T]):
def foo(self, x: T) -> T:
return x
|}
[];
assert_type_errors
{|
from typing import TypeVar, Generic, Callable
T = TypeVar('T')
class A(Generic[T]):
def foo(self, x: T) -> Callable[[T], int]:
def bar(x: T) -> int:
return 42
return bar
|}
[];
assert_type_errors
{|
from typing import TypeVar, Dict, Any, Union
def loads(obj: object) -> Dict[str, Any]: ...
T = TypeVar('T')
def foo() -> None:
def bar(obj: T, *, top_level: bool = True) -> Union[str, T]:
if isinstance(obj, dict):
return "dict"
else:
loaded = loads(obj)
modified = bar(loaded, top_level = False)
return str(modified)
|}
[];
assert_type_errors
{|
from typing import TypeVar, List, Generic
T_bound_int = TypeVar('T_bound_int', bound=int)
class G(Generic[T_bound_int]):
pass
T = TypeVar('T')
def foo(a: G[List[T]]) -> T: ...
|}
[
"Invalid type parameters [24]: Type parameter `List[Variable[T]]` violates constraints on \
`Variable[T_bound_int (bound to int)]` in generic type `G`.";
];
assert_type_errors
{|
from typing import TypeVar, List, Generic
T_Con = TypeVar('T_Con', contravariant=True)
class G(Generic[T_Con]):
pass
def foo(a: G[str], b: G[int]) -> None:
l: List[G[object]] = [a, b]
|}
[
"Incompatible variable type [9]: l is declared to have type `List[G[object]]` but is used as \
type `List[Union[G[int], G[str]]]`.";
];
assert_type_errors
{|
from typing import Generic, Optional, TypeVar
_T = TypeVar('_T')
class ContextVar(Generic[_T]):
def __init__(self, name: str, *, default: _T = ...) -> None: ...
def foo() -> None:
x: ContextVar[Optional[int]] = ContextVar[Optional[int]]("var1", default=None)
|}
[];
()
let test_check_variable_bindings context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from builtins import str_to_int
import typing
T = typing.TypeVar('T', bound=int)
def foo(t: T) -> None:
str_to_int(t)
|}
[
"Incompatible parameter type [6]: In call `str_to_int`, for 1st positional argument, \
expected `str` but got `Variable[T (bound to int)]`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T', bound=int)
def foo() -> T:
return 1.0
|}
[
"Invalid type variable [34]: The type variable `Variable[T (bound to int)]` isn't present in \
the function's parameters.";
"Incompatible return type [7]: Expected `Variable[T (bound to int)]` but got `float`.";
];
assert_type_errors
{|
from builtins import int_to_str
import typing
T = typing.TypeVar('T', bound=int)
def foo(t: T) -> None:
int_to_str(t)
def bar(x: str) -> None:
foo(x)
|}
[
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`Variable[T (bound to int)]` but got `str`.";
];
assert_type_errors
{|
import typing
class C():
def baz(self) -> int:
return 7
T = typing.TypeVar('T', bound=C)
def foo(t: T) -> int:
return t.baz()
|}
[];
assert_type_errors
{|
from typing import TypeVar
T = TypeVar("T", bound=int)
def f(x: T, y: int) -> T:
return x
def buggy(n: None) -> None:
return f(2, n)
|}
[
"Incompatible return type [7]: Expected `None` but got `int`.";
"Incompatible parameter type [6]: In call `f`, for 2nd positional argument, expected `int` \
but got `None`.";
];
assert_type_errors
{|
import typing
class C: pass
T = typing.TypeVar('T', bound=C)
def foo(input: typing.Type[T]) -> T:
v = input()
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `Variable[T (bound to C)]`."];
assert_type_errors
{|
import typing
_T = typing.TypeVar("T", bound=int)
class Foo:
def foo(self, x: int) -> int:
return x
class Bar(Foo):
def foo(self, x: _T) -> _T:
return x
|}
[];
assert_type_errors
{|
import typing
_T = typing.TypeVar("T", bound=float)
class Foo:
def foo(self, x: int) -> int:
return x
class Bar(Foo):
def foo(self, x: _T) -> _T:
return x
|}
[
"Inconsistent override [15]: `test.Bar.foo` overrides method defined in `Foo` inconsistently. "
^ "Returned type `Variable[_T (bound to float)]` is not a subtype of the overridden return "
^ "`int`.";
];
assert_type_errors
{|
import typing
_T = typing.TypeVar("T", bound=float)
class Foo:
def foo(self, x: _T) -> _T:
return x
class Bar(Foo):
def foo(self, x: int) -> int:
return x
|}
[
"Inconsistent override [14]: `test.Bar.foo` overrides method defined in `Foo` inconsistently. "
^ "Parameter of type `int` is not a supertype of the overridden parameter "
^ "`Variable[_T (bound to float)]`.";
];
assert_type_errors
{|
from typing import TypeVar
_SelfT = TypeVar("SelfT", bound=C)
class C():
def clone(self: _SelfT) -> _SelfT: ...
def foo(self: _SelfT) -> _SelfT:
x = self.clone()
reveal_type(x)
return x
|}
["Revealed type [-1]: Revealed type for `x` is `Variable[_SelfT (bound to C)]`."];
assert_type_errors
{|
from typing import TypeVar, Type
_SelfT = TypeVar("SelfT", bound=C)
class C():
@classmethod
def clone(cls: Type[_SelfT]) -> _SelfT: ...
@classmethod
def foop(cls: Type[_SelfT]) -> _SelfT:
x = cls.clone()
reveal_type(x)
return x
|}
["Revealed type [-1]: Revealed type for `x` is `Variable[_SelfT (bound to C)]`."];
assert_type_errors
{|
import typing
X = typing.TypeVar("X", bound=C)
class Foo(typing.Generic[X]): pass
class C(): pass
class D(C): pass
reveal_type(Foo[C])
reveal_type(Foo[C]())
reveal_type(Foo[D]())
Foo[int]()
|}
[
"Revealed type [-1]: Revealed type for `test.Foo[test.C]` is `typing.Type[Foo[C]]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.C]()` is `Foo[C]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.D]()` is `Foo[D]`.";
"Incompatible parameter type [6]: In call `typing.GenericMeta.__getitem__`, for 1st \
positional argument, expected `Type[Variable[X (bound to C)]]` but got `Type[int]`.";
];
assert_type_errors
{|
import typing
X = typing.TypeVar("X", Mineral, Animal)
class Foo(typing.Generic[X]): pass
class Mineral(): pass
class Animal(): pass
class Fish(Animal): pass
reveal_type(Foo[Animal])
reveal_type(Foo[Animal]())
reveal_type(Foo[Mineral]())
reveal_type(Foo[Fish]())
Foo[int]()
|}
[
"Revealed type [-1]: Revealed type for `test.Foo[test.Animal]` is "
^ "`typing.Type[Foo[Animal]]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.Animal]()` is `Foo[Animal]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.Mineral]()` is `Foo[Mineral]`.";
"Revealed type [-1]: Revealed type for `test.Foo[test.Fish]()` is `Foo[Animal]`.";
"Incompatible parameter type [6]: In call `typing.GenericMeta.__getitem__`, for 1st \
positional argument, expected `Type[Variable[X <: [Mineral, Animal]]]` but got `Type[int]`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T', bound=int)
class ConstrainedBase(typing.Generic[T]): pass
class BadChild(ConstrainedBase[str]): pass
|}
[
"Invalid type parameters [24]: Type parameter `str` violates constraints on "
^ "`Variable[T (bound to int)]` in generic type `ConstrainedBase`.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar('T', bound=int)
class ConstrainedBase(typing.Generic[T]): pass
class AnyChild(ConstrainedBase[typing.Any]): pass
|}
[];
assert_type_errors
{|
from typing import TypeVar, Generic
T = TypeVar('T', bound="G")
class G(Generic[T]):
pass
|}
["Invalid type parameters [24]: Generic type `G` expects 1 type parameter."];
assert_type_errors
{|
from typing import TypeVar, Generic
TSelf = TypeVar("TSelf", bound="G")
T = TypeVar("T")
class G(Generic[T]):
# This method restricts the inputs to be less than `G[Any]` but does
# not enforce that the two inputs are of the same type.
def expect_self(self: TSelf, other: TSelf) -> TSelf: ...
x: G[int]
y: G[str]
x.expect_self(y)
reveal_type(x.expect_self(y))
z: bool
x.expect_self(z)
|}
[
"Invalid type parameters [24]: Generic type `G` expects 1 type parameter.";
"Revealed type [-1]: Revealed type for `x.expect_self(y)` is `typing.Union[G[int], G[str]]`.";
"Incompatible parameter type [6]: In call `G.expect_self`, for 1st positional argument, \
expected `Variable[TSelf (bound to G[typing.Any])]` but got `bool`.";
];
assert_type_errors
{|
from typing import TypeVar, Generic
TSelf = TypeVar("TSelf", bound="G")
T = TypeVar("T")
class G(Generic[T]):
# This method restricts the inputs to be less than `G[Any]` but does
# not enforce that the two inputs are of the same type.
def expect_self(self, other: TSelf) -> TSelf: ...
x: G[int]
y: G[str]
x.expect_self(y)
reveal_type(x.expect_self(y))
z: bool
x.expect_self(z)
|}
[
"Invalid type parameters [24]: Generic type `G` expects 1 type parameter.";
"Revealed type [-1]: Revealed type for `x.expect_self(y)` is `G[str]`.";
"Incompatible parameter type [6]: In call `G.expect_self`, for 1st positional argument, \
expected `Variable[TSelf (bound to G[typing.Any])]` but got `bool`.";
];
assert_type_errors
{|
from typing import TypeVar, Generic
TSelf = TypeVar("TSelf", bound="G")
T = TypeVar("T")
class G(Generic[T]):
def expect_same_type(self: G[T], other: G[T]) -> G[T]: ...
x: G[int]
y: G[str]
x.expect_same_type(y)
reveal_type(x.expect_same_type(y))
z: bool
x.expect_same_type(z)
|}
[
"Invalid type parameters [24]: Generic type `G` expects 1 type parameter.";
"Incompatible parameter type [6]: In call `G.expect_same_type`, for 1st positional argument, \
expected `G[int]` but got `G[str]`.";
"Revealed type [-1]: Revealed type for `x.expect_same_type(y)` is `G[int]`.";
"Incompatible parameter type [6]: In call `G.expect_same_type`, for 1st positional argument, \
expected `G[int]` but got `bool`.";
];
Setting the bound as a parameter - less generic class ` INode ` replaces the parameters with Any .
This is equivalent to writing ` bound = INode[Any ] ` .
This is equivalent to writing `bound=INode[Any]`. *)
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
T = TypeVar("T")
class INode(Generic[T]): ...
TBoundToINode = TypeVar("TNodeGetResult", bound=INode)
TResult = TypeVar("TResult")
class Query(Generic[TResult]):
def get_result(self) -> TResult: ...
class NodeGetQuery(Query[TBoundToINode]): ...
y: NodeGetQuery[int]
z: NodeGetQuery[INode[str]]
z3: NodeGetQuery[INode[int]]
|}
[
"Invalid type parameters [24]: Generic type `INode` expects 1 type parameter.";
"Invalid type parameters [24]: Type parameter `int` violates constraints on \
`Variable[TBoundToINode (bound to test.INode)]` in generic type `NodeGetQuery`.";
];
assert_type_errors
{|
from typing import Generic, Optional, TypeVar
T = TypeVar("T")
class Foo(Generic[T]): ...
def create(x: Optional[T]) -> Foo[T]: ...
def main(x: T) -> Foo[T]:
return create(x)
|}
[];
()
let test_unbound_variables context =
let assert_type_errors = assert_type_errors ~context in
let assert_default_type_errors = assert_default_type_errors ~context in
assert_type_errors
{|
def foo() -> None:
x = []
|}
[
"Incomplete type [37]: Type `typing.List[Variable[_T]]` inferred for `x` is incomplete, "
^ "add an explicit annotation.";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.List[int] = []
|}
[];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Sequence[int] = []
|}
[];
assert_type_errors
{|
def foo() -> None:
x: int = []
|}
[
"Incompatible variable type [9]: x is declared to have type `int` but is used as type \
`List[Variable[_T]]`.";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Optional[typing.List[int]]
x = []
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is `typing.Optional[typing.List[int]]` (inferred: \
`typing.List[int]`).";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Dict[str, typing.List[int]] = { "A" : [] }
|}
[];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.List[int] = {}
|}
[
"Incompatible variable type [9]: x is declared to have type `List[int]` but is used as type \
`Dict[Variable[_KT], Variable[_VT]]`.";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Dict[int, str] = []
|}
[
"Incompatible variable type [9]: x is declared to have type `Dict[int, str]` but is used as \
type `List[Variable[_T]]`.";
];
assert_type_errors
{|
import typing
def foo() -> None:
x: typing.Dict[int, typing.List[int]] = { "A" : [] }
|}
[
"Incompatible variable type [9]: x is declared to have type `Dict[int, List[int]]` but is \
used as type `Dict[str, List[int]]`.";
];
assert_type_errors
{|
import typing
def foo() -> typing.List[int]:
return []
|}
[];
assert_type_errors
{|
import typing
def bar(x: typing.List[int]) -> None:
pass
def foo() -> None:
bar([])
|}
[];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
def bar(x: typing.List[T]) -> T:
return x[0]
def foo() -> None:
x = bar([])
|}
["Incomplete type [37]: Type inferred for `x` is incomplete, add an explicit annotation."];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[int]:
return G()
|}
[];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[int]:
g = G()
reveal_type(g)
return g
|}
[
"Incomplete type [37]: Type `G[Variable[T_Explicit <: [int, str]]]` inferred for `g` is "
^ "incomplete, add an explicit annotation.";
"Revealed type [-1]: Revealed type for `g` is `G[typing.Any]`.";
];
assert_default_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[int]:
g = G()
reveal_type(g)
return g
|}
["Revealed type [-1]: Revealed type for `g` is `G[typing.Any]`."];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[int]:
g: G[int] = G()
reveal_type(g)
return g
|}
["Revealed type [-1]: Revealed type for `g` is `G[int]`."];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[bool]:
g: G[bool] = G()
reveal_type(g)
return g
|}
[
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Revealed type [-1]: Revealed type for `g` is `G[typing.Any]`.";
];
assert_default_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def bar() -> G[bool]:
g: G[bool] = G()
reveal_type(g)
return g
|}
[
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Revealed type [-1]: Revealed type for `g` is `G[typing.Any]`.";
];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
T = typing.TypeVar("T")
class G(typing.Generic[T_Explicit, T]):
def __init__(self) -> None:
pass
def bar(g: G[bool, bool]) -> None:
reveal_type(g)
|}
[
"Invalid type parameters [24]: Type parameter `bool` violates constraints on "
^ "`Variable[T_Explicit <: [int, str]]` in generic type `G`.";
"Revealed type [-1]: Revealed type for `g` is `G[typing.Any, bool]`.";
];
assert_type_errors
{|
import typing
T_Explicit = typing.TypeVar("T_Explicit", int, str)
class G(typing.Generic[T_Explicit]):
def __init__(self) -> None:
pass
def foo(self) -> int:
return 7
def bar() -> int:
return G().foo()
|}
[
"Incomplete type [37]: Type `G[Variable[T_Explicit <: [int, str]]]` inferred for `test.G()` "
^ "is incomplete, so attribute `foo` cannot be accessed. Separate the expression into an "
^ "assignment and give it an explicit annotation.";
];
assert_type_errors
{|
def bar() -> None:
for x in []:
pass
|}
[
"Incomplete type [37]: Type `typing.List[Variable[_T]]` inferred for `[]` is incomplete, so \
attribute `__iter__` cannot be accessed. Separate the expression into an assignment and \
give it an explicit annotation.";
];
assert_type_errors
{|
import typing
import collections
def foo() -> None:
x: typing.Dict[int, typing.Dict[int, str]] = collections.defaultdict(dict)
|}
[];
assert_type_errors
{|
import typing
import collections
def foo() -> None:
x: typing.Dict[int, str] = collections.defaultdict(dict)
|}
[
"Incompatible variable type [9]: x is declared to have type `Dict[int, str]` but is used as \
type `DefaultDict[Variable[collections._KT], Dict[Variable[_KT], Variable[_VT]]]`.";
];
assert_type_errors
{|
import typing
def foo() -> typing.Tuple[typing.List[int], typing.List[str]]:
return [], []
|}
[];
assert_type_errors
{|
def foo(x: int) -> None: pass
def bar() -> None:
for x in [1, 2, 3]:
foo([])
|}
[
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected `int` \
but got `List[Variable[_T]]`.";
];
assert_type_errors
{|
import typing
def bar(
a: typing.Optional[typing.List[int]], b: typing.Optional[typing.List[str]]
) -> typing.Tuple[typing.List[int], typing.List[str]]:
return a or [], b or []
|}
[];
assert_type_errors
{|
from typing import Generic, TypeVar, Any
T = TypeVar('T')
class G(Generic[T]):
prop: T
def __init__(self, prop: T) -> None:
self.prop = prop
class C(G[int]):
def foo(self) -> None:
reveal_type(self.prop)
|}
["Revealed type [-1]: Revealed type for `self.prop` is `int`."];
()
let test_distinguish context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
import typing
_T1 = typing.TypeVar("_T1")
_T2 = typing.TypeVar("_T2")
class C(typing.Generic[_T1]):
def pair(self, a: _T1, b: _T2) -> typing.Tuple[_T1, _T2]:
return (a, b)
def foo(q: C[_T2], x: _T2, y:_T1) -> typing.Tuple[_T2, _T1]:
A = q.pair(x, y)
reveal_type(A)
return A
|}
["Revealed type [-1]: Revealed type for `A` is `typing.Tuple[Variable[_T2], Variable[_T1]]`."];
assert_type_errors
{|
import typing
_T1 = typing.TypeVar("_T1")
_T2 = typing.TypeVar("_T2")
def foo(f: typing.Callable[[_T1], _T2], p: _T1) -> _T2:
v = f(p)
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `Variable[_T2]`."];
assert_type_errors
{|
import typing
_T1 = typing.TypeVar("_T1")
_T2 = typing.TypeVar("_T2")
def foo(f: typing.Callable[[_T1], _T2], p: _T1) -> _T2:
return f(1)
|}
[
"Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \
`Variable[_T1]` but got `int`.";
];
assert_type_errors
{|
import typing
_T1 = typing.TypeVar("_T1")
_T2 = typing.TypeVar("_T2")
class B: pass
class C(B): pass
def foo(f: typing.Callable[[typing.List[typing.Tuple[_T1, B]]], _T2], p: _T1) -> _T2:
v = f([(p, C())])
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `Variable[_T2]`."];
assert_type_errors
{|
import typing
class C():
def __init__(self, x: int) -> None:
pass
def foo() -> typing.Iterator[C]:
v = map(C, [1, 2, 3])
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `map[C]`."];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
class C(typing.Generic[T]):
def __init__(self, x: T) -> None:
pass
def foo() -> typing.Iterator[C[int]]:
v = map(C, [1, 2, 3])
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `map[C[int]]`."];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
class C(typing.Generic[T]):
def __init__(self, x: T) -> None:
pass
def foo(x: typing.List[T]) -> typing.Iterator[C[T]]:
v = map(C, x)
reveal_type(v)
return v
|}
["Revealed type [-1]: Revealed type for `v` is `map[C[Variable[T]]]`."];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
def foo(x: T) -> typing.List[T]:
return [x]
T1 = typing.TypeVar("T1")
def bar(x: typing.Callable[[T1], T1]) -> None:
pass
def baz() -> None:
bar(foo)
|}
[
"Mutually recursive type variables [36]: Solving type variables for call `bar` "
^ "led to infinite recursion.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
def foo(x: T) -> T:
return x
T1 = typing.TypeVar("T1")
T2 = typing.TypeVar("T2")
def bar(x: typing.Callable[[T1], T2], y: typing.Callable[[T2], T1]) -> typing.Tuple[T1, T2]:
...
def baz() -> None:
x = bar(foo, foo)
|}
[
"Incomplete type [37]: Type `typing.Tuple[Variable[T1], Variable[T1]]` inferred for `x"
^ "` is incomplete, add an explicit annotation.";
];
assert_type_errors
{|
import typing
T = typing.TypeVar("T")
def identity(x: T) -> T:
return x
def f() -> None:
reveal_type(map(identity, [1, 2, 3]))
|}
["Revealed type [-1]: Revealed type for `map(test.identity, [1, 2, 3])` is `map[int]`."];
()
let test_integer_variables context =
assert_type_errors
~context
{|
import typing_extensions
T = typing_extensions.IntVar("T")
X = typing_extensions.IntVar("X")
def baz(x: X) -> X:
return x
def bop(x: int) -> None:
pass
def foo(x: T) -> T:
y = x.__add__(5)
z = baz(x)
bop(x)
return z
def bar() -> None:
x = foo(1)
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `typing_extensions.Literal[1]`."];
assert_type_errors
~context
{|
import typing_extensions
X = typing_extensions.IntVar("X")
def baz(x: X) -> X:
return x
def bar(y: int) -> None:
baz(y)
|}
[
"Incompatible parameter type [6]: In call `baz`, for 1st positional argument, expected \
`IntegerVariable[X]` but got `int`.";
];
()
let test_nested_variable_error context =
assert_type_errors
~context
{|
import typing
T1 = typing.TypeVar("T1")
T2 = typing.TypeVar("T2", typing.List[T1], typing.Dict[str, T1])
|}
[
"Invalid type [31]: Expression `Variable[T2 <: [typing.List[Variable[test.T1]], "
^ "typing.Dict[str, Variable[test.T1]]]]` is not a valid type. Type variables cannot contain "
^ "other type variables in their constraints.";
];
()
let test_single_explicit_error context =
assert_type_errors
~context
{|
import typing
T1 = typing.TypeVar("T1", int)
|}
[
"Invalid type [31]: TypeVar can't have a single explicit constraint. Did you mean `bound=int`?";
];
()
let test_callable_parameter_variadics context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Callable, List
import pyre_extensions
V = pyre_extensions.ParameterSpecification("V")
def f(x: Callable[V, int]) -> Callable[V, List[int]]: ...
def foo(x: int) -> int:
return 7
def bar(x: int, y: str) -> int:
return 7
def g() -> None:
reveal_type(f(foo))
reveal_type(f(bar))
|}
[
"Revealed type [-1]: Revealed type for `test.f(test.foo)` is `typing.Callable[[Named(x, \
int)], "
^ "List[int]]`.";
"Revealed type [-1]: Revealed type for `test.f(test.bar)` is `typing.Callable[[Named(x, \
int), "
^ "Named(y, str)], List[int]]`.";
];
assert_type_errors
{|
import typing
import pyre_extensions
V = pyre_extensions.ParameterSpecification("V")
class Propagating(typing.List[typing.Callable[V, int]]):
def foo(self) -> int: ...
|}
[];
assert_type_errors
~handle:"qualifier.py"
{|
from typing import Callable, List
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import PositionalArgumentsOf, KeywordArgumentsOf
V = ParameterSpecification("V")
def f(x: Callable[V, int]) -> Callable[V, List[int]]:
def decorated( *args: V.args, **kwargs: V.kwargs) -> List[int]:
return [x( *args, **kwargs)]
return decorated
|}
[];
assert_type_errors
{|
from typing import Callable
from pyre_extensions import ParameterSpecification
TParams = ParameterSpecification("TParams")
def eek(x: Callable[TParams, int]) -> Callable[TParams, float]:
return x
|}
[];
assert_type_errors
{|
from typing import Protocol, Callable, TypeVar
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def call_this_function(__f: Callable[TParams, TReturn], *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
return __f( *args, **kwargs)
def int_to_string(i: int) -> str:
return "A"
def foo() -> None:
x = call_this_function(int_to_string, 1)
reveal_type(x)
y = call_this_function(int_to_string, i=1)
reveal_type(y)
call_this_function(int_to_string, "A")
call_this_function(int_to_string, i="A")
|}
[
"Revealed type [-1]: Revealed type for `x` is `str`.";
"Revealed type [-1]: Revealed type for `y` is `str`.";
"Incompatible parameter type [6]: In call `call_this_function`, for 2nd positional argument, \
expected `int` but got `str`.";
"Incompatible parameter type [6]: In call `call_this_function`, for argument `i`, expected \
`int` but got `str`.";
];
assert_type_errors
{|
from typing import Protocol, Callable, TypeVar, overload, Union
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def call_this_function(__f: Callable[TParams, TReturn], *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
return __f( *args, **kwargs)
@overload
def overloaded(x: int) -> str:...
@overload
def overloaded(x: str) -> int:...
def overloaded(x: Union[int, str]) -> Union[int, str]:
if isinstance(x, int):
return "A"
else:
return 1
def foo() -> None:
x = call_this_function(overloaded, 1)
reveal_type(x)
y = call_this_function(overloaded, "A")
reveal_type(y)
call_this_function(overloaded, 1.0)
|}
[
"Revealed type [-1]: Revealed type for `x` is `str`.";
"Revealed type [-1]: Revealed type for `y` is `int`.";
"Incompatible parameter type [6]: In call `call_this_function`, for 2nd positional argument, \
expected `int` but got `float`.";
];
assert_type_errors
{|
from typing import Protocol, Callable, TypeVar
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def call_n_times(
__f: Callable[TParams, None],
__n: int,
*args: TParams.args,
**kwargs: TParams.kwargs,
) -> None:
for x in range(__n):
__f( *args, **kwargs)
def valid(x: int, y: str) -> None: ...
def invalid(x: int, y: str) -> int: ...
def foo() -> None:
call_n_times(valid, 75, 1, "A")
# invalid first argument
call_n_times(invalid, 75, 1, "A")
# missing second argument
call_n_times(valid, y="A", x=1)
|}
[
"Incompatible parameter type [6]: In call `call_n_times`, for 1st positional argument, \
expected `typing.Callable[test.TParams, None]` but got `typing.Callable(invalid)[[Named(x, \
int), Named(y, str)], int]`.";
"Missing argument [20]: Call `call_n_times` expects argument in position 1.";
];
assert_type_errors
{|
from typing import *
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import Concatenate
P = ParameterSpecification("P")
R = TypeVar("R")
class Client: ...
def with_client(
f: Callable[Concatenate["Foo", Client, P], R]
) -> Callable[Concatenate["Foo", P], R]:
def inner(__self: "Foo", *args: P.args, **kwargs: P.kwargs) -> R:
return f(__self, Client(), *args, **kwargs)
return inner
class Foo:
@with_client
def takes_int_str(self, client: Client, x: int, y: str) -> int:
# Use `client` here.
return x + 7
reveal_type(with_client)
x: Foo
reveal_type(x.takes_int_str)
x.takes_int_str(1, "A") # Accepted
x.takes_int_str("B", 2) # Correctly rejected by the type checker
|}
[
"Revealed type [-1]: Revealed type for `test.with_client` is \
`typing.Callable(with_client)[[Named(f, \
typing.Callable[pyre_extensions.type_variable_operators.Concatenate[Foo, Client, test.P], \
Variable[R]])], typing.Callable[pyre_extensions.type_variable_operators.Concatenate[Foo, \
test.P], Variable[R]]]`.";
"Revealed type [-1]: Revealed type for `x.takes_int_str` is \
`BoundMethod[typing.Callable[[Foo, Named(x, int), Named(y, str)], int], Foo]`.";
"Incompatible parameter type [6]: In anonymous call, for 1st positional argument, expected \
`int` but got `str`.";
"Incompatible parameter type [6]: In anonymous call, for 2nd positional argument, expected \
`str` but got `int`.";
];
PyTorch style delegation pattern
assert_type_errors
{|
from abc import ABCMeta
from typing import Protocol, Callable, TypeVar
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
class HasForward(Protocol[TParams, TReturn]):
forward: Callable[TParams, TReturn]
class Model(metaclass=ABCMeta):
forward: Callable[..., object]
def __call__(__self: HasForward[TParams, TReturn], *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
# do some common stuff
return_value = __self.forward( *args, **kwargs)
# do some more stuff
return return_value
class AModel(Model):
def forward(self, x: int, y: str) -> bool:
...
class BModel(Model):
def forward(self, x: bool, *args: int) -> str:
...
def foo() -> None:
# Correct usages
x = AModel()(1, "A")
reveal_type(x)
y = AModel()(y="A", x=5)
reveal_type(y)
# Incorrect second argument
AModel()(1, 1)
# Different model
z = BModel()(True, 1, 4, 5)
reveal_type(z)
|}
[
"Revealed type [-1]: Revealed type for `x` is `bool`.";
"Revealed type [-1]: Revealed type for `y` is `bool`.";
"Incompatible parameter type [6]: In call `Model.__call__`, for 2nd positional argument, \
expected `str` but got `int`.";
"Revealed type [-1]: Revealed type for `z` is `str`.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import Generic
P = ParameterSpecification("P")
class H(Generic[P]):
def f(self, /, *args: P.args, **kwargs: P.kwargs) -> int:
return 5
def foo(x: H[int, str]) -> None:
reveal_type(x.f.__call__)
# incorrect
x.f()
x.f("A", 1)
# correct
x.f(1, "A")
|}
[
"Revealed type [-1]: Revealed type for `x.f.__call__` is `typing.Callable[[int, str], int]`.";
"Missing argument [20]: Call `H.f` expects argument in position 1.";
"Incompatible parameter type [6]: In call `H.f`, for 1st positional argument, expected `int` \
but got `str`.";
"Incompatible parameter type [6]: In call `H.f`, for 2nd positional argument, expected `str` \
but got `int`.";
];
assert_type_errors
{|
from typing import Callable
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
def outer(f: Callable[TParams, int]) -> None:
def foo(x: int, *args: TParams.args, **kwargs: TParams.kwargs) -> None:
pass
def bar(__x: int, *args: TParams.args, **kwargs: TParams.kwargs) -> None:
pass
def baz(x: int, /, *args: TParams.args, **kwargs: TParams.kwargs) -> None:
pass
reveal_type(foo)
reveal_type(bar)
reveal_type(baz)
|}
[
"Revealed type [-1]: Revealed type for `foo` is \
`typing.Callable[pyre_extensions.type_variable_operators.Concatenate[int, test.TParams], \
None]`.";
"Revealed type [-1]: Revealed type for `bar` is \
`typing.Callable[pyre_extensions.type_variable_operators.Concatenate[int, test.TParams], \
None]`.";
"Revealed type [-1]: Revealed type for `baz` is \
`typing.Callable[pyre_extensions.type_variable_operators.Concatenate[int, test.TParams], \
None]`.";
];
assert_type_errors
{|
from typing import Callable
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
def outer(f: Callable[TParams, int]) -> Callable[TParams, None]:
def foo(x: int, *args: TParams.args, **kwargs: TParams.kwargs) -> None:
f( *args, **kwargs)
def bar( *args: TParams.args, **kwargs: TParams.kwargs) -> None:
foo(1, *args, **kwargs) # Accepted
foo(x=1, *args, **kwargs) # Rejected
return bar
|}
["Unexpected keyword [28]: Unexpected keyword argument `x` to anonymous call."];
assert_type_errors
{|
from typing import Protocol, Callable, TypeVar, overload, Union
import pyre_extensions
TParams = pyre_extensions.ParameterSpecification("TParams")
def doesnt_care_positional( *args: object) -> None:
pass
def doesnt_care_keywords( **kwargs: object) -> None:
pass
def does_care_positional( *args: int) -> None:
pass
def does_care_keywords( **kwargs: int) -> None:
pass
def outer(f: Callable[TParams, int]) -> Callable[TParams, None]:
def foo( *args: TParams.args, **kwargs: TParams.kwargs) -> None:
doesnt_care_positional( *args)
doesnt_care_keywords( **kwargs)
does_care_positional( *args)
does_care_keywords( **kwargs)
f( *args, **kwargs)
return foo
|}
[
"Incompatible parameter type [6]: In call `does_care_positional`, for 1st positional \
argument, expected `int` but got `object`.";
"Incompatible parameter type [6]: In call `does_care_keywords`, for 1st positional argument, \
expected `int` but got `object`.";
];
()
let test_user_defined_parameter_specification_classes context =
let assert_type_errors = assert_type_errors ~context in
Make sure ` typing . ParamSpec ` works .
assert_type_errors
{|
from typing import Callable, ParamSpec
TParams = ParamSpec("TParams")
def client(f: Callable[TParams, int]) -> None:
def inner( *args: TParams.args, **kwargs: TParams.kwargs) -> int:
return f( *args, **kwargs)
|}
[];
Make sure ` typing_extensions . ParamSpec ` works .
assert_type_errors
{|
from typing import Callable
from typing_extensions import ParamSpec
TParams = ParamSpec("TParams")
def client(f: Callable[TParams, int]) -> None:
def inner( *args: TParams.args, **kwargs: TParams.kwargs) -> int:
return f( *args, **kwargs)
|}
[];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def function(param: str) -> str:
...
class MyClass(Generic[TParams, TReturn]):
f: Callable[TParams, TReturn]
def __init__(self, f: Callable[TParams, TReturn]) -> None:
self.f = f
def call(__self, *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
f = __self.f
# do some logging or something
return f( *args, **kwargs)
def client(f: Callable[TParams, TReturn]) -> MyClass[TParams, TReturn]:
return MyClass(f)
def foo() -> None:
x = client(function).call(param="")
reveal_type(x)
client(function).call(parm="")
|}
[
"Revealed type [-1]: Revealed type for `x` is `str`.";
"Unexpected keyword [28]: Unexpected keyword argument `parm` to call `MyClass.call`.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def client(f: Callable[TParams, TReturn]) -> None:
def inner(__x: int, *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn:
return f( *args, **kwargs)
reveal_type(inner)
|}
[
"Revealed type [-1]: Revealed type for `inner` is \
`typing.Callable[pyre_extensions.type_variable_operators.Concatenate[int, test.TParams], \
Variable[TReturn]]`.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable, Protocol
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
class CallableReturningInt(Protocol[TParams]):
def __call__(__self, __f: int, *args: TParams.args, **kwargs: TParams.kwargs) -> int:
...
def remove_int_argument(f: CallableReturningInt[TParams]) -> Callable[TParams, int]: ...
def goof(x: int, y: str) -> int:
return x
def foo() -> None:
f = remove_int_argument(goof)
reveal_type(f)
|}
["Revealed type [-1]: Revealed type for `f` is `typing.Callable[[Named(y, str)], int]`."];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import Concatenate
from typing import TypeVar, Generic, Callable, Protocol
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def remove_int_argument(f: Callable[Concatenate[int, TParams], str]) -> Callable[TParams, int]:
def inner( *args: TParams.args, **kwargs: TParams.kwargs) -> int:
s = f(75, *args, **kwargs)
return int(s)
return inner
def goof(x: int, y: str) -> str:
return str(x)
def foo() -> None:
f = remove_int_argument(goof)
reveal_type(f)
|}
["Revealed type [-1]: Revealed type for `f` is `typing.Callable[[Named(y, str)], int]`."];
assert_type_errors
{|
from typing import Protocol
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
TSelf = TypeVar("TSelf")
class ObjectMethod(Protocol[TSelf, TParams, TReturn]):
def __call__(__self, __other_self: TSelf, *args: TParams.args, **kwargs: TParams.kwargs) -> TReturn: ...
def track_assertion(
assertion: ObjectMethod["TestCommand", TParams, None]
) -> ObjectMethod["TestCommand", TParams, int]:
def assert_test(
__self: "TestCommand",
*args: TParams.args,
**kwargs: TParams.kwargs
) -> int:
assertion(__self, *args, **kwargs)
return 7
return assert_test
class TestCommand:
@track_assertion
def method(self: "TestCommand", x: int) -> None:
pass
def foo() -> None:
m = TestCommand().method
reveal_type(m)
|}
[
"Revealed type [-1]: Revealed type for `m` is `ObjectMethod[TestCommand, [Named(x, int)], \
int]`.";
];
assert_type_errors
{|
from typing import Protocol
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import Concatenate
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
TSelf = TypeVar("TSelf")
def track_assertion(
assertion: Callable[Concatenate["TestCommand", TParams], None]
) -> Callable[Concatenate["TestCommand", TParams], int]:
def assert_test(
__self: "TestCommand",
*args: TParams.args,
**kwargs: TParams.kwargs
) -> int:
assertion(__self, *args, **kwargs)
return 7
return assert_test
class TestCommand:
@track_assertion
def method(self: "TestCommand", x: int) -> None:
pass
def foo() -> None:
m = TestCommand().method
reveal_type(m)
|}
[
"Revealed type [-1]: Revealed type for `m` is `BoundMethod[typing.Callable[[TestCommand, \
Named(x, int)], int], TestCommand]`.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from pyre_extensions.type_variable_operators import Concatenate
from typing import TypeVar, Generic, Callable, Protocol
TParams = ParameterSpecification("TParams")
TReturn = TypeVar("TReturn")
def add_on_argument(f: Callable[TParams, str]) -> Callable[Concatenate[str, TParams], int]:
def inner(first: str, /, *args: TParams.args, **kwargs: TParams.kwargs) -> int:
s = f( *args, **kwargs)
return int(s)
return inner
def goof(x: int) -> str:
return str(x)
def foo() -> None:
f = add_on_argument(goof)
reveal_type(f)
|}
["Revealed type [-1]: Revealed type for `f` is `typing.Callable[[str, Named(x, int)], int]`."];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable
TParams = ParameterSpecification("TParams")
class MyClass(Generic[TParams]):
def __call__(__self, *args: TParams.args, **kwargs: TParams.kwargs) -> bool: ...
IntStrParamSpec = MyClass[int, str]
def foo() -> None:
f: IntStrParamSpec
reveal_type(f)
f(1, "hello")
f("invalid")
|}
[
"Revealed type [-1]: Revealed type for `f` is `MyClass[[int, str]]`.";
"Missing argument [20]: Call `MyClass.__call__` expects argument in position 2.";
];
assert_type_errors
{|
from pyre_extensions import ParameterSpecification
from typing import TypeVar, Generic, Callable, Protocol
TParams = ParameterSpecification("TParams")
class PrependIntProtocol(Protocol[TParams]):
def __call__(__self, __f: int, *args: TParams.args, **kwargs: TParams.kwargs) -> int: ...
IntBoolStrParamSpec = PrependIntProtocol[bool, str]
def foo() -> None:
f: IntBoolStrParamSpec
reveal_type(f)
f(1, True, "hello")
f("invalid")
|}
[
"Revealed type [-1]: Revealed type for `f` is `PrependIntProtocol[[bool, str]]`.";
"Missing argument [20]: Call `PrependIntProtocol.__call__` expects argument in position 2.";
];
()
let test_duplicate_type_variables context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import TypeVar, Generic
T = TypeVar("T")
S = TypeVar("S")
class A(Generic[T, S, T]):
pass
|}
["Duplicate type variables [59]: Duplicate type variable `T` in Generic[...]."];
assert_type_errors
{|
from typing import TypeVar, Protocol
T = TypeVar("T")
class A(Protocol[T, T, T]):
pass
|}
["Duplicate type variables [59]: Duplicate type variable `T` in Protocol[...]."];
assert_type_errors
{|
from typing import Generic
from pyre_extensions import ParameterSpecification
P = ParameterSpecification("P")
class A(Generic[P, P]):
pass
|}
["Duplicate type variables [59]: Duplicate type variable `P` in Generic[...]."];
()
let test_generic_aliases context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import List
MyList = List[int]
x: MyList
reveal_type(x)
reveal_type(x[0])
|}
[
"Revealed type [-1]: Revealed type for `x` is `List[int]`.";
"Revealed type [-1]: Revealed type for `x[0]` is `int`.";
];
assert_type_errors
{|
from typing import Tuple, TypeVar
T = TypeVar("T")
Pair = Tuple[T, T]
x: Pair[str]
reveal_type(x)
reveal_type(x[0])
|}
[
"Revealed type [-1]: Revealed type for `x` is `Tuple[str, str]`.";
"Revealed type [-1]: Revealed type for `x[0]` is `str`.";
];
assert_type_errors
{|
from typing import TypeVar, Union
T = TypeVar("T")
UnionWithInt = Union[T, int]
x: UnionWithInt[str]
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `Union[int, str]`."];
assert_type_errors
{|
from typing import List, Tuple, TypeVar, Union
T = TypeVar("T")
Alias1 = Union[T, int]
Alias2 = Tuple[T, Alias1[T]]
Alias3 = List[Alias2[T]]
x: Alias3[str]
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `List[Tuple[str, Union[int, str]]]`."];
assert_type_errors
{|
from typing import *
T = TypeVar("T")
MyList1 = List[T]
MyList2 = MyList1[int]
MyList3 = MyList2
xs: MyList3[str]
reveal_type(xs)
|}
["Revealed type [-1]: Revealed type for `xs` is `typing.List[int]`."];
let sources_exporting_generic_classes =
[
{
Test.handle = "foo.py";
source =
{|
from typing import Generic, TypeVar
T= TypeVar("T")
class SomeGenericClass(Generic[T]): ...
|};
};
{
handle = "baz.py";
source =
{|
from typing import Dict, Generic, Iterable, Optional, Sequence, Union, TypeVar
from foo import SomeGenericClass
|};
};
]
in
assert_type_errors
~update_environment_with:sources_exporting_generic_classes
{|
from baz import *
from typing import List as MyList
reveal_type(Optional)
reveal_type(Union)
reveal_type(MyList)
reveal_type(Iterable)
reveal_type(SomeGenericClass)
|}
[
"Revealed type [-1]: Revealed type for `baz.Optional` is `typing.Type[typing.Optional]`.";
"Revealed type [-1]: Revealed type for `baz.Union` is `typing.Type[typing.Union]`.";
"Revealed type [-1]: Revealed type for `typing.List` is `typing.Type[list]`.";
"Revealed type [-1]: Revealed type for `baz.Iterable` is `typing.Type[typing.Iterable]`.";
"Revealed type [-1]: Revealed type for `baz.SomeGenericClass` is \
`typing.Type[foo.SomeGenericClass]`.";
];
assert_type_errors
~update_environment_with:sources_exporting_generic_classes
{|
from baz import *
from typing import List as MyList, TypeVar
z: MyList[int] = ["hello"]
z2: Iterable[int] = ["hello"]
z3: SomeGenericClass[int] = ["hello"]
|}
[
"Incompatible variable type [9]: z is declared to have type `MyList[int]` but is used as \
type `MyList[str]`.";
"Incompatible variable type [9]: z2 is declared to have type `Iterable[int]` but is used as \
type `Iterable[str]`.";
"Incompatible variable type [9]: z3 is declared to have type `SomeGenericClass[int]` but is \
used as type `MyList[str]`.";
];
assert_type_errors
~update_environment_with:sources_exporting_generic_classes
{|
from baz import *
x: Optional[Dict[str, int]]
reveal_type(x)
|}
["Revealed type [-1]: Revealed type for `x` is `typing.Optional[typing.Dict[str, int]]`."];
let sources_exporting_generic_classes =
[
{
Test.handle = "bar/baz.py";
source = {|
from typing import Callable
|};
};
]
in
assert_type_errors
~update_environment_with:sources_exporting_generic_classes
{|
from bar.baz import Callable
def foo() -> None:
reveal_type(Callable)
f: Callable[[int], str]
y = f(1)
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `bar.baz.Callable` is `typing.Type[typing.Callable]`.";
"Revealed type [-1]: Revealed type for `y` is `str`.";
];
assert_type_errors
{|
from typing import Callable
C = Callable
def foo() -> None:
f: C[[int], str]
reveal_type(f)
|}
[
"Invalid type parameters [24]: Generic type `Callable` expects 2 type parameters.";
"Revealed type [-1]: Revealed type for `f` is `typing.Callable[[int], str]`.";
];
assert_type_errors
{|
from typing import Callable, Iterable, Iterator, TypeVar
T = TypeVar("T")
Predicate = Callable[[T], int]
def dropwhile(predicate: Predicate[T], iterable: Iterable[T]) -> Iterator[T]: ...
def foo() -> None:
reveal_type(dropwhile)
|}
[
"Revealed type [-1]: Revealed type for `test.dropwhile` is \
`typing.Callable(dropwhile)[[Named(predicate, typing.Callable[[Variable[T]], int]), \
Named(iterable, Iterable[Variable[T]])], Iterator[Variable[T]]]`.";
];
Generic alias for a class respects variance .
assert_type_errors
{|
from typing import TypeVar, Iterable as MyIterable, List as MyList
T = TypeVar("T")
class Base: ...
class Child(Base): ...
xs: MyIterable[Child]
# No error, since Iterable is covariant.
ys: MyIterable[Base] = xs
xs: MyList[Child]
# Error because List is invariant.
ys: MyList[Base] = xs
|}
[
"Incompatible variable type [9]: ys is declared to have type `MyList[Base]` but is used as \
type `MyList[Child]`.";
];
Zero type parameters provided .
assert_type_errors
{|
from typing import Tuple, TypeVar
T = TypeVar("T")
Pair = Tuple[T, T]
y: Pair
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Tuple[typing.Any, typing.Any]`."];
assert_type_errors
{|
from typing import Tuple, TypeVar
T = TypeVar("T")
Pair = Tuple[T, T]
y: Pair[int, str]
reveal_type(y)
|}
[
"Invalid type variable [34]: The type variable `Variable[T]` can only be used to annotate \
generic classes or functions.";
"Revealed type [-1]: Revealed type for `y` is `typing.Any`.";
];
More than one free variable in the alias body .
assert_type_errors
{|
from typing import Tuple, TypeVar
T1 = TypeVar("T1")
T2 = TypeVar("T2")
Pair = Tuple[T1, T2]
y: Pair[int]
reveal_type(y)
y: Pair[int, str]
reveal_type(y)
|}
[
"Invalid type variable [34]: The type variable `Variable[T1]` can only be used to annotate \
generic classes or functions.";
"Invalid type variable [34]: The type variable `Variable[T2]` can only be used to annotate \
generic classes or functions.";
"Revealed type [-1]: Revealed type for `y` is `typing.Any`.";
"Revealed type [-1]: Revealed type for `y` is `Tuple[int, str]`.";
];
assert_type_errors
{|
from typing import Any, Tuple, TypeVar
T = TypeVar("T")
Pair = Tuple[str, int]
y: Pair
reveal_type(y)
y: Pair[str]
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[str, int]`.";
"Revealed type [-1]: Revealed type for `y` is `Tuple[str, int]`.";
];
TODO(T78935633 ): We should error on the naked and treat it as ] .
assert_type_errors
{|
from typing import *
T = TypeVar("T")
MyList = List[T]
def foo(x: T, y: MyList) -> MyList:
return y
foo(1, ['hello'])
foo('some', ['hello'])
reveal_type(foo(1, ['hello']))
|}
[
"Revealed type [-1]: Revealed type for `test.foo(1, [\"hello\"])` is \
`typing.List[typing.Any]`.";
];
assert_type_errors
{|
from typing import *
MyList = List
def foo(x: MyList) -> MyList: ...
reveal_type(foo)
reveal_type(foo(['hello']))
|}
[
"Invalid type parameters [24]: Generic type `list` expects 1 type parameter, use \
`typing.List[<element type>]` to avoid runtime subscripting errors.";
"Revealed type [-1]: Revealed type for `test.foo` is `typing.Callable(foo)[[Named(x, \
typing.List[typing.Any])], typing.List[typing.Any]]`.";
"Revealed type [-1]: Revealed type for `test.foo([\"hello\"])` is `typing.List[typing.Any]`.";
];
assert_type_errors
{|
from typing import List, Tuple, TypeVar, Union
T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")
Alias2Before3 = Tuple[T1, Union[T2, T3], T2]
Alias3Before2 = Tuple[T1, Union[T3, T2], T2]
x: Alias2Before3[int, str, bool]
reveal_type(x)
y: Alias3Before2[int, str, bool]
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `x` is `Tuple[int, Union[bool, str], str]`.";
"Revealed type [-1]: Revealed type for `y` is `Tuple[int, Union[bool, str], str]`.";
];
()
let test_recursive_aliases context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is `test.Tree (resolves to Union[Tuple[Tree, \
Tree], int])`.";
];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
some_int: int
x = some_int
tuple_int: Tuple[int, int]
x = tuple_int
tuple_tuple_int: Tuple[Tuple[int, int], int]
x = tuple_tuple_int
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
x = 1
x = (2, 3)
x = ((4, 5), (6, 7))
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
some_str: str
x = some_str
tuple_int_str: Tuple[int, str]
x = tuple_int_str
|}
[
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `str`.";
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `Tuple[int, str]`.";
];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
x: Tree
x = "hello"
x = (1, "hello")
x = ((2, 3), (4, "hello"))
|}
[
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `str`.";
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `Tuple[int, str]`.";
"Incompatible variable type [9]: x is declared to have type `test.Tree (resolves to \
Union[Tuple[Tree, Tree], int])` but is used as type `Tuple[Tuple[int, int], Tuple[int, \
str]]`.";
];
assert_type_errors
{|
from typing import Mapping, Union
StringDict = Union[str, Mapping[str, "StringDict"]]
valid: StringDict = {"hello": {"world": "from here"}}
contains_int: StringDict = {"hello": {"world": 1}}
|}
[
"Incompatible variable type [9]: contains_int is declared to have type `test.StringDict \
(resolves to Union[Mapping[str, StringDict], str])` but is used as type `Dict[str, \
Dict[str, int]]`.";
];
assert_type_errors
{|
from typing import List, Tuple
Tree = Tuple[str, List["Tree"]]
tree: Tree = ("foo", [])
tree2: Tree = ("foo", [("branch1", [("leaf1", [])]), ("leaf2", [])])
|}
[];
assert_type_errors
{|
from typing import List, Union
X = List["X"]
def foo() -> None:
x: X = [[], [[], []], []]
|}
[];
assert_type_errors
{|
from typing import Mapping, Union
StringMapping = Union[str, Mapping[str, "StringMapping"]]
d: Mapping[str, str]
d2: StringMapping = d
|}
[];
Incompatible because is invariant .
assert_type_errors
{|
from typing import Dict, Union
StringDict = Union[str, Dict[str, "StringDict"]]
d: Dict[str, str]
d2: StringDict = d
|}
[
"Incompatible variable type [9]: d2 is declared to have type `test.StringDict (resolves to \
Union[Dict[str, StringDict], str])` but is used as type `Dict[str, str]`.";
];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
Y = Union[int, Tuple[int, "Y"]]
x: X
y: Y = x
y2: Y
x2: X = y2
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
NotQuiteIsomorphicToX = Union[int, Tuple[str, "NotQuiteIsomorphicToX"]]
x: X
not_quite_isomorphic: NotQuiteIsomorphicToX = x
not_quite_isomorphic2: NotQuiteIsomorphicToX
x2: X = not_quite_isomorphic2
|}
[
"Incompatible variable type [9]: not_quite_isomorphic is declared to have type \
`test.NotQuiteIsomorphicToX (resolves to Union[Tuple[str, NotQuiteIsomorphicToX], int])` \
but is used as type `test.X (resolves to Union[Tuple[int, X], int])`.";
"Incompatible variable type [9]: x2 is declared to have type `test.X (resolves to \
Union[Tuple[int, X], int])` but is used as type `test.NotQuiteIsomorphicToX (resolves to \
Union[Tuple[str, NotQuiteIsomorphicToX], int])`.";
];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
unrolled: Tuple[int, X]
x: X = unrolled
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
unrolled: Tuple[int, X]
unrolled2: Tuple[int, X] = unrolled
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
unrolled_union: Union[int, Tuple[int, X]]
x: X = unrolled_union
x2: X
unrolled_union2: Union[int, Tuple[int, X]] = x2
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
x: X
unrolled_multiple_times: Union[int, Tuple[int, Union[int, Tuple[int, X]]]] = x
unrolled_multiple_times2: Union[int, Tuple[int, Union[int, Tuple[int, X]]]]
x2: X = unrolled_multiple_times2
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
unrolled_once: Union[int, Tuple[int, X]]
unrolled_multiple_times: Union[int, Tuple[int, Union[int, Tuple[int, X]]]]
unrolled_once = unrolled_multiple_times
unrolled_once2: Union[int, Tuple[int, X]]
unrolled_multiple_times2: Union[int, Tuple[int, Union[int, Tuple[int, X]]]]
unrolled_multiple_times2 = unrolled_once2
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
x: X
y: Union[int, Tuple[int, int]] = x
|}
[
"Incompatible variable type [9]: y is declared to have type `Union[Tuple[int, int], int]` \
but is used as type `test.X (resolves to Union[Tuple[int, X], int])`.";
];
Fixpoint should not blow up on a loop that constructs a recursive type .
assert_type_errors
{|
from typing import Tuple, Union
X = Union[int, Tuple[int, "X"]]
def foo(x: X, n: int) -> X:
result = x
for i in range(n):
result = (i, result)
reveal_type(result)
reveal_type(result)
return result
|}
[
"Revealed type [-1]: Revealed type for `result` is `Tuple[int, test.X (resolves to \
Union[Tuple[int, X], int])]`.";
"Revealed type [-1]: Revealed type for `result` is `test.X (resolves to Union[Tuple[int, X], \
int])`.";
];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
def foo(tree: Tree, some_bool: bool) -> Tree:
if some_bool:
x = 42
else:
x = (1, (2, tree))
return x
|}
[];
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
Unrolled = Union[int, Tuple[Union[int, Tuple["Unrolled", "Unrolled"]], "Unrolled"]]
def foo(some_bool: bool) -> Tree:
tree: Tree
unrolled_tree: Unrolled
if some_bool:
x = tree
else:
x = unrolled_tree
return x
|}
[];
Type.RecursiveType.Namespace.reset ();
assert_type_errors
{|
from typing import Tuple, Union
Tree = Union[int, Tuple["Tree", "Tree"]]
# str instead of int.
Wrong = Union[int, Tuple[Union[str, Tuple["Wrong", "Wrong"]], "Wrong"]]
def foo(some_bool: bool) -> Tree:
tree: Tree
wrong_unrolled_tree: Wrong
if some_bool:
x = tree
else:
x = wrong_unrolled_tree
return x
|}
[
"Incompatible return type [7]: Expected `test.Tree (resolves to Union[Tuple[Tree, Tree], \
int])` but got `$RecursiveType1 (resolves to Union[Tuple[Union[Tuple[$RecursiveType1, \
$RecursiveType1], str], $RecursiveType1], Tuple[$RecursiveType1, $RecursiveType1], int])`.";
];
assert_type_errors
{|
from typing import Final
from typing_extensions import Literal
x: Final[str] = "x"
y: Literal["y"] = "y"
reveal_type(x)
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `x` is `str` (inferred: \
`typing_extensions.Literal['x']`, final).";
"Revealed type [-1]: Revealed type for `y` is `typing_extensions.Literal['y']`.";
];
assert_type_errors
{|
x: str = "x"
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is `str` (inferred: \
`typing_extensions.Literal['x']`).";
];
assert_type_errors
{|
from typing_extensions import TypeAlias
MyInt = int
X: TypeAlias = "MyInt"
y: X
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `int`."];
assert_type_errors
{|
from typing import List, Union
X = List[Union[int, "X"]]
def foo() -> None:
x: X
y = x[0]
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Union[int, test.X (resolves to List[Union[X, \
int]])]`.";
];
assert_type_errors
{|
from typing import Dict, Union
D = Dict[str, Union[str, "D"]]
def foo(d: D) -> None:
y = d["hello"]
reveal_type(y)
if isinstance(y, str):
reveal_type(y)
else:
z = y["world"]
reveal_type(z)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Union[str, test.D (resolves to Dict[str, \
Union[D, str]])]`.";
"Revealed type [-1]: Revealed type for `y` is `str`.";
"Revealed type [-1]: Revealed type for `z` is `Union[str, test.D (resolves to Dict[str, \
Union[D, str]])]`.";
];
assert_type_errors
{|
from typing import Union
D = Union[int, "D"]
D2 = Union[int, "D2"]
def foo() -> None:
d: D
reveal_type(d)
d2: D2
d = d2
|}
[
"Missing global annotation [5]: Globally accessible variable `D` has no type specified.";
"Missing global annotation [5]: Globally accessible variable `D2` has no type specified.";
"Undefined or invalid type [11]: Annotation `D` is not defined as a type.";
"Revealed type [-1]: Revealed type for `d` is `typing.Any`.";
"Undefined or invalid type [11]: Annotation `D2` is not defined as a type.";
];
assert_type_errors
{|
from typing import List, Union
NestedList = List[Union[int, "NestedList"]]
def pass_spurious_parameter(x: NestedList[int]) -> None:
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is `test.NestedList (resolves to \
List[Union[NestedList, int]])`.";
];
assert_type_errors
{|
from typing import Tuple, TypeVar, Union
T = TypeVar("T")
GenericTree = Union[T, Tuple["GenericTree[T]", "GenericTree[T]"]]
def foo(x: GenericTree[int]) -> None:
reveal_type(x)
|}
[
"Missing global annotation [5]: Globally accessible variable `GenericTree` has no type \
specified.";
"Undefined or invalid type [11]: Annotation `GenericTree` is not defined as a type.";
"Revealed type [-1]: Revealed type for `x` is `unknown`.";
];
assert_type_errors
{|
from typing import List, Union
X = List["X"]
Y = Union[int, X]
def foo() -> None:
y: Y
y == y
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Union[int, test.X (resolves to List[X])]`."];
assert_type_errors
{|
from typing import List, Sequence, Union
class Foo: ...
X = Union[
Sequence["X"],
List["X"]
]
Y = Union[Foo, X]
def foo() -> None:
y: Y
y == y
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Union[Foo, test.X (resolves to Union[List[X], \
Sequence[X]])]`.";
];
assert_type_errors
{|
from typing import List, Sequence, Union
class Foo: ...
X = Union[
Sequence["X"],
List["X"]
]
Y = Union[Foo, X]
Z = List[Y]
def foo() -> None:
z: Z
reveal_type(z)
|}
[
"Revealed type [-1]: Revealed type for `z` is `List[Union[Foo, test.X (resolves to \
Union[List[X], Sequence[X]])]]`.";
];
()
let test_variadic_tuples context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def foo(x: Tuple[int, Unpack[Ts]]) -> Tuple[bool, Unpack[Ts]]: ...
def bar() -> None:
x: Tuple[int, str, bool]
y = foo(x)
reveal_type(y)
x2: Tuple[int]
y2 = foo(x2)
reveal_type(y2)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[bool, str, bool]`.";
"Revealed type [-1]: Revealed type for `y2` is `Tuple[bool]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def foo(x: Tuple[int, Unpack[Ts], str]) -> Tuple[bool, Unpack[Ts]]: ...
def bar() -> None:
x: Tuple[int]
foo(x)
|}
[
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`typing.Tuple[int, *test.Ts, str]` but got `Tuple[int]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def add_int(xs: Tuple[Unpack[Ts]]) -> Tuple[int, Unpack[Ts]]: ...
def remove_int(xs: Tuple[int, Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def generic_function(xs: Tuple[Unpack[Ts]]) -> None:
y = remove_int(add_int(xs))
reveal_type(y)
add_int(remove_int(xs))
|}
[
"Revealed type [-1]: Revealed type for `y` is `typing.Tuple[*test.Ts]`.";
"Incompatible parameter type [6]: In call `remove_int`, for 1st positional argument, \
expected `typing.Tuple[int, *test.Ts]` but got `typing.Tuple[*test.Ts]`.";
];
We should not infer Tuple[int|bool , str|bool ] for Ts . That would surprise most users who would
expect that the Ts was bound to at least one of the concrete types they specified .
expect that the Ts was bound to at least one of the concrete types they specified. *)
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def expects_same_tuples(x: Tuple[Unpack[Ts]], y: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def bar() -> None:
tuple1: Tuple[int, str]
tuple2: Tuple[bool, bool]
expects_same_tuples(tuple1, tuple2)
|}
[
"Incompatible parameter type [6]: In call `expects_same_tuples`, for 2nd positional \
argument, expected `typing.Tuple[*test.Ts]` but got `Tuple[bool, bool]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def expects_same_tuples(x: Tuple[Unpack[Ts]], y: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def bar() -> None:
tuple1: Tuple[int, str]
shorter_tuple: Tuple[bool]
expects_same_tuples(tuple1, shorter_tuple)
|}
[
"Incompatible parameter type [6]: In call `expects_same_tuples`, for 2nd positional \
argument, expected `typing.Tuple[*test.Ts]` but got `Tuple[bool]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def expects_same_tuples(x: Tuple[Unpack[Ts]], y: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def bar() -> None:
tuple1: Tuple[int, str]
shorter_tuple: Tuple[bool]
expects_same_tuples(tuple1, shorter_tuple)
|}
[
"Incompatible parameter type [6]: In call `expects_same_tuples`, for 2nd positional \
argument, expected `typing.Tuple[*test.Ts]` but got `Tuple[bool]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def add_int(xs: Tuple[Unpack[Tuple[str, ...]]]) -> Tuple[int, Unpack[Tuple[str, ...]]]: ...
def foo() -> None:
xs: Tuple[str, str]
y = add_int(xs)
reveal_type(y)
invalid: Tuple[int, str]
add_int(invalid)
|}
[
"Revealed type [-1]: Revealed type for `y` is `typing.Tuple[int, *Tuple[str, ...]]`.";
"Incompatible parameter type [6]: In call `add_int`, for 1st positional argument, expected \
`typing.Tuple[str, ...]` but got `Tuple[int, str]`.";
];
assert_type_errors
{|
from typing import Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def foo(xs: Tuple[Unpack[Ts]]) -> Tuple[Unpack[Ts]]: ...
def baz() -> None:
unbounded_tuple: Tuple[int, ...]
y = foo(unbounded_tuple)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `typing.Tuple[int, ...]`."];
assert_type_errors
{|
from typing import Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
def foo(xs: Tuple[T, Unpack[Tuple[str, ...]]]) -> T: ...
def baz() -> None:
some_tuple: Tuple[int, str, str]
y = foo(some_tuple)
reveal_type(y)
invalid_tuple: Tuple[int, str, int]
foo(invalid_tuple)
|}
[
"Revealed type [-1]: Revealed type for `y` is `int`.";
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`typing.Tuple[Variable[T], *Tuple[str, ...]]` but got `Tuple[int, str, int]`.";
];
assert_type_errors
{|
from typing import Any, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
N = TypeVar("N", bound=int)
def foo(x: Tuple[N, Unpack[Ts]]) -> Tuple[Unpack[Ts], N]: ...
def bar() -> None:
x: Tuple[Any, ...]
y = foo(x)
reveal_type(y)
x2: Tuple[int, ...]
y2 = foo(x2)
reveal_type(y2)
|}
[
"Prohibited any [33]: Explicit annotation for `x` cannot contain `Any`.";
"Revealed type [-1]: Revealed type for `y` is `typing.Tuple[*Tuple[typing.Any, ...], \
typing.Any]`.";
"Revealed type [-1]: Revealed type for `y2` is `typing.Tuple[*Tuple[int, ...], int]`.";
];
assert_type_errors
{|
from typing import Any, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
N = TypeVar("N", bound=int)
def foo(x: Tuple[N, Unpack[Ts]]) -> Tuple[Unpack[Ts], N]: ...
def bar() -> None:
x_error: Tuple[str, ...]
y_error = foo(x_error)
reveal_type(y_error)
|}
[
"Incomplete type [37]: Type `typing.Tuple[*test.Ts, Variable[N (bound to int)]]` inferred \
for `y_error` is incomplete, add an explicit annotation.";
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`typing.Tuple[Variable[N (bound to int)], *test.Ts]` but got `typing.Tuple[str, ...]`.";
"Revealed type [-1]: Revealed type for `y_error` is `typing.Tuple[*Tuple[typing.Any, ...], \
typing.Any]`.";
];
assert_type_errors
{|
from typing import Any, Tuple, TypeVar
N = TypeVar("N", bound=int)
def foo(x: Tuple[N]) -> Tuple[N]: ...
def bar() -> None:
x: Tuple[int, ...]
y = foo(x)
reveal_type(y)
x_error: Tuple[str, ...]
foo(x_error)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[int]`.";
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`Tuple[Variable[N (bound to int)]]` but got `typing.Tuple[str, ...]`.";
];
()
let test_variadic_classes context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Generic
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]): ...
def add_bool(x: Tensor[int, Unpack[Ts], str]) -> Tensor[bool, Unpack[Ts]]: ...
def foo() -> None:
x: Tensor[int, bool, str]
y = add_bool(x)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Tensor[bool, bool]`."];
Expect the same Tensor type for both parameters . We do n't infer ` Ts = Tuple[int | bool , str |
bool ] ` even though it is sound , because it is unintuitive .
bool]` even though it is sound, because it is unintuitive. *)
assert_type_errors
{|
from typing import Generic
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]): ...
def expects_same_tensors(x: Tensor[Unpack[Ts]], y: Tensor[Unpack[Ts]]) -> Tensor[Unpack[Ts]]: ...
def bar() -> None:
tensor: Tensor[int, str]
tensor2: Tensor[bool, bool]
y = expects_same_tensors(tensor, tensor2)
reveal_type(y)
|}
[
"Incompatible parameter type [6]: In call `expects_same_tensors`, for 2nd positional \
argument, expected `Tensor[*test.Ts]` but got `Tensor[bool, bool]`.";
"Revealed type [-1]: Revealed type for `y` is `Tensor[int, str]`.";
];
assert_type_errors
{|
from typing import Generic
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]): ...
def expects_same_length(xs: Tensor[Unpack[Ts]], ys: Tensor[Unpack[Ts]]) -> Tensor[Unpack[Ts]]: ...
def bar() -> None:
xs: Tensor[int, str]
ys: Tensor[bool]
expects_same_length(xs, ys)
|}
[
"Incompatible parameter type [6]: In call `expects_same_length`, for 2nd positional \
argument, expected `Tensor[*test.Ts]` but got `Tensor[bool]`.";
];
assert_type_errors
{|
from typing import Generic, List, Protocol, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
class Base: ...
class Child(Base): ...
def foo(x: Tensor[float, Base, Base]) -> None: ...
def bar() -> None:
child: Tensor[float, Child, Child]
foo(child)
int_tensor: Tensor[int, Base, Base]
foo(int_tensor)
|}
[
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`Tensor[float, Base, Base]` but got `Tensor[int, Base, Base]`.";
];
assert_type_errors
{|
from typing import Generic, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
Ts = TypeVarTuple("Ts")
Tin = TypeVar("Tin")
Tout = TypeVar("Tout")
class Tensor(Generic[Unpack[Ts]]): ...
class Linear(Generic[Tin, Tout]):
"""Transform the last dimension from Tin to Tout."""
def __init__(self, in_dimension: Tin, out_dimension: Tout) -> None:
self.in_dimension = in_dimension
self.out_dimension = out_dimension
def __call__(self, x: Tensor[Unpack[Ts], Tin]) -> Tensor[Unpack[Ts], Tout]: ...
def bar() -> None:
x: Tensor[L[10], L[20]]
layer1 = Linear(20, 30)
layer2 = Linear(30, 40)
layer3 = Linear(40, 50)
y = layer3(layer2(layer1(x)))
reveal_type(y)
shape_mismatch = (10, 21)
layer1(shape_mismatch)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tensor[typing_extensions.Literal[10], \
typing_extensions.Literal[50]]`.";
"Incompatible parameter type [6]: In call `Linear.__call__`, for 1st positional argument, \
expected `Tensor[*test.Ts, typing_extensions.Literal[20]]` but got \
`Tuple[typing_extensions.Literal[10], typing_extensions.Literal[21]]`.";
];
assert_type_errors
{|
from typing import Generic
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]):
def some_method(self, x: Tensor[Unpack[Ts]]) -> None: ...
def bar() -> None:
xs: Tensor[int, str]
xs.some_method(xs)
|}
[];
assert_type_errors
{|
from typing import Generic, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
def bar() -> None:
x = Tensor.__getitem__
reveal_type(x)
|}
[
"Revealed type [-1]: Revealed type for `x` is \
`BoundMethod[typing.Callable(typing.GenericMeta.__getitem__)[[Named(self, unknown), \
typing.Tuple[typing.Type[Variable[T]], typing.Any]], typing.Type[Tensor[Variable[T], \
typing.Any]]], typing.Type[Tensor]]`.";
];
assert_type_errors
{|
from typing import Generic, List, Protocol, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class VariadicProtocol(Protocol[T, Unpack[Ts]]):
def foo(self, x: Tuple[T, Unpack[Ts]]) -> None: ...
class Tensor(Generic[Unpack[Ts]]):
"""This implements VariadicProtocol with T = List[int] and Ts = Tuple[Unpack[Ts]]."""
def foo(self, x: Tuple[List[int], Unpack[Ts]]) -> None:...
def accepts_variadic_protocol(x: VariadicProtocol[T, Unpack[Ts]]) -> VariadicProtocol[T, Unpack[Ts]]: ...
def bar() -> None:
x: Tensor[int, str]
y = accepts_variadic_protocol(x)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `VariadicProtocol[List[int], int, str]`."];
TODO(T84553937 ): While Tensor is indeed invariant , we should have inferred ` Tensor[int , Base ,
Base ] ` below .
Base]` below. *)
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]):
def __init__(self, default: T, shape: Tuple[Unpack[Ts]]) -> None: ...
class Base: ...
class Child(Base): ...
def expects_base(t: Tensor[int, Base, Base]) -> None: ...
def bar() -> None:
expects_base(Tensor(1, (Child(), Child())))
|}
[
"Incompatible parameter type [6]: In call `expects_base`, for 1st positional argument, \
expected `Tensor[int, Base, Base]` but got `Tensor[int, Child, Child]`.";
];
assert_type_errors
{|
from typing import Generic, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
FloatTensor = Tensor[float, Unpack[Ts]]
def bar() -> None:
x: FloatTensor[L[10], L[20]]
reveal_type(x)
y: FloatTensor
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `x` is `Tensor[float, typing_extensions.Literal[10], \
typing_extensions.Literal[20]]`.";
"Revealed type [-1]: Revealed type for `y` is `Tensor[float, *Tuple[typing.Any, ...]]`.";
];
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
def get_last_type(t: Tensor[float, Unpack[Tuple[int, ...]], T]) -> T: ...
def bar() -> None:
x: Tensor[float, L[10], L[20]]
y = get_last_type(x)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `typing_extensions.Literal[20]`."];
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
# pyre-ignore[24]: Generic type `Tensor` expects at least 1 type parameter.
def accept_arbitrary_tensor(t: Tensor) -> Tensor: ...
def bar() -> None:
x: Tensor[float, L[10], L[20]]
y = accept_arbitrary_tensor(x)
reveal_type(y)
# pyre-ignore[24]: Generic type `Tensor` expects at least 1 type parameter.
no_parameters: Tensor
accept_arbitrary_tensor(no_parameters)
|}
["Revealed type [-1]: Revealed type for `y` is `Tensor[typing.Any, *Tuple[typing.Any, ...]]`."];
assert_type_errors
{|
from typing import Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[T, Unpack[Ts]]): ...
def strip_last(x: Tensor[int, Unpack[Ts], int]) -> Tensor[int, Unpack[Ts]]: ...
def bar() -> None:
invalid: Tensor[int, L[10], str]
y = strip_last(invalid)
reveal_type(y)
|}
[
"Incomplete type [37]: Type `Tensor[int, *test.Ts]` inferred for `y` is incomplete, add an \
explicit annotation.";
"Incompatible parameter type [6]: In call `strip_last`, for 1st positional argument, \
expected `Tensor[int, *test.Ts, int]` but got `Tensor[int, int, str]`.";
"Revealed type [-1]: Revealed type for `y` is `Tensor[int, *Tuple[typing.Any, ...]]`.";
];
assert_type_errors
{|
from typing import Callable, Generic, Tuple, TypeVar
from pyre_extensions import ParameterSpecification, TypeVarTuple, Unpack
from typing_extensions import Literal as L
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
TParams = ParameterSpecification("TParams")
class Tensor(Generic[T, TParams, Unpack[Ts]]):
def __init__(self, f: Callable[TParams, T], shape: Tuple[Unpack[Ts]]) -> None:
self.f = f
self.shape = shape
def bar() -> None:
tensor: Tensor[float, [int, str], int, str]
y = tensor.f( *tensor.shape)
reveal_type(y)
tensor.f("wrong argument")
|}
[
"Revealed type [-1]: Revealed type for `y` is `float`.";
"Missing argument [20]: PositionalOnly call expects argument in position 1.";
];
()
let test_variadic_callables context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing import Callable, Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def make_tuple(leave_this_out: int, *args: Unpack[Ts], message: str) -> Tuple[Unpack[Ts], bool]: ...
def foo() -> None:
y = make_tuple(1, 2, 3, message="hello")
reveal_type(y)
y2 = make_tuple(1, message="hello")
reveal_type(y2)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[typing_extensions.Literal[2], \
typing_extensions.Literal[3], bool]`.";
"Revealed type [-1]: Revealed type for `y2` is `Tuple[bool]`.";
];
assert_type_errors
{|
from typing import Callable, Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def make_tuple(leave_this_out: int, *args: Unpack[Tuple[int, Unpack[Ts], str]], message: str) -> Tuple[int, Unpack[Ts], str]:
return args
def foo() -> None:
y = make_tuple(1, 2, 3, "has to end with a string", message="hello")
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[int, typing_extensions.Literal[3], str]`.";
];
Unpack an unbounded tuple .
assert_type_errors
{|
from typing import Callable, Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def make_tuple( *args: Unpack[Tuple[int, Unpack[Ts], str]]) -> None: ...
def foo(x: Tuple[Unpack[Ts]]) -> None:
unbounded_tuple: Tuple[int, ...]
make_tuple(1, *unbounded_tuple, "foo")
make_tuple( *unbounded_tuple, "foo")
unbounded_str_tuple: Tuple[str, ...]
make_tuple( *unbounded_str_tuple, "foo")
|}
[
"Invalid argument [32]: Argument types `*Tuple[str, ...], typing_extensions.Literal['foo']` \
are not compatible with expected variadic elements `int, *test.Ts, str`.";
];
assert_type_errors
{|
from typing import Callable, Tuple
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def make_tuple( *args: Unpack[Tuple[int, Unpack[Ts], str]]) -> None: ...
def foo(x: Tuple[Unpack[Ts]]) -> None:
make_tuple(1, 2)
make_tuple(1, *x, *x, "foo")
|}
[
"Invalid argument [32]: Argument types `typing_extensions.Literal[1], \
typing_extensions.Literal[2]` are not compatible with expected variadic elements `int, \
*test.Ts, str`.";
"Invalid argument [32]: Variadic type variable `int, *test.Ts, str` cannot be made to \
contain `typing_extensions.Literal[1], *test.Ts, *test.Ts, \
typing_extensions.Literal['foo']`; concatenation of multiple variadic type variables is not \
yet implemented.";
];
assert_type_errors
{|
from typing import Callable, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def strip_int_parameter(f: Callable[[int, Unpack[Ts]], None]) -> Callable[[Unpack[Ts]], None]: ...
def foo(x: int, y: str, z: bool) -> None: ...
def baz() -> None:
f = strip_int_parameter(foo)
reveal_type(f)
# Valid
f("hello", True)
# Error
f("hello")
|}
[
"Revealed type [-1]: Revealed type for `f` is `typing.Callable[[str, bool], None]`.";
"Missing argument [20]: PositionalOnly call expects argument in position 1.";
];
assert_type_errors
{|
from typing import Callable, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
def strip_int_parameter(f: Callable[[int, Unpack[Ts]], None]) -> Callable[[Unpack[Ts]], None]: ...
def no_leading_int(y: str, z: bool) -> None: ...
def foo() -> None:
strip_int_parameter(no_leading_int)
|}
[
"Incompatible parameter type [6]: In call `strip_int_parameter`, for 1st positional \
argument, expected `typing.Callable[[Variable(int, *test.Ts)], None]` but got \
`typing.Callable(no_leading_int)[[Named(y, str), Named(z, bool)], None]`.";
];
assert_type_errors
{|
from typing import Callable, Generic, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
class Tensor(Generic[Unpack[Ts]]):
def some_method(self, *args: Unpack[Ts]) -> Tuple[Unpack[Ts]]: ...
def bar() -> None:
x: Tensor[int, str]
y = x.some_method(1, "hello")
reveal_type(y)
x.some_method("invalid")
|}
[
"Revealed type [-1]: Revealed type for `y` is `Tuple[int, str]`.";
"Missing argument [20]: Call `Tensor.some_method` expects argument in position 2.";
];
assert_type_errors
{|
from typing import Callable, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
T = TypeVar("T")
def apply(f: Callable[[Unpack[Ts]], T], *args: Unpack[Ts]) -> T: ...
def foo(x: int, y: str, z: bool) -> str: ...
def bar(a: int, b: str, c: bool) -> None:
y = apply(foo, a, b, c)
reveal_type(y)
apply(foo, a, b)
|}
[
"Revealed type [-1]: Revealed type for `y` is `str`.";
"Invalid argument [32]: Argument types `int, str` are not compatible with expected variadic \
elements `*test.Ts`.";
];
assert_type_errors
{|
from typing import Callable, Tuple, TypeVar
from pyre_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple("Ts")
T = TypeVar("T")
def apply(f: Callable[[Unpack[Ts]], T], *args: Unpack[Ts]) -> T: ...
class Base: ...
class Child(Base): ...
def expects_base(x: int, y: str, z: Base) -> str: ...
def expects_child(x: int, y: str, z: Child) -> str: ...
def bar() -> None:
child: Child
apply(expects_base, 1, "hello", child)
base: Base
apply(expects_child, 1, "hello", base)
|}
[
"Invalid argument [32]: Argument types `typing_extensions.Literal[1], \
typing_extensions.Literal['hello'], test.Base` are not compatible with expected variadic \
elements `*test.Ts`.";
];
()
let test_self_type context =
let assert_type_errors = assert_type_errors ~context in
assert_type_errors
{|
from typing_extensions import Self
class Shape:
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
def set_scale(self, scale: float) -> Self:
reveal_type(self)
self.scale = scale
return self
class Circle(Shape):
def __init__(self, scale: float = 0.0, radius: float = 0.0) -> None:
super(Circle, self).__init__(scale)
self.radius = radius
def set_radius(self, radius: float) -> Self:
self.radius = radius
return self
def foo() -> None:
circle: Circle
y = circle.set_scale(0.5).set_radius(2.7)
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_Shape__ (bound to \
Shape)]`.";
"Revealed type [-1]: Revealed type for `y` is `Circle`.";
];
assert_type_errors
{|
from typing_extensions import Self
from typing import Protocol
class ShapeProtocol(Protocol):
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
def set_scale(self, scale: float) -> Self:
reveal_type(self)
self.scale = scale
return self
class CircleProtocol(ShapeProtocol, Protocol):
def __init__(self, scale: float = 0.0, radius: float = 0.0) -> None:
super(CircleProtocol, self).__init__(scale)
self.radius = radius
def set_radius(self, radius: float) -> Self:
self.radius = radius
return self
def foo() -> None:
circle: CircleProtocol
y = circle.set_scale(0.5).set_radius(2.7)
reveal_type(y)
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_ShapeProtocol__ (bound \
to ShapeProtocol)]`.";
"Revealed type [-1]: Revealed type for `y` is `CircleProtocol`.";
];
assert_type_errors
{|
from typing_extensions import Self
from typing import Protocol
class ShapeProtocol(Protocol):
def set_scale(self, scale: float) -> Self: ...
class ReturnSelf:
scale: float = 1.0
def set_scale(self, scale: float) -> Self:
self.scale = scale
return self
class ReturnConcreteShape:
scale: float = 1.0
def set_scale(self, scale: float) -> ReturnConcreteShape:
self.scale = scale
return self
class BadReturnType:
scale: float = 1.0
def set_scale(self, scale: float) -> int:
self.scale = scale
return 42
def foo(shape: ShapeProtocol) -> None:
y = shape.set_scale(0.5)
reveal_type(y)
def main() -> None:
return_self_shape: ReturnSelf
return_concrete_shape: ReturnConcreteShape
bad_return_type: BadReturnType
foo(return_self_shape)
foo(return_concrete_shape)
foo(bad_return_type)
|}
[
"Revealed type [-1]: Revealed type for `y` is `ShapeProtocol`.";
"Incompatible parameter type [6]: In call `foo`, for 1st positional argument, expected \
`ShapeProtocol` but got `BadReturnType`.";
];
assert_type_errors
{|
from typing_extensions import Self
class Shape:
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
def set_scale(self, scale: float) -> Self:
self.scale = scale
return self
class Circle(Shape):
def set_scale(self, scale: float) -> Self:
self.scale = scale + 1.0
return self
class CircleArc(Circle):
def set_scale(self, scale: float) -> Self:
self.scale = scale * 3.14
return self
|}
[];
assert_type_errors
{|
from typing_extensions import Self
class Shape:
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
@classmethod
def with_scale(cls, scale: float) -> Self:
return cls(scale)
class Circle(Shape):
@classmethod
def with_scale(cls, scale: float) -> Self:
return cls(scale + 1.0)
class CircleArc(Circle):
@classmethod
def with_scale(cls, scale: float) -> Self:
return cls(scale * 3.14)
|}
[];
Generic class .
assert_type_errors
{|
from typing_extensions import Self
from typing import Generic, TypeVar
T = TypeVar("T")
class Container(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def set_value(self, value: T) -> Self:
reveal_type(self)
self.value = value
return self
class ChildContainer(Container[T]): ...
class ConcreteContainer(ChildContainer[int]): ...
def foo() -> None:
child: ChildContainer[str]
y = child.set_value("hello")
reveal_type(y)
child.set_value(42)
concrete: ConcreteContainer
y2 = concrete.set_value(42)
reveal_type(y2)
concrete.set_value("bad")
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_Container__ (bound to \
Container[typing.Any])]`.";
"Revealed type [-1]: Revealed type for `y` is `ChildContainer[str]`.";
"Incompatible parameter type [6]: In call `Container.set_value`, for 1st positional \
argument, expected `str` but got `int`.";
"Revealed type [-1]: Revealed type for `y2` is `ConcreteContainer`.";
"Incompatible parameter type [6]: In call `Container.set_value`, for 1st positional \
argument, expected `int` but got `str`.";
];
assert_type_errors
{|
from typing_extensions import Self
class Outer:
class Shape:
def __init__(self, scale: float = 0.0) -> None:
self.scale = scale
def set_scale(self, scale: float) -> Self:
self.scale = scale
return self
class Circle(Shape): ...
def foo() -> None:
circle: Outer.Circle
y = circle.set_scale(0.5)
reveal_type(y)
|}
["Revealed type [-1]: Revealed type for `y` is `Outer.Circle`."];
assert_type_errors
{|
from typing_extensions import Self
class Shape:
def __init__(self, scale: float) -> None: ...
@classmethod
def from_config(cls, config: dict[str, float]) -> Self:
reveal_type(cls)
return cls(config["scale"])
class Circle(Shape): ...
def foo() -> None:
circle = Circle.from_config({"scale": 7.0})
reveal_type(circle)
|}
[
"Revealed type [-1]: Revealed type for `cls` is `typing.Type[Variable[_Self_test_Shape__ \
(bound to Shape)]]`.";
"Revealed type [-1]: Revealed type for `circle` is `Circle`.";
];
assert_type_errors
{|
from typing_extensions import Self
class IsMergeable:
def can_merge(self, other: Self) -> bool:
reveal_type(self)
reveal_type(other)
return True
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_IsMergeable__ (bound \
to IsMergeable)]`.";
"Revealed type [-1]: Revealed type for `other` is `Variable[_Self_test_IsMergeable__ (bound \
to IsMergeable)]`.";
];
assert_type_errors
{|
from typing_extensions import Self
class Merger:
def merge(self, other: Self) -> Self:
reveal_type(self)
reveal_type(other)
return self
class ChildMerger(Merger):
pass
class BadOverriddenMerger(Merger):
def merge(self, other: Self) -> Self:
return self
class GoodOverriddenMerger(Merger):
def merge(self, other: Merger) -> Self:
return self
Merger().merge(Merger())
ChildMerger().merge(ChildMerger())
ChildMerger().merge(123)
Merger().merge(123)
# Classes do NOT need to match exactly, parent/children are allowed:
ChildMerger().merge(Merger())
Merger().merge(ChildMerger())
|}
[
"Revealed type [-1]: Revealed type for `self` is `Variable[_Self_test_Merger__ (bound to \
Merger)]`.";
"Revealed type [-1]: Revealed type for `other` is `Variable[_Self_test_Merger__ (bound to \
Merger)]`.";
"Inconsistent override [14]: `test.BadOverriddenMerger.merge` overrides method defined in \
`Merger` inconsistently. Parameter of type `Variable[_Self_test_BadOverriddenMerger__ \
(bound to BadOverriddenMerger)]` is not a supertype of the overridden parameter \
`Variable[_Self_test_Merger__ (bound to Merger)]`.";
"Incompatible parameter type [6]: In call `Merger.merge`, for 1st positional argument, \
expected `Variable[_Self_test_Merger__ (bound to Merger)]` but got `int`.";
"Incompatible parameter type [6]: In call `Merger.merge`, for 1st positional argument, \
expected `Variable[_Self_test_Merger__ (bound to Merger)]` but got `int`.";
];
()
let () =
"typeVariable"
>::: [
"check_bounded_variables" >:: test_check_bounded_variables;
"check_unbounded_variables" >:: test_check_unbounded_variables;
"check_variable_bindings" >:: test_check_variable_bindings;
"unbound_variables" >:: test_unbound_variables;
"distinguish" >:: test_distinguish;
"integer_variables" >:: test_integer_variables;
"nested_variable_error" >:: test_nested_variable_error;
"single_explicit_error" >:: test_single_explicit_error;
"callable_parameter_variadics" >:: test_callable_parameter_variadics;
"user_defined_parameter_variadics" >:: test_user_defined_parameter_specification_classes;
"duplicate_type_variables" >:: test_duplicate_type_variables;
"generic_aliases" >:: test_generic_aliases;
"recursive_aliases" >:: test_recursive_aliases;
"variadic_tuples" >:: test_variadic_tuples;
"variadic_classes" >:: test_variadic_classes;
"variadic_callables" >:: test_variadic_callables;
"self_type" >:: test_self_type;
]
|> Test.run
|
f698bd28715e58228f09487a706c421c063eb46bdb7c4f13ba00997568946057 | janestreet/memtrace_viewer_with_deps | ascii_table_kernel.ml | open! Core_kernel
open! Import
include Ascii_table_kernel_intf
module Align = Column.Align
module Attr = Attr
module Column = Column
module Table_char = Table_char
module Display = struct
type t = Grid.Display.t =
| Short_box
| Tall_box
| Line
| Blank
| Column_titles
[@@deriving compare, sexp_of]
let short_box = Short_box
let tall_box = Tall_box
let line = Line
let blank = Blank
let column_titles = Column_titles
end
module Screen = struct
(* [Screen] is mostly private stuff, so we explicitly export the public bits instead of
saying [Private] everywhere. *)
type t = Screen.t
let render = Screen.render
let to_string = Screen.to_string
end
let draw
?(display = Display.short_box)
?(spacing = 1)
?(limit_width_to = 90)
?(header_attr = [])
?(display_empty_rows = false)
cols
data
=
match cols with
| [] -> None
| _ :: _ ->
Some
(Grid.create
~spacing
~display
~max_width:limit_width_to
~header_attr
cols
data
~display_empty_rows
|> Grid.to_screen)
;;
module Private = struct
module Text = Text
end
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/textutils/ascii_table/kernel/ascii_table_kernel.ml | ocaml | [Screen] is mostly private stuff, so we explicitly export the public bits instead of
saying [Private] everywhere. | open! Core_kernel
open! Import
include Ascii_table_kernel_intf
module Align = Column.Align
module Attr = Attr
module Column = Column
module Table_char = Table_char
module Display = struct
type t = Grid.Display.t =
| Short_box
| Tall_box
| Line
| Blank
| Column_titles
[@@deriving compare, sexp_of]
let short_box = Short_box
let tall_box = Tall_box
let line = Line
let blank = Blank
let column_titles = Column_titles
end
module Screen = struct
type t = Screen.t
let render = Screen.render
let to_string = Screen.to_string
end
let draw
?(display = Display.short_box)
?(spacing = 1)
?(limit_width_to = 90)
?(header_attr = [])
?(display_empty_rows = false)
cols
data
=
match cols with
| [] -> None
| _ :: _ ->
Some
(Grid.create
~spacing
~display
~max_width:limit_width_to
~header_attr
cols
data
~display_empty_rows
|> Grid.to_screen)
;;
module Private = struct
module Text = Text
end
|
6d4c21edec4a347b9186678e9407018673eade12e80456806e0e97c7ca423039 | tolitius/mount | printing.cljc | (ns mount.test.printing
(:require
#?@(:cljs [[cljs.test :as t :refer-macros [is are deftest testing use-fixtures]]
[mount.core :as mount :refer-macros [defstate]]]
:clj [[clojure.test :as t :refer [is are deftest testing use-fixtures]]
[mount.core :as mount :refer [defstate]]])))
#?(:clj (alter-meta! *ns* assoc ::load false))
(defstate foo
:start (do (println "Starting!") 42))
(deftest test-printing-has-no-side-effects
;; Test that printing an unstarted DerefableState does not have the
;; side-effect of starting it
(println foo)
(is (not= 42 foo)))
| null | https://raw.githubusercontent.com/tolitius/mount/c85da6149ceab96c903c1574106ec56f78338b5f/test/core/mount/test/printing.cljc | clojure | Test that printing an unstarted DerefableState does not have the
side-effect of starting it | (ns mount.test.printing
(:require
#?@(:cljs [[cljs.test :as t :refer-macros [is are deftest testing use-fixtures]]
[mount.core :as mount :refer-macros [defstate]]]
:clj [[clojure.test :as t :refer [is are deftest testing use-fixtures]]
[mount.core :as mount :refer [defstate]]])))
#?(:clj (alter-meta! *ns* assoc ::load false))
(defstate foo
:start (do (println "Starting!") 42))
(deftest test-printing-has-no-side-effects
(println foo)
(is (not= 42 foo)))
|
cb669dda9868f3b6ff8b0c74ec0aa0ab08636736a69045c0f9aee77260c5601c | rescript-lang/rescript-compiler | lam_compile_external_call.ml | Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P.
* Copyright ( C ) 2017 - , Authors of ReScript
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2017 - Hongbo Zhang, Authors of ReScript
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
[@@@warning "+9"]
module E = Js_exp_make
let splice_apply fn args =
E.runtime_call Js_runtime_modules.caml_splice_call "spliceApply"
[ fn; E.array Immutable args ]
let splice_new_apply fn args =
E.runtime_call Js_runtime_modules.caml_splice_call "spliceNewApply"
[ fn; E.array Immutable args ]
let splice_obj_apply obj name args =
E.runtime_call Js_runtime_modules.caml_splice_call "spliceObjApply"
[ obj; E.str name; E.array Immutable args ]
(**
[bind_name] is a hint to the compiler to generate
better names for external module
*)
let handle_external
( { bundle ; module_bind_name } : External_ffi_types.external_module_name )
: Ident.t * string
=
Lam_compile_env.add_js_module module_bind_name bundle ,
bundle
({bundle ; module_bind_name} : External_ffi_types.external_module_name)
: Ident.t * string
=
Lam_compile_env.add_js_module module_bind_name bundle ,
bundle *)
let external_var
({ bundle; module_bind_name } : External_ffi_types.external_module_name) =
let id = Lam_compile_env.add_js_module module_bind_name bundle false in
E.external_var id ~external_name:bundle
let ( module_name : External_ffi_types.external_module_name option )
: ( Ident.t * string ) option =
match module_name with
| Some module_name - > Some ( handle_external module_name )
| None - > None
(module_name : External_ffi_types.external_module_name option)
: (Ident.t * string) option =
match module_name with
| Some module_name -> Some (handle_external module_name)
| None -> None
*)
type arg_expression = Js_of_lam_variant.arg_expression =
| Splice0
| Splice1 of E.t
| Splice2 of E.t * E.t
let append_list x xs =
match x with
| Splice0 -> xs
| Splice1 a -> a :: xs
| Splice2 (a, b) -> a :: b :: xs
The first return value is value , the second argument is side effect expressions
Only the [ unit ] with no label will be ignored
When we are passing a boxed value to external(optional ) , we need
unbox it in the first place .
Note when optional value is not passed , the unboxed value would be
[ undefined ] , with the combination of ` [ @int ] ` it would be still be
[ undefined ] , this by default is still correct ..
{ [
( function ( ) {
switch ( undefined ) {
case 97 :
return " a " ;
case 98 :
return " b " ;
}
} ( ) ) = = = undefined
] }
This would not work with [ NonNullString ]
Only the [unit] with no label will be ignored
When we are passing a boxed value to external(optional), we need
unbox it in the first place.
Note when optional value is not passed, the unboxed value would be
[undefined], with the combination of `[@int]` it would be still be
[undefined], this by default is still correct..
{[
(function () {
switch (undefined) {
case 97 :
return "a";
case 98 :
return "b";
}
}()) === undefined
]}
This would not work with [NonNullString]
*)
let ocaml_to_js_eff ~(arg_label : External_arg_spec.label_noname)
~(arg_type : External_arg_spec.attr) (raw_arg : E.t) :
arg_expression * E.t list =
let arg =
match arg_label with
| Arg_optional ->
Js_of_lam_option.get_default_undefined_from_optional raw_arg
| Arg_label | Arg_empty -> raw_arg
in
match arg_type with
| Arg_cst _ -> assert false
| Fn_uncurry_arity _ -> assert false
has to be preprocessed by { ! } module first
| Extern_unit ->
( (if arg_label = Arg_empty then Splice0 else Splice1 E.unit),
if Js_analyzer.no_side_effect_expression arg then [] else [ arg ] )
(* leave up later to decide *)
| Ignore ->
( Splice0,
if Js_analyzer.no_side_effect_expression arg then [] else [ arg ] )
| Poly_var_string { descr } -> (Splice1 (Js_of_lam_variant.eval arg descr), [])
| Poly_var { descr } -> (Js_of_lam_variant.eval_as_event arg descr, [])
(* FIXME: encode invariant below in the signature*)
length of 2
- the poly var tag
- the value
- the poly var tag
- the value
*)
| Int dispatches ->
(Splice1 (Js_of_lam_variant.eval_as_int arg dispatches), [])
| Unwrap ->
let single_arg =
match arg_label with
| Arg_optional ->
If this is an optional arg ( like ` ? arg ` ) , we have to potentially do
2 levels of unwrapping :
- if ocaml arg is ` None ` , let js arg be ` undefined ` ( no unwrapping )
- if ocaml arg is ` Some x ` , unwrap the arg to get the ` x ` , then
unwrap the ` x ` itself
- Here ` Some x ` is ` x ` due to the current encoding
Lets inline here since it depends on the runtime encoding
If this is an optional arg (like `?arg`), we have to potentially do
2 levels of unwrapping:
- if ocaml arg is `None`, let js arg be `undefined` (no unwrapping)
- if ocaml arg is `Some x`, unwrap the arg to get the `x`, then
unwrap the `x` itself
- Here `Some x` is `x` due to the current encoding
Lets inline here since it depends on the runtime encoding
*)
Js_of_lam_option.option_unwrap raw_arg
| _ -> Js_of_lam_variant.eval_as_unwrap raw_arg
in
(Splice1 single_arg, [])
| Nothing -> (Splice1 arg, [])
let empty_pair = ([], [])
let add_eff eff e = match eff with None -> e | Some v -> E.seq v e
type specs = External_arg_spec.params
type exprs = E.t list
TODO : fix splice ,
we need a static guarantee that it is static array construct
otherwise , we should provide a good error message here ,
no compiler failure here
Invariant : Array encoding
@return arguments and effect
we need a static guarantee that it is static array construct
otherwise, we should provide a good error message here,
no compiler failure here
Invariant : Array encoding
@return arguments and effect
*)
let assemble_args_no_splice (arg_types : specs) (args : exprs) :
exprs * E.t option =
let rec aux (labels : specs) (args : exprs) : exprs * exprs =
match (labels, args) with
| [], _ ->
assert (args = []);
empty_pair
| { arg_type = Arg_cst cst; _ } :: labels, args ->
(* can not be Optional *)
let accs, eff = aux labels args in
(Lam_compile_const.translate_arg_cst cst :: accs, eff)
| { arg_label; arg_type } :: labels, arg :: args ->
let accs, eff = aux labels args in
let acc, new_eff = ocaml_to_js_eff ~arg_label ~arg_type arg in
(append_list acc accs, Ext_list.append new_eff eff)
| _ :: _, [] -> assert false
in
let args, eff = aux arg_types args in
( args,
match eff with
| [] -> None
| x :: xs ->
(* FIXME: the order of effects? *)
Some (E.fuse_to_seq x xs) )
let assemble_args_has_splice (arg_types : specs) (args : exprs) :
exprs * E.t option * bool =
let dynamic = ref false in
let rec aux (labels : specs) (args : exprs) =
match (labels, args) with
| [], _ ->
assert (args = []);
empty_pair
| { arg_type = Arg_cst cst; _ } :: labels, args ->
let accs, eff = aux labels args in
(Lam_compile_const.translate_arg_cst cst :: accs, eff)
| { arg_label; arg_type } :: labels, arg :: args -> (
let accs, eff = aux labels args in
match (args, (arg : E.t)) with
| [], { expression_desc = Array (ls, _mutable_flag); _ } ->
(Ext_list.append ls accs, eff)
| _ ->
if args = [] then dynamic := true;
let acc, new_eff = ocaml_to_js_eff ~arg_type ~arg_label arg in
(append_list acc accs, Ext_list.append new_eff eff))
| _ :: _, [] -> assert false
in
let args, eff = aux arg_types args in
( args,
(match eff with
| [] -> None
| x :: xs ->
(* FIXME: the order of effects? *)
Some (E.fuse_to_seq x xs)),
!dynamic )
let translate_scoped_module_val
(module_name : External_ffi_types.external_module_name option) (fn : string)
(scopes : string list) =
match module_name with
| Some { bundle; module_bind_name } -> (
match scopes with
| [] ->
let default = fn = "default" in
let id =
Lam_compile_env.add_js_module module_bind_name bundle default
in
E.external_var_field ~external_name:bundle ~field:fn ~default id
| x :: rest ->
(* TODO: what happens when scope contains "default" ?*)
let default = false in
let id =
Lam_compile_env.add_js_module module_bind_name bundle default
in
let start =
E.external_var_field ~external_name:bundle ~field:x ~default id
in
Ext_list.fold_left (Ext_list.append rest [ fn ]) start E.dot)
| None -> (
(* no [@@module], assume it's global *)
match scopes with
| [] -> E.js_global fn
| x :: rest ->
let start = E.js_global x in
Ext_list.fold_left (Ext_list.append_one rest fn) start E.dot)
let translate_scoped_access scopes obj =
match scopes with
| [] -> obj
| x :: xs -> Ext_list.fold_left xs (E.dot obj x) E.dot
let translate_ffi (cxt : Lam_compile_context.t) arg_types
(ffi : External_ffi_types.external_spec) (args : J.expression list) =
match ffi with
| Js_call { external_module_name = module_name; name = fn; splice; scopes } ->
let fn = translate_scoped_module_val module_name fn scopes in
if splice then
let args, eff, dynamic = assemble_args_has_splice arg_types args in
add_eff eff
(if dynamic then splice_apply fn args
else E.call ~info:{ arity = Full; call_info = Call_na } fn args)
else
let args, eff = assemble_args_no_splice arg_types args in
add_eff eff
@@ E.call ~info:{ arity = Full; call_info = Call_na } fn args
| Js_module_as_fn { external_module_name; splice } ->
let fn = external_var external_module_name in
if splice then
let args, eff, dynamic = assemble_args_has_splice arg_types args in
(* TODO: fix in rest calling convention *)
add_eff eff
(if dynamic then splice_apply fn args
else E.call ~info:{ arity = Full; call_info = Call_na } fn args)
else
let args, eff = assemble_args_no_splice arg_types args in
(* TODO: fix in rest calling convention *)
add_eff eff (E.call ~info:{ arity = Full; call_info = Call_na } fn args)
| Js_new { external_module_name = module_name; name = fn; splice; scopes } ->
handle [ @@new ]
This has some side effect , it will
mark its identifier ( If it has ) as an object ,
ATTENTION :
order also matters here , since we mark its jsobject property ,
it will affect the code gen later
TODO : we should propagate this property
as much as we can(in alias table )
mark its identifier (If it has) as an object,
ATTENTION:
order also matters here, since we mark its jsobject property,
it will affect the code gen later
TODO: we should propagate this property
as much as we can(in alias table)
*)
let mark () =
match cxt.continuation with
| Declare (_, id) | Assign id ->
(* Format.fprintf Format.err_formatter "%a@."Ident.print id; *)
Ext_ident.make_js_object id
| EffectCall _ | NeedValue _ -> ()
in
if splice then
let args, eff, dynamic = assemble_args_has_splice arg_types args in
let fn = translate_scoped_module_val module_name fn scopes in
add_eff eff
(mark ();
if dynamic then splice_new_apply fn args
else E.new_ fn args)
else
let args, eff = assemble_args_no_splice arg_types args in
let fn = translate_scoped_module_val module_name fn scopes in
add_eff eff
(mark (); E.new_ fn args)
| Js_send { splice; name; js_send_scopes } -> (
match args with
| self :: args ->
PR2162 [ self_type ] more checks in syntax :
- should not be [ @as ]
- should not be [@as] *)
let[@warning "-8"] (_self_type :: arg_types) = arg_types in
if splice then
let args, eff, dynamic = assemble_args_has_splice arg_types args in
add_eff eff
(let self = translate_scoped_access js_send_scopes self in
if dynamic then splice_obj_apply self name args
else
E.call
~info:{ arity = Full; call_info = Call_na }
(E.dot self name) args)
else
let args, eff = assemble_args_no_splice arg_types args in
add_eff eff
(let self = translate_scoped_access js_send_scopes self in
E.call
~info:{ arity = Full; call_info = Call_na }
(E.dot self name) args)
| _ -> assert false)
| Js_module_as_var module_name -> external_var module_name
| Js_var { name; external_module_name; scopes } ->
TODO # 11
1 . check args -- error checking
2 . support [ @@scope " window " ]
we need know whether we should call [ ] or not
1. check args -- error checking
2. support [@@scope "window"]
we need know whether we should call [add_js_module] or not
*)
translate_scoped_module_val external_module_name name scopes
| Js_module_as_class module_name ->
let fn = external_var module_name in
let args, eff = assemble_args_no_splice arg_types args in
(* TODO: fix in rest calling convention *)
add_eff eff
((match cxt.continuation with
| Declare (_, id) | Assign id ->
(* Format.fprintf Format.err_formatter "%a@."Ident.print id; *)
Ext_ident.make_js_object id
| EffectCall _ | NeedValue _ -> ());
E.new_ fn args)
| Js_get { js_get_name = name; js_get_scopes = scopes } -> (
let args, cur_eff = assemble_args_no_splice arg_types args in
add_eff cur_eff
@@
match args with
| [ obj ] ->
let obj = translate_scoped_access scopes obj in
E.dot obj name
| _ -> assert false
(* Note these assertion happens in call site *))
| Js_set { js_set_name = name; js_set_scopes = scopes } -> (
(* assert (js_splice = false) ; *)
let args, cur_eff = assemble_args_no_splice arg_types args in
add_eff cur_eff
@@
match (args, arg_types) with
| [ obj; v ], _ ->
let obj = translate_scoped_access scopes obj in
E.assign (E.dot obj name) v
| _ -> assert false)
| Js_get_index { js_get_index_scopes = scopes } -> (
let args, cur_eff = assemble_args_no_splice arg_types args in
add_eff cur_eff
@@
match args with
| [ obj; v ] -> Js_arr.ref_array (translate_scoped_access scopes obj) v
| _ -> assert false)
| Js_set_index { js_set_index_scopes = scopes } -> (
let args, cur_eff = assemble_args_no_splice arg_types args in
add_eff cur_eff
@@
match args with
| [ obj; v; value ] ->
Js_arr.set_array (translate_scoped_access scopes obj) v value
| _ -> assert false)
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/7b206bf06c0f3c267017898aaa0ba1ef5f310cca/jscomp/core/lam_compile_external_call.ml | ocaml | *
[bind_name] is a hint to the compiler to generate
better names for external module
leave up later to decide
FIXME: encode invariant below in the signature
can not be Optional
FIXME: the order of effects?
FIXME: the order of effects?
TODO: what happens when scope contains "default" ?
no [@@module], assume it's global
TODO: fix in rest calling convention
TODO: fix in rest calling convention
Format.fprintf Format.err_formatter "%a@."Ident.print id;
TODO: fix in rest calling convention
Format.fprintf Format.err_formatter "%a@."Ident.print id;
Note these assertion happens in call site
assert (js_splice = false) ; | Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P.
* Copyright ( C ) 2017 - , Authors of ReScript
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2017 - Hongbo Zhang, Authors of ReScript
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
[@@@warning "+9"]
module E = Js_exp_make
let splice_apply fn args =
E.runtime_call Js_runtime_modules.caml_splice_call "spliceApply"
[ fn; E.array Immutable args ]
let splice_new_apply fn args =
E.runtime_call Js_runtime_modules.caml_splice_call "spliceNewApply"
[ fn; E.array Immutable args ]
let splice_obj_apply obj name args =
E.runtime_call Js_runtime_modules.caml_splice_call "spliceObjApply"
[ obj; E.str name; E.array Immutable args ]
let handle_external
( { bundle ; module_bind_name } : External_ffi_types.external_module_name )
: Ident.t * string
=
Lam_compile_env.add_js_module module_bind_name bundle ,
bundle
({bundle ; module_bind_name} : External_ffi_types.external_module_name)
: Ident.t * string
=
Lam_compile_env.add_js_module module_bind_name bundle ,
bundle *)
let external_var
({ bundle; module_bind_name } : External_ffi_types.external_module_name) =
let id = Lam_compile_env.add_js_module module_bind_name bundle false in
E.external_var id ~external_name:bundle
let ( module_name : External_ffi_types.external_module_name option )
: ( Ident.t * string ) option =
match module_name with
| Some module_name - > Some ( handle_external module_name )
| None - > None
(module_name : External_ffi_types.external_module_name option)
: (Ident.t * string) option =
match module_name with
| Some module_name -> Some (handle_external module_name)
| None -> None
*)
type arg_expression = Js_of_lam_variant.arg_expression =
| Splice0
| Splice1 of E.t
| Splice2 of E.t * E.t
let append_list x xs =
match x with
| Splice0 -> xs
| Splice1 a -> a :: xs
| Splice2 (a, b) -> a :: b :: xs
The first return value is value , the second argument is side effect expressions
Only the [ unit ] with no label will be ignored
When we are passing a boxed value to external(optional ) , we need
unbox it in the first place .
Note when optional value is not passed , the unboxed value would be
[ undefined ] , with the combination of ` [ @int ] ` it would be still be
[ undefined ] , this by default is still correct ..
{ [
( function ( ) {
switch ( undefined ) {
case 97 :
return " a " ;
case 98 :
return " b " ;
}
} ( ) ) = = = undefined
] }
This would not work with [ NonNullString ]
Only the [unit] with no label will be ignored
When we are passing a boxed value to external(optional), we need
unbox it in the first place.
Note when optional value is not passed, the unboxed value would be
[undefined], with the combination of `[@int]` it would be still be
[undefined], this by default is still correct..
{[
(function () {
switch (undefined) {
case 97 :
return "a";
case 98 :
return "b";
}
}()) === undefined
]}
This would not work with [NonNullString]
*)
let ocaml_to_js_eff ~(arg_label : External_arg_spec.label_noname)
~(arg_type : External_arg_spec.attr) (raw_arg : E.t) :
arg_expression * E.t list =
let arg =
match arg_label with
| Arg_optional ->
Js_of_lam_option.get_default_undefined_from_optional raw_arg
| Arg_label | Arg_empty -> raw_arg
in
match arg_type with
| Arg_cst _ -> assert false
| Fn_uncurry_arity _ -> assert false
has to be preprocessed by { ! } module first
| Extern_unit ->
( (if arg_label = Arg_empty then Splice0 else Splice1 E.unit),
if Js_analyzer.no_side_effect_expression arg then [] else [ arg ] )
| Ignore ->
( Splice0,
if Js_analyzer.no_side_effect_expression arg then [] else [ arg ] )
| Poly_var_string { descr } -> (Splice1 (Js_of_lam_variant.eval arg descr), [])
| Poly_var { descr } -> (Js_of_lam_variant.eval_as_event arg descr, [])
length of 2
- the poly var tag
- the value
- the poly var tag
- the value
*)
| Int dispatches ->
(Splice1 (Js_of_lam_variant.eval_as_int arg dispatches), [])
| Unwrap ->
let single_arg =
match arg_label with
| Arg_optional ->
If this is an optional arg ( like ` ? arg ` ) , we have to potentially do
2 levels of unwrapping :
- if ocaml arg is ` None ` , let js arg be ` undefined ` ( no unwrapping )
- if ocaml arg is ` Some x ` , unwrap the arg to get the ` x ` , then
unwrap the ` x ` itself
- Here ` Some x ` is ` x ` due to the current encoding
Lets inline here since it depends on the runtime encoding
If this is an optional arg (like `?arg`), we have to potentially do
2 levels of unwrapping:
- if ocaml arg is `None`, let js arg be `undefined` (no unwrapping)
- if ocaml arg is `Some x`, unwrap the arg to get the `x`, then
unwrap the `x` itself
- Here `Some x` is `x` due to the current encoding
Lets inline here since it depends on the runtime encoding
*)
Js_of_lam_option.option_unwrap raw_arg
| _ -> Js_of_lam_variant.eval_as_unwrap raw_arg
in
(Splice1 single_arg, [])
| Nothing -> (Splice1 arg, [])
let empty_pair = ([], [])
let add_eff eff e = match eff with None -> e | Some v -> E.seq v e
type specs = External_arg_spec.params
type exprs = E.t list
TODO : fix splice ,
we need a static guarantee that it is static array construct
otherwise , we should provide a good error message here ,
no compiler failure here
Invariant : Array encoding
@return arguments and effect
we need a static guarantee that it is static array construct
otherwise, we should provide a good error message here,
no compiler failure here
Invariant : Array encoding
@return arguments and effect
*)
let assemble_args_no_splice (arg_types : specs) (args : exprs) :
exprs * E.t option =
let rec aux (labels : specs) (args : exprs) : exprs * exprs =
match (labels, args) with
| [], _ ->
assert (args = []);
empty_pair
| { arg_type = Arg_cst cst; _ } :: labels, args ->
let accs, eff = aux labels args in
(Lam_compile_const.translate_arg_cst cst :: accs, eff)
| { arg_label; arg_type } :: labels, arg :: args ->
let accs, eff = aux labels args in
let acc, new_eff = ocaml_to_js_eff ~arg_label ~arg_type arg in
(append_list acc accs, Ext_list.append new_eff eff)
| _ :: _, [] -> assert false
in
let args, eff = aux arg_types args in
( args,
match eff with
| [] -> None
| x :: xs ->
Some (E.fuse_to_seq x xs) )
let assemble_args_has_splice (arg_types : specs) (args : exprs) :
exprs * E.t option * bool =
let dynamic = ref false in
let rec aux (labels : specs) (args : exprs) =
match (labels, args) with
| [], _ ->
assert (args = []);
empty_pair
| { arg_type = Arg_cst cst; _ } :: labels, args ->
let accs, eff = aux labels args in
(Lam_compile_const.translate_arg_cst cst :: accs, eff)
| { arg_label; arg_type } :: labels, arg :: args -> (
let accs, eff = aux labels args in
match (args, (arg : E.t)) with
| [], { expression_desc = Array (ls, _mutable_flag); _ } ->
(Ext_list.append ls accs, eff)
| _ ->
if args = [] then dynamic := true;
let acc, new_eff = ocaml_to_js_eff ~arg_type ~arg_label arg in
(append_list acc accs, Ext_list.append new_eff eff))
| _ :: _, [] -> assert false
in
let args, eff = aux arg_types args in
( args,
(match eff with
| [] -> None
| x :: xs ->
Some (E.fuse_to_seq x xs)),
!dynamic )
let translate_scoped_module_val
(module_name : External_ffi_types.external_module_name option) (fn : string)
(scopes : string list) =
match module_name with
| Some { bundle; module_bind_name } -> (
match scopes with
| [] ->
let default = fn = "default" in
let id =
Lam_compile_env.add_js_module module_bind_name bundle default
in
E.external_var_field ~external_name:bundle ~field:fn ~default id
| x :: rest ->
let default = false in
let id =
Lam_compile_env.add_js_module module_bind_name bundle default
in
let start =
E.external_var_field ~external_name:bundle ~field:x ~default id
in
Ext_list.fold_left (Ext_list.append rest [ fn ]) start E.dot)
| None -> (
match scopes with
| [] -> E.js_global fn
| x :: rest ->
let start = E.js_global x in
Ext_list.fold_left (Ext_list.append_one rest fn) start E.dot)
let translate_scoped_access scopes obj =
match scopes with
| [] -> obj
| x :: xs -> Ext_list.fold_left xs (E.dot obj x) E.dot
let translate_ffi (cxt : Lam_compile_context.t) arg_types
(ffi : External_ffi_types.external_spec) (args : J.expression list) =
match ffi with
| Js_call { external_module_name = module_name; name = fn; splice; scopes } ->
let fn = translate_scoped_module_val module_name fn scopes in
if splice then
let args, eff, dynamic = assemble_args_has_splice arg_types args in
add_eff eff
(if dynamic then splice_apply fn args
else E.call ~info:{ arity = Full; call_info = Call_na } fn args)
else
let args, eff = assemble_args_no_splice arg_types args in
add_eff eff
@@ E.call ~info:{ arity = Full; call_info = Call_na } fn args
| Js_module_as_fn { external_module_name; splice } ->
let fn = external_var external_module_name in
if splice then
let args, eff, dynamic = assemble_args_has_splice arg_types args in
add_eff eff
(if dynamic then splice_apply fn args
else E.call ~info:{ arity = Full; call_info = Call_na } fn args)
else
let args, eff = assemble_args_no_splice arg_types args in
add_eff eff (E.call ~info:{ arity = Full; call_info = Call_na } fn args)
| Js_new { external_module_name = module_name; name = fn; splice; scopes } ->
handle [ @@new ]
This has some side effect , it will
mark its identifier ( If it has ) as an object ,
ATTENTION :
order also matters here , since we mark its jsobject property ,
it will affect the code gen later
TODO : we should propagate this property
as much as we can(in alias table )
mark its identifier (If it has) as an object,
ATTENTION:
order also matters here, since we mark its jsobject property,
it will affect the code gen later
TODO: we should propagate this property
as much as we can(in alias table)
*)
let mark () =
match cxt.continuation with
| Declare (_, id) | Assign id ->
Ext_ident.make_js_object id
| EffectCall _ | NeedValue _ -> ()
in
if splice then
let args, eff, dynamic = assemble_args_has_splice arg_types args in
let fn = translate_scoped_module_val module_name fn scopes in
add_eff eff
(mark ();
if dynamic then splice_new_apply fn args
else E.new_ fn args)
else
let args, eff = assemble_args_no_splice arg_types args in
let fn = translate_scoped_module_val module_name fn scopes in
add_eff eff
(mark (); E.new_ fn args)
| Js_send { splice; name; js_send_scopes } -> (
match args with
| self :: args ->
PR2162 [ self_type ] more checks in syntax :
- should not be [ @as ]
- should not be [@as] *)
let[@warning "-8"] (_self_type :: arg_types) = arg_types in
if splice then
let args, eff, dynamic = assemble_args_has_splice arg_types args in
add_eff eff
(let self = translate_scoped_access js_send_scopes self in
if dynamic then splice_obj_apply self name args
else
E.call
~info:{ arity = Full; call_info = Call_na }
(E.dot self name) args)
else
let args, eff = assemble_args_no_splice arg_types args in
add_eff eff
(let self = translate_scoped_access js_send_scopes self in
E.call
~info:{ arity = Full; call_info = Call_na }
(E.dot self name) args)
| _ -> assert false)
| Js_module_as_var module_name -> external_var module_name
| Js_var { name; external_module_name; scopes } ->
TODO # 11
1 . check args -- error checking
2 . support [ @@scope " window " ]
we need know whether we should call [ ] or not
1. check args -- error checking
2. support [@@scope "window"]
we need know whether we should call [add_js_module] or not
*)
translate_scoped_module_val external_module_name name scopes
| Js_module_as_class module_name ->
let fn = external_var module_name in
let args, eff = assemble_args_no_splice arg_types args in
add_eff eff
((match cxt.continuation with
| Declare (_, id) | Assign id ->
Ext_ident.make_js_object id
| EffectCall _ | NeedValue _ -> ());
E.new_ fn args)
| Js_get { js_get_name = name; js_get_scopes = scopes } -> (
let args, cur_eff = assemble_args_no_splice arg_types args in
add_eff cur_eff
@@
match args with
| [ obj ] ->
let obj = translate_scoped_access scopes obj in
E.dot obj name
| _ -> assert false
| Js_set { js_set_name = name; js_set_scopes = scopes } -> (
let args, cur_eff = assemble_args_no_splice arg_types args in
add_eff cur_eff
@@
match (args, arg_types) with
| [ obj; v ], _ ->
let obj = translate_scoped_access scopes obj in
E.assign (E.dot obj name) v
| _ -> assert false)
| Js_get_index { js_get_index_scopes = scopes } -> (
let args, cur_eff = assemble_args_no_splice arg_types args in
add_eff cur_eff
@@
match args with
| [ obj; v ] -> Js_arr.ref_array (translate_scoped_access scopes obj) v
| _ -> assert false)
| Js_set_index { js_set_index_scopes = scopes } -> (
let args, cur_eff = assemble_args_no_splice arg_types args in
add_eff cur_eff
@@
match args with
| [ obj; v; value ] ->
Js_arr.set_array (translate_scoped_access scopes obj) v value
| _ -> assert false)
|
6bdbc01e9603401382229bbc09a560d71390c26fc0f84bf7c615b7c9dad2b4db | markcox80/lisp-executable | test-creation.lisp | Copyright ( c ) 2011 ,
;; 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.
;; 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
HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package "LISP-EXECUTABLE.TESTS")
(define-program example-program (&options help)
(cond
(help
(format *standard-output* "Help has arrived"))
(t
(format *standard-output* "You are doomed!")))
(terpri))
(define-test create-executable
(let* ((executable-name (make-pathname :name (string-downcase
(symbol-name
(gensym "lisp-executable-create-executable-test-filename")))
:directory '(:relative "tests")))
(directory (directory-namestring
(asdf:component-pathname
(asdf:find-system "lisp-executable-tests"))))
(filename (merge-pathnames executable-name directory)))
(assert-false (probe-file filename))
(with-output-to-string (lisp-executable:*lisp-machine-output-stream*)
(unwind-protect
(progn
(lisp-executable:create-executable 'example-program filename :asdf-system "lisp-executable-tests")
(unless (probe-file filename)
(pprint-logical-block (*standard-output* nil :prefix ";; ")
(write-string (get-output-stream-string lisp-executable:*lisp-machine-output-stream*))))
(assert-true (probe-file filename)))
(map nil #'(lambda (filename)
(when (probe-file filename)
(delete-file filename)))
(lisp-executable:executable-files filename))
(assert-false (probe-file filename))))))
| null | https://raw.githubusercontent.com/markcox80/lisp-executable/989b68ed946e1d99e6e65b7383a64ff035e833c7/tests/test-creation.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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | Copyright ( c ) 2011 ,
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
(in-package "LISP-EXECUTABLE.TESTS")
(define-program example-program (&options help)
(cond
(help
(format *standard-output* "Help has arrived"))
(t
(format *standard-output* "You are doomed!")))
(terpri))
(define-test create-executable
(let* ((executable-name (make-pathname :name (string-downcase
(symbol-name
(gensym "lisp-executable-create-executable-test-filename")))
:directory '(:relative "tests")))
(directory (directory-namestring
(asdf:component-pathname
(asdf:find-system "lisp-executable-tests"))))
(filename (merge-pathnames executable-name directory)))
(assert-false (probe-file filename))
(with-output-to-string (lisp-executable:*lisp-machine-output-stream*)
(unwind-protect
(progn
(lisp-executable:create-executable 'example-program filename :asdf-system "lisp-executable-tests")
(unless (probe-file filename)
(pprint-logical-block (*standard-output* nil :prefix ";; ")
(write-string (get-output-stream-string lisp-executable:*lisp-machine-output-stream*))))
(assert-true (probe-file filename)))
(map nil #'(lambda (filename)
(when (probe-file filename)
(delete-file filename)))
(lisp-executable:executable-files filename))
(assert-false (probe-file filename))))))
|
bb0d8d01a7529a401b273abfeaefb4dc85dcae4917e3690e5b5c7ec80553c4d3 | wagjo/hangman | words.clj | Copyright ( C ) 2012 , .
;;
;; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0
;; (-1.0.php) which can be found
;; in the file epl-v10.html at the root of this distribution.
;;
;; By using this software in any fashion, you are agreeing to be bound
;; by the terms of this license.
;;
;; You must not remove this notice, or any other, from this software.
(ns hangman.words
"Obtaining words for hangman." ; optional docstring for namespace
(:require [hangman.util :as util]
[incanter.core :as incanter]
[incanter.charts :as charts]
[clojure.java.io :as jio]))
For Hangman , we need a list of words to guess .
STEP 1 : Where is the list of words located
;; URL of a .zip file containing list of words
(def words-url
"")
(def words-local
(jio/resource "hangman/words.zip"))
STEP 2 : Get list of words
(comment
;; word list reader
(util/unzip-from-url words-local)
;; whole word list as a single string
(slurp (util/unzip-from-url words-local))
;; count number of characters
(let [words (slurp (util/unzip-from-url words-local))]
(count words))
;; char seq on word list
(seq (slurp (util/unzip-from-url words-local)))
NOTE : file contains one word per line , we can separate
;; words by separating lines
;; line seq on word list
(line-seq (util/unzip-from-url words-local))
;; count number of words
(let [words (line-seq (util/unzip-from-url words-local))]
(count words))
)
(defn- get-words
"Returns seq of words."
[url]
(line-seq (util/unzip-from-url url)))
;; NOTE: defn- defines private function. Private functions cannot
;; be called from other namespaces.
STEP 3 : select only words of given length
(comment
;; seq of words
(get-words words-local)
;; number of words
(count (get-words words-local))
;; how long are the words?
(map count (get-words words-local))
what is the min and length of words ?
(let [words (get-words words-local)
lengths (map count words)]
[(apply min lengths)
(apply max lengths)])
;; NOTE: "apply" calls given function and use elements from
;; supplied collection as a parameters for the function
;; how are lengths distributed?
(let [counts (map count (get-words words-local))]
(incanter/view (charts/histogram counts :nbins 25)))
remove words shorter than 5
(let [words (get-words words-local)
remove? (fn [word] (< (count word) 5))]
(remove remove? words))
only keep words having length between 5 and 7
(let [words (get-words words-local)
keep? #(< 4 (count %) 8)]
(filter keep? words))
)
(defn- trim-words
"Returns trimmed seq of words.
Words are trimmed by length.
Range is specified as a second parameter."
[words [min max]] ; using destructuting here
(let [keep? #(<= min (count %) max)]
(filter keep? words)))
;; NOTE: for more info on destructuring,
;; see
(comment
;; test trim-words
(let [trimmed-words (trim-words (get-words words-local) [5 7])
trimmed-count (map count trimmed-words)]
(-> trimmed-count
(charts/histogram :nbins 3)
incanter/view))
;; how many words are left?
(count (trim-words (get-words words-local) [5 7]))
)
STEP 4 : choose random word
(comment
get first word
(first (get-words words-local))
get second word
(second (get-words words-local))
get one hundredth word
(nth (get-words words-local) 99)
get five hundredth word
(nth (get-words words-local) 499)
;; get last word
(last (get-words words-local))
;; what if we are out of bounds?
(nth (get-words words-local) 1337)
;; we do not want an exception
(nth (get-words words-local) 1337 :not-found)
;; get random word
(rand-nth (get-words words-local))
)
;;;; Public API
;; Following function supports multiple arities
(defn get-random-word
"Returns random word from the list of words located at url
(defaults to words-local), having length in a range (defaults
to [5 7])."
([]
(get-random-word [5 7]))
([range]
(get-random-word range words-local))
([range url]
(-> url
get-words
(trim-words range)
seq
rand-nth)))
(comment
;; test random word
(get-random-word)
(get-random-word [0 1])
(get-random-word [3 3])
(get-random-word [10 11])
)
| null | https://raw.githubusercontent.com/wagjo/hangman/6abab88feb593c2ee3629f0047fbabb844caf194/src/hangman/words.clj | clojure |
The use and distribution terms for this software are covered by the
(-1.0.php) which can be found
in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound
by the terms of this license.
You must not remove this notice, or any other, from this software.
optional docstring for namespace
URL of a .zip file containing list of words
word list reader
whole word list as a single string
count number of characters
char seq on word list
words by separating lines
line seq on word list
count number of words
NOTE: defn- defines private function. Private functions cannot
be called from other namespaces.
seq of words
number of words
how long are the words?
NOTE: "apply" calls given function and use elements from
supplied collection as a parameters for the function
how are lengths distributed?
using destructuting here
NOTE: for more info on destructuring,
see
test trim-words
how many words are left?
get last word
what if we are out of bounds?
we do not want an exception
get random word
Public API
Following function supports multiple arities
test random word | Copyright ( C ) 2012 , .
Eclipse Public License 1.0
(ns hangman.words
(:require [hangman.util :as util]
[incanter.core :as incanter]
[incanter.charts :as charts]
[clojure.java.io :as jio]))
For Hangman , we need a list of words to guess .
STEP 1 : Where is the list of words located
(def words-url
"")
(def words-local
(jio/resource "hangman/words.zip"))
STEP 2 : Get list of words
(comment
(util/unzip-from-url words-local)
(slurp (util/unzip-from-url words-local))
(let [words (slurp (util/unzip-from-url words-local))]
(count words))
(seq (slurp (util/unzip-from-url words-local)))
NOTE : file contains one word per line , we can separate
(line-seq (util/unzip-from-url words-local))
(let [words (line-seq (util/unzip-from-url words-local))]
(count words))
)
(defn- get-words
"Returns seq of words."
[url]
(line-seq (util/unzip-from-url url)))
STEP 3 : select only words of given length
(comment
(get-words words-local)
(count (get-words words-local))
(map count (get-words words-local))
what is the min and length of words ?
(let [words (get-words words-local)
lengths (map count words)]
[(apply min lengths)
(apply max lengths)])
(let [counts (map count (get-words words-local))]
(incanter/view (charts/histogram counts :nbins 25)))
remove words shorter than 5
(let [words (get-words words-local)
remove? (fn [word] (< (count word) 5))]
(remove remove? words))
only keep words having length between 5 and 7
(let [words (get-words words-local)
keep? #(< 4 (count %) 8)]
(filter keep? words))
)
(defn- trim-words
"Returns trimmed seq of words.
Words are trimmed by length.
Range is specified as a second parameter."
(let [keep? #(<= min (count %) max)]
(filter keep? words)))
(comment
(let [trimmed-words (trim-words (get-words words-local) [5 7])
trimmed-count (map count trimmed-words)]
(-> trimmed-count
(charts/histogram :nbins 3)
incanter/view))
(count (trim-words (get-words words-local) [5 7]))
)
STEP 4 : choose random word
(comment
get first word
(first (get-words words-local))
get second word
(second (get-words words-local))
get one hundredth word
(nth (get-words words-local) 99)
get five hundredth word
(nth (get-words words-local) 499)
(last (get-words words-local))
(nth (get-words words-local) 1337)
(nth (get-words words-local) 1337 :not-found)
(rand-nth (get-words words-local))
)
(defn get-random-word
"Returns random word from the list of words located at url
(defaults to words-local), having length in a range (defaults
to [5 7])."
([]
(get-random-word [5 7]))
([range]
(get-random-word range words-local))
([range url]
(-> url
get-words
(trim-words range)
seq
rand-nth)))
(comment
(get-random-word)
(get-random-word [0 1])
(get-random-word [3 3])
(get-random-word [10 11])
)
|
5b8e2271dd4a530cf66cf25afd9416be2a412a78d5a51d8db258c4f2f56b5544 | spwhitton/consfigurator | package.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
Copyright ( C ) 2021 < >
;;; This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 , or ( at your option )
;;; any later version.
;;; This file is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
You should have received a copy of the GNU General Public License
;;; along with this program. If not, see </>.
(in-package :consfigurator.property.package)
(named-readtables:in-readtable :consfigurator)
(define-constant +consfigurator-system-dependencies+
'(:apt ("build-essential" "libacl1-dev" "libcap-dev"))
:test #'equal)
(defgeneric %command (package-manager)
(:documentation
"Returns a command which, if found on PATH, indicates that the system package
manager identified by PACKAGE-MANAGER is available."))
(defmethod %command ((package-manager (eql :apt)))
"apt-get")
(defgeneric %installed (package-manager packages)
(:documentation
"Install each of PACKAGES using the system package manager identified by
PACKAGE-MANAGER.
Implementations should not fail just because we are not root, or otherwise
privileged, if the package is already installed."))
(defmethod %installed ((package-manager (eql :apt)) packages)
;; Call APPLY-PROPAPP directly because we want the :CHECK subroutine run,
;; but it does not make sense to run the :HOSTATTRS subroutine because
;; *HOST* does not necessarily correspond to the host we're attempting to
;; install packages on.
(apply-propapp `(apt:installed ,@packages)))
(define-simple-error package-manager-not-found (aborted-change))
(defprop installed :posix
(package-manager &rest package-lists &aux package-list)
"Attempt to use a system package manager to install system packages as
specified by PACKAGE-LISTS. If PACKAGE-MANAGER, a keyword, use that
particular package manager; otherwise, see what we can find on PATH.
Each of PACKAGE-LISTS is a plist where the keys identify package managers, and
where the values are lists of package names to install using that package
manager. See PACKAGE:+CONSFIGURATOR-SYSTEM-DEPENDENCIES+ for an example.
This property should not typically be applied to hosts. It is preferable to
use an operating system-specific property, such as APT:INSTALLED. This
property exists because in a few cases it is necessary to install packages
where there is no known-valid HOST value for the machine upon which we need to
install packages, and thus we cannot infer what package manager to use from
the host's OS, and must fall back to seeing what's on PATH.
In particular, when starting up a remote Lisp image when the REMAINING
argument to ESTABLISH-CONNECTION is non-nil, we might be starting up Lisp on a
machine other than the one to be deployed and we do not have HOST values for
intermediate hops. Another case is INSTALLED:CLEANLY-INSTALLED-ONCE;
regardless of REMAINING, the initial OS might be the one we will replace, not
the declared OS for the host."
(:apply
(dolist (list package-lists)
(doplist (k v list)
(dolist (p (ensure-cons v))
(push p (getf package-list k)))))
(loop with reversed
for (k v) on package-list by #'cddr
do (push v reversed) (push k reversed)
finally (setq package-list reversed))
(if package-manager
(return-from installed
(%installed package-manager (getf package-list package-manager)))
(doplist (package-manager packages package-list)
(when (remote-executable-find (%command package-manager))
(return-from installed (%installed package-manager packages)))))
(package-manager-not-found
"Could not find any package manager on PATH with which to install ~S."
package-list)))
| null | https://raw.githubusercontent.com/spwhitton/consfigurator/3019bfea87ab6df33845f3bf7f7df03a33a5970d/src/property/package.lisp | lisp | Consfigurator -- Lisp declarative configuration management system
This file is free software; you can redistribute it and/or modify
either version 3 , or ( at your option )
any later version.
This file is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
Call APPLY-PROPAPP directly because we want the :CHECK subroutine run,
but it does not make sense to run the :HOSTATTRS subroutine because
*HOST* does not necessarily correspond to the host we're attempting to
install packages on.
otherwise, see what we can find on PATH.
|
Copyright ( C ) 2021 < >
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
(in-package :consfigurator.property.package)
(named-readtables:in-readtable :consfigurator)
(define-constant +consfigurator-system-dependencies+
'(:apt ("build-essential" "libacl1-dev" "libcap-dev"))
:test #'equal)
(defgeneric %command (package-manager)
(:documentation
"Returns a command which, if found on PATH, indicates that the system package
manager identified by PACKAGE-MANAGER is available."))
(defmethod %command ((package-manager (eql :apt)))
"apt-get")
(defgeneric %installed (package-manager packages)
(:documentation
"Install each of PACKAGES using the system package manager identified by
PACKAGE-MANAGER.
Implementations should not fail just because we are not root, or otherwise
privileged, if the package is already installed."))
(defmethod %installed ((package-manager (eql :apt)) packages)
(apply-propapp `(apt:installed ,@packages)))
(define-simple-error package-manager-not-found (aborted-change))
(defprop installed :posix
(package-manager &rest package-lists &aux package-list)
"Attempt to use a system package manager to install system packages as
specified by PACKAGE-LISTS. If PACKAGE-MANAGER, a keyword, use that
Each of PACKAGE-LISTS is a plist where the keys identify package managers, and
where the values are lists of package names to install using that package
manager. See PACKAGE:+CONSFIGURATOR-SYSTEM-DEPENDENCIES+ for an example.
This property should not typically be applied to hosts. It is preferable to
use an operating system-specific property, such as APT:INSTALLED. This
property exists because in a few cases it is necessary to install packages
where there is no known-valid HOST value for the machine upon which we need to
install packages, and thus we cannot infer what package manager to use from
the host's OS, and must fall back to seeing what's on PATH.
In particular, when starting up a remote Lisp image when the REMAINING
argument to ESTABLISH-CONNECTION is non-nil, we might be starting up Lisp on a
machine other than the one to be deployed and we do not have HOST values for
regardless of REMAINING, the initial OS might be the one we will replace, not
the declared OS for the host."
(:apply
(dolist (list package-lists)
(doplist (k v list)
(dolist (p (ensure-cons v))
(push p (getf package-list k)))))
(loop with reversed
for (k v) on package-list by #'cddr
do (push v reversed) (push k reversed)
finally (setq package-list reversed))
(if package-manager
(return-from installed
(%installed package-manager (getf package-list package-manager)))
(doplist (package-manager packages package-list)
(when (remote-executable-find (%command package-manager))
(return-from installed (%installed package-manager packages)))))
(package-manager-not-found
"Could not find any package manager on PATH with which to install ~S."
package-list)))
|
b20640d16a0676b69bca8ad5c4cbeec60cd42a89f75b2e44c3945474ebee0b17 | project-oak/hafnium-verification | PulseAbstractValue.ml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
type t = int [@@deriving compare]
let equal = [%compare.equal: t]
let next_fresh = ref 1
let mk_fresh () =
let l = !next_fresh in
incr next_fresh ; l
let pp f l = F.fprintf f "v%d" l
let init () = next_fresh := 1
type state = int
let get_state () = !next_fresh
let set_state counter = next_fresh := counter
module PPKey = struct
type nonrec t = t
let compare = compare
let pp = pp
end
module Set = PrettyPrintable.MakePPSet (PPKey)
module Map = PrettyPrintable.MakePPMap (PPKey)
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/pulse/PulseAbstractValue.ml | ocaml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
type t = int [@@deriving compare]
let equal = [%compare.equal: t]
let next_fresh = ref 1
let mk_fresh () =
let l = !next_fresh in
incr next_fresh ; l
let pp f l = F.fprintf f "v%d" l
let init () = next_fresh := 1
type state = int
let get_state () = !next_fresh
let set_state counter = next_fresh := counter
module PPKey = struct
type nonrec t = t
let compare = compare
let pp = pp
end
module Set = PrettyPrintable.MakePPSet (PPKey)
module Map = PrettyPrintable.MakePPMap (PPKey)
| |
ba52a3cc66808d98000b439617f171f294f5a1b7c21fd0b2a746856382af4d1b | DrTom/clj-pg-types | all.clj | (ns pg-types.all
(:require
[pg-types.read-column.array]
[pg-types.read-column.json]
[pg-types.read-column.timestamp.java-time]
[pg-types.read-column]
[pg-types.sql-parameter.array]
[pg-types.sql-parameter.json]
[pg-types.sql-parameter.timestamp]
[pg-types.sql-parameter.uuid]
[pg-types.sql-parameter]))
| null | https://raw.githubusercontent.com/DrTom/clj-pg-types/d847735c46b2da173fd50a6ebe492bead0d75dd5/src/pg_types/all.clj | clojure | (ns pg-types.all
(:require
[pg-types.read-column.array]
[pg-types.read-column.json]
[pg-types.read-column.timestamp.java-time]
[pg-types.read-column]
[pg-types.sql-parameter.array]
[pg-types.sql-parameter.json]
[pg-types.sql-parameter.timestamp]
[pg-types.sql-parameter.uuid]
[pg-types.sql-parameter]))
| |
0bca48847854be2ea6cb9b13d86fa66c89f7ef39549e0c4c3e7bd0efbab4f48c | manavpatnaik/haskell | 17_largest_of_two_nums.hs | largestOfTwoNums :: (Ord a) => a -> a -> a
largestOfTwoNums a b
| (a >= b) = a
| otherwise = b
main = do
print(largestOfTwoNums 2 2)
print(largestOfTwoNums 2 4)
print(largestOfTwoNums 21 4) | null | https://raw.githubusercontent.com/manavpatnaik/haskell/af45c3eb5c3461aa77cf25610dfcb3b41c7f7ef9/practice-set-1-basics/17_largest_of_two_nums.hs | haskell | largestOfTwoNums :: (Ord a) => a -> a -> a
largestOfTwoNums a b
| (a >= b) = a
| otherwise = b
main = do
print(largestOfTwoNums 2 2)
print(largestOfTwoNums 2 4)
print(largestOfTwoNums 21 4) | |
3a85298f28409fc6bba73b6dae92d23d274f631f28c8686d3c665bac800152ff | ltoth/unison | transfer.mli | Unison file synchronizer : src / transfer.mli
Copyright 1999 - 2010 , ( see COPYING for details )
Rsync : general algorithm description
The rsync algorithm is a technique for reducing the cost of a file
transfer by avoiding the transfer of blocks that are already at the
destination .
Imagine we have source and destination computers that have files X and
Y respectively , where X and Y are similar . The algorithm proceeds as
follows :
- The destination computer divides file Y into blocks of an agreed - upon
size each block , the destination computer computes two functions of the
block 's contents :
- A 128 - bit fingerprint of the block , which with very high
probability is different from the fingerprints of different blocks .
- A small checksum , which can be computed in a " rolling " fashion .
More precisely , if we are given the checksum for the N - byte block
at offset k , and we are given the bytes at offsets k and N+k , we
can efficiently compute the checksum for the N - byte block at offset
k+1 .
- The destination computer sends a list of fingerprints and checksums to
the source computer . Blocks are identified implicitly by the order in
which they appear in the list .
- The source computer searches through file X to identify blocks that
have the same fingerprints as blocks that appear in the list sent
from B. The checksums are used to find candidate blocks in a single
pass through file X. Blocks with identical fingerprints are presumed
to be identical .
- The source computer sends instructions for reconstructing file X at the
destination . These instructions avoid transmitting blocks of X that are
identical to other blocks in Y by providing the numbers of identical
blocks and the strings containing the differences .
Rsync : general algorithm description
The rsync algorithm is a technique for reducing the cost of a file
transfer by avoiding the transfer of blocks that are already at the
destination.
Imagine we have source and destination computers that have files X and
Y respectively, where X and Y are similar. The algorithm proceeds as
follows :
- The destination computer divides file Y into blocks of an agreed-upon
size N.
- For each block, the destination computer computes two functions of the
block's contents :
- A 128-bit fingerprint of the block, which with very high
probability is different from the fingerprints of different blocks.
- A small checksum, which can be computed in a "rolling" fashion.
More precisely, if we are given the checksum for the N-byte block
at offset k, and we are given the bytes at offsets k and N+k, we
can efficiently compute the checksum for the N-byte block at offset
k+1.
- The destination computer sends a list of fingerprints and checksums to
the source computer. Blocks are identified implicitly by the order in
which they appear in the list.
- The source computer searches through file X to identify blocks that
have the same fingerprints as blocks that appear in the list sent
from B. The checksums are used to find candidate blocks in a single
pass through file X. Blocks with identical fingerprints are presumed
to be identical.
- The source computer sends instructions for reconstructing file X at the
destination. These instructions avoid transmitting blocks of X that are
identical to other blocks in Y by providing the numbers of identical
blocks and the strings containing the differences.
*)
(* Transfer instruction giving data to build a file incrementally *)
type transfer_instruction = Bytearray.t * int * int
type transmitter = transfer_instruction -> unit Lwt.t
(*************************************************************************)
(* GENERIC TRANSMISSION *)
(*************************************************************************)
(* Send the whole source file encoded in transfer instructions *)
val send :
in_channel (* source file descriptor *)
-> Uutil.Filesize.t (* source file length *)
-> (int -> unit) (* progress report *)
-> transmitter (* transfer instruction transmitter *)
-> unit Lwt.t
val receive :
out_channel (* destination file descriptor *)
-> (int -> unit) (* progress report *)
-> transfer_instruction (* transfer instruction received *)
-> bool (* Whether we have reach the end of the file *)
(*************************************************************************)
(* RSYNC TRANSMISSION *)
(*************************************************************************)
module Rsync :
sig
(*** DESTINATION HOST ***)
(* The rsync compression can only be activated when the file size is
greater than the threshold *)
val aboveRsyncThreshold : Uutil.Filesize.t -> bool
Built from the old file by the destination computer
type rsync_block_info
Expected size of the [ rsync_block_info ] datastructure ( in KiB ) .
val memoryFootprint : Uutil.Filesize.t -> Uutil.Filesize.t -> int
(* Compute block informations from the old file *)
val rsyncPreprocess :
in_channel (* old file descriptor *)
-> Uutil.Filesize.t (* source file length *)
-> Uutil.Filesize.t (* destination file length *)
-> rsync_block_info * int
(* Interpret a transfer instruction *)
val rsyncDecompress :
int (* block size *)
-> in_channel (* old file descriptor *)
-> out_channel (* output file descriptor *)
-> (int -> unit) (* progress report *)
-> transfer_instruction (* transfer instruction received *)
-> bool
(*** SOURCE HOST ***)
(* Using block informations, parse the new file and send transfer
instructions accordingly *)
val rsyncCompress :
rsync_block_info
(* block info received from the destination *)
-> in_channel (* new file descriptor *)
-> Uutil.Filesize.t (* source file length *)
-> (int -> unit) (* progress report *)
-> transmitter (* transfer instruction transmitter *)
-> unit Lwt.t
end
| null | https://raw.githubusercontent.com/ltoth/unison/e763510165e3d93c5140a4c5f2ea0dcbf5825a0c/transfer.mli | ocaml | Transfer instruction giving data to build a file incrementally
***********************************************************************
GENERIC TRANSMISSION
***********************************************************************
Send the whole source file encoded in transfer instructions
source file descriptor
source file length
progress report
transfer instruction transmitter
destination file descriptor
progress report
transfer instruction received
Whether we have reach the end of the file
***********************************************************************
RSYNC TRANSMISSION
***********************************************************************
** DESTINATION HOST **
The rsync compression can only be activated when the file size is
greater than the threshold
Compute block informations from the old file
old file descriptor
source file length
destination file length
Interpret a transfer instruction
block size
old file descriptor
output file descriptor
progress report
transfer instruction received
** SOURCE HOST **
Using block informations, parse the new file and send transfer
instructions accordingly
block info received from the destination
new file descriptor
source file length
progress report
transfer instruction transmitter | Unison file synchronizer : src / transfer.mli
Copyright 1999 - 2010 , ( see COPYING for details )
Rsync : general algorithm description
The rsync algorithm is a technique for reducing the cost of a file
transfer by avoiding the transfer of blocks that are already at the
destination .
Imagine we have source and destination computers that have files X and
Y respectively , where X and Y are similar . The algorithm proceeds as
follows :
- The destination computer divides file Y into blocks of an agreed - upon
size each block , the destination computer computes two functions of the
block 's contents :
- A 128 - bit fingerprint of the block , which with very high
probability is different from the fingerprints of different blocks .
- A small checksum , which can be computed in a " rolling " fashion .
More precisely , if we are given the checksum for the N - byte block
at offset k , and we are given the bytes at offsets k and N+k , we
can efficiently compute the checksum for the N - byte block at offset
k+1 .
- The destination computer sends a list of fingerprints and checksums to
the source computer . Blocks are identified implicitly by the order in
which they appear in the list .
- The source computer searches through file X to identify blocks that
have the same fingerprints as blocks that appear in the list sent
from B. The checksums are used to find candidate blocks in a single
pass through file X. Blocks with identical fingerprints are presumed
to be identical .
- The source computer sends instructions for reconstructing file X at the
destination . These instructions avoid transmitting blocks of X that are
identical to other blocks in Y by providing the numbers of identical
blocks and the strings containing the differences .
Rsync : general algorithm description
The rsync algorithm is a technique for reducing the cost of a file
transfer by avoiding the transfer of blocks that are already at the
destination.
Imagine we have source and destination computers that have files X and
Y respectively, where X and Y are similar. The algorithm proceeds as
follows :
- The destination computer divides file Y into blocks of an agreed-upon
size N.
- For each block, the destination computer computes two functions of the
block's contents :
- A 128-bit fingerprint of the block, which with very high
probability is different from the fingerprints of different blocks.
- A small checksum, which can be computed in a "rolling" fashion.
More precisely, if we are given the checksum for the N-byte block
at offset k, and we are given the bytes at offsets k and N+k, we
can efficiently compute the checksum for the N-byte block at offset
k+1.
- The destination computer sends a list of fingerprints and checksums to
the source computer. Blocks are identified implicitly by the order in
which they appear in the list.
- The source computer searches through file X to identify blocks that
have the same fingerprints as blocks that appear in the list sent
from B. The checksums are used to find candidate blocks in a single
pass through file X. Blocks with identical fingerprints are presumed
to be identical.
- The source computer sends instructions for reconstructing file X at the
destination. These instructions avoid transmitting blocks of X that are
identical to other blocks in Y by providing the numbers of identical
blocks and the strings containing the differences.
*)
type transfer_instruction = Bytearray.t * int * int
type transmitter = transfer_instruction -> unit Lwt.t
val send :
-> unit Lwt.t
val receive :
module Rsync :
sig
val aboveRsyncThreshold : Uutil.Filesize.t -> bool
Built from the old file by the destination computer
type rsync_block_info
Expected size of the [ rsync_block_info ] datastructure ( in KiB ) .
val memoryFootprint : Uutil.Filesize.t -> Uutil.Filesize.t -> int
val rsyncPreprocess :
-> rsync_block_info * int
val rsyncDecompress :
-> bool
val rsyncCompress :
rsync_block_info
-> unit Lwt.t
end
|
3d2c612bfed73f3953605fdf2e20680c03f0fc5d43c6fe32cc030c3467255172 | xh4/web-toolkit | box.lisp | (in-package :css-test)
(in-suite :css-test)
(test margin
(margin-top "1px")
(margin-right "1px")
(margin-bottom "1px")
(margin-left "1px")
(margin "1px")
(margin "1px 2px")
(margin "1px 2px 3px")
(margin "1px 2px 3px 4px"))
(test padding
(padding-top "1px")
(padding-right "1px")
(padding-bottom "1px")
(padding-left "1px")
(padding "1px")
(padding "1px 2px")
(padding "1px 2px 3px")
(padding "1px 2px 3px 4px"))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/test/css/box.lisp | lisp | (in-package :css-test)
(in-suite :css-test)
(test margin
(margin-top "1px")
(margin-right "1px")
(margin-bottom "1px")
(margin-left "1px")
(margin "1px")
(margin "1px 2px")
(margin "1px 2px 3px")
(margin "1px 2px 3px 4px"))
(test padding
(padding-top "1px")
(padding-right "1px")
(padding-bottom "1px")
(padding-left "1px")
(padding "1px")
(padding "1px 2px")
(padding "1px 2px 3px")
(padding "1px 2px 3px 4px"))
| |
bed2eaeb698b0dd2bd34f81cad04a158a839c21072c3ef44ea7bd7ee84ae1719 | mzp/coq-ruby | uoptions.mli | (**************************************************************************)
(* Cameleon *)
(* *)
Copyright ( C ) 2002 Institut National de Recherche en Informatique et
(* en Automatique. All rights reserved. *)
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
(* any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
(* 02111-1307 USA *)
(* *)
(* Contact: *)
(**************************************************************************)
*
This module implements a simple mechanism to handle program options files .
An options file is defined as a set of [ variable = value ] lines ,
where value can be a simple string , a list of values ( between brackets
or parentheses ) or a set of [ variable = value ] lines between braces .
The option file is automatically loaded and saved , and options are
manipulated inside the program as easily as references .
Code from Fabrice Le Fessant .
This module implements a simple mechanism to handle program options files.
An options file is defined as a set of [variable = value] lines,
where value can be a simple string, a list of values (between brackets
or parentheses) or a set of [variable = value] lines between braces.
The option file is automatically loaded and saved, and options are
manipulated inside the program as easily as references.
Code from Fabrice Le Fessant.
*)
type 'a option_class
(** The abstract type for a class of options. A class is a set of options
which use the same conversion functions from loading and saving.*)
type 'a option_record
(** The abstract type for an option *)
type options_file
val create_options_file : string -> options_file
val set_options_file : options_file -> string -> unit
val prune_file : options_file -> unit
* { 2 Operations on option files }
val load : options_file -> unit
(** [load file] loads the option file. All options whose value is specified
in the option file are updated. *)
val append : options_file -> string -> unit
(** [append filename] loads the specified option file. All options whose
value is specified in this file are updated. *)
val save : options_file -> unit
(** [save file] saves all the options values to the option file. *)
val save_with_help : options_file -> unit
(** [save_with_help ()] saves all the options values to the option file,
with the help provided for each option. *)
* { 2 Creating options }
val define_option : options_file ->
string list -> string -> 'a option_class -> 'a -> 'a option_record
val option_hook : 'a option_record -> (unit -> unit) -> unit
val string_option : string option_class
val color_option : string option_class
val font_option : string option_class
val int_option : int option_class
val bool_option : bool option_class
val float_option : float option_class
val string2_option : (string * string) option_class
(* parameterized options *)
val list_option : 'a option_class -> 'a list option_class
val smalllist_option : 'a option_class -> 'a list option_class
val sum_option : (string * 'a) list -> 'a option_class
val tuple2_option :
'a option_class * 'b option_class -> ('a * 'b) option_class
val tuple3_option : 'a option_class * 'b option_class * 'c option_class ->
('a * 'b * 'c) option_class
val tuple4_option :
'a option_class * 'b option_class * 'c option_class * 'd option_class ->
('a * 'b * 'c * 'd) option_class
* { 2 Using options }
val ( !! ) : 'a option_record -> 'a
val ( =:= ) : 'a option_record -> 'a -> unit
val shortname : 'a option_record -> string
val get_help : 'a option_record -> string
* { 2 Creating new option classes }
val get_class : 'a option_record -> 'a option_class
val class_hook : 'a option_class -> ('a option_record -> unit) -> unit
type option_value =
Module of option_module
| StringValue of string
| IntValue of int
| FloatValue of float
| List of option_value list
| SmallList of option_value list
and option_module =
(string * option_value) list
val define_option_class :
string -> (option_value -> 'a) -> ('a -> option_value) -> 'a option_class
val to_value : 'a option_class -> 'a -> option_value
val from_value : 'a option_class -> option_value -> 'a
val value_to_string : option_value -> string
val string_to_value : string -> option_value
val value_to_int : option_value -> int
val int_to_value : int -> option_value
val bool_of_string : string -> bool
val value_to_bool : option_value -> bool
val bool_to_value : bool -> option_value
val value_to_float : option_value -> float
val float_to_value : float -> option_value
val value_to_string2 : option_value -> string * string
val string2_to_value : string * string -> option_value
val value_to_list : (option_value -> 'a) -> option_value -> 'a list
val list_to_value : ('a -> option_value) -> 'a list -> option_value
val smalllist_to_value : ('a -> option_value) -> 'a list -> option_value
val set_simple_option : options_file -> string -> string -> unit
val simple_options : options_file -> (string * string) list
val get_simple_option : options_file -> string -> string
val set_option_hook : options_file -> string -> (unit -> unit) -> unit
val set_string_wrappers : 'a option_record ->
('a -> string) -> (string -> 'a) -> unit
* { 2 Other functions }
val simple_args : options_file -> (string * Arg.spec * string) list
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/ide/utils/uoptions.mli | ocaml | ************************************************************************
Cameleon
en Automatique. All rights reserved.
This program is free software; you can redistribute it and/or modify
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
02111-1307 USA
Contact:
************************************************************************
* The abstract type for a class of options. A class is a set of options
which use the same conversion functions from loading and saving.
* The abstract type for an option
* [load file] loads the option file. All options whose value is specified
in the option file are updated.
* [append filename] loads the specified option file. All options whose
value is specified in this file are updated.
* [save file] saves all the options values to the option file.
* [save_with_help ()] saves all the options values to the option file,
with the help provided for each option.
parameterized options | Copyright ( C ) 2002 Institut National de Recherche en Informatique et
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
*
This module implements a simple mechanism to handle program options files .
An options file is defined as a set of [ variable = value ] lines ,
where value can be a simple string , a list of values ( between brackets
or parentheses ) or a set of [ variable = value ] lines between braces .
The option file is automatically loaded and saved , and options are
manipulated inside the program as easily as references .
Code from Fabrice Le Fessant .
This module implements a simple mechanism to handle program options files.
An options file is defined as a set of [variable = value] lines,
where value can be a simple string, a list of values (between brackets
or parentheses) or a set of [variable = value] lines between braces.
The option file is automatically loaded and saved, and options are
manipulated inside the program as easily as references.
Code from Fabrice Le Fessant.
*)
type 'a option_class
type 'a option_record
type options_file
val create_options_file : string -> options_file
val set_options_file : options_file -> string -> unit
val prune_file : options_file -> unit
* { 2 Operations on option files }
val load : options_file -> unit
val append : options_file -> string -> unit
val save : options_file -> unit
val save_with_help : options_file -> unit
* { 2 Creating options }
val define_option : options_file ->
string list -> string -> 'a option_class -> 'a -> 'a option_record
val option_hook : 'a option_record -> (unit -> unit) -> unit
val string_option : string option_class
val color_option : string option_class
val font_option : string option_class
val int_option : int option_class
val bool_option : bool option_class
val float_option : float option_class
val string2_option : (string * string) option_class
val list_option : 'a option_class -> 'a list option_class
val smalllist_option : 'a option_class -> 'a list option_class
val sum_option : (string * 'a) list -> 'a option_class
val tuple2_option :
'a option_class * 'b option_class -> ('a * 'b) option_class
val tuple3_option : 'a option_class * 'b option_class * 'c option_class ->
('a * 'b * 'c) option_class
val tuple4_option :
'a option_class * 'b option_class * 'c option_class * 'd option_class ->
('a * 'b * 'c * 'd) option_class
* { 2 Using options }
val ( !! ) : 'a option_record -> 'a
val ( =:= ) : 'a option_record -> 'a -> unit
val shortname : 'a option_record -> string
val get_help : 'a option_record -> string
* { 2 Creating new option classes }
val get_class : 'a option_record -> 'a option_class
val class_hook : 'a option_class -> ('a option_record -> unit) -> unit
type option_value =
Module of option_module
| StringValue of string
| IntValue of int
| FloatValue of float
| List of option_value list
| SmallList of option_value list
and option_module =
(string * option_value) list
val define_option_class :
string -> (option_value -> 'a) -> ('a -> option_value) -> 'a option_class
val to_value : 'a option_class -> 'a -> option_value
val from_value : 'a option_class -> option_value -> 'a
val value_to_string : option_value -> string
val string_to_value : string -> option_value
val value_to_int : option_value -> int
val int_to_value : int -> option_value
val bool_of_string : string -> bool
val value_to_bool : option_value -> bool
val bool_to_value : bool -> option_value
val value_to_float : option_value -> float
val float_to_value : float -> option_value
val value_to_string2 : option_value -> string * string
val string2_to_value : string * string -> option_value
val value_to_list : (option_value -> 'a) -> option_value -> 'a list
val list_to_value : ('a -> option_value) -> 'a list -> option_value
val smalllist_to_value : ('a -> option_value) -> 'a list -> option_value
val set_simple_option : options_file -> string -> string -> unit
val simple_options : options_file -> (string * string) list
val get_simple_option : options_file -> string -> string
val set_option_hook : options_file -> string -> (unit -> unit) -> unit
val set_string_wrappers : 'a option_record ->
('a -> string) -> (string -> 'a) -> unit
* { 2 Other functions }
val simple_args : options_file -> (string * Arg.spec * string) list
|
956ad0c7874ddcd4eec1a65292c6a92d44c19634c81c2dfec7350070111f961d | racket/typed-racket | tc-apply.rkt | #lang racket/unit
(require racket/match racket/list
"signatures.rkt"
"tc-app-helper.rkt"
"../types/utils.rkt"
"../types/abbrev.rkt"
"../types/substitute.rkt"
"../types/type-table.rkt"
"../utils/tc-utils.rkt"
"tc-funapp.rkt"
"../rep/type-rep.rkt"
"../rep/core-rep.rkt"
"../rep/values-rep.rkt"
"../infer/infer.rkt")
(import tc-expr^ tc-lambda^ tc-let^ tc-app^)
(export tc-apply^)
(define (do-ret t)
(match t
[(Values: (list (Result: ts _ _) ...)) (ret ts)]
[(ValuesDots: (list (Result: ts _ _) ...) dty dbound)
(ret ts
(for/list ([t (in-list ts)]) -tt-propset)
(for/list ([t (in-list ts)]) -empty-obj)
dty dbound)]
[(AnyValues: p) (-tc-any-results p)]
[_ (int-err "do-ret fails: ~a" t)]))
(define (tc/apply f args)
(define f-ty (single-value f))
produces the first n-1 elements of the list , and the last element
(define (split l) (let-values ([(f r) (split-at l (sub1 (length l)))])
(values f (car r))))
(define-values (fixed-args tail)
(let ([args* (syntax->list args)])
(if (null? args*)
(tc-error "apply requires a final list argument, given only a function argument of type ~a" (match f-ty [(tc-result1: t) t]))
(split args*))))
(define arg-tres (map tc-expr fixed-args))
(define arg-tys (map (match-lambda [(tc-result1: t _ _) t]) arg-tres))
(define full-tail-ty (tc-expr/t tail))
(define-values (tail-ty tail-bound)
(match full-tail-ty
[(ListDots: tail-ty tail-bound)
(values tail-ty tail-bound)]
[t (values #f #f)]))
;; Raises an error message for the case that the arguments do not match any of the domains
(define (failure)
(match f-ty
[(tc-result1:
(and t (AnyPoly-names: _ _
(Fun: (list (Arrow: doms rests (list (Keyword: _ _ #f) ...) rngs) ..1)))))
(domain-mismatches f args t doms rests rngs arg-tres full-tail-ty #f
#:msg-thunk (lambda (dom)
(string-append
"Bad arguments to function in `apply':\n"
dom)))]))
(match f-ty
;; apply of a simple function or polymorphic function
[(tc-result1:
(AnyPoly: vars dotted-vars (Fun: (list arrows ..1))))
#:when (not (for*/or ([a (in-list arrows)]
[kws (in-value (Arrow-kws a))])
(ormap Keyword-required? kws)))
(or
(for/or ([arrow (in-list arrows)])
(match arrow
[(Arrow: domain rst _ rng)
;; Takes a possible substitution and computes
;; the substituted range type if it is not #f
(define (finish substitution)
(begin0
(and substitution (do-ret (subst-all substitution rng)))
(add-typeof-expr f (ret (make-Fun (list arrow))))))
(finish
(infer vars dotted-vars
(list (-Tuple* arg-tys full-tail-ty))
(list (-Tuple* domain (Rest->Type rst)))
rng))]))
(failure))]
[(tc-result1: (and (? Intersection? f-ty^)))
(tc/funapp f args f-ty^ (append arg-tres
(match full-tail-ty
[(List: ty) (list (ret ty))]))
#f)]
[(tc-result1: (AnyPoly: _ _ (Fun: '())))
(tc-error/expr "Function has no cases")]
[(tc-result1: f-ty)
(tc-error/expr "Type of argument to apply is not a function type: \n~a" f-ty)]))
| null | https://raw.githubusercontent.com/racket/typed-racket/8b7bd594c66e53beba3d2568ca5ecb28f61c6d96/typed-racket-lib/typed-racket/typecheck/tc-apply.rkt | racket | Raises an error message for the case that the arguments do not match any of the domains
apply of a simple function or polymorphic function
Takes a possible substitution and computes
the substituted range type if it is not #f | #lang racket/unit
(require racket/match racket/list
"signatures.rkt"
"tc-app-helper.rkt"
"../types/utils.rkt"
"../types/abbrev.rkt"
"../types/substitute.rkt"
"../types/type-table.rkt"
"../utils/tc-utils.rkt"
"tc-funapp.rkt"
"../rep/type-rep.rkt"
"../rep/core-rep.rkt"
"../rep/values-rep.rkt"
"../infer/infer.rkt")
(import tc-expr^ tc-lambda^ tc-let^ tc-app^)
(export tc-apply^)
(define (do-ret t)
(match t
[(Values: (list (Result: ts _ _) ...)) (ret ts)]
[(ValuesDots: (list (Result: ts _ _) ...) dty dbound)
(ret ts
(for/list ([t (in-list ts)]) -tt-propset)
(for/list ([t (in-list ts)]) -empty-obj)
dty dbound)]
[(AnyValues: p) (-tc-any-results p)]
[_ (int-err "do-ret fails: ~a" t)]))
(define (tc/apply f args)
(define f-ty (single-value f))
produces the first n-1 elements of the list , and the last element
(define (split l) (let-values ([(f r) (split-at l (sub1 (length l)))])
(values f (car r))))
(define-values (fixed-args tail)
(let ([args* (syntax->list args)])
(if (null? args*)
(tc-error "apply requires a final list argument, given only a function argument of type ~a" (match f-ty [(tc-result1: t) t]))
(split args*))))
(define arg-tres (map tc-expr fixed-args))
(define arg-tys (map (match-lambda [(tc-result1: t _ _) t]) arg-tres))
(define full-tail-ty (tc-expr/t tail))
(define-values (tail-ty tail-bound)
(match full-tail-ty
[(ListDots: tail-ty tail-bound)
(values tail-ty tail-bound)]
[t (values #f #f)]))
(define (failure)
(match f-ty
[(tc-result1:
(and t (AnyPoly-names: _ _
(Fun: (list (Arrow: doms rests (list (Keyword: _ _ #f) ...) rngs) ..1)))))
(domain-mismatches f args t doms rests rngs arg-tres full-tail-ty #f
#:msg-thunk (lambda (dom)
(string-append
"Bad arguments to function in `apply':\n"
dom)))]))
(match f-ty
[(tc-result1:
(AnyPoly: vars dotted-vars (Fun: (list arrows ..1))))
#:when (not (for*/or ([a (in-list arrows)]
[kws (in-value (Arrow-kws a))])
(ormap Keyword-required? kws)))
(or
(for/or ([arrow (in-list arrows)])
(match arrow
[(Arrow: domain rst _ rng)
(define (finish substitution)
(begin0
(and substitution (do-ret (subst-all substitution rng)))
(add-typeof-expr f (ret (make-Fun (list arrow))))))
(finish
(infer vars dotted-vars
(list (-Tuple* arg-tys full-tail-ty))
(list (-Tuple* domain (Rest->Type rst)))
rng))]))
(failure))]
[(tc-result1: (and (? Intersection? f-ty^)))
(tc/funapp f args f-ty^ (append arg-tres
(match full-tail-ty
[(List: ty) (list (ret ty))]))
#f)]
[(tc-result1: (AnyPoly: _ _ (Fun: '())))
(tc-error/expr "Function has no cases")]
[(tc-result1: f-ty)
(tc-error/expr "Type of argument to apply is not a function type: \n~a" f-ty)]))
|
78e7b08b2e4f51a46d0b7b15c82a8d5c9dc55cf165b109f2b3bc8e80f568b802 | ocurrent/ocaml-ci | analyse_ocamlformat.mli | (** Detect the required version of ocamlformat used in a source repository. *)
type source =
| Opam of { version : string; opam_repo_commit : string }
* Should install OCamlformat from Opam .
| Vendored of { path : string }
* OCamlformat is vendored . [ path ] is relative to the project 's root .
[@@deriving yojson, eq, ord]
val pp_source : source Fmt.t
(** Pretty print [source]. *)
val get_ocamlformat_source :
Current.Job.t ->
opam_files:string list ->
root:Fpath.t ->
find_opam_repo_commit:
(string -> (string * Selection.t, [ `Msg of string ]) Lwt_result.t) ->
(source option * Selection.t option, [ `Msg of string ]) Lwt_result.t
* Detect the required version of OCamlformat or if it 's vendored . Vendored
OCamlformat is detected by looking at file names in [ opam_files ] .
OCamlformat is detected by looking at file names in [opam_files]. *)
| null | https://raw.githubusercontent.com/ocurrent/ocaml-ci/bac90619e2404a4761e8dcd95fe87b64489f7739/lib/analyse_ocamlformat.mli | ocaml | * Detect the required version of ocamlformat used in a source repository.
* Pretty print [source]. |
type source =
| Opam of { version : string; opam_repo_commit : string }
* Should install OCamlformat from Opam .
| Vendored of { path : string }
* OCamlformat is vendored . [ path ] is relative to the project 's root .
[@@deriving yojson, eq, ord]
val pp_source : source Fmt.t
val get_ocamlformat_source :
Current.Job.t ->
opam_files:string list ->
root:Fpath.t ->
find_opam_repo_commit:
(string -> (string * Selection.t, [ `Msg of string ]) Lwt_result.t) ->
(source option * Selection.t option, [ `Msg of string ]) Lwt_result.t
* Detect the required version of OCamlformat or if it 's vendored . Vendored
OCamlformat is detected by looking at file names in [ opam_files ] .
OCamlformat is detected by looking at file names in [opam_files]. *)
|
e4b9968cfd20429ec8fa48739cb676e0d55047f9ab448279da2fa0e6c8bfa617 | mks-m/wower | realm_helper.erl | -module(realm_helper).
-export([chars/2,
number_of_chars/2,
realms/0]).
-import(common_helper, [do/1]).
-include("database_records.hrl").
-include_lib("stdlib/include/qlc.hrl").
number_of_chars(int ( ) , int ( ) ) - > int ( ) .
number_of_chars(AccId, RealmId) ->
length(chars(AccId, RealmId)).
realms ( ) - > list(tuple ( ) ) .
realms() ->
do(qlc:q([X || X <- mnesia:table(realm)])).
@spec chars(int ( ) , int ( ) ) - > list(tuple ( ) ) .
chars(AccId, RealmId) ->
do(qlc:q([X || X <- mnesia:table(char),
X#char.account_id =:= AccId,
X#char.realm_id =:= RealmId])).
| null | https://raw.githubusercontent.com/mks-m/wower/ce9724876cf57b67ce72f2a9a6f74bb1ebffd53a/realm/src/realm_helper.erl | erlang | -module(realm_helper).
-export([chars/2,
number_of_chars/2,
realms/0]).
-import(common_helper, [do/1]).
-include("database_records.hrl").
-include_lib("stdlib/include/qlc.hrl").
number_of_chars(int ( ) , int ( ) ) - > int ( ) .
number_of_chars(AccId, RealmId) ->
length(chars(AccId, RealmId)).
realms ( ) - > list(tuple ( ) ) .
realms() ->
do(qlc:q([X || X <- mnesia:table(realm)])).
@spec chars(int ( ) , int ( ) ) - > list(tuple ( ) ) .
chars(AccId, RealmId) ->
do(qlc:q([X || X <- mnesia:table(char),
X#char.account_id =:= AccId,
X#char.realm_id =:= RealmId])).
| |
a4524bc256c85a29d2daae191a35f53e3ffab4135432b1583f048fee6e4579e3 | alyssa-p-hacker/SchemeBBS | bbs.scm | (load-option 'format)
(load "lib/utils")
(load "deps/irregex")
(load "deps/srfi-26")
(load "deps/httpio")
(load "deps/server")
(load "lib/html")
(load "lib/parameters")
(load "lib/markup")
(load "templates")
(define *sexp* "data/sexp")
(define *html* "data/html")
(define *frontpage-threads* 10)
(define *max-headline-size* 78)
(define *max-post-size* 8192)
(define *max-posts* 300)
(define (get-form-hash)
"TODO"
(call-with-input-file "hash" read))
;;; helpers
(define (make-path . args)
(string-join args "/"))
(define (make-abs-path . args)
(string-join (cons "" args) "/"))
(define server (create-server))
(define (make-response template)
`(200 ,(list (make-http-header 'content-type "text/html; charset=utf-8"))
,(with-output-to-string (lambda () (sxml->html template)))))
(define (write-and-serve path template)
(with-output-to-file path (lambda () (sxml->html template)))
(serve-file path (list (make-http-header 'content-type "text/html; charset=utf-8")
(make-http-header 'cache-control "Private"))))
;;; static files
(get server (serve-static "static") '("static"))
(get server (lambda (req params) (serve-file "static/favicon.ico")) '("favicon.ico"))
(add-handler server (lambda (req params) (route req)))
(define (ignore-qstring fullpath)
(let ((l (string-split fullpath #\?)))
(car l)))
(define (get-query-string fullpath)
(let ((l (string-split fullpath #\?)))
(if (null? (cdr l))
""
(cadr l))))
(define (add-query-string path query-string)
(if (string-null? query-string)
path
(string-append path "?" query-string)))
(define (route req)
(let* ((fullpath (uri->string (http-request-uri req)))
(path (string-split (ignore-qstring fullpath) #\/))
(query-string (get-query-string fullpath))
(method (http-request-method req))
(headers (http-request-headers req))
(ip (http-header 'x-forwarded-for headers #f))
)
;(pp ip)
(pp req)
;(pp headers)
(pp (http-header 'x-forwarded-for headers #f))
;(pp (http-header 'host headers #f))
(cond ((equal? method "GET")
(match path
(() () '(200 () "site root"))
((,board) () (view-index board))
((,board "list") () (view-list board))
((,board "preferences") () (set-preferences board query-string))
((,board ,thread) (integer? (string->number thread)) (view-thread board thread))
((,board ,thread ,posts) (and (integer? (string->number thread)) (range? posts) (< (string-length posts) 40))
(view-thread board thread posts))
(_ () not-found)))
((equal? method "POST")
(match path
((,board "post") () (post-thread board req query-string))
((,board ,thread "post") (integer? (string->number thread)) (post-message board thread req query-string))
(_ () method-not-allowed)))
(else method-not-allowed))))
;;; errors
(define bad-request
`(400 () "Bad Request"))
(define not-found
`(404 () "Not found"))
(define method-not-allowed
'(405 () "Method not allowed"))
(define (title board)
(string-append "/" board "/ - SchemeBBS"))
;;; views
(define (thread-template board thread posts headline filter-func)
(main-template (title board) (thread-view board thread posts headline filter-func) "thread"))
(define (list-template board threads)
(main-template (title board) (list-view board threads)))
(define (index-template board threads)
(main-template (title board) (frontpage-view board threads)))
(define (preferences-template board query-string-list)
(main-template (title board) (preferences-view board query-string-list)))
(define (retry-thread-template board headline message flash)
(main-template (title board) (make-thread-form board headline message flash) "thread"))
(define (retry-post-template board thread frontpage? message flash)
(main-template (title board) `(dl ,(make-post-form board thread frontpage? message flash)) "thread"))
;;; controllers GET
(define (set-preferences board query-string)
(let ((query-string-list (parameters->alist query-string)))
(make-response (preferences-template board query-string-list))))
(define (view-thread board thread #!optional range)
(let ((path (make-path *sexp* board thread))
(cache (make-path *html* board thread)))
(cond ((file-exists? path)
(let* ((t (call-with-input-file path read))
(headline (lookup-def 'headline t))
(posts (lookup-def 'posts t))
(norange (default-object? range))
(rangeonce (if norange "unused" (posts-range range)))
(filter-func (if norange
(lambda (e) #t)
(lambda (e) (vector-ref rangeonce (car e))))))
(cond (norange
(if (not (file-exists? cache))
(write-and-serve cache (thread-template board thread posts headline filter-func))
(serve-file cache))) ;; we shouldn't go here, reverse proxy fetches the page itself
((and (string->number range)
(> (string->number range) (length posts)))
not-found)
(else (make-response (thread-template board thread posts headline filter-func))))))
(else not-found))))
(define (range? posts)
(irregex-match "[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?(,[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?){0,20}" posts))
(define (posts-range range)
(define (expand-range x)
(cond ((> (length x) 1)
(let* ((a (string->number (car x)))
(b (string->number (cadr x)))
(low (if (> a *max-posts*) *max-posts* a))
(high (if (> b *max-posts*) *max-posts* b))
(count (+ (- high low) 1)))
(if (> high low)
(lambda () (iota count low))
(lambda () (list low)))))
(else (let* ((a (string->number (car x)))
(low (if (> a *max-posts*) *max-posts* a)))
(lambda () (list low))))))
(define (invoke-loop-set vector lamb)
(for-each (lambda (e) (vector-set! vector e #t))
(lamb)))
(let* ((r1 (string-split range #\,))
(r2 (map (lambda (x) (string-split x #\-)) r1))
(r3 (map expand-range r2))
(vec (make-vector (+ *max-posts* 1) #f)))
(for-each (lambda (e) (invoke-loop-set vec e))
r3)
vec))
(define (view-list board)
(let* ((path (make-path *sexp* board "list"))
(cache (make-path *html* board "list"))
(threads (if (file-exists? path) (call-with-input-file path read) '())))
(cond ((file-exists? path)
(if (not (file-exists? cache))
(write-and-serve cache (list-template board threads))
(serve-file cache))) ;; we shouldn't go there with a reverse proxy
(else not-found))))
;(make-response (list-template board threads))))
(define (view-index board)
(let* ((path (make-path *sexp* board "index"))
(cache (make-path *html* board "index"))
(threads (if (file-exists? path)
(call-with-input-file path read)
'())))
(cond ((file-exists? path)
(if (not (file-exists? cache))
(write-and-serve cache (index-template board threads))
(serve-file cache)))
(else not-found))))
;;; controllers POST
(define (post-message board thread req query-string)
(let ((path (make-path *sexp* board thread))
(cache (make-path *html* board thread)))
TODO verify if thread is archived
(cond ((file-exists? path)
(let* ((t (call-with-input-file path read))
(posts (lookup-def 'posts t))
(post-number (+ 1 (car (last posts))))
(body (http-request-body req))
(params (parameters->alist body))
(frontpage (lookup-def 'frontpage params))
(message (decode-formdata (lookup-def 'epistula params)))
(date (get-date))
(vip (assq 'vip params))
(validation (validate-form params message)))
(cond ((> post-number *max-posts*)
TODO
((eq? validation 'ok)
(let ((sxml (markup->sxml message board thread)))
(cond ((null? sxml) bad-request)
(else
(append! posts `((,post-number . ((date . ,date)
(vip . ,vip)
(content . ,sxml)))))
(call-with-output-file path (lambda (port) (write t port)))
(if (file-exists? cache) (delete-file cache))
(if vip
(update-post-count board thread date post-number)
(update-thread-list board (string->number thread) date post-number))
(update-frontpage board)
(if (equal? frontpage "true")
(redirection board thread (number->string post-number) query-string #t #f)
(redirection board thread (number->string post-number) query-string #f #f))))))
((eq? validation 'spam) `(301 ,(list (make-http-header 'location "")) "SNAFU"))
(else
(retry-post-form validation board thread frontpage params)))))
(else not-found))))
(define (redirection board thread post query-string frontpage? newthread?)
(if frontpage?
`(303 ,(list (make-http-header
'location
(if newthread?
(add-query-string (string-append "/" board) query-string)
(string-append (add-query-string (string-append "/" board) query-string) "#t" thread "p" post))))
"That was SICP quality!")
`(303 ,(list (make-http-header
'location
(string-append (add-query-string (string-append "/" board "/" thread) query-string) "#t" thread "p" post)))
"That was SICP quality")))
(define (update-post-count board thread date post-count)
(let ((cache (make-path *html* board "list")))
(if (file-exists? cache) (delete-file cache)))
(let* ((threads (call-with-input-file (make-path *sexp* board "list") read))
(t (lookup-def (string->number thread) threads))
(old-count (assq 'messages t))
(old-date (assq 'date t)))
(set-cdr! old-count post-count)
(set-cdr! old-date (string-append date " *"))
(call-with-output-file
(make-path *sexp* board "list")
(lambda (port) (write threads port)))))
(define (update-thread-list board thread date post-count)
(let ((cache (make-path *html* board "list")))
(if (file-exists? cache) (delete-file cache)))
(let* ((threads (call-with-input-file (make-path *sexp* board "list") read))
(headline (lookup-def 'headline (cdr (assv thread threads)))))
(call-with-output-file
(make-path *sexp* board "list")
(lambda (port)
(write
(cons `(,thread . ((headline . ,headline) (date . ,date) (messages . ,post-count)))
(del-assv thread threads))
port)))))
(define (update-frontpage board)
(let ((cache (make-path *html* board "index")))
(if (file-exists? cache) (delete-file cache)))
(let* ((threads (call-with-input-file (make-path *sexp* board "list") read))
(top-threads (if (> (length threads) *frontpage-threads*)
(take threads *frontpage-threads*)
threads)))
(with-output-to-file
(make-path *sexp* board "index")
(lambda ()
(write
(map
(lambda (t)
(let ((path (make-path *sexp* board (number->string (car t))))
(headline (lookup-def 'headline (cdr t))))
`(,(car t) . ,(alist-cons 'headline headline (latest-posts path)))))
top-threads))))))
(define (latest-posts path)
(let* ((thread (call-with-input-file path read))
(posts (lookup-def 'posts thread)))
(if (> (length posts) 6)
`((truncated . ,#t) (posts . (,(cons (car posts) (take-right posts 5)))))
`((truncated . ,#f) (posts . (,posts))))))
(define (post-thread board req query-string)
(cond ((file-exists? (make-path *sexp* board))
(let* ((list-path (make-path *sexp* board "list"))
(index-path (make-path *sexp* board "index"))
(threads (if (file-exists? list-path)
(call-with-input-file list-path read)
'()))
(body (http-request-body req))
(params (parameters->alist body))
(message (decode-formdata (lookup-def 'epistula params)))
(headline (decode-formdata (lookup-def 'titulus params)))
(date (get-date))
(validation (validate-form params message headline)))
(cond ((eq? validation 'ok)
(let* ((thread-number (get-next-thread-number threads))
(path (make-path *sexp* board (number->string thread-number)))
(sxml (markup->sxml message board (number->string thread-number))))
(cond ((null? sxml) bad-request)
(else
(create-thread path headline date sxml)
(add-thread-to-list list-path board threads thread-number headline date)
(add-thread-to-index (make-path *sexp* board "index")
board
thread-number
headline
date
sxml)
(redirection board (number->string thread-number) "1" query-string #t #t)))))
((eq? validation 'spam)
`(200 () "SNAFU."))
(else (retry-thread-form validation board params)))))
(else not-found)))
(define (create-thread path headline date sxml)
(with-output-to-file
path
(lambda ()
(write `((headline . ,headline)
(posts ((1 (date . ,date) (vip . #f) (content . ,sxml)))))))))
(define (add-thread-to-list path board threads thread-number headline date)
(let ((cache (make-path *html* board "list")))
(if (file-exists? cache) (delete-file cache)))
(let ((thread `(,thread-number (headline . ,headline) (date . ,date) (messages . 1))))
(with-output-to-file
path
(lambda ()
(write (cons thread threads))))))
(define (add-thread-to-index path board thread-number headline date sxml)
(let ((cache (make-path *html* board "index")))
(if (file-exists? cache) (delete-file cache)))
(let ((threads (if (file-exists? path) (call-with-input-file path read) '()))
(thread `(,thread-number
(headline . ,headline)
(truncated . #f)
(posts ((1 (date . ,date) (vip . #f) (content . ,sxml)))))))
(with-output-to-file
path
(lambda ()
(write
(if (< (length threads) *frontpage-threads*)
(cons thread threads)
(cons thread (take threads (dec *frontpage-threads*)))))))))
(define (get-next-thread-number threads)
(if (null? threads)
1
(inc (apply max (map car threads)))))
(define (validate-form params message #!optional headline)
(let ((fake-message (lookup-def 'message params ""))
(fake-name (lookup-def 'name params ""))
(hash (lookup-def 'ornamentum params "")))
(cond ((and (not (default-object? headline)) (string-null? headline))
'(empty-headline . "New threads must have a headline"))
((string-null? message)
'(empty-message . "Empty post"))
((and (not (default-object? headline)) (> (string-length headline) *max-headline-size*))
`(headline-too-long . (string-append "Headline too long (max: " ,(number->string *max-headline-size*) " bytes)")))
((> (string-length message) *max-post-size*)
`(message-too-long . (string-append "Your post is too long (max: " ,(number->string *max-post-size*) " bytes)")))
((not (and (string-null? fake-message)
(string-null? fake-name)))
'spam)
(else 'ok))))
(define (retry-thread-form validation board params)
(let ((headline (lookup-def 'titulus params ""))
(message (lookup-def 'epistula params "")))
(make-response (retry-thread-template
board
(decode-formdata headline)
(decode-formdata message)
(cdr validation)))))
(define (retry-post-form validation board thread frontpage? params)
(let ((message (lookup-def 'epistula params "")))
(make-response (retry-post-template
board
thread
frontpage?
(decode-formdata message)
(cdr validation)))))
(listen server (string->number (car (command-line))))
| null | https://raw.githubusercontent.com/alyssa-p-hacker/SchemeBBS/7a5506e7fad22472e1e94671b4fabfce6432199a/bbs.scm | scheme | helpers
static files
(pp ip)
(pp headers)
(pp (http-header 'host headers #f))
errors
views
controllers GET
we shouldn't go here, reverse proxy fetches the page itself
we shouldn't go there with a reverse proxy
(make-response (list-template board threads))))
controllers POST | (load-option 'format)
(load "lib/utils")
(load "deps/irregex")
(load "deps/srfi-26")
(load "deps/httpio")
(load "deps/server")
(load "lib/html")
(load "lib/parameters")
(load "lib/markup")
(load "templates")
(define *sexp* "data/sexp")
(define *html* "data/html")
(define *frontpage-threads* 10)
(define *max-headline-size* 78)
(define *max-post-size* 8192)
(define *max-posts* 300)
(define (get-form-hash)
"TODO"
(call-with-input-file "hash" read))
(define (make-path . args)
(string-join args "/"))
(define (make-abs-path . args)
(string-join (cons "" args) "/"))
(define server (create-server))
(define (make-response template)
`(200 ,(list (make-http-header 'content-type "text/html; charset=utf-8"))
,(with-output-to-string (lambda () (sxml->html template)))))
(define (write-and-serve path template)
(with-output-to-file path (lambda () (sxml->html template)))
(serve-file path (list (make-http-header 'content-type "text/html; charset=utf-8")
(make-http-header 'cache-control "Private"))))
(get server (serve-static "static") '("static"))
(get server (lambda (req params) (serve-file "static/favicon.ico")) '("favicon.ico"))
(add-handler server (lambda (req params) (route req)))
(define (ignore-qstring fullpath)
(let ((l (string-split fullpath #\?)))
(car l)))
(define (get-query-string fullpath)
(let ((l (string-split fullpath #\?)))
(if (null? (cdr l))
""
(cadr l))))
(define (add-query-string path query-string)
(if (string-null? query-string)
path
(string-append path "?" query-string)))
(define (route req)
(let* ((fullpath (uri->string (http-request-uri req)))
(path (string-split (ignore-qstring fullpath) #\/))
(query-string (get-query-string fullpath))
(method (http-request-method req))
(headers (http-request-headers req))
(ip (http-header 'x-forwarded-for headers #f))
)
(pp req)
(pp (http-header 'x-forwarded-for headers #f))
(cond ((equal? method "GET")
(match path
(() () '(200 () "site root"))
((,board) () (view-index board))
((,board "list") () (view-list board))
((,board "preferences") () (set-preferences board query-string))
((,board ,thread) (integer? (string->number thread)) (view-thread board thread))
((,board ,thread ,posts) (and (integer? (string->number thread)) (range? posts) (< (string-length posts) 40))
(view-thread board thread posts))
(_ () not-found)))
((equal? method "POST")
(match path
((,board "post") () (post-thread board req query-string))
((,board ,thread "post") (integer? (string->number thread)) (post-message board thread req query-string))
(_ () method-not-allowed)))
(else method-not-allowed))))
(define bad-request
`(400 () "Bad Request"))
(define not-found
`(404 () "Not found"))
(define method-not-allowed
'(405 () "Method not allowed"))
(define (title board)
(string-append "/" board "/ - SchemeBBS"))
(define (thread-template board thread posts headline filter-func)
(main-template (title board) (thread-view board thread posts headline filter-func) "thread"))
(define (list-template board threads)
(main-template (title board) (list-view board threads)))
(define (index-template board threads)
(main-template (title board) (frontpage-view board threads)))
(define (preferences-template board query-string-list)
(main-template (title board) (preferences-view board query-string-list)))
(define (retry-thread-template board headline message flash)
(main-template (title board) (make-thread-form board headline message flash) "thread"))
(define (retry-post-template board thread frontpage? message flash)
(main-template (title board) `(dl ,(make-post-form board thread frontpage? message flash)) "thread"))
(define (set-preferences board query-string)
(let ((query-string-list (parameters->alist query-string)))
(make-response (preferences-template board query-string-list))))
(define (view-thread board thread #!optional range)
(let ((path (make-path *sexp* board thread))
(cache (make-path *html* board thread)))
(cond ((file-exists? path)
(let* ((t (call-with-input-file path read))
(headline (lookup-def 'headline t))
(posts (lookup-def 'posts t))
(norange (default-object? range))
(rangeonce (if norange "unused" (posts-range range)))
(filter-func (if norange
(lambda (e) #t)
(lambda (e) (vector-ref rangeonce (car e))))))
(cond (norange
(if (not (file-exists? cache))
(write-and-serve cache (thread-template board thread posts headline filter-func))
((and (string->number range)
(> (string->number range) (length posts)))
not-found)
(else (make-response (thread-template board thread posts headline filter-func))))))
(else not-found))))
(define (range? posts)
(irregex-match "[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?(,[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?){0,20}" posts))
(define (posts-range range)
(define (expand-range x)
(cond ((> (length x) 1)
(let* ((a (string->number (car x)))
(b (string->number (cadr x)))
(low (if (> a *max-posts*) *max-posts* a))
(high (if (> b *max-posts*) *max-posts* b))
(count (+ (- high low) 1)))
(if (> high low)
(lambda () (iota count low))
(lambda () (list low)))))
(else (let* ((a (string->number (car x)))
(low (if (> a *max-posts*) *max-posts* a)))
(lambda () (list low))))))
(define (invoke-loop-set vector lamb)
(for-each (lambda (e) (vector-set! vector e #t))
(lamb)))
(let* ((r1 (string-split range #\,))
(r2 (map (lambda (x) (string-split x #\-)) r1))
(r3 (map expand-range r2))
(vec (make-vector (+ *max-posts* 1) #f)))
(for-each (lambda (e) (invoke-loop-set vec e))
r3)
vec))
(define (view-list board)
(let* ((path (make-path *sexp* board "list"))
(cache (make-path *html* board "list"))
(threads (if (file-exists? path) (call-with-input-file path read) '())))
(cond ((file-exists? path)
(if (not (file-exists? cache))
(write-and-serve cache (list-template board threads))
(else not-found))))
(define (view-index board)
(let* ((path (make-path *sexp* board "index"))
(cache (make-path *html* board "index"))
(threads (if (file-exists? path)
(call-with-input-file path read)
'())))
(cond ((file-exists? path)
(if (not (file-exists? cache))
(write-and-serve cache (index-template board threads))
(serve-file cache)))
(else not-found))))
(define (post-message board thread req query-string)
(let ((path (make-path *sexp* board thread))
(cache (make-path *html* board thread)))
TODO verify if thread is archived
(cond ((file-exists? path)
(let* ((t (call-with-input-file path read))
(posts (lookup-def 'posts t))
(post-number (+ 1 (car (last posts))))
(body (http-request-body req))
(params (parameters->alist body))
(frontpage (lookup-def 'frontpage params))
(message (decode-formdata (lookup-def 'epistula params)))
(date (get-date))
(vip (assq 'vip params))
(validation (validate-form params message)))
(cond ((> post-number *max-posts*)
TODO
((eq? validation 'ok)
(let ((sxml (markup->sxml message board thread)))
(cond ((null? sxml) bad-request)
(else
(append! posts `((,post-number . ((date . ,date)
(vip . ,vip)
(content . ,sxml)))))
(call-with-output-file path (lambda (port) (write t port)))
(if (file-exists? cache) (delete-file cache))
(if vip
(update-post-count board thread date post-number)
(update-thread-list board (string->number thread) date post-number))
(update-frontpage board)
(if (equal? frontpage "true")
(redirection board thread (number->string post-number) query-string #t #f)
(redirection board thread (number->string post-number) query-string #f #f))))))
((eq? validation 'spam) `(301 ,(list (make-http-header 'location "")) "SNAFU"))
(else
(retry-post-form validation board thread frontpage params)))))
(else not-found))))
(define (redirection board thread post query-string frontpage? newthread?)
(if frontpage?
`(303 ,(list (make-http-header
'location
(if newthread?
(add-query-string (string-append "/" board) query-string)
(string-append (add-query-string (string-append "/" board) query-string) "#t" thread "p" post))))
"That was SICP quality!")
`(303 ,(list (make-http-header
'location
(string-append (add-query-string (string-append "/" board "/" thread) query-string) "#t" thread "p" post)))
"That was SICP quality")))
(define (update-post-count board thread date post-count)
(let ((cache (make-path *html* board "list")))
(if (file-exists? cache) (delete-file cache)))
(let* ((threads (call-with-input-file (make-path *sexp* board "list") read))
(t (lookup-def (string->number thread) threads))
(old-count (assq 'messages t))
(old-date (assq 'date t)))
(set-cdr! old-count post-count)
(set-cdr! old-date (string-append date " *"))
(call-with-output-file
(make-path *sexp* board "list")
(lambda (port) (write threads port)))))
(define (update-thread-list board thread date post-count)
(let ((cache (make-path *html* board "list")))
(if (file-exists? cache) (delete-file cache)))
(let* ((threads (call-with-input-file (make-path *sexp* board "list") read))
(headline (lookup-def 'headline (cdr (assv thread threads)))))
(call-with-output-file
(make-path *sexp* board "list")
(lambda (port)
(write
(cons `(,thread . ((headline . ,headline) (date . ,date) (messages . ,post-count)))
(del-assv thread threads))
port)))))
(define (update-frontpage board)
(let ((cache (make-path *html* board "index")))
(if (file-exists? cache) (delete-file cache)))
(let* ((threads (call-with-input-file (make-path *sexp* board "list") read))
(top-threads (if (> (length threads) *frontpage-threads*)
(take threads *frontpage-threads*)
threads)))
(with-output-to-file
(make-path *sexp* board "index")
(lambda ()
(write
(map
(lambda (t)
(let ((path (make-path *sexp* board (number->string (car t))))
(headline (lookup-def 'headline (cdr t))))
`(,(car t) . ,(alist-cons 'headline headline (latest-posts path)))))
top-threads))))))
(define (latest-posts path)
(let* ((thread (call-with-input-file path read))
(posts (lookup-def 'posts thread)))
(if (> (length posts) 6)
`((truncated . ,#t) (posts . (,(cons (car posts) (take-right posts 5)))))
`((truncated . ,#f) (posts . (,posts))))))
(define (post-thread board req query-string)
(cond ((file-exists? (make-path *sexp* board))
(let* ((list-path (make-path *sexp* board "list"))
(index-path (make-path *sexp* board "index"))
(threads (if (file-exists? list-path)
(call-with-input-file list-path read)
'()))
(body (http-request-body req))
(params (parameters->alist body))
(message (decode-formdata (lookup-def 'epistula params)))
(headline (decode-formdata (lookup-def 'titulus params)))
(date (get-date))
(validation (validate-form params message headline)))
(cond ((eq? validation 'ok)
(let* ((thread-number (get-next-thread-number threads))
(path (make-path *sexp* board (number->string thread-number)))
(sxml (markup->sxml message board (number->string thread-number))))
(cond ((null? sxml) bad-request)
(else
(create-thread path headline date sxml)
(add-thread-to-list list-path board threads thread-number headline date)
(add-thread-to-index (make-path *sexp* board "index")
board
thread-number
headline
date
sxml)
(redirection board (number->string thread-number) "1" query-string #t #t)))))
((eq? validation 'spam)
`(200 () "SNAFU."))
(else (retry-thread-form validation board params)))))
(else not-found)))
(define (create-thread path headline date sxml)
(with-output-to-file
path
(lambda ()
(write `((headline . ,headline)
(posts ((1 (date . ,date) (vip . #f) (content . ,sxml)))))))))
(define (add-thread-to-list path board threads thread-number headline date)
(let ((cache (make-path *html* board "list")))
(if (file-exists? cache) (delete-file cache)))
(let ((thread `(,thread-number (headline . ,headline) (date . ,date) (messages . 1))))
(with-output-to-file
path
(lambda ()
(write (cons thread threads))))))
(define (add-thread-to-index path board thread-number headline date sxml)
(let ((cache (make-path *html* board "index")))
(if (file-exists? cache) (delete-file cache)))
(let ((threads (if (file-exists? path) (call-with-input-file path read) '()))
(thread `(,thread-number
(headline . ,headline)
(truncated . #f)
(posts ((1 (date . ,date) (vip . #f) (content . ,sxml)))))))
(with-output-to-file
path
(lambda ()
(write
(if (< (length threads) *frontpage-threads*)
(cons thread threads)
(cons thread (take threads (dec *frontpage-threads*)))))))))
(define (get-next-thread-number threads)
(if (null? threads)
1
(inc (apply max (map car threads)))))
(define (validate-form params message #!optional headline)
(let ((fake-message (lookup-def 'message params ""))
(fake-name (lookup-def 'name params ""))
(hash (lookup-def 'ornamentum params "")))
(cond ((and (not (default-object? headline)) (string-null? headline))
'(empty-headline . "New threads must have a headline"))
((string-null? message)
'(empty-message . "Empty post"))
((and (not (default-object? headline)) (> (string-length headline) *max-headline-size*))
`(headline-too-long . (string-append "Headline too long (max: " ,(number->string *max-headline-size*) " bytes)")))
((> (string-length message) *max-post-size*)
`(message-too-long . (string-append "Your post is too long (max: " ,(number->string *max-post-size*) " bytes)")))
((not (and (string-null? fake-message)
(string-null? fake-name)))
'spam)
(else 'ok))))
(define (retry-thread-form validation board params)
(let ((headline (lookup-def 'titulus params ""))
(message (lookup-def 'epistula params "")))
(make-response (retry-thread-template
board
(decode-formdata headline)
(decode-formdata message)
(cdr validation)))))
(define (retry-post-form validation board thread frontpage? params)
(let ((message (lookup-def 'epistula params "")))
(make-response (retry-post-template
board
thread
frontpage?
(decode-formdata message)
(cdr validation)))))
(listen server (string->number (car (command-line))))
|
a3bb9611e242a3d6ecef90e1622d033aab16920d1554aa24284a707c4ac2671e | returntocorp/semgrep | graph_code_prolog.mli | type context =
| NoCtx
| CallCtx of Graph_code.node
| AssignCtx of Graph_code.node
val hook_use_edge_for_prolog :
context ->
bool ->
Graph_code.node * Graph_code.node ->
Graph_code.t ->
Parse_info.token_location ->
unit
val build : Graph_code.t -> Prolog_code.fact list
| null | https://raw.githubusercontent.com/returntocorp/semgrep/855abad9ada6ea5fd72d437fd69ff2e5fa42c1f1/libs/graph_code/graph_code_prolog.mli | ocaml | type context =
| NoCtx
| CallCtx of Graph_code.node
| AssignCtx of Graph_code.node
val hook_use_edge_for_prolog :
context ->
bool ->
Graph_code.node * Graph_code.node ->
Graph_code.t ->
Parse_info.token_location ->
unit
val build : Graph_code.t -> Prolog_code.fact list
| |
83d844c0a1fdf977b25a017f7c5cd47a1d5dc12d6e48e8b4b64bacba5677ab1e | AHartNtkn/IotaTT | TypeChecker.hs | module TypeChecker where
import qualified Data.Map.Strict as Map
import Control.Monad.Reader hiding (liftIO)
import Control.Monad.State hiding (liftIO)
import Control.Monad.Except hiding (liftIO)
import Control.Monad.Trans.Except hiding (liftIO)
import AbstractSyntax
import PrettyPrinting
infer :: ATerm -> Proof ATerm
infer tr = do
wtr <- whnf tr
case wtr of
AVS s -> snd <$> lookupVar s
AV s n -> do
ctx <- ask
case (ctx , n) of
([] , _) -> proofError $ "Cannot infer term variable " ++ pshowA (AV s n) ++ " in empty context."
((x : _) , 0) -> local tail $ do
infer x -- Note: this isn't used, x just needs some type.
return (quote x)
((_ : _) , n) -> local tail (infer (AV s (n - 1))) >>= return . quote
ALam st (AAnn ty tr) -> do
liftMin (unquote ty) -- Note: this isn't used, unquote ty just needs some type.
ity <- local (unquote tr:) (infer tr)
return (APi st (unquote ty) ity)
ALam st tr -> proofError $ "Cannot infer the type of unannotated lambda term " ++ pshowA (ALam st tr) ++ "."
AAnn aty tr -> do
ctx <- ask
case ctx of
(cty : _) -> do
naty <- nf aty
ncty <- nf (quote cty)
if naty == ncty
then infer tr
else proofError $ "Type annotation " ++ pshowA aty ++ " didn't match contextual " ++
pshowA cty ++ " during inference."
_ -> proofError $ "Annotation " ++ pshowA aty ++
" appeared without being added to local context during type inference."
AApp tr1 tr2 -> do
tr1ty <- nwhnf =<< infer tr1
case tr1ty of
APi _ tp1 tp2 -> check tr2 tp1 >> return (sub tr2 tp2)
_ -> proofError $ "Term " ++ pshowA tr1 ++ " is not a pi type, and so cannot be applied to an argument."
ALAM st (AAnn ty tr) -> do
liftMin (unquote ty) -- Note: this isn't used, unquote ty just needs to be a.
ity <- local (unquote tr:) (infer tr)
return (AIPi st (unquote ty) ity)
ALAM st tr -> proofError $ "Cannot infer the type of unannotated implicit lambda term " ++ pshowA (ALam st tr) ++ "."
AAppi tr1 tr2 -> do
tr1ty <- nwhnf =<< infer tr1
case tr1ty of
AIPi _ tp1 tp2 -> check tr2 tp1 >> return (sub tr2 tp2)
_ -> proofError $ "Term " ++ pshowA tr1 ++
" is not an implicit product type, and so cannot be applied to an argument."
AIPair tr1 tr2 -> proofError $ "Cannot infer the type of iota constructor " ++ pshowA (AIPair tr1 tr2) ++ "."
AFst tr -> do
trty <- nwhnf =<< infer tr
case trty of
AIota _ ty1 ty2 -> return ty1
_ -> proofError $ "Term " ++ pshowA tr ++ " is not a dependent intersection, and so cannot take first element."
ASnd tr -> do
trty <- nwhnf =<< infer tr
case trty of
AIota _ tp1 tp2 -> return (sub (AFst tr) tp2)
_ -> proofError $ "Term " ++ pshowA tr ++ " is not a dependent intersection, and so cannot take second element."
ABeta -> proofError "Identity proofs cannot be inferred."
ARho st tr1 ty tr2 -> do
tr1ty <- nwhnf =<< infer tr1
case tr1ty of
AId x y -> do
check tr2 (sub x ty)
liftMin (sub x ty) -- Note: this isn't used, unquote ty just needs some type.
return (sub y ty)
_ -> proofError $ "Term " ++ pshowA tr1 ++ " is a " ++ pshowA tr1ty ++ ", not an identity during term inference."
APi st ty1 ty2 -> do
liftMin ty1
local (ty1:) $ do
i <- liftMin ty2
return (AU i)
AIPi st ty1 ty2 -> do
liftMin ty1
local (ty1:) $ do
i <- liftMin ty2
return (AU i)
AIota st ty1 ty2 -> do
liftMin ty1
local (ty1:) $ do
i <- liftMin ty2
return (AU i)
AId x y -> do
ix <- liftMin =<< infer x
iy <- liftMin =<< infer y
return (AU (max ix iy))
AU i -> return (AU (i + 1))
check :: ATerm -> ATerm -> Proof ()
check tr ty = do
tyw <- nwhnf ty
case (tr, tyw) of
(AVS s, ty) -> do
tbl <- get
case Map.lookup s tbl of
Nothing -> proofError $ "Token " ++ s ++ " not found in context during type checking."
Just (_, t) -> do
tynf <- nf ty
tnf <- nf t
case (tynf, tnf) of
(AU j, AU i) ->
if i <= j
then return ()
else proofError $ "Size error during global name lookup. " ++ pshowA tr ++ " of type "
++ pshowA tnf ++ " is too big for universe " ++ pshowA tynf ++ "."
_ -> do
if tnf == tynf
then return ()
else proofError $ "Type didn't match during lookup. Expected something of type "
++ pshowA tynf ++ "; saw " ++ pshowA (AVS s) ++ " of type " ++ pshowA tnf ++ " instead."
(AV st n, ty) -> do
ctx <- ask
case (ctx , n) of
([], _) -> proofError $ "Cannot check type of variable term in an empty context."
(x:g, 0) -> do
tynf <- erase =<< nf ty
xnf <- erase =<< nf (quote x)
case (tynf, xnf) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during local variable lookup. " ++ pshowA tr ++ " of type "
++ pshowA x ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if tynf == xnf
then do
tyty <- infer ty
local tail $ check x (unquote tyty)
else proofError $ "Term does not have correct type. Expected something of type "
++ pshowA ty ++ "; saw " ++ pshowA (AV st n) ++ " of type " ++ pshowA x ++ " instead."
(_:g, _) -> local tail $ check (AV st (n - 1)) (unquote ty)
(ALam st tr, APi _ ty1 ty2) -> local (ty1:) (check tr ty2)
(ALam st tr, _) -> proofError $ "Lambdas can only be Pi types, not " ++ pshowA tyw ++ "."
(AAnn aty tr, ty) -> do
ctx <- ask
case ctx of
(cty : _) -> do
naty <- nf aty
ncty <- nf (quote cty)
case (naty, ncty) of
(AU j, AU i) ->
if i <= j
then return ()
else proofError $ "Size error during annotation check. " ++ pshowA tr ++ " of type "
++ pshowA naty ++ " is too big for universe " ++ pshowA ncty ++ "."
_ ->
if naty == ncty
then check tr ty
else proofError "Type annotation didn't match check."
_ -> proofError "Annotation appeared without being added to local context."
(AApp tr1 tr2, ty) -> do
tynf <- erase =<< nf ty
itynf <- erase =<< nf =<< infer (AApp tr1 tr2)
case (tynf, itynf) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during application check. " ++ pshowA (AApp tr1 tr2) ++ " of type "
++ pshowU (itynf) ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if tynf == itynf
then do
liftMin ty
return () -- Note: this isn't used, ty just needs some type.
else proofError $ "Failed to unify at application. Expected something of type "
++ pshowA ty ++ "; instead saw " ++ pshowA (AApp tr1 tr2) ++ " of type " ++
pshowU (itynf) ++ "."
(ALAM st tr, AIPi _ ty1 ty2) -> local (ty1:) (check tr ty2)
(ALAM st tr, _) -> proofError $ "Implicit lambdas can only be implicit products types, not " ++ pshowA tyw ++ "."
(AAppi tr1 tr2, ty)-> do
tynf <- erase =<< nf ty
itynf <- erase =<< nf =<< infer (AAppi tr1 tr2)
case (tynf, itynf) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during application check. " ++ pshowA (AAppi tr1 tr2) ++ " of type "
++ pshowU (itynf) ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if tynf == itynf
then liftMin ty >> return () -- Note: this isn't used, ty just needs some type.
else proofError $ "Failed to unify at application. Expected something of type "
++ pshowA ty ++ "; instead saw " ++ pshowA (AAppi tr1 tr2) ++ " of type " ++
pshowU (itynf) ++ "."
(AIPair t1 t2, AIota st tp1 tp2) -> do
nt1 <- erase =<< nf t1
nt2 <- erase =<< nf t2
if nt1 == nt2
then check t1 tp1 >> check t2 (sub t1 tp2)
else proofError $ "Iota constructor does not erase properly. " ++ pshowA t1 ++ " erases to " ++
pshowU nt1 ++ " while " ++ pshowA t2 ++ " erases to " ++ pshowU nt2 ++ "."
(AIPair t1 t2, _) -> proofError $ "IIota constructor must be a dependent intersection, not " ++ pshowA tyw ++ "."
(AFst tr, ty) -> do
ity <- infer (AFst tr)
nty <- erase =<< nf ty
nity <- erase =<< nf ity
case (nty, nity) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during iota elimination (#1). " ++ pshowA (AFst tr) ++ " of type "
++ pshowA (ity) ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if nty == nity
then infer ty >> return () -- Note: this isn't used, ty just needs some type.
else proofError $ "Failed to unify at iota elimination. (#1) " ++ pshowA (AFst tr) ++ " of type "
++ pshowA (ity) ++ " is not of type " ++ pshowA ty ++ "."
(ASnd tr, ty) -> do
ity <- infer (ASnd tr)
nty <- erase =<< nf ty
nity <- erase =<< nf ity
case (nty, nity) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during iota elimination (#2). " ++ pshowA (ASnd tr) ++ " of type "
++ pshowA (ity) ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if nty == nity
then infer ty >> return () -- Note: this isn't used, ty just needs some type.
else proofError $ "Failed to unify at iota elimination. (#2) " ++ pshowA (ASnd tr) ++ " of type "
++ pshowA (ity) ++ " is not of type " ++ pshowA ty ++ "."
(ABeta, AId t1 t2) -> do
nt1 <- erase =<< nf t1
nt2 <- erase =<< nf t2
if nt1 == nt2
then return ()
else proofError $ "Left hand side " ++ pshowA t1 ++ ", which erased to " ++ pshowU nt1 ++
", did not match right hand side " ++ pshowA t2 ++ ", which erased to "
++ pshowU nt2 ++ " during Beta check."
(ABeta, _) -> proofError "Identity constructor must construct identity."
(ARho st tr1 x tr2, ty) -> do
ntr1ty <- nwhnf =<< infer tr1
case ntr1ty of
AId t1 t2 -> do
nty <- erase =<< nf ty
nt2 <- erase =<< nf (sub t2 x)
if nty == nt2
then do
liftMin ty -- Note: This isn't used, ty just needs to have some type.
check tr2 (sub t1 x)
else proofError $ "Left hand side " ++ pshowA ty ++ ", which erased to " ++ pshowU nty ++
", did not match right hand side " ++ pshowA (sub t2 x) ++ ", which erased to "
++ pshowU nt2 ++ " during Rho check."
_ -> proofError "Term is not an identity during term checking."
(APi st ty1 ty2, AU i) -> liftMin ty1 >> local (ty1:) (check ty2 (AU i))
(APi st ty1 ty2, _) -> proofError $ "Pi types can only be in Universe types, not " ++ pshowA tyw ++ "."
(AIPi st ty1 ty2, AU i) -> liftMin ty1 >> local (ty1:) (check ty2 (AU i))
(AIPi st ty1 ty2, _) -> proofError $ "Implicit product types can only be in Universe types, not " ++ pshowA tyw ++ "."
(AIota st ty1 ty2, AU i) -> check ty1 (AU i) >> local (ty1:) (check ty2 (AU i))
(AIota st ty1 ty2, _) -> proofError $ "Dependent intersections types can only be in Universe types, not " ++ pshowA tyw ++ "."
(AId x y, AU i) -> do
xty <- infer x
check xty (AU i)
yty <- infer y
check yty (AU i)
return ()
(AId x y, _) -> proofError $ "Heterogeneous equalities can only be in Universe types, not " ++ pshowA tyw ++ "."
(AU i, AU j) -> if i < j then return () else proofError $ "Size error, level " ++ show i ++
" universe is not a term in the level " ++ show j ++ " universe."
(AU i, _) -> proofError $ "Universes can only exist in other universes, not " ++ pshowA tyw ++ "."
-- Gives the lowest type universe of a term.
liftMin :: ATerm -> Proof Int
liftMin a = do
aty <- infer a
case aty of
AU j -> return j
_ -> proofError $ "Universe error during lift, " ++ pshowA a ++ " is a " ++ pshowA aty ++ ", not a type."
| null | https://raw.githubusercontent.com/AHartNtkn/IotaTT/ada8e4b5aa7b525463369b56591ddc58dca91b4d/TypeChecker.hs | haskell | Note: this isn't used, x just needs some type.
Note: this isn't used, unquote ty just needs some type.
Note: this isn't used, unquote ty just needs to be a.
Note: this isn't used, unquote ty just needs some type.
Note: this isn't used, ty just needs some type.
Note: this isn't used, ty just needs some type.
Note: this isn't used, ty just needs some type.
Note: this isn't used, ty just needs some type.
Note: This isn't used, ty just needs to have some type.
Gives the lowest type universe of a term. | module TypeChecker where
import qualified Data.Map.Strict as Map
import Control.Monad.Reader hiding (liftIO)
import Control.Monad.State hiding (liftIO)
import Control.Monad.Except hiding (liftIO)
import Control.Monad.Trans.Except hiding (liftIO)
import AbstractSyntax
import PrettyPrinting
infer :: ATerm -> Proof ATerm
infer tr = do
wtr <- whnf tr
case wtr of
AVS s -> snd <$> lookupVar s
AV s n -> do
ctx <- ask
case (ctx , n) of
([] , _) -> proofError $ "Cannot infer term variable " ++ pshowA (AV s n) ++ " in empty context."
((x : _) , 0) -> local tail $ do
return (quote x)
((_ : _) , n) -> local tail (infer (AV s (n - 1))) >>= return . quote
ALam st (AAnn ty tr) -> do
ity <- local (unquote tr:) (infer tr)
return (APi st (unquote ty) ity)
ALam st tr -> proofError $ "Cannot infer the type of unannotated lambda term " ++ pshowA (ALam st tr) ++ "."
AAnn aty tr -> do
ctx <- ask
case ctx of
(cty : _) -> do
naty <- nf aty
ncty <- nf (quote cty)
if naty == ncty
then infer tr
else proofError $ "Type annotation " ++ pshowA aty ++ " didn't match contextual " ++
pshowA cty ++ " during inference."
_ -> proofError $ "Annotation " ++ pshowA aty ++
" appeared without being added to local context during type inference."
AApp tr1 tr2 -> do
tr1ty <- nwhnf =<< infer tr1
case tr1ty of
APi _ tp1 tp2 -> check tr2 tp1 >> return (sub tr2 tp2)
_ -> proofError $ "Term " ++ pshowA tr1 ++ " is not a pi type, and so cannot be applied to an argument."
ALAM st (AAnn ty tr) -> do
ity <- local (unquote tr:) (infer tr)
return (AIPi st (unquote ty) ity)
ALAM st tr -> proofError $ "Cannot infer the type of unannotated implicit lambda term " ++ pshowA (ALam st tr) ++ "."
AAppi tr1 tr2 -> do
tr1ty <- nwhnf =<< infer tr1
case tr1ty of
AIPi _ tp1 tp2 -> check tr2 tp1 >> return (sub tr2 tp2)
_ -> proofError $ "Term " ++ pshowA tr1 ++
" is not an implicit product type, and so cannot be applied to an argument."
AIPair tr1 tr2 -> proofError $ "Cannot infer the type of iota constructor " ++ pshowA (AIPair tr1 tr2) ++ "."
AFst tr -> do
trty <- nwhnf =<< infer tr
case trty of
AIota _ ty1 ty2 -> return ty1
_ -> proofError $ "Term " ++ pshowA tr ++ " is not a dependent intersection, and so cannot take first element."
ASnd tr -> do
trty <- nwhnf =<< infer tr
case trty of
AIota _ tp1 tp2 -> return (sub (AFst tr) tp2)
_ -> proofError $ "Term " ++ pshowA tr ++ " is not a dependent intersection, and so cannot take second element."
ABeta -> proofError "Identity proofs cannot be inferred."
ARho st tr1 ty tr2 -> do
tr1ty <- nwhnf =<< infer tr1
case tr1ty of
AId x y -> do
check tr2 (sub x ty)
return (sub y ty)
_ -> proofError $ "Term " ++ pshowA tr1 ++ " is a " ++ pshowA tr1ty ++ ", not an identity during term inference."
APi st ty1 ty2 -> do
liftMin ty1
local (ty1:) $ do
i <- liftMin ty2
return (AU i)
AIPi st ty1 ty2 -> do
liftMin ty1
local (ty1:) $ do
i <- liftMin ty2
return (AU i)
AIota st ty1 ty2 -> do
liftMin ty1
local (ty1:) $ do
i <- liftMin ty2
return (AU i)
AId x y -> do
ix <- liftMin =<< infer x
iy <- liftMin =<< infer y
return (AU (max ix iy))
AU i -> return (AU (i + 1))
check :: ATerm -> ATerm -> Proof ()
check tr ty = do
tyw <- nwhnf ty
case (tr, tyw) of
(AVS s, ty) -> do
tbl <- get
case Map.lookup s tbl of
Nothing -> proofError $ "Token " ++ s ++ " not found in context during type checking."
Just (_, t) -> do
tynf <- nf ty
tnf <- nf t
case (tynf, tnf) of
(AU j, AU i) ->
if i <= j
then return ()
else proofError $ "Size error during global name lookup. " ++ pshowA tr ++ " of type "
++ pshowA tnf ++ " is too big for universe " ++ pshowA tynf ++ "."
_ -> do
if tnf == tynf
then return ()
else proofError $ "Type didn't match during lookup. Expected something of type "
++ pshowA tynf ++ "; saw " ++ pshowA (AVS s) ++ " of type " ++ pshowA tnf ++ " instead."
(AV st n, ty) -> do
ctx <- ask
case (ctx , n) of
([], _) -> proofError $ "Cannot check type of variable term in an empty context."
(x:g, 0) -> do
tynf <- erase =<< nf ty
xnf <- erase =<< nf (quote x)
case (tynf, xnf) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during local variable lookup. " ++ pshowA tr ++ " of type "
++ pshowA x ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if tynf == xnf
then do
tyty <- infer ty
local tail $ check x (unquote tyty)
else proofError $ "Term does not have correct type. Expected something of type "
++ pshowA ty ++ "; saw " ++ pshowA (AV st n) ++ " of type " ++ pshowA x ++ " instead."
(_:g, _) -> local tail $ check (AV st (n - 1)) (unquote ty)
(ALam st tr, APi _ ty1 ty2) -> local (ty1:) (check tr ty2)
(ALam st tr, _) -> proofError $ "Lambdas can only be Pi types, not " ++ pshowA tyw ++ "."
(AAnn aty tr, ty) -> do
ctx <- ask
case ctx of
(cty : _) -> do
naty <- nf aty
ncty <- nf (quote cty)
case (naty, ncty) of
(AU j, AU i) ->
if i <= j
then return ()
else proofError $ "Size error during annotation check. " ++ pshowA tr ++ " of type "
++ pshowA naty ++ " is too big for universe " ++ pshowA ncty ++ "."
_ ->
if naty == ncty
then check tr ty
else proofError "Type annotation didn't match check."
_ -> proofError "Annotation appeared without being added to local context."
(AApp tr1 tr2, ty) -> do
tynf <- erase =<< nf ty
itynf <- erase =<< nf =<< infer (AApp tr1 tr2)
case (tynf, itynf) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during application check. " ++ pshowA (AApp tr1 tr2) ++ " of type "
++ pshowU (itynf) ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if tynf == itynf
then do
liftMin ty
else proofError $ "Failed to unify at application. Expected something of type "
++ pshowA ty ++ "; instead saw " ++ pshowA (AApp tr1 tr2) ++ " of type " ++
pshowU (itynf) ++ "."
(ALAM st tr, AIPi _ ty1 ty2) -> local (ty1:) (check tr ty2)
(ALAM st tr, _) -> proofError $ "Implicit lambdas can only be implicit products types, not " ++ pshowA tyw ++ "."
(AAppi tr1 tr2, ty)-> do
tynf <- erase =<< nf ty
itynf <- erase =<< nf =<< infer (AAppi tr1 tr2)
case (tynf, itynf) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during application check. " ++ pshowA (AAppi tr1 tr2) ++ " of type "
++ pshowU (itynf) ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if tynf == itynf
else proofError $ "Failed to unify at application. Expected something of type "
++ pshowA ty ++ "; instead saw " ++ pshowA (AAppi tr1 tr2) ++ " of type " ++
pshowU (itynf) ++ "."
(AIPair t1 t2, AIota st tp1 tp2) -> do
nt1 <- erase =<< nf t1
nt2 <- erase =<< nf t2
if nt1 == nt2
then check t1 tp1 >> check t2 (sub t1 tp2)
else proofError $ "Iota constructor does not erase properly. " ++ pshowA t1 ++ " erases to " ++
pshowU nt1 ++ " while " ++ pshowA t2 ++ " erases to " ++ pshowU nt2 ++ "."
(AIPair t1 t2, _) -> proofError $ "IIota constructor must be a dependent intersection, not " ++ pshowA tyw ++ "."
(AFst tr, ty) -> do
ity <- infer (AFst tr)
nty <- erase =<< nf ty
nity <- erase =<< nf ity
case (nty, nity) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during iota elimination (#1). " ++ pshowA (AFst tr) ++ " of type "
++ pshowA (ity) ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if nty == nity
else proofError $ "Failed to unify at iota elimination. (#1) " ++ pshowA (AFst tr) ++ " of type "
++ pshowA (ity) ++ " is not of type " ++ pshowA ty ++ "."
(ASnd tr, ty) -> do
ity <- infer (ASnd tr)
nty <- erase =<< nf ty
nity <- erase =<< nf ity
case (nty, nity) of
(U j, U i) ->
if i <= j
then return ()
else proofError $ "Size error during iota elimination (#2). " ++ pshowA (ASnd tr) ++ " of type "
++ pshowA (ity) ++ " is too big for universe " ++ pshowA ty ++ "."
_ ->
if nty == nity
else proofError $ "Failed to unify at iota elimination. (#2) " ++ pshowA (ASnd tr) ++ " of type "
++ pshowA (ity) ++ " is not of type " ++ pshowA ty ++ "."
(ABeta, AId t1 t2) -> do
nt1 <- erase =<< nf t1
nt2 <- erase =<< nf t2
if nt1 == nt2
then return ()
else proofError $ "Left hand side " ++ pshowA t1 ++ ", which erased to " ++ pshowU nt1 ++
", did not match right hand side " ++ pshowA t2 ++ ", which erased to "
++ pshowU nt2 ++ " during Beta check."
(ABeta, _) -> proofError "Identity constructor must construct identity."
(ARho st tr1 x tr2, ty) -> do
ntr1ty <- nwhnf =<< infer tr1
case ntr1ty of
AId t1 t2 -> do
nty <- erase =<< nf ty
nt2 <- erase =<< nf (sub t2 x)
if nty == nt2
then do
check tr2 (sub t1 x)
else proofError $ "Left hand side " ++ pshowA ty ++ ", which erased to " ++ pshowU nty ++
", did not match right hand side " ++ pshowA (sub t2 x) ++ ", which erased to "
++ pshowU nt2 ++ " during Rho check."
_ -> proofError "Term is not an identity during term checking."
(APi st ty1 ty2, AU i) -> liftMin ty1 >> local (ty1:) (check ty2 (AU i))
(APi st ty1 ty2, _) -> proofError $ "Pi types can only be in Universe types, not " ++ pshowA tyw ++ "."
(AIPi st ty1 ty2, AU i) -> liftMin ty1 >> local (ty1:) (check ty2 (AU i))
(AIPi st ty1 ty2, _) -> proofError $ "Implicit product types can only be in Universe types, not " ++ pshowA tyw ++ "."
(AIota st ty1 ty2, AU i) -> check ty1 (AU i) >> local (ty1:) (check ty2 (AU i))
(AIota st ty1 ty2, _) -> proofError $ "Dependent intersections types can only be in Universe types, not " ++ pshowA tyw ++ "."
(AId x y, AU i) -> do
xty <- infer x
check xty (AU i)
yty <- infer y
check yty (AU i)
return ()
(AId x y, _) -> proofError $ "Heterogeneous equalities can only be in Universe types, not " ++ pshowA tyw ++ "."
(AU i, AU j) -> if i < j then return () else proofError $ "Size error, level " ++ show i ++
" universe is not a term in the level " ++ show j ++ " universe."
(AU i, _) -> proofError $ "Universes can only exist in other universes, not " ++ pshowA tyw ++ "."
liftMin :: ATerm -> Proof Int
liftMin a = do
aty <- infer a
case aty of
AU j -> return j
_ -> proofError $ "Universe error during lift, " ++ pshowA a ++ " is a " ++ pshowA aty ++ ", not a type."
|
5222ca2920d4628df62186c83c6b22c610dd2f9543bb31692ff5ebe2aea50eb5 | scrintal/heroicons-reagent | hand_thumb_down.cljs | (ns com.scrintal.heroicons.mini.hand-thumb-down)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:d "M18.905 12.75a1.25 1.25 0 01-2.5 0v-7.5a1.25 1.25 0 112.5 0v7.5zM8.905 17v1.3c0 .268-.14.526-.395.607A2 2 0 015.905 17c0-.995.182-1.948.514-2.826.204-.54-.166-1.174-.744-1.174h-2.52c-1.242 0-2.26-1.01-2.146-2.247.193-2.08.652-4.082 1.341-5.974C2.752 3.678 3.833 3 5.005 3h3.192a3 3 0 011.342.317l2.733 1.366A3 3 0 0013.613 5h1.292v7h-.963c-.684 0-1.258.482-1.612 1.068a4.012 4.012 0 01-2.165 1.73c-.433.143-.854.386-1.012.814-.16.432-.248.9-.248 1.388z"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/mini/hand_thumb_down.cljs | clojure | (ns com.scrintal.heroicons.mini.hand-thumb-down)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:d "M18.905 12.75a1.25 1.25 0 01-2.5 0v-7.5a1.25 1.25 0 112.5 0v7.5zM8.905 17v1.3c0 .268-.14.526-.395.607A2 2 0 015.905 17c0-.995.182-1.948.514-2.826.204-.54-.166-1.174-.744-1.174h-2.52c-1.242 0-2.26-1.01-2.146-2.247.193-2.08.652-4.082 1.341-5.974C2.752 3.678 3.833 3 5.005 3h3.192a3 3 0 011.342.317l2.733 1.366A3 3 0 0013.613 5h1.292v7h-.963c-.684 0-1.258.482-1.612 1.068a4.012 4.012 0 01-2.165 1.73c-.433.143-.854.386-1.012.814-.16.432-.248.9-.248 1.388z"}]]) | |
31cc6df863c048ccdc58ef916a391f3ff283f16ea852954678540a26adec1786 | jrm-code-project/LISP-Machine | fasupd.lisp | ;; -*-Mode:LISP; Package:ZWEI; Base:8 -*-
(DEFCOM COM-FASL-UPDATE
"Update the fasl file of the file you are visiting.
Uses the function definitions present in the environment,
offering to compile them if they have changed.
Note that DECLAREs and EVAL-WHEN (COMPILE)s will be ignored!" ()
(LET ((BUFFER (READ-BUFFER-NAME "Update fasl file of buffer:"
*INTERVAL* ;Default is current buffer.
NIL)))
(OR (BUFFER-FILE-ID BUFFER)
(BARF "This buffer is not associated with a file"))
(SI:FILE-OPERATION-WITH-WARNINGS
((AND (BUFFER-FILE-ID BUFFER)
(FUNCALL (SEND BUFFER ':GENERIC-PATHNAME) ':GENERIC-PATHNAME))
':COMPILE NIL)
(COMPILER:COMPILER-WARNINGS-CONTEXT-BIND
(COMPILE-BUFFER-CHANGED-FUNCTIONS BUFFER T)))
(FASL-UPDATE BUFFER))
DIS-NONE)
Write out the compilations of the functions whose sources are in BUFFER .
;; We assume that the user has compiled all the functions he has changed.
The QFASL file name is formed from the name of the buffer .
;; We don't actually do any compilation or evaluation of the buffer,
;; though we do expand the macros.
;; Normally, we read each form from the buffer and process it.
For forms starting with DEFUN and DEFMETHOD , we read only the
;; function name, which is enough to use to dump the function,
and then we skip the rest of the form and cons up a dummy DEFUN or DEFMETHOD
;; with no body or arglist to use in doing the dumping.
(DEFUN FASL-UPDATE (BUFFER &OPTIONAL OUTFILE &AUX INFILE)
(SETQ INFILE (BUFFER-PATHNAME BUFFER))
(SETQ OUTFILE
(IF OUTFILE
(FS:MERGE-PATHNAME-DEFAULTS OUTFILE INFILE ':QFASL)
(FUNCALL INFILE ':NEW-TYPE ':QFASL)))
(COMPILER#:FASL-UPDATE-STREAM INFILE OUTFILE (INTERVAL-STREAM BUFFER)
'FASL-UPDATE-BUFFER-READ-FUNCTION))
;;; This function acts like READ, but it doesn't always really do a READ.
;;; It can examine the form coming up and skip it, returning a dummy form.
(DEFUN FASL-UPDATE-BUFFER-READ-FUNCTION (INPUT-STREAM EOF-OPTION)
;; Find next interesting object in buffer.
(LET ((BP (SKIP-OVER-BLANK-LINES-AND-COMMENTS
(FUNCALL INPUT-STREAM ':READ-BP))))
(IF (NULL BP) EOF-OPTION
;; This is intended to look at the form that follows,
;; decide whether it is a defun, and if so
;; just create a dummy, since we will not look at the body anyway.
(MULTIPLE-VALUE-BIND (DEFTYPE FNNAME)
(FASL-UPDATE-CHECK-DEFUN BP)
(COND ((AND DEFTYPE
(FDEFINEDP (IF (EQ DEFTYPE 'DEFMETHOD)
(CONS ':METHOD FNNAME)
FNNAME)))
(FUNCALL INPUT-STREAM ':SET-BP
;; The memo-izing lisp parser can cons permanent information
(LET ((DEFAULT-CONS-AREA SYS:BACKGROUND-CONS-AREA))
(FORWARD-SEXP BP)))
`(,DEFTYPE ,FNNAME NIL NIL))
(T
(FUNCALL INPUT-STREAM ':SET-BP BP)
(READ INPUT-STREAM EOF-OPTION)))))))
;; This is the list of types of form that we don't even need to read.
(DECLARE (SPECIAL FASL-UPDATE-DEFTYPES-ALIST))
(SETQ FASL-UPDATE-DEFTYPES-ALIST
'(("DEFUN" DEFUN) ("DEFMETHOD" DEFMETHOD)))
(DEFUN FASL-UPDATE-CHECK-DEFUN (BP &AUX BP1 DEFTYPE FNNAME)
Now get the second word after BP .
(AND (= (BP-CH-CHAR BP) #/()
(SETQ BP (FORWARD-CHAR BP))
(SETQ BP1 (FORWARD-ATOM BP))
(SETQ DEFTYPE (CADR (ASS 'EQUALP (STRING-INTERVAL BP BP1)
FASL-UPDATE-DEFTYPES-ALIST)))
(SETQ BP (FORWARD-OVER *BLANKS* BP1))
(SETQ BP1 (FORWARD-SEXP BP))
(SETQ FNNAME (STRING-REMOVE-FONTS (STRING-INTERVAL BP BP1)))
(VALUES DEFTYPE (READ-FROM-STRING FNNAME))))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/zwei/fasupd.lisp | lisp | -*-Mode:LISP; Package:ZWEI; Base:8 -*-
Default is current buffer.
We assume that the user has compiled all the functions he has changed.
We don't actually do any compilation or evaluation of the buffer,
though we do expand the macros.
Normally, we read each form from the buffer and process it.
function name, which is enough to use to dump the function,
with no body or arglist to use in doing the dumping.
This function acts like READ, but it doesn't always really do a READ.
It can examine the form coming up and skip it, returning a dummy form.
Find next interesting object in buffer.
This is intended to look at the form that follows,
decide whether it is a defun, and if so
just create a dummy, since we will not look at the body anyway.
The memo-izing lisp parser can cons permanent information
This is the list of types of form that we don't even need to read. |
(DEFCOM COM-FASL-UPDATE
"Update the fasl file of the file you are visiting.
Uses the function definitions present in the environment,
offering to compile them if they have changed.
Note that DECLAREs and EVAL-WHEN (COMPILE)s will be ignored!" ()
(LET ((BUFFER (READ-BUFFER-NAME "Update fasl file of buffer:"
NIL)))
(OR (BUFFER-FILE-ID BUFFER)
(BARF "This buffer is not associated with a file"))
(SI:FILE-OPERATION-WITH-WARNINGS
((AND (BUFFER-FILE-ID BUFFER)
(FUNCALL (SEND BUFFER ':GENERIC-PATHNAME) ':GENERIC-PATHNAME))
':COMPILE NIL)
(COMPILER:COMPILER-WARNINGS-CONTEXT-BIND
(COMPILE-BUFFER-CHANGED-FUNCTIONS BUFFER T)))
(FASL-UPDATE BUFFER))
DIS-NONE)
Write out the compilations of the functions whose sources are in BUFFER .
The QFASL file name is formed from the name of the buffer .
For forms starting with DEFUN and DEFMETHOD , we read only the
and then we skip the rest of the form and cons up a dummy DEFUN or DEFMETHOD
(DEFUN FASL-UPDATE (BUFFER &OPTIONAL OUTFILE &AUX INFILE)
(SETQ INFILE (BUFFER-PATHNAME BUFFER))
(SETQ OUTFILE
(IF OUTFILE
(FS:MERGE-PATHNAME-DEFAULTS OUTFILE INFILE ':QFASL)
(FUNCALL INFILE ':NEW-TYPE ':QFASL)))
(COMPILER#:FASL-UPDATE-STREAM INFILE OUTFILE (INTERVAL-STREAM BUFFER)
'FASL-UPDATE-BUFFER-READ-FUNCTION))
(DEFUN FASL-UPDATE-BUFFER-READ-FUNCTION (INPUT-STREAM EOF-OPTION)
(LET ((BP (SKIP-OVER-BLANK-LINES-AND-COMMENTS
(FUNCALL INPUT-STREAM ':READ-BP))))
(IF (NULL BP) EOF-OPTION
(MULTIPLE-VALUE-BIND (DEFTYPE FNNAME)
(FASL-UPDATE-CHECK-DEFUN BP)
(COND ((AND DEFTYPE
(FDEFINEDP (IF (EQ DEFTYPE 'DEFMETHOD)
(CONS ':METHOD FNNAME)
FNNAME)))
(FUNCALL INPUT-STREAM ':SET-BP
(LET ((DEFAULT-CONS-AREA SYS:BACKGROUND-CONS-AREA))
(FORWARD-SEXP BP)))
`(,DEFTYPE ,FNNAME NIL NIL))
(T
(FUNCALL INPUT-STREAM ':SET-BP BP)
(READ INPUT-STREAM EOF-OPTION)))))))
(DECLARE (SPECIAL FASL-UPDATE-DEFTYPES-ALIST))
(SETQ FASL-UPDATE-DEFTYPES-ALIST
'(("DEFUN" DEFUN) ("DEFMETHOD" DEFMETHOD)))
(DEFUN FASL-UPDATE-CHECK-DEFUN (BP &AUX BP1 DEFTYPE FNNAME)
Now get the second word after BP .
(AND (= (BP-CH-CHAR BP) #/()
(SETQ BP (FORWARD-CHAR BP))
(SETQ BP1 (FORWARD-ATOM BP))
(SETQ DEFTYPE (CADR (ASS 'EQUALP (STRING-INTERVAL BP BP1)
FASL-UPDATE-DEFTYPES-ALIST)))
(SETQ BP (FORWARD-OVER *BLANKS* BP1))
(SETQ BP1 (FORWARD-SEXP BP))
(SETQ FNNAME (STRING-REMOVE-FONTS (STRING-INTERVAL BP BP1)))
(VALUES DEFTYPE (READ-FROM-STRING FNNAME))))
|
f3c032bd68d84563554bbfe868a5942fa7101f804315e906dd24f80469fae075 | aligusnet/mltool | GradientDescent.hs | |
Module : MachineLearning . Optimization . GradientDescent
Description : Gradient Descent
Copyright : ( c ) , 2016
License : BSD-3
Stability : experimental
Portability : POSIX
Module: MachineLearning.Optimization.GradientDescent
Description: Gradient Descent
Copyright: (c) Alexander Ignatyev, 2016
License: BSD-3
Stability: experimental
Portability: POSIX
-}
module MachineLearning.Optimization.GradientDescent
(
gradientDescent
)
where
import MachineLearning.Types (R, Vector, Matrix)
import MachineLearning.Regularization (Regularization)
import qualified Data.Vector.Storable as V
import qualified Numeric.LinearAlgebra as LA
import qualified MachineLearning.Model as Model
-- | Gradient Descent method implementation. See "MachineLearning.Regression" for usage details.
gradientDescent :: Model.Model a => R-> a -> R -> Int -> Regularization -> Matrix -> Vector -> Vector -> (Vector, Matrix)
gradientDescent alpha model eps maxIters lambda x y theta = helper theta maxIters []
where gradient = Model.gradient model lambda
cost = Model.cost model lambda
helper theta nIters optPath =
let theta' = theta - (LA.scale alpha (gradient x y theta))
j = cost x y theta'
gradientTest = LA.norm_2 (theta' - theta) < eps
optPathRow = V.concat [LA.vector [(fromIntegral $ maxIters - nIters), j], theta']
optPath' = optPathRow : optPath
in if gradientTest || nIters <= 1
then (theta, LA.fromRows $ reverse optPath')
else helper theta' (nIters - 1) optPath'
| null | https://raw.githubusercontent.com/aligusnet/mltool/92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b/src/MachineLearning/Optimization/GradientDescent.hs | haskell | | Gradient Descent method implementation. See "MachineLearning.Regression" for usage details. | |
Module : MachineLearning . Optimization . GradientDescent
Description : Gradient Descent
Copyright : ( c ) , 2016
License : BSD-3
Stability : experimental
Portability : POSIX
Module: MachineLearning.Optimization.GradientDescent
Description: Gradient Descent
Copyright: (c) Alexander Ignatyev, 2016
License: BSD-3
Stability: experimental
Portability: POSIX
-}
module MachineLearning.Optimization.GradientDescent
(
gradientDescent
)
where
import MachineLearning.Types (R, Vector, Matrix)
import MachineLearning.Regularization (Regularization)
import qualified Data.Vector.Storable as V
import qualified Numeric.LinearAlgebra as LA
import qualified MachineLearning.Model as Model
gradientDescent :: Model.Model a => R-> a -> R -> Int -> Regularization -> Matrix -> Vector -> Vector -> (Vector, Matrix)
gradientDescent alpha model eps maxIters lambda x y theta = helper theta maxIters []
where gradient = Model.gradient model lambda
cost = Model.cost model lambda
helper theta nIters optPath =
let theta' = theta - (LA.scale alpha (gradient x y theta))
j = cost x y theta'
gradientTest = LA.norm_2 (theta' - theta) < eps
optPathRow = V.concat [LA.vector [(fromIntegral $ maxIters - nIters), j], theta']
optPath' = optPathRow : optPath
in if gradientTest || nIters <= 1
then (theta, LA.fromRows $ reverse optPath')
else helper theta' (nIters - 1) optPath'
|
2da83a52081c1055a37447070c4d68cdbefcfa50976fdecde88eda8bfceb842e | processone/ejabberd | ejabberd_auth_mnesia.erl | %%%----------------------------------------------------------------------
%%% File : ejabberd_auth_mnesia.erl
Author : < >
%%% Purpose : Authentication via mnesia
Created : 12 Dec 2004 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(ejabberd_auth_mnesia).
-author('').
-behaviour(ejabberd_auth).
-export([start/1, stop/1, set_password/3, try_register/3,
get_users/2, init_db/0,
count_users/2, get_password/2,
remove_user/2, store_type/1, import/2,
plain_password_required/1, use_cache/1]).
-export([need_transform/1, transform/1]).
-include("logger.hrl").
-include_lib("xmpp/include/scram.hrl").
-include("ejabberd_auth.hrl").
-record(reg_users_counter, {vhost = <<"">> :: binary(),
count = 0 :: integer() | '$1'}).
%%%----------------------------------------------------------------------
%%% API
%%%----------------------------------------------------------------------
start(Host) ->
init_db(),
update_reg_users_counter_table(Host),
ok.
stop(_Host) ->
ok.
init_db() ->
ejabberd_mnesia:create(?MODULE, passwd,
[{disc_only_copies, [node()]},
{attributes, record_info(fields, passwd)}]),
ejabberd_mnesia:create(?MODULE, reg_users_counter,
[{ram_copies, [node()]},
{attributes, record_info(fields, reg_users_counter)}]).
update_reg_users_counter_table(Server) ->
Set = get_users(Server, []),
Size = length(Set),
LServer = jid:nameprep(Server),
F = fun () ->
mnesia:write(#reg_users_counter{vhost = LServer,
count = Size})
end,
mnesia:sync_dirty(F).
use_cache(Host) ->
case mnesia:table_info(passwd, storage_type) of
disc_only_copies ->
ejabberd_option:auth_use_cache(Host);
_ ->
false
end.
plain_password_required(Server) ->
store_type(Server) == scram.
store_type(Server) ->
ejabberd_auth:password_format(Server).
set_password(User, Server, Password) ->
US = {User, Server},
F = fun () ->
mnesia:write(#passwd{us = US, password = Password})
end,
case mnesia:transaction(F) of
{atomic, ok} ->
{cache, {ok, Password}};
{aborted, Reason} ->
?ERROR_MSG("Mnesia transaction failed: ~p", [Reason]),
{nocache, {error, db_failure}}
end.
try_register(User, Server, Password) ->
US = {User, Server},
F = fun () ->
case mnesia:read({passwd, US}) of
[] ->
mnesia:write(#passwd{us = US, password = Password}),
mnesia:dirty_update_counter(reg_users_counter, Server, 1),
{ok, Password};
[_] ->
{error, exists}
end
end,
case mnesia:transaction(F) of
{atomic, Res} ->
{cache, Res};
{aborted, Reason} ->
?ERROR_MSG("Mnesia transaction failed: ~p", [Reason]),
{nocache, {error, db_failure}}
end.
get_users(Server, []) ->
mnesia:dirty_select(passwd,
[{#passwd{us = '$1', _ = '_'},
[{'==', {element, 2, '$1'}, Server}], ['$1']}]);
get_users(Server, [{from, Start}, {to, End}])
when is_integer(Start) and is_integer(End) ->
get_users(Server, [{limit, End - Start + 1}, {offset, Start}]);
get_users(Server, [{limit, Limit}, {offset, Offset}])
when is_integer(Limit) and is_integer(Offset) ->
case get_users(Server, []) of
[] ->
[];
Users ->
Set = lists:keysort(1, Users),
L = length(Set),
Start = if Offset < 1 -> 1;
Offset > L -> L;
true -> Offset
end,
lists:sublist(Set, Start, Limit)
end;
get_users(Server, [{prefix, Prefix}]) when is_binary(Prefix) ->
Set = [{U, S} || {U, S} <- get_users(Server, []), str:prefix(Prefix, U)],
lists:keysort(1, Set);
get_users(Server, [{prefix, Prefix}, {from, Start}, {to, End}])
when is_binary(Prefix) and is_integer(Start) and is_integer(End) ->
get_users(Server, [{prefix, Prefix}, {limit, End - Start + 1},
{offset, Start}]);
get_users(Server, [{prefix, Prefix}, {limit, Limit}, {offset, Offset}])
when is_binary(Prefix) and is_integer(Limit) and is_integer(Offset) ->
case [{U, S} || {U, S} <- get_users(Server, []), str:prefix(Prefix, U)] of
[] ->
[];
Users ->
Set = lists:keysort(1, Users),
L = length(Set),
Start = if Offset < 1 -> 1;
Offset > L -> L;
true -> Offset
end,
lists:sublist(Set, Start, Limit)
end;
get_users(Server, _) ->
get_users(Server, []).
count_users(Server, []) ->
case mnesia:dirty_select(
reg_users_counter,
[{#reg_users_counter{vhost = Server, count = '$1'},
[], ['$1']}]) of
[Count] -> Count;
_ -> 0
end;
count_users(Server, [{prefix, Prefix}]) when is_binary(Prefix) ->
Set = [{U, S} || {U, S} <- get_users(Server, []), str:prefix(Prefix, U)],
length(Set);
count_users(Server, _) ->
count_users(Server, []).
get_password(User, Server) ->
case mnesia:dirty_read(passwd, {User, Server}) of
[{passwd, _, {scram, SK, SEK, Salt, IC}}] ->
{cache, {ok, #scram{storedkey = SK, serverkey = SEK,
salt = Salt, hash = sha, iterationcount = IC}}};
[#passwd{password = Password}] ->
{cache, {ok, Password}};
_ ->
{cache, error}
end.
remove_user(User, Server) ->
US = {User, Server},
F = fun () ->
mnesia:delete({passwd, US}),
mnesia:dirty_update_counter(reg_users_counter, Server, -1),
ok
end,
case mnesia:transaction(F) of
{atomic, ok} ->
ok;
{aborted, Reason} ->
?ERROR_MSG("Mnesia transaction failed: ~p", [Reason]),
{error, db_failure}
end.
need_transform(#reg_users_counter{}) ->
false;
need_transform({passwd, {U, S}, Pass}) ->
case Pass of
_ when is_binary(Pass) ->
case store_type(S) of
scram ->
?INFO_MSG("Passwords in Mnesia table 'passwd' "
"will be SCRAM'ed", []),
true;
plain ->
false
end;
{scram, _, _, _, _} ->
case store_type(S) of
scram ->
false;
plain ->
?WARNING_MSG("Some passwords were stored in the database "
"as SCRAM, but 'auth_password_format' "
"is not configured as 'scram': some "
"authentication mechanisms such as DIGEST-MD5 "
"would *fail*", []),
false
end;
#scram{} ->
case store_type(S) of
scram ->
false;
plain ->
?WARNING_MSG("Some passwords were stored in the database "
"as SCRAM, but 'auth_password_format' "
"is not configured as 'scram': some "
"authentication mechanisms such as DIGEST-MD5 "
"would *fail*", []),
false
end;
_ when is_list(U) orelse is_list(S) orelse is_list(Pass) ->
?INFO_MSG("Mnesia table 'passwd' will be converted to binary", []),
true
end.
transform({passwd, {U, S}, Pass})
when is_list(U) orelse is_list(S) orelse is_list(Pass) ->
NewUS = {iolist_to_binary(U), iolist_to_binary(S)},
NewPass = case Pass of
#scram{storedkey = StoredKey,
serverkey = ServerKey,
salt = Salt} ->
Pass#scram{
storedkey = iolist_to_binary(StoredKey),
serverkey = iolist_to_binary(ServerKey),
salt = iolist_to_binary(Salt)};
_ ->
iolist_to_binary(Pass)
end,
transform(#passwd{us = NewUS, password = NewPass});
transform(#passwd{us = {U, S}, password = Password} = P)
when is_binary(Password) ->
case store_type(S) of
scram ->
case jid:resourceprep(Password) of
error ->
?ERROR_MSG("SASLprep failed for password of user ~ts@~ts",
[U, S]),
P;
_ ->
Scram = ejabberd_auth:password_to_scram(S, Password),
P#passwd{password = Scram}
end;
plain ->
P
end;
transform({passwd, _, {scram, _, _, _, _}} = P) ->
P;
transform(#passwd{password = #scram{}} = P) ->
P.
import(LServer, [LUser, Password, _TimeStamp]) ->
mnesia:dirty_write(
#passwd{us = {LUser, LServer}, password = Password}).
| null | https://raw.githubusercontent.com/processone/ejabberd/c103182bc7e5b8a8ab123ce02d1959a54e939480/src/ejabberd_auth_mnesia.erl | erlang | ----------------------------------------------------------------------
File : ejabberd_auth_mnesia.erl
Purpose : Authentication via mnesia
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
----------------------------------------------------------------------
API
---------------------------------------------------------------------- | Author : < >
Created : 12 Dec 2004 by < >
ejabberd , Copyright ( C ) 2002 - 2023 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(ejabberd_auth_mnesia).
-author('').
-behaviour(ejabberd_auth).
-export([start/1, stop/1, set_password/3, try_register/3,
get_users/2, init_db/0,
count_users/2, get_password/2,
remove_user/2, store_type/1, import/2,
plain_password_required/1, use_cache/1]).
-export([need_transform/1, transform/1]).
-include("logger.hrl").
-include_lib("xmpp/include/scram.hrl").
-include("ejabberd_auth.hrl").
-record(reg_users_counter, {vhost = <<"">> :: binary(),
count = 0 :: integer() | '$1'}).
start(Host) ->
init_db(),
update_reg_users_counter_table(Host),
ok.
stop(_Host) ->
ok.
init_db() ->
ejabberd_mnesia:create(?MODULE, passwd,
[{disc_only_copies, [node()]},
{attributes, record_info(fields, passwd)}]),
ejabberd_mnesia:create(?MODULE, reg_users_counter,
[{ram_copies, [node()]},
{attributes, record_info(fields, reg_users_counter)}]).
update_reg_users_counter_table(Server) ->
Set = get_users(Server, []),
Size = length(Set),
LServer = jid:nameprep(Server),
F = fun () ->
mnesia:write(#reg_users_counter{vhost = LServer,
count = Size})
end,
mnesia:sync_dirty(F).
use_cache(Host) ->
case mnesia:table_info(passwd, storage_type) of
disc_only_copies ->
ejabberd_option:auth_use_cache(Host);
_ ->
false
end.
plain_password_required(Server) ->
store_type(Server) == scram.
store_type(Server) ->
ejabberd_auth:password_format(Server).
set_password(User, Server, Password) ->
US = {User, Server},
F = fun () ->
mnesia:write(#passwd{us = US, password = Password})
end,
case mnesia:transaction(F) of
{atomic, ok} ->
{cache, {ok, Password}};
{aborted, Reason} ->
?ERROR_MSG("Mnesia transaction failed: ~p", [Reason]),
{nocache, {error, db_failure}}
end.
try_register(User, Server, Password) ->
US = {User, Server},
F = fun () ->
case mnesia:read({passwd, US}) of
[] ->
mnesia:write(#passwd{us = US, password = Password}),
mnesia:dirty_update_counter(reg_users_counter, Server, 1),
{ok, Password};
[_] ->
{error, exists}
end
end,
case mnesia:transaction(F) of
{atomic, Res} ->
{cache, Res};
{aborted, Reason} ->
?ERROR_MSG("Mnesia transaction failed: ~p", [Reason]),
{nocache, {error, db_failure}}
end.
get_users(Server, []) ->
mnesia:dirty_select(passwd,
[{#passwd{us = '$1', _ = '_'},
[{'==', {element, 2, '$1'}, Server}], ['$1']}]);
get_users(Server, [{from, Start}, {to, End}])
when is_integer(Start) and is_integer(End) ->
get_users(Server, [{limit, End - Start + 1}, {offset, Start}]);
get_users(Server, [{limit, Limit}, {offset, Offset}])
when is_integer(Limit) and is_integer(Offset) ->
case get_users(Server, []) of
[] ->
[];
Users ->
Set = lists:keysort(1, Users),
L = length(Set),
Start = if Offset < 1 -> 1;
Offset > L -> L;
true -> Offset
end,
lists:sublist(Set, Start, Limit)
end;
get_users(Server, [{prefix, Prefix}]) when is_binary(Prefix) ->
Set = [{U, S} || {U, S} <- get_users(Server, []), str:prefix(Prefix, U)],
lists:keysort(1, Set);
get_users(Server, [{prefix, Prefix}, {from, Start}, {to, End}])
when is_binary(Prefix) and is_integer(Start) and is_integer(End) ->
get_users(Server, [{prefix, Prefix}, {limit, End - Start + 1},
{offset, Start}]);
get_users(Server, [{prefix, Prefix}, {limit, Limit}, {offset, Offset}])
when is_binary(Prefix) and is_integer(Limit) and is_integer(Offset) ->
case [{U, S} || {U, S} <- get_users(Server, []), str:prefix(Prefix, U)] of
[] ->
[];
Users ->
Set = lists:keysort(1, Users),
L = length(Set),
Start = if Offset < 1 -> 1;
Offset > L -> L;
true -> Offset
end,
lists:sublist(Set, Start, Limit)
end;
get_users(Server, _) ->
get_users(Server, []).
count_users(Server, []) ->
case mnesia:dirty_select(
reg_users_counter,
[{#reg_users_counter{vhost = Server, count = '$1'},
[], ['$1']}]) of
[Count] -> Count;
_ -> 0
end;
count_users(Server, [{prefix, Prefix}]) when is_binary(Prefix) ->
Set = [{U, S} || {U, S} <- get_users(Server, []), str:prefix(Prefix, U)],
length(Set);
count_users(Server, _) ->
count_users(Server, []).
get_password(User, Server) ->
case mnesia:dirty_read(passwd, {User, Server}) of
[{passwd, _, {scram, SK, SEK, Salt, IC}}] ->
{cache, {ok, #scram{storedkey = SK, serverkey = SEK,
salt = Salt, hash = sha, iterationcount = IC}}};
[#passwd{password = Password}] ->
{cache, {ok, Password}};
_ ->
{cache, error}
end.
remove_user(User, Server) ->
US = {User, Server},
F = fun () ->
mnesia:delete({passwd, US}),
mnesia:dirty_update_counter(reg_users_counter, Server, -1),
ok
end,
case mnesia:transaction(F) of
{atomic, ok} ->
ok;
{aborted, Reason} ->
?ERROR_MSG("Mnesia transaction failed: ~p", [Reason]),
{error, db_failure}
end.
need_transform(#reg_users_counter{}) ->
false;
need_transform({passwd, {U, S}, Pass}) ->
case Pass of
_ when is_binary(Pass) ->
case store_type(S) of
scram ->
?INFO_MSG("Passwords in Mnesia table 'passwd' "
"will be SCRAM'ed", []),
true;
plain ->
false
end;
{scram, _, _, _, _} ->
case store_type(S) of
scram ->
false;
plain ->
?WARNING_MSG("Some passwords were stored in the database "
"as SCRAM, but 'auth_password_format' "
"is not configured as 'scram': some "
"authentication mechanisms such as DIGEST-MD5 "
"would *fail*", []),
false
end;
#scram{} ->
case store_type(S) of
scram ->
false;
plain ->
?WARNING_MSG("Some passwords were stored in the database "
"as SCRAM, but 'auth_password_format' "
"is not configured as 'scram': some "
"authentication mechanisms such as DIGEST-MD5 "
"would *fail*", []),
false
end;
_ when is_list(U) orelse is_list(S) orelse is_list(Pass) ->
?INFO_MSG("Mnesia table 'passwd' will be converted to binary", []),
true
end.
transform({passwd, {U, S}, Pass})
when is_list(U) orelse is_list(S) orelse is_list(Pass) ->
NewUS = {iolist_to_binary(U), iolist_to_binary(S)},
NewPass = case Pass of
#scram{storedkey = StoredKey,
serverkey = ServerKey,
salt = Salt} ->
Pass#scram{
storedkey = iolist_to_binary(StoredKey),
serverkey = iolist_to_binary(ServerKey),
salt = iolist_to_binary(Salt)};
_ ->
iolist_to_binary(Pass)
end,
transform(#passwd{us = NewUS, password = NewPass});
transform(#passwd{us = {U, S}, password = Password} = P)
when is_binary(Password) ->
case store_type(S) of
scram ->
case jid:resourceprep(Password) of
error ->
?ERROR_MSG("SASLprep failed for password of user ~ts@~ts",
[U, S]),
P;
_ ->
Scram = ejabberd_auth:password_to_scram(S, Password),
P#passwd{password = Scram}
end;
plain ->
P
end;
transform({passwd, _, {scram, _, _, _, _}} = P) ->
P;
transform(#passwd{password = #scram{}} = P) ->
P.
import(LServer, [LUser, Password, _TimeStamp]) ->
mnesia:dirty_write(
#passwd{us = {LUser, LServer}, password = Password}).
|
8b0b2be4d383ae9333b1736963f9f22c430eaacb409a3ffc4551160b9ddb99ac | finnishtransportagency/harja | indeksit_test.clj | (ns harja.palvelin.palvelut.indeksit-test
(:require [clojure.test :refer :all]
[taoensso.timbre :as log]
[harja.palvelin.komponentit.tietokanta :as tietokanta]
[harja.palvelin.palvelut.indeksit :refer :all]
[harja.testi :refer :all]
[com.stuartsierra.component :as component]
[clojure.string :as str]
[harja.domain.urakka :as urakka]
[harja.palvelin.palvelut.indeksit :as indeksit]
[harja.palvelin.palvelut.budjettisuunnittelu :as budjettisuunnittelu]))
(defn jarjestelma-fixture [testit]
(alter-var-root #'jarjestelma
(fn [_]
(component/start
(component/system-map
:db (tietokanta/luo-tietokanta testitietokanta)
:http-palvelin (testi-http-palvelin)
:indeksit (component/using
(->Indeksit)
[:http-palvelin :db])))))
(testit)
(alter-var-root #'jarjestelma component/stop))
(use-fixtures :each (compose-fixtures tietokanta-fixture jarjestelma-fixture))
maku 2005 vuonna 2013
[ " MAKU 2005 " 2013 ] { : 2013 , 12 110.1 , 11 110.5 , 1 109.2 } }
(deftest kaikki-indeksit-haettu-oikein
(let [indeksit (kutsu-palvelua (:http-palvelin jarjestelma)
:indeksit +kayttaja-jvh+)
maku-2005-2013 (get indeksit ["MAKU 2005" 2013])]
(is (> (count indeksit) 0))
(is (= (count maku-2005-2013) 13))
(is (every? some? maku-2005-2013))
(is (= (:vuosi maku-2005-2013) 2013))
< - odota ongelmia
;; HAR-4035 bugin verifiointi
(deftest kuukauden-indeksikorotuksen-laskenta
(let [korotus
(ffirst (q (str "SELECT korotus from laske_kuukauden_indeksikorotus
(2016, 10, 'MAKU 2005', 387800, 135.4);")))]
(is (=marginaalissa? korotus 1145.64))))
(deftest urakkatyypin-indeksien-haku
(let [indeksit (kutsu-palvelua (:http-palvelin jarjestelma)
:urakkatyypin-indeksit +kayttaja-jvh+)
{:keys [hoito tiemerkinta paallystys vesivayla-kanavien-hoito]}
(group-by :urakkatyyppi indeksit)]
(is (some #(= "MAKU 2005" (:indeksinimi %)) hoito))
(is (some #(= "MAKU 2010" (:indeksinimi %)) hoito))
(is (some #(= "MAKU 2015" (:indeksinimi %)) hoito))
(is (some #(= "MAKU 2010" (:indeksinimi %)) tiemerkinta))
(is (some #(= "Platts: FO 3,5%S CIF NWE Cargo" (:indeksinimi %)) paallystys))
(is (some #(= "bitumi" (:raakaaine %)) paallystys))
(is (some #(= "ABWGL03" (:koodi %)) paallystys))
(is (some #(str/includes? (:indeksinimi %) "Platts") paallystys))
(is (some #(= "Palvelujen tuottajahintaindeksi 2010" (:indeksinimi %)) vesivayla-kanavien-hoito))
(is (some #(= "Palvelujen tuottajahintaindeksi 2015" (:indeksinimi %)) vesivayla-kanavien-hoito))))
(deftest paallystysurakan-indeksitietojen-haku
(let [indeksit (kutsu-palvelua (:http-palvelin jarjestelma)
:paallystysurakan-indeksitiedot
+kayttaja-jvh+
{::urakka/id 5})]
(is (= 2 (count indeksit)))
spec'atun
(is (= "Platts: testiindeksi XYZ" (:indeksinimi (:indeksi (first indeksit)))))
(is (=marginaalissa? 225.0 (:arvo (:indeksi (first indeksit)))))))
(deftest paallystysurakan-indeksitiedot-tallennus
(let [hyotykuorma [{:id -1 :urakka 5
:lahtotason-vuosi 2014 :lahtotason-kuukausi 9
:indeksi {:id 8 :urakkatyyppi :paallystys
:indeksinimi "Platts: Propane CIF NWE 7kt+"
:raakaaine "nestekaasu"
:koodi "PMUEE03"}}]
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysurakan-indeksitiedot
+kayttaja-jvh+
hyotykuorma)]
Lisättiin yksi , joten nyt indeksejä on kolme
(is (= 3 (count vastaus)) "indeksivuosien lukumäärä tallennuksen jälkeen")
(testing "Indeksin merkitseminen poistetuksi"
(let [hyotykuorma (assoc-in vastaus [0 :poistettu] true)
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysurakan-indeksitiedot
+kayttaja-jvh+
hyotykuorma)]
(is (= 2 (count vastaus)) "indeksejä on 2 poiston jälkeen")))))
(deftest laske-vesivaylaurakan-indeksilaskennan-perusluku
(let [ur (hae-urakan-id-nimella "Helsingin väyläyksikön väylänhoito ja -käyttö, Itäinen SL")
perusluku (ffirst (q (str "select * from indeksilaskennan_perusluku(" ur ");")))]
( 103.9 + 105.2 + 106.2 ) / 3 = 105.1 M tammi , helmi- urakan alkuvuonna
(is (= 105.1M perusluku))))
(deftest laske-tampereen-2017-alkavan-hoitourakan-indeksilaskennan-perusluku
(let [ur (hae-urakan-id-nimella "Tampereen alueurakka 2017-2022")
perusluku (ffirst (q (str "select * from indeksilaskennan_perusluku(" ur ");")))]
alkupvm : ää edeltävän vuoden syys- , loka- ja marraskuun keskiarvo urakan alkuvuonna
(is (= 115.4M perusluku))))
(defn indeksilaskennan-perusluku [urakka]
(ffirst (q (format "select * from indeksilaskennan_perusluku(%s)" urakka))))
(defn kiinteahintainen-tyo-summa-indeksikorjattu [id]
(ffirst (q (format "select summa_indeksikorjattu from kiinteahintainen_tyo where id = %s" id))))
(defn kustannusarvioitu-tyo-summa-indeksikorjattu [id]
(ffirst (q (format "select summa_indeksikorjattu from kustannusarvioitu_tyo where id = %s" id))))
(defn johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu [id]
(ffirst (q (format "select tuntipalkka_indeksikorjattu from johto_ja_hallintokorvaus where id = %s" id))))
(defn urakka-tavoite-tavoitehinta-indeksikorjattu [id]
(ffirst (q (format "select tavoitehinta_indeksikorjattu from urakka_tavoite where id = %s" id))))
(defn urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu [id]
(ffirst (q (format "select tavoitehinta_siirretty_indeksikorjattu from urakka_tavoite where id = %s" id))))
(defn urakka-tavoite-kattohinta-indeksikorjattu [id]
(ffirst (q (format "select kattohinta_indeksikorjattu from urakka_tavoite where id = %s" id))))
(defn indeksikorjaa
"Indeksikorjaa samalla tavalla kuin kustannussuunnitelmassa"
[{:keys [db urakka-id hoitovuosi-nro summa]}]
(let [urakan-indeksit (budjettisuunnittelu/hae-urakan-indeksikertoimet db +kayttaja-jvh+ {:urakka-id urakka-id})
indeksikerroin (budjettisuunnittelu/indeksikerroin urakan-indeksit hoitovuosi-nro)]
(bigdec (budjettisuunnittelu/indeksikorjaa indeksikerroin summa))))
(defn lisaa-kiinteahintainen-tyo [{:keys [vuosi, kuukausi, summa, toimenpideinstanssi]}]
(i (format "INSERT INTO kiinteahintainen_tyo (vuosi, kuukausi, summa, toimenpideinstanssi) VALUES (%s, %s, %s, %s)"
vuosi kuukausi summa toimenpideinstanssi)))
(defn lisaa-kustannusarvioitu-tyo [{:keys [vuosi, kuukausi, summa, toimenpideinstanssi]}]
(i (format "INSERT INTO kustannusarvioitu_tyo (vuosi, kuukausi, summa, toimenpideinstanssi) VALUES (%s, %s, %s, %s)"
vuosi kuukausi summa toimenpideinstanssi)))
(defn lisaa-tilaajan-rahavaraus [{:keys [vuosi, kuukausi, summa, toimenpideinstanssi]}]
(i (format "INSERT INTO kustannusarvioitu_tyo (vuosi, kuukausi, summa, toimenpideinstanssi, tehtavaryhma) VALUES (%s, %s, %s, %s, (select id from tehtavaryhma tr where tr.yksiloiva_tunniste = 'a6614475-1950-4a61-82c6-fda0fd19bb54'))"
vuosi kuukausi summa toimenpideinstanssi)))
(defn lisaa-johto-ja-hallintokorvaus [{:keys [vuosi, kuukausi, tuntipalkka, urakka]}]
(i (format "INSERT INTO johto_ja_hallintokorvaus (\"urakka-id\", tuntipalkka, vuosi, kuukausi, \"toimenkuva-id\") VALUES (%s, %s, %s, %s, (SELECT id FROM johto_ja_hallintokorvaus_toimenkuva WHERE toimenkuva = 'harjoittelija'))"
urakka tuntipalkka vuosi kuukausi)))
(defn lisaa-urakka-tavoite [{:keys [urakka hoitokausi tavoitehinta tavoitehinta-siirretty kattohinta]}]
(println "lisaa-urakka-tavoite" urakka hoitokausi tavoitehinta tavoitehinta-siirretty kattohinta)
(println (format "INSERT INTO urakka_tavoite (urakka, hoitokausi, tavoitehinta, tavoitehinta_siirretty, kattohinta) VALUES (%s, %s, %s, %s, %s)"
urakka hoitokausi tavoitehinta tavoitehinta-siirretty kattohinta))
(u (format "DELETE FROM urakka_tavoite WHERE urakka = %s AND hoitokausi = %s"
urakka hoitokausi))
(i (format "INSERT INTO urakka_tavoite (urakka, hoitokausi, tavoitehinta, tavoitehinta_siirretty, kattohinta) VALUES (%s, %s, %s, %s, %s)"
urakka hoitokausi tavoitehinta tavoitehinta-siirretty kattohinta)))
(deftest indeksikorjaukset-lasketaan-uudelleen-kun-indeksia-muokataan
(let [db (:db jarjestelma)
urakka (hae-urakan-id-nimella "Kittilän MHU 2019-2024")
indeksi "TESTI-INDEKSI 2015"]
Päivitä Kittilän testiurakka käyttämään indeksiä
(is (= 1 (u (format "update urakka set indeksi = '%s' where id = %s" indeksi urakka))))
(is (nil? (indeksilaskennan-perusluku urakka))
"Indeksilaskennan peruslukua ei voi vielä laskea, koska indeksejä ei ole")
(let [summa 70979.86M
toimenpideinstanssi (hae-kittila-mhu-talvihoito-tpi-id)
kiinteahintainen-tyo (lisaa-kiinteahintainen-tyo
{:vuosi 2020 :kuukausi 10 :summa summa :toimenpideinstanssi toimenpideinstanssi})
kustannusarvioitu-tyo (lisaa-kustannusarvioitu-tyo
{:vuosi 2020 :kuukausi 10 :summa summa :toimenpideinstanssi toimenpideinstanssi})
tilaajan-rahavaraus (lisaa-tilaajan-rahavaraus
{:vuosi 2020 :kuukausi 10 :summa summa
:toimenpideinstanssi (hae-kittila-mhu-hallinnolliset-toimenpiteet-tp-id)})
johto-ja-hallintokorvaus (lisaa-johto-ja-hallintokorvaus
{:vuosi 2020 :kuukausi 10 :tuntipalkka summa :urakka urakka})
tavoitehinta summa
tavoitehinta-siirretty (+ summa 1)
kattohinta (+ summa 2)
urakka-tavoite (lisaa-urakka-tavoite
{:urakka urakka
:hoitokausi 2
:tavoitehinta tavoitehinta
:tavoitehinta-siirretty tavoitehinta-siirretty
:kattohinta kattohinta})]
(is (number? kiinteahintainen-tyo))
(is (number? kustannusarvioitu-tyo))
(is (number? tilaajan-rahavaraus))
(is (number? johto-ja-hallintokorvaus))
(is (number? urakka-tavoite))
Lisää 2018 syys- , loka-
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? false
:vuosi 2018
9 101.1
10 101.6
11 101.8}]})
(is (= 101.5M (indeksilaskennan-perusluku urakka))
"Indeksilaskennan perusluku on urakan alkupvm:ää edeltävän vuoden syys-, loka- ja marraskuun keskiarvo")
(is (nil? (kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"kiinteahintainen_tyo.summa_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu kustannusarvioitu-tyo))
"kustannusarvioitu_tyo.summa_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu tilaajan-rahavaraus))
"tilaajan rahavaraukselle ei lasketa indeksikorjausta")
(is (nil? (johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu johto-ja-hallintokorvaus))
"johto_ja_hallintokorvaus.tuntipalkka_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (urakka-tavoite-tavoitehinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_siirretty_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (urakka-tavoite-kattohinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.kattohinta_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
2019 ja 2020 indeksit , jotta voidaan
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? false
:vuosi 2019
9 102.4M}
{:kannassa? false
:vuosi 2020
9 102.9M}]})
(let [indeksikorjattu-summa (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa summa})]
(is (= indeksikorjattu-summa ; CLJ-indeksikorjaus
(kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo)) ; SQL-indeksikorjaus
"kiinteahintainen_tyo.summa_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (= indeksikorjattu-summa
(kustannusarvioitu-tyo-summa-indeksikorjattu kustannusarvioitu-tyo))
"kustannusarvioitu_tyo.summa_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu tilaajan-rahavaraus))
"tilaajan rahavaraukselle ei lasketa indeksikorjausta")
(is (= indeksikorjattu-summa
(johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu johto-ja-hallintokorvaus))
"johto_ja_hallintokorvaus.tuntipalkka_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa tavoitehinta})
(urakka-tavoite-tavoitehinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa tavoitehinta-siirretty})
(urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_siirretty_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa kattohinta})
(urakka-tavoite-kattohinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.kattohinta_indeksikorjattu on laskettu indeksin lisäämisen jälkeen"))
Päivitä indeksiä
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? true
:vuosi 2020
9 666.66666666M}]})
(let [indeksikorjattu-summa (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa summa})]
(is (= indeksikorjattu-summa
(kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"kiinteahintainen_tyo.summa_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (= indeksikorjattu-summa
(kustannusarvioitu-tyo-summa-indeksikorjattu kustannusarvioitu-tyo))
"kustannusarvioitu_tyo.summa_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu tilaajan-rahavaraus))
"tilaajan rahavaraukselle ei lasketa indeksikorjausta")
(is (= indeksikorjattu-summa
(johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu johto-ja-hallintokorvaus))
"johto_ja_hallintokorvaus.tuntipalkka_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa tavoitehinta})
(urakka-tavoite-tavoitehinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa tavoitehinta-siirretty})
(urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_siirretty_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa kattohinta})
(urakka-tavoite-kattohinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.kattohinta_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen"))
Poista indeksi
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? true
:vuosi 2020
9 nil}]})
(is (nil? (kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"kiinteahintainen_tyo.summa_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"kustannusarvioitu_tyo.summa_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu tilaajan-rahavaraus))
"tilaajan rahavaraukselle ei lasketa indeksikorjausta")
(is (nil? (johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu johto-ja-hallintokorvaus))
"johto_ja_hallintokorvaus.tuntipalkka_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (urakka-tavoite-tavoitehinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_siirretty_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (urakka-tavoite-kattohinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.kattohinta_indeksikorjattu on poistettu indeksin poistamisen jälkeen"))))
(deftest vahvistettua-indeksikorjausta-ei-muokata
(let [db (:db jarjestelma)
urakka (hae-urakan-id-nimella "Kittilän MHU 2019-2024")
indeksi "TESTI-INDEKSI 2015"]
Päivitä Kittilän testiurakka käyttämään indeksiä
(is (= 1 (u (format "update urakka set indeksi = '%s' where id = %s" indeksi urakka))))
työ urakan ensimmäiselle kuukaudelle
(let [summa 70979.86M
kiinteahintainen-tyo (i (format "INSERT INTO kiinteahintainen_tyo (vuosi, kuukausi, summa, toimenpideinstanssi, summa_indeksikorjattu, indeksikorjaus_vahvistettu) VALUES (2019, 10, %s, %s, %s, NOW())"
summa
(hae-kittila-mhu-talvihoito-tpi-id)
summa))]
Lisää 2018 syys- , loka-
2019 indeksi , jotta voidaan
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? false
:vuosi 2018
9 101.1
10 101.6
11 101.8}
{:kannassa? false
:vuosi 2019
9 102.9M}]})
(is (= 101.5M (indeksilaskennan-perusluku urakka))
"Indeksilaskennan perusluku on urakan alkupvm:ää edeltävän vuoden syys-, loka- ja marraskuun keskiarvo")
(is (= summa (kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"Vahvistettua indeksikorjattua summaa ei saa muuttaa"))))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/c57d742beaff2bef7b30318819f07d4a13423404/test/clj/harja/palvelin/palvelut/indeksit_test.clj | clojure | HAR-4035 bugin verifiointi
")))]
CLJ-indeksikorjaus
SQL-indeksikorjaus | (ns harja.palvelin.palvelut.indeksit-test
(:require [clojure.test :refer :all]
[taoensso.timbre :as log]
[harja.palvelin.komponentit.tietokanta :as tietokanta]
[harja.palvelin.palvelut.indeksit :refer :all]
[harja.testi :refer :all]
[com.stuartsierra.component :as component]
[clojure.string :as str]
[harja.domain.urakka :as urakka]
[harja.palvelin.palvelut.indeksit :as indeksit]
[harja.palvelin.palvelut.budjettisuunnittelu :as budjettisuunnittelu]))
(defn jarjestelma-fixture [testit]
(alter-var-root #'jarjestelma
(fn [_]
(component/start
(component/system-map
:db (tietokanta/luo-tietokanta testitietokanta)
:http-palvelin (testi-http-palvelin)
:indeksit (component/using
(->Indeksit)
[:http-palvelin :db])))))
(testit)
(alter-var-root #'jarjestelma component/stop))
(use-fixtures :each (compose-fixtures tietokanta-fixture jarjestelma-fixture))
maku 2005 vuonna 2013
[ " MAKU 2005 " 2013 ] { : 2013 , 12 110.1 , 11 110.5 , 1 109.2 } }
(deftest kaikki-indeksit-haettu-oikein
(let [indeksit (kutsu-palvelua (:http-palvelin jarjestelma)
:indeksit +kayttaja-jvh+)
maku-2005-2013 (get indeksit ["MAKU 2005" 2013])]
(is (> (count indeksit) 0))
(is (= (count maku-2005-2013) 13))
(is (every? some? maku-2005-2013))
(is (= (:vuosi maku-2005-2013) 2013))
< - odota ongelmia
(deftest kuukauden-indeksikorotuksen-laskenta
(let [korotus
(ffirst (q (str "SELECT korotus from laske_kuukauden_indeksikorotus
(is (=marginaalissa? korotus 1145.64))))
(deftest urakkatyypin-indeksien-haku
(let [indeksit (kutsu-palvelua (:http-palvelin jarjestelma)
:urakkatyypin-indeksit +kayttaja-jvh+)
{:keys [hoito tiemerkinta paallystys vesivayla-kanavien-hoito]}
(group-by :urakkatyyppi indeksit)]
(is (some #(= "MAKU 2005" (:indeksinimi %)) hoito))
(is (some #(= "MAKU 2010" (:indeksinimi %)) hoito))
(is (some #(= "MAKU 2015" (:indeksinimi %)) hoito))
(is (some #(= "MAKU 2010" (:indeksinimi %)) tiemerkinta))
(is (some #(= "Platts: FO 3,5%S CIF NWE Cargo" (:indeksinimi %)) paallystys))
(is (some #(= "bitumi" (:raakaaine %)) paallystys))
(is (some #(= "ABWGL03" (:koodi %)) paallystys))
(is (some #(str/includes? (:indeksinimi %) "Platts") paallystys))
(is (some #(= "Palvelujen tuottajahintaindeksi 2010" (:indeksinimi %)) vesivayla-kanavien-hoito))
(is (some #(= "Palvelujen tuottajahintaindeksi 2015" (:indeksinimi %)) vesivayla-kanavien-hoito))))
(deftest paallystysurakan-indeksitietojen-haku
(let [indeksit (kutsu-palvelua (:http-palvelin jarjestelma)
:paallystysurakan-indeksitiedot
+kayttaja-jvh+
{::urakka/id 5})]
(is (= 2 (count indeksit)))
spec'atun
(is (= "Platts: testiindeksi XYZ" (:indeksinimi (:indeksi (first indeksit)))))
(is (=marginaalissa? 225.0 (:arvo (:indeksi (first indeksit)))))))
(deftest paallystysurakan-indeksitiedot-tallennus
(let [hyotykuorma [{:id -1 :urakka 5
:lahtotason-vuosi 2014 :lahtotason-kuukausi 9
:indeksi {:id 8 :urakkatyyppi :paallystys
:indeksinimi "Platts: Propane CIF NWE 7kt+"
:raakaaine "nestekaasu"
:koodi "PMUEE03"}}]
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysurakan-indeksitiedot
+kayttaja-jvh+
hyotykuorma)]
Lisättiin yksi , joten nyt indeksejä on kolme
(is (= 3 (count vastaus)) "indeksivuosien lukumäärä tallennuksen jälkeen")
(testing "Indeksin merkitseminen poistetuksi"
(let [hyotykuorma (assoc-in vastaus [0 :poistettu] true)
vastaus (kutsu-palvelua (:http-palvelin jarjestelma)
:tallenna-paallystysurakan-indeksitiedot
+kayttaja-jvh+
hyotykuorma)]
(is (= 2 (count vastaus)) "indeksejä on 2 poiston jälkeen")))))
(deftest laske-vesivaylaurakan-indeksilaskennan-perusluku
(let [ur (hae-urakan-id-nimella "Helsingin väyläyksikön väylänhoito ja -käyttö, Itäinen SL")
perusluku (ffirst (q (str "select * from indeksilaskennan_perusluku(" ur ");")))]
( 103.9 + 105.2 + 106.2 ) / 3 = 105.1 M tammi , helmi- urakan alkuvuonna
(is (= 105.1M perusluku))))
(deftest laske-tampereen-2017-alkavan-hoitourakan-indeksilaskennan-perusluku
(let [ur (hae-urakan-id-nimella "Tampereen alueurakka 2017-2022")
perusluku (ffirst (q (str "select * from indeksilaskennan_perusluku(" ur ");")))]
alkupvm : ää edeltävän vuoden syys- , loka- ja marraskuun keskiarvo urakan alkuvuonna
(is (= 115.4M perusluku))))
(defn indeksilaskennan-perusluku [urakka]
(ffirst (q (format "select * from indeksilaskennan_perusluku(%s)" urakka))))
(defn kiinteahintainen-tyo-summa-indeksikorjattu [id]
(ffirst (q (format "select summa_indeksikorjattu from kiinteahintainen_tyo where id = %s" id))))
(defn kustannusarvioitu-tyo-summa-indeksikorjattu [id]
(ffirst (q (format "select summa_indeksikorjattu from kustannusarvioitu_tyo where id = %s" id))))
(defn johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu [id]
(ffirst (q (format "select tuntipalkka_indeksikorjattu from johto_ja_hallintokorvaus where id = %s" id))))
(defn urakka-tavoite-tavoitehinta-indeksikorjattu [id]
(ffirst (q (format "select tavoitehinta_indeksikorjattu from urakka_tavoite where id = %s" id))))
(defn urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu [id]
(ffirst (q (format "select tavoitehinta_siirretty_indeksikorjattu from urakka_tavoite where id = %s" id))))
(defn urakka-tavoite-kattohinta-indeksikorjattu [id]
(ffirst (q (format "select kattohinta_indeksikorjattu from urakka_tavoite where id = %s" id))))
(defn indeksikorjaa
"Indeksikorjaa samalla tavalla kuin kustannussuunnitelmassa"
[{:keys [db urakka-id hoitovuosi-nro summa]}]
(let [urakan-indeksit (budjettisuunnittelu/hae-urakan-indeksikertoimet db +kayttaja-jvh+ {:urakka-id urakka-id})
indeksikerroin (budjettisuunnittelu/indeksikerroin urakan-indeksit hoitovuosi-nro)]
(bigdec (budjettisuunnittelu/indeksikorjaa indeksikerroin summa))))
(defn lisaa-kiinteahintainen-tyo [{:keys [vuosi, kuukausi, summa, toimenpideinstanssi]}]
(i (format "INSERT INTO kiinteahintainen_tyo (vuosi, kuukausi, summa, toimenpideinstanssi) VALUES (%s, %s, %s, %s)"
vuosi kuukausi summa toimenpideinstanssi)))
(defn lisaa-kustannusarvioitu-tyo [{:keys [vuosi, kuukausi, summa, toimenpideinstanssi]}]
(i (format "INSERT INTO kustannusarvioitu_tyo (vuosi, kuukausi, summa, toimenpideinstanssi) VALUES (%s, %s, %s, %s)"
vuosi kuukausi summa toimenpideinstanssi)))
(defn lisaa-tilaajan-rahavaraus [{:keys [vuosi, kuukausi, summa, toimenpideinstanssi]}]
(i (format "INSERT INTO kustannusarvioitu_tyo (vuosi, kuukausi, summa, toimenpideinstanssi, tehtavaryhma) VALUES (%s, %s, %s, %s, (select id from tehtavaryhma tr where tr.yksiloiva_tunniste = 'a6614475-1950-4a61-82c6-fda0fd19bb54'))"
vuosi kuukausi summa toimenpideinstanssi)))
(defn lisaa-johto-ja-hallintokorvaus [{:keys [vuosi, kuukausi, tuntipalkka, urakka]}]
(i (format "INSERT INTO johto_ja_hallintokorvaus (\"urakka-id\", tuntipalkka, vuosi, kuukausi, \"toimenkuva-id\") VALUES (%s, %s, %s, %s, (SELECT id FROM johto_ja_hallintokorvaus_toimenkuva WHERE toimenkuva = 'harjoittelija'))"
urakka tuntipalkka vuosi kuukausi)))
(defn lisaa-urakka-tavoite [{:keys [urakka hoitokausi tavoitehinta tavoitehinta-siirretty kattohinta]}]
(println "lisaa-urakka-tavoite" urakka hoitokausi tavoitehinta tavoitehinta-siirretty kattohinta)
(println (format "INSERT INTO urakka_tavoite (urakka, hoitokausi, tavoitehinta, tavoitehinta_siirretty, kattohinta) VALUES (%s, %s, %s, %s, %s)"
urakka hoitokausi tavoitehinta tavoitehinta-siirretty kattohinta))
(u (format "DELETE FROM urakka_tavoite WHERE urakka = %s AND hoitokausi = %s"
urakka hoitokausi))
(i (format "INSERT INTO urakka_tavoite (urakka, hoitokausi, tavoitehinta, tavoitehinta_siirretty, kattohinta) VALUES (%s, %s, %s, %s, %s)"
urakka hoitokausi tavoitehinta tavoitehinta-siirretty kattohinta)))
(deftest indeksikorjaukset-lasketaan-uudelleen-kun-indeksia-muokataan
(let [db (:db jarjestelma)
urakka (hae-urakan-id-nimella "Kittilän MHU 2019-2024")
indeksi "TESTI-INDEKSI 2015"]
Päivitä Kittilän testiurakka käyttämään indeksiä
(is (= 1 (u (format "update urakka set indeksi = '%s' where id = %s" indeksi urakka))))
(is (nil? (indeksilaskennan-perusluku urakka))
"Indeksilaskennan peruslukua ei voi vielä laskea, koska indeksejä ei ole")
(let [summa 70979.86M
toimenpideinstanssi (hae-kittila-mhu-talvihoito-tpi-id)
kiinteahintainen-tyo (lisaa-kiinteahintainen-tyo
{:vuosi 2020 :kuukausi 10 :summa summa :toimenpideinstanssi toimenpideinstanssi})
kustannusarvioitu-tyo (lisaa-kustannusarvioitu-tyo
{:vuosi 2020 :kuukausi 10 :summa summa :toimenpideinstanssi toimenpideinstanssi})
tilaajan-rahavaraus (lisaa-tilaajan-rahavaraus
{:vuosi 2020 :kuukausi 10 :summa summa
:toimenpideinstanssi (hae-kittila-mhu-hallinnolliset-toimenpiteet-tp-id)})
johto-ja-hallintokorvaus (lisaa-johto-ja-hallintokorvaus
{:vuosi 2020 :kuukausi 10 :tuntipalkka summa :urakka urakka})
tavoitehinta summa
tavoitehinta-siirretty (+ summa 1)
kattohinta (+ summa 2)
urakka-tavoite (lisaa-urakka-tavoite
{:urakka urakka
:hoitokausi 2
:tavoitehinta tavoitehinta
:tavoitehinta-siirretty tavoitehinta-siirretty
:kattohinta kattohinta})]
(is (number? kiinteahintainen-tyo))
(is (number? kustannusarvioitu-tyo))
(is (number? tilaajan-rahavaraus))
(is (number? johto-ja-hallintokorvaus))
(is (number? urakka-tavoite))
Lisää 2018 syys- , loka-
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? false
:vuosi 2018
9 101.1
10 101.6
11 101.8}]})
(is (= 101.5M (indeksilaskennan-perusluku urakka))
"Indeksilaskennan perusluku on urakan alkupvm:ää edeltävän vuoden syys-, loka- ja marraskuun keskiarvo")
(is (nil? (kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"kiinteahintainen_tyo.summa_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu kustannusarvioitu-tyo))
"kustannusarvioitu_tyo.summa_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu tilaajan-rahavaraus))
"tilaajan rahavaraukselle ei lasketa indeksikorjausta")
(is (nil? (johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu johto-ja-hallintokorvaus))
"johto_ja_hallintokorvaus.tuntipalkka_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (urakka-tavoite-tavoitehinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_siirretty_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
(is (nil? (urakka-tavoite-kattohinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.kattohinta_indeksikorjattu voidaan laskea vasta kun saadaan syyskuun 2019 indeksi")
2019 ja 2020 indeksit , jotta voidaan
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? false
:vuosi 2019
9 102.4M}
{:kannassa? false
:vuosi 2020
9 102.9M}]})
(let [indeksikorjattu-summa (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa summa})]
"kiinteahintainen_tyo.summa_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (= indeksikorjattu-summa
(kustannusarvioitu-tyo-summa-indeksikorjattu kustannusarvioitu-tyo))
"kustannusarvioitu_tyo.summa_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu tilaajan-rahavaraus))
"tilaajan rahavaraukselle ei lasketa indeksikorjausta")
(is (= indeksikorjattu-summa
(johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu johto-ja-hallintokorvaus))
"johto_ja_hallintokorvaus.tuntipalkka_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa tavoitehinta})
(urakka-tavoite-tavoitehinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa tavoitehinta-siirretty})
(urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_siirretty_indeksikorjattu on laskettu indeksin lisäämisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa kattohinta})
(urakka-tavoite-kattohinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.kattohinta_indeksikorjattu on laskettu indeksin lisäämisen jälkeen"))
Päivitä indeksiä
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? true
:vuosi 2020
9 666.66666666M}]})
(let [indeksikorjattu-summa (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa summa})]
(is (= indeksikorjattu-summa
(kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"kiinteahintainen_tyo.summa_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (= indeksikorjattu-summa
(kustannusarvioitu-tyo-summa-indeksikorjattu kustannusarvioitu-tyo))
"kustannusarvioitu_tyo.summa_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu tilaajan-rahavaraus))
"tilaajan rahavaraukselle ei lasketa indeksikorjausta")
(is (= indeksikorjattu-summa
(johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu johto-ja-hallintokorvaus))
"johto_ja_hallintokorvaus.tuntipalkka_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa tavoitehinta})
(urakka-tavoite-tavoitehinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa tavoitehinta-siirretty})
(urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_siirretty_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen")
(is (= (indeksikorjaa {:db db :urakka-id urakka :hoitovuosi-nro 2 :summa kattohinta})
(urakka-tavoite-kattohinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.kattohinta_indeksikorjattu on laskettu uusiksi indeksin muokkaamisen jälkeen"))
Poista indeksi
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? true
:vuosi 2020
9 nil}]})
(is (nil? (kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"kiinteahintainen_tyo.summa_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"kustannusarvioitu_tyo.summa_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (kustannusarvioitu-tyo-summa-indeksikorjattu tilaajan-rahavaraus))
"tilaajan rahavaraukselle ei lasketa indeksikorjausta")
(is (nil? (johto-ja-hallintokorvaus-tuntipalkka-indeksikorjattu johto-ja-hallintokorvaus))
"johto_ja_hallintokorvaus.tuntipalkka_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (urakka-tavoite-tavoitehinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (urakka-tavoite-tavoitehinta-siirretty-indeksikorjattu urakka-tavoite))
"urakka_tavoite.tavoitehinta_siirretty_indeksikorjattu on poistettu indeksin poistamisen jälkeen")
(is (nil? (urakka-tavoite-kattohinta-indeksikorjattu urakka-tavoite))
"urakka_tavoite.kattohinta_indeksikorjattu on poistettu indeksin poistamisen jälkeen"))))
(deftest vahvistettua-indeksikorjausta-ei-muokata
(let [db (:db jarjestelma)
urakka (hae-urakan-id-nimella "Kittilän MHU 2019-2024")
indeksi "TESTI-INDEKSI 2015"]
Päivitä Kittilän testiurakka käyttämään indeksiä
(is (= 1 (u (format "update urakka set indeksi = '%s' where id = %s" indeksi urakka))))
työ urakan ensimmäiselle kuukaudelle
(let [summa 70979.86M
kiinteahintainen-tyo (i (format "INSERT INTO kiinteahintainen_tyo (vuosi, kuukausi, summa, toimenpideinstanssi, summa_indeksikorjattu, indeksikorjaus_vahvistettu) VALUES (2019, 10, %s, %s, %s, NOW())"
summa
(hae-kittila-mhu-talvihoito-tpi-id)
summa))]
Lisää 2018 syys- , loka-
2019 indeksi , jotta voidaan
(indeksit/tallenna-indeksi
db
+kayttaja-jvh+
{:nimi indeksi
:indeksit [{:kannassa? false
:vuosi 2018
9 101.1
10 101.6
11 101.8}
{:kannassa? false
:vuosi 2019
9 102.9M}]})
(is (= 101.5M (indeksilaskennan-perusluku urakka))
"Indeksilaskennan perusluku on urakan alkupvm:ää edeltävän vuoden syys-, loka- ja marraskuun keskiarvo")
(is (= summa (kiinteahintainen-tyo-summa-indeksikorjattu kiinteahintainen-tyo))
"Vahvistettua indeksikorjattua summaa ei saa muuttaa"))))
|
e0247af5a85470c2b3b16c79327a1ce26044bd7043f28b9ec95a358dcd3a9f3a | lisp/de.setf.thrift | DenseLinkingTest-types.lisp | ;;; -*- Package: thrift-generated -*-
;;;
Autogenerated by Thrift
;;; DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
(def-package :thrift-generated)
(thrift:def-struct "oneofeachzz"
(("im_true" nil :type bool :id 1)
("im_false" nil :type bool :id 2)
("a_bite" nil :type byte :id 3)
("integer16" nil :type i16 :id 4)
("integer32" nil :type i32 :id 5)
("integer64" nil :type i64 :id 6)
("double_precision" nil :type double :id 7)
("some_characters" nil :type string :id 8)
("zomg_unicode" nil :type string :id 9)
("what_who" nil :type bool :id 10)))
(thrift:def-struct "bonkzz"
(("type" nil :type i32 :id 1)
("message" nil :type string :id 2)))
(thrift:def-struct "nestingzz"
(("my_bonk" nil :type (struct "bonkzz") :id 1)
("my_ooe" nil :type (struct "oneofeachzz") :id 2)))
(thrift:def-struct "holymoleyzz"
(("big" nil :type (list (struct "oneofeachzz")) :id 1)
("contain" nil :type (set (list string)) :id 2)
("bonks" nil :type (map string (list (struct "bonkzz"))) :id 3)))
(thrift:def-struct "backwardszz"
(("first_tag2" nil :type i32 :id 2)
("second_tag1" nil :type i32 :id 1)))
(thrift:def-struct "emptyzz"
())
(thrift:def-struct "wrapperzz"
(("foo" nil :type (struct "emptyzz") :id 1)))
(thrift:def-struct "randomstuffzz"
(("a" nil :type i32 :id 1)
("b" nil :type i32 :id 2)
("c" nil :type i32 :id 3)
("d" nil :type i32 :id 4)
("myintlist" nil :type (list i32) :id 5)
("maps" nil :type (map i32 (struct "wrapperzz")) :id 6)
("bigint" nil :type i64 :id 7)
("triple" nil :type double :id 8)))
(thrift:def-service "Srv" nil
(:method "Janky" ((("arg" i32 1)) i32)))
| null | https://raw.githubusercontent.com/lisp/de.setf.thrift/32b0d1ca3d9fa95327165b8090e1021bc563ed3e/test/gen-cl/DenseLinkingTest-types.lisp | lisp | -*- Package: thrift-generated -*-
DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING | Autogenerated by Thrift
(def-package :thrift-generated)
(thrift:def-struct "oneofeachzz"
(("im_true" nil :type bool :id 1)
("im_false" nil :type bool :id 2)
("a_bite" nil :type byte :id 3)
("integer16" nil :type i16 :id 4)
("integer32" nil :type i32 :id 5)
("integer64" nil :type i64 :id 6)
("double_precision" nil :type double :id 7)
("some_characters" nil :type string :id 8)
("zomg_unicode" nil :type string :id 9)
("what_who" nil :type bool :id 10)))
(thrift:def-struct "bonkzz"
(("type" nil :type i32 :id 1)
("message" nil :type string :id 2)))
(thrift:def-struct "nestingzz"
(("my_bonk" nil :type (struct "bonkzz") :id 1)
("my_ooe" nil :type (struct "oneofeachzz") :id 2)))
(thrift:def-struct "holymoleyzz"
(("big" nil :type (list (struct "oneofeachzz")) :id 1)
("contain" nil :type (set (list string)) :id 2)
("bonks" nil :type (map string (list (struct "bonkzz"))) :id 3)))
(thrift:def-struct "backwardszz"
(("first_tag2" nil :type i32 :id 2)
("second_tag1" nil :type i32 :id 1)))
(thrift:def-struct "emptyzz"
())
(thrift:def-struct "wrapperzz"
(("foo" nil :type (struct "emptyzz") :id 1)))
(thrift:def-struct "randomstuffzz"
(("a" nil :type i32 :id 1)
("b" nil :type i32 :id 2)
("c" nil :type i32 :id 3)
("d" nil :type i32 :id 4)
("myintlist" nil :type (list i32) :id 5)
("maps" nil :type (map i32 (struct "wrapperzz")) :id 6)
("bigint" nil :type i64 :id 7)
("triple" nil :type double :id 8)))
(thrift:def-service "Srv" nil
(:method "Janky" ((("arg" i32 1)) i32)))
|
b11b1788dcc27961f702dc847164eb15b3cb1e3480e752356193bb6ca1f0f088 | erlang/erlide_kernel | erlide_log.erl | %%% ******************************************************************************
Copyright ( c ) 2008 and others .
%%% All rights reserved. This program and the accompanying materials
%%% are made available under the terms of the Eclipse Public License v1.0
%%% which accompanies this distribution, and is available at
-v10.html
%%%
%%% Contributors:
%%% ******************************************************************************/
%%% File : erlide_log.erl
Author :
%%% Description :
-module(erlide_log).
-export([log/1, logp/1, logp/2, log/2, erlangLog/4, erlangLogStack/4]).
-define(DEFAULT_LEVEL, info).
log(Msg) ->
log(?DEFAULT_LEVEL, Msg).
logp(Msg) ->
logp("~p", [Msg]).
logp(Fmt, Msgs) when is_list(Fmt), is_list(Msgs) ->
log(?DEFAULT_LEVEL, lists:flatten(io_lib:format(Fmt, Msgs))).
log(Level, Msg) when is_atom(Level) ->
erlide_jrpc:event(log, {Level, Msg}).
erlangLog(Module, Line, Level, Msg) when is_atom(Level) ->
erlide_jrpc:event(erlang_log, {Module, Line, Level, Msg}).
erlangLogStack(Module, Line, Level, Msg) when is_atom(Level) ->
erlide_jrpc:event(erlang_log, {Module, Line, Level, Msg, erlang:process_info(self(), backtrace)}).
| null | https://raw.githubusercontent.com/erlang/erlide_kernel/763a7fe47213f374b59862fd5a17d5dcc2811c7b/common/apps/erlide_common/src/erlide_log.erl | erlang | ******************************************************************************
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
******************************************************************************/
File : erlide_log.erl
Description : | Copyright ( c ) 2008 and others .
-v10.html
Author :
-module(erlide_log).
-export([log/1, logp/1, logp/2, log/2, erlangLog/4, erlangLogStack/4]).
-define(DEFAULT_LEVEL, info).
log(Msg) ->
log(?DEFAULT_LEVEL, Msg).
logp(Msg) ->
logp("~p", [Msg]).
logp(Fmt, Msgs) when is_list(Fmt), is_list(Msgs) ->
log(?DEFAULT_LEVEL, lists:flatten(io_lib:format(Fmt, Msgs))).
log(Level, Msg) when is_atom(Level) ->
erlide_jrpc:event(log, {Level, Msg}).
erlangLog(Module, Line, Level, Msg) when is_atom(Level) ->
erlide_jrpc:event(erlang_log, {Module, Line, Level, Msg}).
erlangLogStack(Module, Line, Level, Msg) when is_atom(Level) ->
erlide_jrpc:event(erlang_log, {Module, Line, Level, Msg, erlang:process_info(self(), backtrace)}).
|
2de8f5a29dd813ff5e0f03d78e26a036526d13ec7d20267c399ac09777d95c2a | shimmering-void/sketches | project.clj | (defproject sketches "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.10.0"]
[org.clojure/clojurescript "1.10.773"]]
:source-paths ["src"]
:aliases {"fig" ["trampoline" "run" "-m" "figwheel.main"]
"fig:build" ["trampoline" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
"fig:min" ["run" "-m" "figwheel.main" "-O" "advanced" "-bo" "dev"]
"fig:test" ["run" "-m" "figwheel.main" "-co" "test.cljs.edn" "-m" "sketches.test-runner"]}
:profiles {:dev {:dependencies [[com.bhauman/figwheel-main "0.2.11"]
[com.bhauman/rebel-readline-cljs "0.1.4"]
[quil "3.0.0"]]
:resource-paths ["target"]
;; need to add the compiled assets to the :clean-targets
:clean-targets ^{:protect false} ["target"]}})
| null | https://raw.githubusercontent.com/shimmering-void/sketches/84d29636a798720e8db3379c21814fe9f92686fd/project.clj | clojure | need to add the compiled assets to the :clean-targets | (defproject sketches "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:min-lein-version "2.7.1"
:dependencies [[org.clojure/clojure "1.10.0"]
[org.clojure/clojurescript "1.10.773"]]
:source-paths ["src"]
:aliases {"fig" ["trampoline" "run" "-m" "figwheel.main"]
"fig:build" ["trampoline" "run" "-m" "figwheel.main" "-b" "dev" "-r"]
"fig:min" ["run" "-m" "figwheel.main" "-O" "advanced" "-bo" "dev"]
"fig:test" ["run" "-m" "figwheel.main" "-co" "test.cljs.edn" "-m" "sketches.test-runner"]}
:profiles {:dev {:dependencies [[com.bhauman/figwheel-main "0.2.11"]
[com.bhauman/rebel-readline-cljs "0.1.4"]
[quil "3.0.0"]]
:resource-paths ["target"]
:clean-targets ^{:protect false} ["target"]}})
|
80b60e8a32a3f0cbb337d40cd3c9eb33d98d74625e61eee7124ca843ead08c1c | bradrn/brassica | MDF.hs | # LANGUAGE BlockArguments #
# LANGUAGE DeriveFunctor #
# LANGUAGE LambdaCase #
# LANGUAGE ViewPatterns #
| This module contains types and functions for working with the MDF
dictionary format , used by programs such as [ SIL Toolbox]( / toolbox/ ) .
For more on the MDF format , refer to e.g.
[ Coward & Grimes ( 2000 ) , /Making Dictionaries : A guide to lexicography and the Multi - Dictionary Formatter/]( / legacy / shoebox / MDF_2000.pdf ) .
dictionary format, used by programs such as [SIL Toolbox](/).
For more on the MDF format, refer to e.g.
[Coward & Grimes (2000), /Making Dictionaries: A guide to lexicography and the Multi-Dictionary Formatter/]().
-}
module Brassica.MDF
(
-- * MDF files
MDF(..)
, MDFLanguage(..)
, fieldLangs
-- * Parsing
, parseMDFRaw
, parseMDFWithTokenisation
-- ** Re-export
, errorBundlePretty
-- * Conversion
, componentiseMDF
, componentiseMDFWordsOnly
, duplicateEtymologies
) where
import Control.Category ((>>>))
import Data.Char (isSpace)
import Data.Void (Void)
import qualified Data.Map as M
import Text.Megaparsec
import Text.Megaparsec.Char
import Brassica.SoundChange.Tokenise
import Brassica.SoundChange.Types (Grapheme, PWord)
import Data.Maybe (fromMaybe)
-- | An MDF (Multi-Dictionary Formatter) file, represented as a list
-- of (field marker, whitespace, field value) tuples. The field marker
-- is represented excluding its initial slash; whitespace after the
-- field marker is also stored, allowing the original MDF file to be
-- precisely recovered. Field values should includes all whitespace to
the next marker . All field values are stored as ' 's , with the
exception of ' Vernacular ' fields , which have type @v@.
--
-- For instance, the following MDF file:
--
-- > \lx kapa
-- > \ps n
-- > \ge parent
-- > \se sakapa
-- > \ge father
--
-- Could be stored as:
--
-- > MDF [ ("lx", " ", Right "kapa\n")
-- > , ("ps", " ", Left "n\n")
> , ( " ge " , " " , Left " parent\n " )
-- > , ("se", " ", Right "sakapa\n")
> , ( " ge " , " " , Left " father " )
-- > ]
newtype MDF v = MDF { unMDF :: [(String, String, Either String v)] }
deriving (Show, Functor)
type Parser = Parsec Void String
sc :: Parser String
sc = fmap (fromMaybe "") $ optional $ takeWhile1P (Just "white space") isSpace
parseToSlash :: Parser String
parseToSlash = takeWhileP (Just "field value") (/= '\\')
entry :: Parser v -> Parser (String, String, Either String v)
entry pv = do
_ <- char '\\'
marker <- takeWhile1P (Just "field name") (not . isSpace)
s <- sc
value <- case M.lookup marker fieldLangs of
Just Vernacular -> Right <$> pv
_ -> Left <$> parseToSlash
pure (marker, s, value)
| Parse an MDF file to an ' MDF ' , storing the ' Vernacular ' fields as ' 's .
parseMDFRaw :: String -> Either (ParseErrorBundle String Void) (MDF String)
parseMDFRaw = runParser (fmap MDF $ sc *> many (entry parseToSlash) <* eof) ""
| Parse an MDF file to an ' MDF ' , parsing the ' Vernacular ' fields
-- into 'Component's in the process.
parseMDFWithTokenisation
:: [Grapheme]
-> String
-> Either (ParseErrorBundle String Void) (MDF [Component PWord])
parseMDFWithTokenisation (sortByDescendingLength -> gs) =
runParser (fmap MDF $ sc *> p <* eof) ""
where
p = many $ entry $ componentsParser $ wordParser "\\" gs
-- | Convert an 'MDF' to a list of 'Component's representing the same
textual content . Vernacular field values are left as is ; everything
-- else is treated as a 'Separator', so that it is not disturbed by
-- operations such as rule application or rendering to text.
componentiseMDF :: MDF [Component a] -> [Component a]
componentiseMDF = unMDF >>> concatMap \case
(m, s, Left v) -> [Separator ('\\':m ++ s ++ v)]
(m, s, Right v) -> Separator ('\\':m ++ s) : v
-- | As with 'componentiseMDF', but the resulting 'Component's contain
the contents of ' Vernacular ' fields only ; all else is
discarded . The first parameter specifies the ' Separator ' to insert
-- after each vernacular field.
componentiseMDFWordsOnly :: MDF [Component a] -> [Component a]
componentiseMDFWordsOnly = unMDF >>> concatMap \case
(_, _, Right v) -> v
_ -> []
-- | Add etymological fields to an 'MDF' by duplicating the values in
-- @\lx@, @\se@ and @\ge@ fields. e.g.:
--
-- > \lx kapa
-- > \ps n
-- > \ge parent
-- > \se sakapa
-- > \ge father
--
-- Would become:
--
-- > \lx kapa
-- > \ps n
-- > \ge parent
-- > \et kapa
> parent
-- > \se sakapa
-- > \ge father
-- > \et sakapa
-- > \eg father
--
-- This can be helpful when applying sound changes to an MDF file: the
-- vernacular words can be copied as etymologies, and then the sound
-- changes can be applied leaving the etymologies as is.
duplicateEtymologies
:: (v -> String)
-- ^ Function to convert from vernacular field values to
-- strings. Can also be used to preprocess the value of the
resulting @\et@ fields , e.g. by prepending @*@ or similar .
-> MDF v -> MDF v
duplicateEtymologies typeset = MDF . go Nothing Nothing . unMDF
where
mkEt word gloss = word' gloss'
where
word' = case word of
Just et -> (("et", " ", Left $ typeset et) :)
Nothing -> id
gloss' = case gloss of
Just eg -> [("eg", " ", Left eg)]
Nothing -> []
go word gloss [] = mkEt word gloss
go word _ (f@("ge", _, Left gloss'):fs) -- store gloss field for future etymology
= f : go word (Just gloss') fs
go word gloss (f@(m, _, Right word'):fs) -- add etymology & store word if word or subentry field reached
| m == "lx" || m == "se"
= mkEt word gloss ++ f : go (Just word') Nothing fs
go word gloss (f@("dt", _, _):fs) -- add etymology if date (usually final field in entry) reached
= mkEt word gloss ++ f : go Nothing Nothing fs
go word gloss (f:fs) = f : go word gloss fs
-- | The designated language of an MDF field.
data MDFLanguage = English | National | Regional | Vernacular | Other
deriving (Eq, Show)
-- | A 'M.Map' from the most common field markers to the language of
-- their values.
--
-- (Note: This is currently hardcoded in the source code, based on the
values in the MDF definitions from SIL Toolbox . There ’s probably a
-- more principled way of defining this, but hardcoding should suffice
-- for now.)
fieldLangs :: M.Map String MDFLanguage
fieldLangs = M.fromList
[ ("1d" , Vernacular) , ("1e" , Vernacular) , ("1i" , Vernacular)
, ("1p" , Vernacular) , ("1s" , Vernacular) , ("2d" , Vernacular)
, ("2p" , Vernacular) , ("2s" , Vernacular) , ("3d" , Vernacular)
, ("3p" , Vernacular) , ("3s" , Vernacular) , ("4d" , Vernacular)
, ("4p" , Vernacular) , ("4s" , Vernacular) , ("a" , Vernacular)
, ("an" , Vernacular) , ("bb" , English) , ("bw" , English)
, ("ce" , English) , ("cf" , Vernacular) , ("cn" , National)
, ("cr" , National) , ("de" , English) , ("dn" , National)
, ("dr" , Regional) , ("dt" , Other) , ("dv" , Vernacular)
, ("ec" , English) , ("ee" , English) , ("eg" , English)
, ("en" , National) , ("er" , Regional) , ("es" , English)
defined as vernacular in SIL Toolbox , but by
definition it 's really a different language
definition it's really a different language -}
, ("ev" , Vernacular) , ("ge" , English)
, ("gn" , National) , ("gr" , Regional) , ("gv" , Vernacular)
, ("hm" , English) , ("is" , English) , ("lc" , Vernacular)
, ("le" , English) , ("lf" , English) , ("ln" , National)
, ("lr" , Regional) , ("lt" , English) , ("lv" , Vernacular)
, ("lx" , Vernacular) , ("mn" , Vernacular) , ("mr" , Vernacular)
, ("na" , English) , ("nd" , English) , ("ng" , English)
, ("np" , English) , ("nq" , English) , ("ns" , English)
, ("nt" , English) , ("oe" , English) , ("on" , National)
, ("or" , Regional) , ("ov" , Vernacular) , ("pc" , English)
, ("pd" , English) , ("pde", English) , ("pdl", English)
, ("pdn", National) , ("pdr", Regional) , ("pdv", Vernacular)
, ("ph" , Other) , ("pl" , Vernacular) , ("pn" , National)
, ("ps" , English) , ("rd" , Vernacular) , ("re" , English)
, ("rf" , English) , ("rn" , National) , ("rr" , Regional)
, ("sc" , English) , ("sd" , English) , ("se" , Vernacular)
, ("sg" , Vernacular) , ("sn" , English) , ("so" , English)
, ("st" , English) , ("sy" , Vernacular) , ("tb" , English)
, ("th" , Vernacular) , ("u" , Vernacular) , ("ue" , English)
, ("un" , National) , ("ur" , Regional) , ("uv" , Vernacular)
, ("va" , Vernacular) , ("ve" , English) , ("vn" , National)
, ("vr" , Regional) , ("we" , English) , ("wn" , National)
, ("wr" , Regional) , ("xe" , English) , ("xn" , National)
, ("xr" , Regional) , ("xv" , Vernacular)
]
| null | https://raw.githubusercontent.com/bradrn/brassica/6be84287fe3c3027493d47064d0a6bbba04b0ef8/src/Brassica/MDF.hs | haskell | * MDF files
* Parsing
** Re-export
* Conversion
| An MDF (Multi-Dictionary Formatter) file, represented as a list
of (field marker, whitespace, field value) tuples. The field marker
is represented excluding its initial slash; whitespace after the
field marker is also stored, allowing the original MDF file to be
precisely recovered. Field values should includes all whitespace to
For instance, the following MDF file:
> \lx kapa
> \ps n
> \ge parent
> \se sakapa
> \ge father
Could be stored as:
> MDF [ ("lx", " ", Right "kapa\n")
> , ("ps", " ", Left "n\n")
> , ("se", " ", Right "sakapa\n")
> ]
into 'Component's in the process.
| Convert an 'MDF' to a list of 'Component's representing the same
else is treated as a 'Separator', so that it is not disturbed by
operations such as rule application or rendering to text.
| As with 'componentiseMDF', but the resulting 'Component's contain
after each vernacular field.
| Add etymological fields to an 'MDF' by duplicating the values in
@\lx@, @\se@ and @\ge@ fields. e.g.:
> \lx kapa
> \ps n
> \ge parent
> \se sakapa
> \ge father
Would become:
> \lx kapa
> \ps n
> \ge parent
> \et kapa
> \se sakapa
> \ge father
> \et sakapa
> \eg father
This can be helpful when applying sound changes to an MDF file: the
vernacular words can be copied as etymologies, and then the sound
changes can be applied leaving the etymologies as is.
^ Function to convert from vernacular field values to
strings. Can also be used to preprocess the value of the
store gloss field for future etymology
add etymology & store word if word or subentry field reached
add etymology if date (usually final field in entry) reached
| The designated language of an MDF field.
| A 'M.Map' from the most common field markers to the language of
their values.
(Note: This is currently hardcoded in the source code, based on the
more principled way of defining this, but hardcoding should suffice
for now.)
| # LANGUAGE BlockArguments #
# LANGUAGE DeriveFunctor #
# LANGUAGE LambdaCase #
# LANGUAGE ViewPatterns #
| This module contains types and functions for working with the MDF
dictionary format , used by programs such as [ SIL Toolbox]( / toolbox/ ) .
For more on the MDF format , refer to e.g.
[ Coward & Grimes ( 2000 ) , /Making Dictionaries : A guide to lexicography and the Multi - Dictionary Formatter/]( / legacy / shoebox / MDF_2000.pdf ) .
dictionary format, used by programs such as [SIL Toolbox](/).
For more on the MDF format, refer to e.g.
[Coward & Grimes (2000), /Making Dictionaries: A guide to lexicography and the Multi-Dictionary Formatter/]().
-}
module Brassica.MDF
(
MDF(..)
, MDFLanguage(..)
, fieldLangs
, parseMDFRaw
, parseMDFWithTokenisation
, errorBundlePretty
, componentiseMDF
, componentiseMDFWordsOnly
, duplicateEtymologies
) where
import Control.Category ((>>>))
import Data.Char (isSpace)
import Data.Void (Void)
import qualified Data.Map as M
import Text.Megaparsec
import Text.Megaparsec.Char
import Brassica.SoundChange.Tokenise
import Brassica.SoundChange.Types (Grapheme, PWord)
import Data.Maybe (fromMaybe)
the next marker . All field values are stored as ' 's , with the
exception of ' Vernacular ' fields , which have type @v@.
> , ( " ge " , " " , Left " parent\n " )
> , ( " ge " , " " , Left " father " )
newtype MDF v = MDF { unMDF :: [(String, String, Either String v)] }
deriving (Show, Functor)
type Parser = Parsec Void String
sc :: Parser String
sc = fmap (fromMaybe "") $ optional $ takeWhile1P (Just "white space") isSpace
parseToSlash :: Parser String
parseToSlash = takeWhileP (Just "field value") (/= '\\')
entry :: Parser v -> Parser (String, String, Either String v)
entry pv = do
_ <- char '\\'
marker <- takeWhile1P (Just "field name") (not . isSpace)
s <- sc
value <- case M.lookup marker fieldLangs of
Just Vernacular -> Right <$> pv
_ -> Left <$> parseToSlash
pure (marker, s, value)
| Parse an MDF file to an ' MDF ' , storing the ' Vernacular ' fields as ' 's .
parseMDFRaw :: String -> Either (ParseErrorBundle String Void) (MDF String)
parseMDFRaw = runParser (fmap MDF $ sc *> many (entry parseToSlash) <* eof) ""
| Parse an MDF file to an ' MDF ' , parsing the ' Vernacular ' fields
parseMDFWithTokenisation
:: [Grapheme]
-> String
-> Either (ParseErrorBundle String Void) (MDF [Component PWord])
parseMDFWithTokenisation (sortByDescendingLength -> gs) =
runParser (fmap MDF $ sc *> p <* eof) ""
where
p = many $ entry $ componentsParser $ wordParser "\\" gs
textual content . Vernacular field values are left as is ; everything
componentiseMDF :: MDF [Component a] -> [Component a]
componentiseMDF = unMDF >>> concatMap \case
(m, s, Left v) -> [Separator ('\\':m ++ s ++ v)]
(m, s, Right v) -> Separator ('\\':m ++ s) : v
the contents of ' Vernacular ' fields only ; all else is
discarded . The first parameter specifies the ' Separator ' to insert
componentiseMDFWordsOnly :: MDF [Component a] -> [Component a]
componentiseMDFWordsOnly = unMDF >>> concatMap \case
(_, _, Right v) -> v
_ -> []
> parent
duplicateEtymologies
:: (v -> String)
resulting @\et@ fields , e.g. by prepending @*@ or similar .
-> MDF v -> MDF v
duplicateEtymologies typeset = MDF . go Nothing Nothing . unMDF
where
mkEt word gloss = word' gloss'
where
word' = case word of
Just et -> (("et", " ", Left $ typeset et) :)
Nothing -> id
gloss' = case gloss of
Just eg -> [("eg", " ", Left eg)]
Nothing -> []
go word gloss [] = mkEt word gloss
= f : go word (Just gloss') fs
| m == "lx" || m == "se"
= mkEt word gloss ++ f : go (Just word') Nothing fs
= mkEt word gloss ++ f : go Nothing Nothing fs
go word gloss (f:fs) = f : go word gloss fs
data MDFLanguage = English | National | Regional | Vernacular | Other
deriving (Eq, Show)
values in the MDF definitions from SIL Toolbox . There ’s probably a
fieldLangs :: M.Map String MDFLanguage
fieldLangs = M.fromList
[ ("1d" , Vernacular) , ("1e" , Vernacular) , ("1i" , Vernacular)
, ("1p" , Vernacular) , ("1s" , Vernacular) , ("2d" , Vernacular)
, ("2p" , Vernacular) , ("2s" , Vernacular) , ("3d" , Vernacular)
, ("3p" , Vernacular) , ("3s" , Vernacular) , ("4d" , Vernacular)
, ("4p" , Vernacular) , ("4s" , Vernacular) , ("a" , Vernacular)
, ("an" , Vernacular) , ("bb" , English) , ("bw" , English)
, ("ce" , English) , ("cf" , Vernacular) , ("cn" , National)
, ("cr" , National) , ("de" , English) , ("dn" , National)
, ("dr" , Regional) , ("dt" , Other) , ("dv" , Vernacular)
, ("ec" , English) , ("ee" , English) , ("eg" , English)
, ("en" , National) , ("er" , Regional) , ("es" , English)
defined as vernacular in SIL Toolbox , but by
definition it 's really a different language
definition it's really a different language -}
, ("ev" , Vernacular) , ("ge" , English)
, ("gn" , National) , ("gr" , Regional) , ("gv" , Vernacular)
, ("hm" , English) , ("is" , English) , ("lc" , Vernacular)
, ("le" , English) , ("lf" , English) , ("ln" , National)
, ("lr" , Regional) , ("lt" , English) , ("lv" , Vernacular)
, ("lx" , Vernacular) , ("mn" , Vernacular) , ("mr" , Vernacular)
, ("na" , English) , ("nd" , English) , ("ng" , English)
, ("np" , English) , ("nq" , English) , ("ns" , English)
, ("nt" , English) , ("oe" , English) , ("on" , National)
, ("or" , Regional) , ("ov" , Vernacular) , ("pc" , English)
, ("pd" , English) , ("pde", English) , ("pdl", English)
, ("pdn", National) , ("pdr", Regional) , ("pdv", Vernacular)
, ("ph" , Other) , ("pl" , Vernacular) , ("pn" , National)
, ("ps" , English) , ("rd" , Vernacular) , ("re" , English)
, ("rf" , English) , ("rn" , National) , ("rr" , Regional)
, ("sc" , English) , ("sd" , English) , ("se" , Vernacular)
, ("sg" , Vernacular) , ("sn" , English) , ("so" , English)
, ("st" , English) , ("sy" , Vernacular) , ("tb" , English)
, ("th" , Vernacular) , ("u" , Vernacular) , ("ue" , English)
, ("un" , National) , ("ur" , Regional) , ("uv" , Vernacular)
, ("va" , Vernacular) , ("ve" , English) , ("vn" , National)
, ("vr" , Regional) , ("we" , English) , ("wn" , National)
, ("wr" , Regional) , ("xe" , English) , ("xn" , National)
, ("xr" , Regional) , ("xv" , Vernacular)
]
|
151b84492806469eb9c13c83ab3b270c2cb5d1b4aac353d583d94c99d6e328a0 | geneweb/geneweb | checkItem.mli | $ I d : checkItem.mli , v 1.12 2007 - 09 - 05 13:19:25
Copyright ( c ) 2006 - 2007 INRIA
open Gwdb
type base_error = person Def.error
(** Database specification error *)
type base_warning =
(iper, person, ifam, family, title, pers_event, fam_event) Def.warning
(** Database specification warning *)
(* *)
type base_misc = (person, family, title) Def.misc
val check_siblings :
?onchange:bool ->
base ->
(base_warning -> unit) ->
ifam * family ->
(person -> unit) ->
unit
* [ check_siblings ? onchange base warning ( ifam , fam ) callback ]
Checks birth date consistency between siblings .
Also calls [ callback ] with each child .
Checks birth date consistency between siblings.
Also calls [callback] with each child. *)
val person :
?onchange:bool ->
base ->
(base_warning -> unit) ->
person ->
(iper * person * Def.sex option * relation list option) list option
(** [person onchange base warn p] checks person's properties:
- personal events
- person's age
- person's titles dates
- etc.
If [onchange] is set then sort person's events
Calls [warn] on corresponding [base_warning] when find some inconsistencies. *)
val family :
?onchange:bool -> base -> (base_warning -> unit) -> ifam -> family -> unit
(** [family onchange base warn f] checks family properties like :
- familial events
- parents marraige
- children age gap and birth
- etc.
If [onchange] is set then sort family's events
Calls [warn] on corresponding [base_warning] when find some inconsistencies. *)
val on_person_update : base -> (base_warning -> unit) -> person -> unit
(** Unlike [person] who checks directly the properties of a person, checks the properties
of a person in relation to other people (his children, parents, spouses, witnesses, etc).
Calls [warn] on corresponding [base_warning] when find some inconsistencies.
*)
val sort_children : base -> iper array -> (iper array * iper array) option
(** Sort array of children by their birth date from oldest to youngest.
Returns old array and sorted version. *)
val check_other_fields : base -> (base_misc -> unit) -> ifam -> family -> unit
* if family , father and mother have sources . Otherwise call [ misc ] on [ base_misc ]
val eq_warning : base -> base_warning -> base_warning -> bool
(** equality between base_warnings *)
val person_warnings : Config.config -> base -> person -> base_warning list
(** [person_warnings conf base p]
Shorthand for [CheckItem.person] and [CheckItem.on_person_update] on [p]
and [CheckItem.check_siblings] on they children
using [auth_warning] for filtering.
*)
| null | https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/lib/checkItem.mli | ocaml | * Database specification error
* Database specification warning
* [person onchange base warn p] checks person's properties:
- personal events
- person's age
- person's titles dates
- etc.
If [onchange] is set then sort person's events
Calls [warn] on corresponding [base_warning] when find some inconsistencies.
* [family onchange base warn f] checks family properties like :
- familial events
- parents marraige
- children age gap and birth
- etc.
If [onchange] is set then sort family's events
Calls [warn] on corresponding [base_warning] when find some inconsistencies.
* Unlike [person] who checks directly the properties of a person, checks the properties
of a person in relation to other people (his children, parents, spouses, witnesses, etc).
Calls [warn] on corresponding [base_warning] when find some inconsistencies.
* Sort array of children by their birth date from oldest to youngest.
Returns old array and sorted version.
* equality between base_warnings
* [person_warnings conf base p]
Shorthand for [CheckItem.person] and [CheckItem.on_person_update] on [p]
and [CheckItem.check_siblings] on they children
using [auth_warning] for filtering.
| $ I d : checkItem.mli , v 1.12 2007 - 09 - 05 13:19:25
Copyright ( c ) 2006 - 2007 INRIA
open Gwdb
type base_error = person Def.error
type base_warning =
(iper, person, ifam, family, title, pers_event, fam_event) Def.warning
type base_misc = (person, family, title) Def.misc
val check_siblings :
?onchange:bool ->
base ->
(base_warning -> unit) ->
ifam * family ->
(person -> unit) ->
unit
* [ check_siblings ? onchange base warning ( ifam , fam ) callback ]
Checks birth date consistency between siblings .
Also calls [ callback ] with each child .
Checks birth date consistency between siblings.
Also calls [callback] with each child. *)
val person :
?onchange:bool ->
base ->
(base_warning -> unit) ->
person ->
(iper * person * Def.sex option * relation list option) list option
val family :
?onchange:bool -> base -> (base_warning -> unit) -> ifam -> family -> unit
val on_person_update : base -> (base_warning -> unit) -> person -> unit
val sort_children : base -> iper array -> (iper array * iper array) option
val check_other_fields : base -> (base_misc -> unit) -> ifam -> family -> unit
* if family , father and mother have sources . Otherwise call [ misc ] on [ base_misc ]
val eq_warning : base -> base_warning -> base_warning -> bool
val person_warnings : Config.config -> base -> person -> base_warning list
|
814435157cdc577093b507574c76e74b69dcb72b726aa1e6be1d3dc1996b982f | rd--/hsc3 | integrator.help.hs | -- integrator
let x = mouseX kr 0.001 0.999 Exponential 0.2
o = lfPulse ar 300 0.2 0.1 * 0.1
in integrator o x
-- integrator ; used as an envelope
let i = lfPulse ar 3 0.2 0.0004
o = sinOsc ar 700 0 * 0.1
in integrator i 0.999 * o
-- integrator ; scope
let x = mouseX kr 0.01 0.999 Exponential 0.2
o = lfPulse ar (1500 / 4) 0.2 0.1
in integrator o x * 0.1
-- integrator ; a triangle wave is the integration of square wave
let f = mouseX kr 440 8800 Exponential 0.2
o = pulse ar f 0.5
in integrator o 0.99 * 0.05
---- ; drawings
UI.ui_sc3_scope 2 0 (2 ^ 14) 0 "audio" 0
Sound.Sc3.Plot.plot_ugen 0.006 (integrator (lfPulse ar (1500 / 4) 0.2 0.1) (mce [0.1,0.4,0.7]))
| null | https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Ugen/integrator.help.hs | haskell | integrator
integrator ; used as an envelope
integrator ; scope
integrator ; a triangle wave is the integration of square wave
-- ; drawings | let x = mouseX kr 0.001 0.999 Exponential 0.2
o = lfPulse ar 300 0.2 0.1 * 0.1
in integrator o x
let i = lfPulse ar 3 0.2 0.0004
o = sinOsc ar 700 0 * 0.1
in integrator i 0.999 * o
let x = mouseX kr 0.01 0.999 Exponential 0.2
o = lfPulse ar (1500 / 4) 0.2 0.1
in integrator o x * 0.1
let f = mouseX kr 440 8800 Exponential 0.2
o = pulse ar f 0.5
in integrator o 0.99 * 0.05
UI.ui_sc3_scope 2 0 (2 ^ 14) 0 "audio" 0
Sound.Sc3.Plot.plot_ugen 0.006 (integrator (lfPulse ar (1500 / 4) 0.2 0.1) (mce [0.1,0.4,0.7]))
|
a4f197cb655b25b5cc4944ba7a5b9c1eb50f7f67b7b51ee776442ca9349f32c4 | shenxs/about-scheme | 16.5.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname |16.5|) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "abstraction.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "abstraction.rkt" "teachpack" "2htdp")) #f)))
(define (extract R l n)
(cond
[(empty? l) '()]
[else (if (R (first l) n)
(cons (first l) (extract R (rest l) n))
(extract R (rest l) n))]))
(define (square>? a b)
(> (* a a ) b))
( extract < ( list 1 2 3 4 5 ) 7 )
(extract square>? (list 3 4 5 7 8) 10)
( extract < ( cons 6 ( cons 4 ' ( ) ) ) 5 )
( extract < ( cons 4 ' ( ) ) 5 )
| null | https://raw.githubusercontent.com/shenxs/about-scheme/d458776a62cb0bbcbfbb2a044ed18b849f26fd0f/HTDP/16.5.rkt | racket | about the language level of this file in a form that our tools can easily process. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname |16.5|) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "abstraction.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "abstraction.rkt" "teachpack" "2htdp")) #f)))
(define (extract R l n)
(cond
[(empty? l) '()]
[else (if (R (first l) n)
(cons (first l) (extract R (rest l) n))
(extract R (rest l) n))]))
(define (square>? a b)
(> (* a a ) b))
( extract < ( list 1 2 3 4 5 ) 7 )
(extract square>? (list 3 4 5 7 8) 10)
( extract < ( cons 6 ( cons 4 ' ( ) ) ) 5 )
( extract < ( cons 4 ' ( ) ) 5 )
|
9fa96737aa1154a2a38f8419ec6e711ccb89235cdcc5015d06c8eefecbe5cde6 | blindglobe/clocc | cmd-frame.lisp | -*- Mode : Lisp ; Package : CLIO - OPEN ; ; Lowercase : T ; Syntax : Common - Lisp -*-
;;;----------------------------------------------------------------------------------+
;;; |
;;; TEXAS INSTRUMENTS INCORPORATED |
;;; P.O. BOX 149149 |
, TEXAS 78714 - 9149 |
;;; |
Copyright ( C ) 1989 , 1990 Texas Instruments Incorporated . |
;;; |
;;; Permission is granted to any individual or institution to use, copy, modify, and |
;;; distribute this software, provided that this complete copyright and permission |
;;; notice is maintained, intact, in all copies and supporting documentation. |
;;; |
Texas Instruments Incorporated provides this software " as is " without express or |
;;; implied warranty. |
;;; |
;;;----------------------------------------------------------------------------------+
(in-package "CLIO-OPEN")
(export '(
command-frame
command-frame-content
command-frame-controls
make-command-frame
)
'clio-open)
(defcontact command-frame (core core-shell top-level-session)
()
(:documentation "A top-level-session containing a content and a set of controls.")
(:resources
(content :type (or function list) :initform nil)
(controls :type (or function list) :initform nil)))
(defmethod initialize-instance :after ((command-frame command-frame)
&rest initargs &key content controls)
(with-slots (width height) command-frame
Initialize command - frame - form
(assert content () "No content defined for ~a." command-frame)
(multiple-value-bind (content-constructor content-initargs)
(etypecase content
(function content)
(list (values (first content) (rest content))))
(let*
((content-name (or (getf content-initargs :name) :content))
(hlinks `((
:from :command-frame-form
:to ,content-name
:attach-from :left
:attach-to :left
:maximum 0)
(
:from ,content-name
:to :command-frame-form
:attach-from :right
:attach-to :right
:maximum 0)
(
:from :command-frame-form
:to :controls
:attach-from :left
:attach-to :left
:maximum 0)
(
:from :controls
:to :command-frame-form
:attach-from :right
:attach-to :right
:maximum 0)))
(vlinks `((
:from :command-frame-form
:to :controls
:attach-from :top
:attach-to :top
:maximum 0)
(
:from :controls
:to ,content-name
:maximum 0)
(
:from ,content-name
:to :command-frame-form
:attach-from :bottom
:attach-to :bottom
:maximum 0)
))
(form (make-form
:name :command-frame-form
:parent command-frame
:width width
:height height
:horizontal-links hlinks
:vertical-links vlinks)))
Initialize content
(apply content-constructor
:name content-name
:parent form
:max-height :infinite
:min-height 0
:max-width :infinite
:min-width 0
content-initargs)
Initialize controls area
(multiple-value-bind (controls-constructor controls-initargs)
(etypecase controls
(null
(let ((space (point-pixels
(contact-screen command-frame)
(getf *dialog-point-spacing* (contact-scale command-frame)))))
(values 'make-table
`(
:columns :maximum
:column-alignment :center
:same-height-in-row :on
:horizontal-space ,space
:left-margin ,space
:right-margin ,space
:top-margin ,(pixel-round space 2)
:bottom-margin ,(pixel-round space 2)))))
(function controls)
(list (values (first controls) (rest controls))))
(apply controls-constructor
:parent form
:name :controls
:border-width 0
:max-width :infinite
:min-width 0
controls-initargs))))))
(defun command-frame-form (command-frame)
(first (slot-value command-frame 'children)))
(defmethod command-frame-content ((command-frame command-frame))
(first (slot-value (command-frame-form command-frame) 'children)))
(defmethod command-frame-controls ((command-frame command-frame))
(second (slot-value (command-frame-form command-frame) 'children)))
(defun make-command-frame (&rest initargs)
(apply #'make-contact 'command-frame initargs))
(defmethod rescale :before ((command-frame command-frame))
(let ((controls (command-frame-controls command-frame)))
(multiple-value-bind (pw ph) (preferred-size controls)
(declare (ignore pw))
(setf (form-max-height controls) (setf (form-min-height controls) ph))))) | null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clue/clio/examples/cmd-frame.lisp | lisp | Package : CLIO - OPEN ; ; Lowercase : T ; Syntax : Common - Lisp -*-
----------------------------------------------------------------------------------+
|
TEXAS INSTRUMENTS INCORPORATED |
P.O. BOX 149149 |
|
|
Permission is granted to any individual or institution to use, copy, modify, and |
distribute this software, provided that this complete copyright and permission |
notice is maintained, intact, in all copies and supporting documentation. |
|
implied warranty. |
|
----------------------------------------------------------------------------------+ |
, TEXAS 78714 - 9149 |
Copyright ( C ) 1989 , 1990 Texas Instruments Incorporated . |
Texas Instruments Incorporated provides this software " as is " without express or |
(in-package "CLIO-OPEN")
(export '(
command-frame
command-frame-content
command-frame-controls
make-command-frame
)
'clio-open)
(defcontact command-frame (core core-shell top-level-session)
()
(:documentation "A top-level-session containing a content and a set of controls.")
(:resources
(content :type (or function list) :initform nil)
(controls :type (or function list) :initform nil)))
(defmethod initialize-instance :after ((command-frame command-frame)
&rest initargs &key content controls)
(with-slots (width height) command-frame
Initialize command - frame - form
(assert content () "No content defined for ~a." command-frame)
(multiple-value-bind (content-constructor content-initargs)
(etypecase content
(function content)
(list (values (first content) (rest content))))
(let*
((content-name (or (getf content-initargs :name) :content))
(hlinks `((
:from :command-frame-form
:to ,content-name
:attach-from :left
:attach-to :left
:maximum 0)
(
:from ,content-name
:to :command-frame-form
:attach-from :right
:attach-to :right
:maximum 0)
(
:from :command-frame-form
:to :controls
:attach-from :left
:attach-to :left
:maximum 0)
(
:from :controls
:to :command-frame-form
:attach-from :right
:attach-to :right
:maximum 0)))
(vlinks `((
:from :command-frame-form
:to :controls
:attach-from :top
:attach-to :top
:maximum 0)
(
:from :controls
:to ,content-name
:maximum 0)
(
:from ,content-name
:to :command-frame-form
:attach-from :bottom
:attach-to :bottom
:maximum 0)
))
(form (make-form
:name :command-frame-form
:parent command-frame
:width width
:height height
:horizontal-links hlinks
:vertical-links vlinks)))
Initialize content
(apply content-constructor
:name content-name
:parent form
:max-height :infinite
:min-height 0
:max-width :infinite
:min-width 0
content-initargs)
Initialize controls area
(multiple-value-bind (controls-constructor controls-initargs)
(etypecase controls
(null
(let ((space (point-pixels
(contact-screen command-frame)
(getf *dialog-point-spacing* (contact-scale command-frame)))))
(values 'make-table
`(
:columns :maximum
:column-alignment :center
:same-height-in-row :on
:horizontal-space ,space
:left-margin ,space
:right-margin ,space
:top-margin ,(pixel-round space 2)
:bottom-margin ,(pixel-round space 2)))))
(function controls)
(list (values (first controls) (rest controls))))
(apply controls-constructor
:parent form
:name :controls
:border-width 0
:max-width :infinite
:min-width 0
controls-initargs))))))
(defun command-frame-form (command-frame)
(first (slot-value command-frame 'children)))
(defmethod command-frame-content ((command-frame command-frame))
(first (slot-value (command-frame-form command-frame) 'children)))
(defmethod command-frame-controls ((command-frame command-frame))
(second (slot-value (command-frame-form command-frame) 'children)))
(defun make-command-frame (&rest initargs)
(apply #'make-contact 'command-frame initargs))
(defmethod rescale :before ((command-frame command-frame))
(let ((controls (command-frame-controls command-frame)))
(multiple-value-bind (pw ph) (preferred-size controls)
(declare (ignore pw))
(setf (form-max-height controls) (setf (form-min-height controls) ph))))) |
024bc580d893d26d9f412bbfa1931dea08e960da0d6c1878277d3ecf219ed2c8 | GaloisInc/daedalus | JSON.hs | module Daedalus.RTS.JSON
( JSON
, jsonToBytes
, jsNull
, jsText
, jsString
, jsArray
, jsObject
, jsTagged
, ToJSON(..)
) where
import Data.ByteString(ByteString)
import Data.ByteString.Short(fromShort,ShortByteString)
import Data.Text(Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Map (Map)
import qualified Data.Map as Map
import Data.ByteString.Builder
import Data.List(intersperse)
import Data.Coerce(coerce)
newtype JSON = JSON Builder
jsonToBytes :: JSON -> ByteString
jsonToBytes = LBS.toStrict . toLazyByteString . coerce
class ToJSON a where
toJSON :: a -> JSON
instance ToJSON JSON where
toJSON = id
instance ToJSON Integer where
toJSON = JSON . integerDec
instance ToJSON Int where
toJSON = toJSON . toInteger
instance ToJSON Float where
toJSON = jsFloating
instance ToJSON Double where
toJSON = jsFloating
instance ToJSON Bool where
toJSON b = JSON (if b then "true" else "false")
instance ToJSON () where
toJSON _ = jsObject []
instance ToJSON Text where
toJSON = jsText . Text.encodeUtf8
instance ToJSON ShortByteString where
toJSON = jsText . fromShort
This is DDL specific
instance (ToJSON a) => ToJSON (Maybe a) where
toJSON a = case a of
Nothing -> jsNull
Just v -> jsTagged "$just" (toJSON v)
This is DDL specific
instance (ToJSON a, ToJSON b) => ToJSON (Map a b) where
toJSON = jsTagged "$$map" . jsArray . map pair . Map.toList
where pair (k,v) = jsArray [ toJSON k, toJSON v ]
instance (ToJSON a) => ToJSON [a] where
toJSON = jsArray . map toJSON
instance (ToJSON a, ToJSON b) => ToJSON (a,b) where
toJSON (a,b) = jsArray [ toJSON a, toJSON b ]
jsNull :: JSON
jsNull = JSON "null"
jsArray :: [ JSON ] -> JSON
jsArray xs = JSON ("[" <> mconcat (intersperse "," (coerce xs)) <> "]")
jsObject :: [ (ByteString, JSON) ] -> JSON
jsObject xs = JSON ("{" <> mconcat (intersperse "," fs) <> "}")
where fs = [ coerce (jsText k) <> ":" <> coerce v | (k,v) <- xs ]
-- | A shortcur for a common encoding of sum types
jsTagged :: ByteString -> JSON -> JSON
jsTagged t v = jsObject [ (t, v) ]
jsString :: String -> JSON
jsString = toJSON . Text.pack
jsFloating :: (Show a, RealFloat a) => a -> JSON
jsFloating x
| isInfinite x = jsTagged "$$inf" jsNull
| isNaN x = jsTagged "$$nan" jsNull
| otherwise = JSON (string7 (show x))
jsText :: ByteString -> JSON
jsText x = coerce (char7 '"' <> escaped x <> char7 '"')
where
escaped cs =
case BS.break esc cs of
(as,bs)
| BS.null bs -> byteString as
| BS.null as -> escFirst bs
| otherwise -> byteString as <> escFirst bs
escFirst cs = doEsc (BS.head cs) <> escaped (BS.tail cs)
esc c = c == 34 {- " -} || c == 92 {- \ -} || c < 32 || c > 126
hex d =
case d of
0x0 -> "0"
0x1 -> "1"
0x2 -> "2"
0x3 -> "3"
0x4 -> "4"
0x5 -> "5"
0x6 -> "6"
0x7 -> "7"
0x8 -> "8"
0x9 -> "9"
0xA -> "A"
0xB -> "B"
0xC -> "C"
0xD -> "D"
0xE -> "E"
0xF -> "F"
_ -> error "not hex"
doEsc c =
case c of
08 -> "\\b"
09 -> "\\t"
10 -> "\\n"
12 -> "\\f"
13 -> "\\r"
34 -> "\\\""
92 -> "\\\\"
_ -> "\\u00" <> hex (div c 16) <> hex (mod c 16)
| null | https://raw.githubusercontent.com/GaloisInc/daedalus/3f180d29441960e35386654ec79a2b205bddc157/rts-hs-data/src/Daedalus/RTS/JSON.hs | haskell | | A shortcur for a common encoding of sum types
"
\ | module Daedalus.RTS.JSON
( JSON
, jsonToBytes
, jsNull
, jsText
, jsString
, jsArray
, jsObject
, jsTagged
, ToJSON(..)
) where
import Data.ByteString(ByteString)
import Data.ByteString.Short(fromShort,ShortByteString)
import Data.Text(Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.Map (Map)
import qualified Data.Map as Map
import Data.ByteString.Builder
import Data.List(intersperse)
import Data.Coerce(coerce)
newtype JSON = JSON Builder
jsonToBytes :: JSON -> ByteString
jsonToBytes = LBS.toStrict . toLazyByteString . coerce
class ToJSON a where
toJSON :: a -> JSON
instance ToJSON JSON where
toJSON = id
instance ToJSON Integer where
toJSON = JSON . integerDec
instance ToJSON Int where
toJSON = toJSON . toInteger
instance ToJSON Float where
toJSON = jsFloating
instance ToJSON Double where
toJSON = jsFloating
instance ToJSON Bool where
toJSON b = JSON (if b then "true" else "false")
instance ToJSON () where
toJSON _ = jsObject []
instance ToJSON Text where
toJSON = jsText . Text.encodeUtf8
instance ToJSON ShortByteString where
toJSON = jsText . fromShort
This is DDL specific
instance (ToJSON a) => ToJSON (Maybe a) where
toJSON a = case a of
Nothing -> jsNull
Just v -> jsTagged "$just" (toJSON v)
This is DDL specific
instance (ToJSON a, ToJSON b) => ToJSON (Map a b) where
toJSON = jsTagged "$$map" . jsArray . map pair . Map.toList
where pair (k,v) = jsArray [ toJSON k, toJSON v ]
instance (ToJSON a) => ToJSON [a] where
toJSON = jsArray . map toJSON
instance (ToJSON a, ToJSON b) => ToJSON (a,b) where
toJSON (a,b) = jsArray [ toJSON a, toJSON b ]
jsNull :: JSON
jsNull = JSON "null"
jsArray :: [ JSON ] -> JSON
jsArray xs = JSON ("[" <> mconcat (intersperse "," (coerce xs)) <> "]")
jsObject :: [ (ByteString, JSON) ] -> JSON
jsObject xs = JSON ("{" <> mconcat (intersperse "," fs) <> "}")
where fs = [ coerce (jsText k) <> ":" <> coerce v | (k,v) <- xs ]
jsTagged :: ByteString -> JSON -> JSON
jsTagged t v = jsObject [ (t, v) ]
jsString :: String -> JSON
jsString = toJSON . Text.pack
jsFloating :: (Show a, RealFloat a) => a -> JSON
jsFloating x
| isInfinite x = jsTagged "$$inf" jsNull
| isNaN x = jsTagged "$$nan" jsNull
| otherwise = JSON (string7 (show x))
jsText :: ByteString -> JSON
jsText x = coerce (char7 '"' <> escaped x <> char7 '"')
where
escaped cs =
case BS.break esc cs of
(as,bs)
| BS.null bs -> byteString as
| BS.null as -> escFirst bs
| otherwise -> byteString as <> escFirst bs
escFirst cs = doEsc (BS.head cs) <> escaped (BS.tail cs)
hex d =
case d of
0x0 -> "0"
0x1 -> "1"
0x2 -> "2"
0x3 -> "3"
0x4 -> "4"
0x5 -> "5"
0x6 -> "6"
0x7 -> "7"
0x8 -> "8"
0x9 -> "9"
0xA -> "A"
0xB -> "B"
0xC -> "C"
0xD -> "D"
0xE -> "E"
0xF -> "F"
_ -> error "not hex"
doEsc c =
case c of
08 -> "\\b"
09 -> "\\t"
10 -> "\\n"
12 -> "\\f"
13 -> "\\r"
34 -> "\\\""
92 -> "\\\\"
_ -> "\\u00" <> hex (div c 16) <> hex (mod c 16)
|
fa35fd3f0a2aa7f11725b7bf310a1c29c9e8754c6d05e04e5663ae54e58d0e21 | shayan-najd/NativeMetaprogramming | T11120.hs | # LANGUAGE TypeInType , MagicHash , DataKinds #
-- See also TypeOf.hs
import GHC.Prim
import Data.Typeable
data CharHash = CharHash Char#
main :: IO ()
main = print $ typeRep (Proxy :: Proxy 'CharHash)
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_run/T11120.hs | haskell | See also TypeOf.hs | # LANGUAGE TypeInType , MagicHash , DataKinds #
import GHC.Prim
import Data.Typeable
data CharHash = CharHash Char#
main :: IO ()
main = print $ typeRep (Proxy :: Proxy 'CharHash)
|
10016e680e8c679bdb5c3eda0a7a2f2146eae86f8b3a454f60870402deffb6ab | dongcarl/guix | hg-download.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 , 2015 , 2016 , 2017 , 2019 < >
Copyright © 2016 < >
Copyright © 2021 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix hg-download)
#:use-module (guix gexp)
#:use-module (guix store)
#:use-module (guix monads)
#:use-module (guix records)
#:use-module (guix modules)
#:use-module (guix packages)
#:autoload (guix build-system gnu) (standard-packages)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-35)
#:use-module (ice-9 match)
#:use-module (ice-9 popen)
#:use-module (ice-9 rdelim)
#:export (hg-reference
hg-reference?
hg-reference-url
hg-reference-changeset
hg-predicate
hg-fetch
hg-version
hg-file-name))
;;; Commentary:
;;;
An < origin > method that fetches a specific changeset from a Mercurial
;;; repository. The repository URL and changeset ID are specified with a
;;; <hg-reference> object.
;;;
;;; Code:
(define-record-type* <hg-reference>
hg-reference make-hg-reference
hg-reference?
(url hg-reference-url)
(changeset hg-reference-changeset))
(define (hg-package)
"Return the default Mercurial package."
(let ((distro (resolve-interface '(gnu packages version-control))))
(module-ref distro 'mercurial)))
(define* (hg-fetch ref hash-algo hash
#:optional name
#:key (system (%current-system)) (guile (default-guile))
(hg (hg-package)))
"Return a fixed-output derivation that fetches REF, a <hg-reference>
object. The output is expected to have recursive hash HASH of type
HASH-ALGO (a symbol). Use NAME as the file name, or a generic name if #f."
(define inputs
;; The 'swh-download' procedure requires tar and gzip.
`(("gzip" ,(module-ref (resolve-interface '(gnu packages compression))
'gzip))
("tar" ,(module-ref (resolve-interface '(gnu packages base))
'tar))))
(define guile-zlib
(module-ref (resolve-interface '(gnu packages guile)) 'guile-zlib))
(define guile-json
(module-ref (resolve-interface '(gnu packages guile)) 'guile-json-4))
(define gnutls
(module-ref (resolve-interface '(gnu packages tls)) 'gnutls))
(define modules
(delete '(guix config)
(source-module-closure '((guix build hg)
(guix build download-nar)
(guix swh)))))
(define build
(with-imported-modules modules
(with-extensions (list guile-json gnutls ;for (guix swh)
guile-zlib)
#~(begin
(use-modules (guix build hg)
(guix build utils) ;for `set-path-environment-variable'
(guix build download-nar)
(guix swh)
(ice-9 match))
(set-path-environment-variable "PATH" '("bin")
(match '#+inputs
(((names dirs outputs ...) ...)
dirs)))
(setvbuf (current-output-port) 'line)
(setvbuf (current-error-port) 'line)
(or (hg-fetch '#$(hg-reference-url ref)
'#$(hg-reference-changeset ref)
#$output
#:hg-command (string-append #+hg "/bin/hg"))
(download-nar #$output)
As a last resort , attempt to download from Software Heritage .
;; Disable X.509 certificate verification to avoid depending
;; on nss-certs--we're authenticating the checkout anyway.
(parameterize ((%verify-swh-certificate? #f))
(format (current-error-port)
"Trying to download from Software Heritage...~%")
(swh-download #$(hg-reference-url ref)
#$(hg-reference-changeset ref)
#$output)))))))
(mlet %store-monad ((guile (package->derivation guile system)))
(gexp->derivation (or name "hg-checkout") build
#:leaked-env-vars '("http_proxy" "https_proxy"
"LC_ALL" "LC_MESSAGES" "LANG"
"COLUMNS")
#:system system
#:local-build? #t ;don't offload repo cloning
#:hash-algo hash-algo
#:hash hash
#:recursive? #t
#:guile-for-build guile)))
(define (hg-version version revision changeset)
"Return the version string for packages using hg-download."
;; hg-version is almost exclusively executed while modules are being loaded.
;; This makes any errors hide their backtrace. Avoid the mysterious error
" Value out of range 0 to N : 7 " when the commit ID is too short , which
;; can happen, for example, when the user swapped the revision and commit
;; arguments by mistake.
(when (< (string-length changeset) 7)
(raise
(condition
(&message (message "hg-version: changeset ID unexpectedly short")))))
(string-append version "-" revision "." (string-take changeset 7)))
(define (hg-file-name name version)
"Return the file-name for packages using hg-download."
(string-append name "-" version "-checkout"))
(define (hg-file-list directory)
"Evaluates to a list of files contained in the repository at path
@var{directory}"
(let* ((port (open-input-pipe (format #f "hg files --repository ~s" directory)))
(files (let loop ((files '()))
(let ((line (read-line port)))
(cond
((eof-object? line) files)
(else
(loop (cons line files))))))))
(close-pipe port)
(map canonicalize-path files)))
(define (should-select? path-list candidate)
"Returns #t in case that @var{candidate} is a file that is part of the given
@var{path-list}."
(let ((canon-candidate (canonicalize-path candidate)))
(let loop ((xs path-list))
(cond
((null? xs)
;; Directories are not part of `hg files', but `local-file' will not
;; recurse if we don't return #t for directories.
(equal? (array-ref (lstat candidate) 13) 'directory))
((string-contains candidate (car xs)) #t)
(else (loop (cdr xs)))))))
(define (hg-predicate directory)
"This procedure evaluates to a predicate that reports back whether a given
@var{file} - @var{stat} combination is part of the files tracked by
Mercurial."
(let ((files (hg-file-list directory)))
(lambda (file stat)
(should-select? files file))))
;;; hg-download.scm ends here
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/guix/hg-download.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Commentary:
repository. The repository URL and changeset ID are specified with a
<hg-reference> object.
Code:
The 'swh-download' procedure requires tar and gzip.
for (guix swh)
for `set-path-environment-variable'
Disable X.509 certificate verification to avoid depending
on nss-certs--we're authenticating the checkout anyway.
don't offload repo cloning
hg-version is almost exclusively executed while modules are being loaded.
This makes any errors hide their backtrace. Avoid the mysterious error
can happen, for example, when the user swapped the revision and commit
arguments by mistake.
Directories are not part of `hg files', but `local-file' will not
recurse if we don't return #t for directories.
hg-download.scm ends here | Copyright © 2014 , 2015 , 2016 , 2017 , 2019 < >
Copyright © 2016 < >
Copyright © 2021 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix hg-download)
#:use-module (guix gexp)
#:use-module (guix store)
#:use-module (guix monads)
#:use-module (guix records)
#:use-module (guix modules)
#:use-module (guix packages)
#:autoload (guix build-system gnu) (standard-packages)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-35)
#:use-module (ice-9 match)
#:use-module (ice-9 popen)
#:use-module (ice-9 rdelim)
#:export (hg-reference
hg-reference?
hg-reference-url
hg-reference-changeset
hg-predicate
hg-fetch
hg-version
hg-file-name))
An < origin > method that fetches a specific changeset from a Mercurial
(define-record-type* <hg-reference>
hg-reference make-hg-reference
hg-reference?
(url hg-reference-url)
(changeset hg-reference-changeset))
(define (hg-package)
"Return the default Mercurial package."
(let ((distro (resolve-interface '(gnu packages version-control))))
(module-ref distro 'mercurial)))
(define* (hg-fetch ref hash-algo hash
#:optional name
#:key (system (%current-system)) (guile (default-guile))
(hg (hg-package)))
"Return a fixed-output derivation that fetches REF, a <hg-reference>
object. The output is expected to have recursive hash HASH of type
HASH-ALGO (a symbol). Use NAME as the file name, or a generic name if #f."
(define inputs
`(("gzip" ,(module-ref (resolve-interface '(gnu packages compression))
'gzip))
("tar" ,(module-ref (resolve-interface '(gnu packages base))
'tar))))
(define guile-zlib
(module-ref (resolve-interface '(gnu packages guile)) 'guile-zlib))
(define guile-json
(module-ref (resolve-interface '(gnu packages guile)) 'guile-json-4))
(define gnutls
(module-ref (resolve-interface '(gnu packages tls)) 'gnutls))
(define modules
(delete '(guix config)
(source-module-closure '((guix build hg)
(guix build download-nar)
(guix swh)))))
(define build
(with-imported-modules modules
guile-zlib)
#~(begin
(use-modules (guix build hg)
(guix build download-nar)
(guix swh)
(ice-9 match))
(set-path-environment-variable "PATH" '("bin")
(match '#+inputs
(((names dirs outputs ...) ...)
dirs)))
(setvbuf (current-output-port) 'line)
(setvbuf (current-error-port) 'line)
(or (hg-fetch '#$(hg-reference-url ref)
'#$(hg-reference-changeset ref)
#$output
#:hg-command (string-append #+hg "/bin/hg"))
(download-nar #$output)
As a last resort , attempt to download from Software Heritage .
(parameterize ((%verify-swh-certificate? #f))
(format (current-error-port)
"Trying to download from Software Heritage...~%")
(swh-download #$(hg-reference-url ref)
#$(hg-reference-changeset ref)
#$output)))))))
(mlet %store-monad ((guile (package->derivation guile system)))
(gexp->derivation (or name "hg-checkout") build
#:leaked-env-vars '("http_proxy" "https_proxy"
"LC_ALL" "LC_MESSAGES" "LANG"
"COLUMNS")
#:system system
#:hash-algo hash-algo
#:hash hash
#:recursive? #t
#:guile-for-build guile)))
(define (hg-version version revision changeset)
"Return the version string for packages using hg-download."
" Value out of range 0 to N : 7 " when the commit ID is too short , which
(when (< (string-length changeset) 7)
(raise
(condition
(&message (message "hg-version: changeset ID unexpectedly short")))))
(string-append version "-" revision "." (string-take changeset 7)))
(define (hg-file-name name version)
"Return the file-name for packages using hg-download."
(string-append name "-" version "-checkout"))
(define (hg-file-list directory)
"Evaluates to a list of files contained in the repository at path
@var{directory}"
(let* ((port (open-input-pipe (format #f "hg files --repository ~s" directory)))
(files (let loop ((files '()))
(let ((line (read-line port)))
(cond
((eof-object? line) files)
(else
(loop (cons line files))))))))
(close-pipe port)
(map canonicalize-path files)))
(define (should-select? path-list candidate)
"Returns #t in case that @var{candidate} is a file that is part of the given
@var{path-list}."
(let ((canon-candidate (canonicalize-path candidate)))
(let loop ((xs path-list))
(cond
((null? xs)
(equal? (array-ref (lstat candidate) 13) 'directory))
((string-contains candidate (car xs)) #t)
(else (loop (cdr xs)))))))
(define (hg-predicate directory)
"This procedure evaluates to a predicate that reports back whether a given
@var{file} - @var{stat} combination is part of the files tracked by
Mercurial."
(let ((files (hg-file-list directory)))
(lambda (file stat)
(should-select? files file))))
|
8babb01d2daf5c9ffdc82473b1c46cc6bb327901d56e7f5b5e8b39e1230368bc | wardle/nhspd | postcode.clj | (ns com.eldrix.nhspd.postcode
"UK postcode normalization and formatting."
(:require
[clojure.string :as str]))
(defn normalize
"Normalizes a postcode into uppercase 8-characters with left-aligned outward
code and right-aligned inward code returning the original if normalization
not possible.
This is the PCD2 standard formatting."
^String [pc]
(when pc
(let [pc' (str/replace pc #"\s+" "")
n (count pc')]
(if-not (>= n 5)
pc
(str/upper-case (format "%-4s %3s" (subs pc' 0 (- n 3)) (subs pc' (- n 3))))))))
(defn egif
"Normalizes a postcode into uppercase with outward code and inward codes
separated by a single space.
This is the PCDS standard formatting."
^String [pc]
(when pc (str/replace (normalize pc) #"\s+" " ")))
(defn distance-between
"Calculates crude distance between two postcodes, determined by the square
root of the sum of the square of the difference in grid coordinates
(Pythagoras), result in metres.
Parameters:
- pc1d - first postcode NHSPD data (map)
- pc2d - second postcode NHSPD data (map)"
[pcd1 pcd2]
(let [n1 (get pcd1 "OSNRTH1M")
n2 (get pcd2 "OSNRTH1M")
e1 (get pcd1 "OSEAST1M")
e2 (get pcd2 "OSEAST1M")]
(when (every? number? [n1 n2 e1 e2])
(let [nd (- n1 n2)
ed (- e1 e2)]
(Math/sqrt (+ (* nd nd) (* ed ed)))))))
| null | https://raw.githubusercontent.com/wardle/nhspd/b3487b10e538a88b7d27f3e81ed9c62bbb62b312/src/com/eldrix/nhspd/postcode.clj | clojure | (ns com.eldrix.nhspd.postcode
"UK postcode normalization and formatting."
(:require
[clojure.string :as str]))
(defn normalize
"Normalizes a postcode into uppercase 8-characters with left-aligned outward
code and right-aligned inward code returning the original if normalization
not possible.
This is the PCD2 standard formatting."
^String [pc]
(when pc
(let [pc' (str/replace pc #"\s+" "")
n (count pc')]
(if-not (>= n 5)
pc
(str/upper-case (format "%-4s %3s" (subs pc' 0 (- n 3)) (subs pc' (- n 3))))))))
(defn egif
"Normalizes a postcode into uppercase with outward code and inward codes
separated by a single space.
This is the PCDS standard formatting."
^String [pc]
(when pc (str/replace (normalize pc) #"\s+" " ")))
(defn distance-between
"Calculates crude distance between two postcodes, determined by the square
root of the sum of the square of the difference in grid coordinates
(Pythagoras), result in metres.
Parameters:
- pc1d - first postcode NHSPD data (map)
- pc2d - second postcode NHSPD data (map)"
[pcd1 pcd2]
(let [n1 (get pcd1 "OSNRTH1M")
n2 (get pcd2 "OSNRTH1M")
e1 (get pcd1 "OSEAST1M")
e2 (get pcd2 "OSEAST1M")]
(when (every? number? [n1 n2 e1 e2])
(let [nd (- n1 n2)
ed (- e1 e2)]
(Math/sqrt (+ (* nd nd) (* ed ed)))))))
| |
8eead4527988a1fac65f9bd2bb683885556d2b45e2412d65f86a81ae82fe7980 | bcc32/projecteuler-ocaml | sol_062.ml | open! Core
open! Import
module Digit_set : sig
type t [@@deriving compare, hash, sexp_of]
val of_int : int -> t
end = struct
type t = int list [@@deriving compare, hash, sexp_of]
let of_int int =
Number_theory.Int.As_base10.to_list int |> List.sort ~compare:Int.compare
;;
end
let find min_permutations =
let cubes_by_digit_set = Hashtbl.create (module Digit_set) in
let[@inline] cube n = Number_theory.Int.addition_chain_pow n 3 in
let rec loop n =
let c = cube n in
let ds = Digit_set.of_int c in
Hashtbl.add_multi cubes_by_digit_set ~key:ds ~data:c;
let cubes = Hashtbl.find_multi cubes_by_digit_set ds in
if List.length cubes >= min_permutations
then Option.value_exn (List.min_elt cubes ~compare:Int.compare)
else loop (n + 1)
in
loop 1
;;
let min_permutations = 5
let main () = find min_permutations |> printf "%d\n"
29.618ms
let%expect_test "answer" =
main ();
[%expect {| 127035954683 |}]
;;
include (val Solution.make ~problem:(Number 62) ~main)
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/e47a58cb8d6a448be8907b1fef2b4d1988fb4c87/sol/sol_062.ml | ocaml | open! Core
open! Import
module Digit_set : sig
type t [@@deriving compare, hash, sexp_of]
val of_int : int -> t
end = struct
type t = int list [@@deriving compare, hash, sexp_of]
let of_int int =
Number_theory.Int.As_base10.to_list int |> List.sort ~compare:Int.compare
;;
end
let find min_permutations =
let cubes_by_digit_set = Hashtbl.create (module Digit_set) in
let[@inline] cube n = Number_theory.Int.addition_chain_pow n 3 in
let rec loop n =
let c = cube n in
let ds = Digit_set.of_int c in
Hashtbl.add_multi cubes_by_digit_set ~key:ds ~data:c;
let cubes = Hashtbl.find_multi cubes_by_digit_set ds in
if List.length cubes >= min_permutations
then Option.value_exn (List.min_elt cubes ~compare:Int.compare)
else loop (n + 1)
in
loop 1
;;
let min_permutations = 5
let main () = find min_permutations |> printf "%d\n"
29.618ms
let%expect_test "answer" =
main ();
[%expect {| 127035954683 |}]
;;
include (val Solution.make ~problem:(Number 62) ~main)
| |
5d1a86f79c9d12df82085991f72ddeaab76514a11e545822fd92a89084c560cd | modular-macros/ocaml-macros | prodcons.ml | Classic producer - consumer
type 'a prodcons =
{ buffer: 'a array;
lock: Mutex.t;
mutable readpos: int;
mutable writepos: int;
notempty: Condition.t;
notfull: Condition.t }
let create size init =
{ buffer = Array.make size init;
lock = Mutex.create();
readpos = 0;
writepos = 0;
notempty = Condition.create();
notfull = Condition.create() }
let put p data =
Mutex.lock p.lock;
while (p.writepos + 1) mod Array.length p.buffer = p.readpos do
Condition.wait p.notfull p.lock
done;
p.buffer.(p.writepos) <- data;
p.writepos <- (p.writepos + 1) mod Array.length p.buffer;
Condition.signal p.notempty;
Mutex.unlock p.lock
let get p =
Mutex.lock p.lock;
while p.writepos = p.readpos do
Condition.wait p.notempty p.lock
done;
let data = p.buffer.(p.readpos) in
p.readpos <- (p.readpos + 1) mod Array.length p.buffer;
Condition.signal p.notfull;
Mutex.unlock p.lock;
data
(* Test *)
let rec produce buff n max =
put buff n;
if n < max then produce buff (n+1) max
let rec consume buff cur max =
let n = get buff in
if n <> cur then false
else if n = max then true
else consume buff (cur + 1) max
let _ =
let buff1 = create 20 0 and buff2 = create 30 0 in
let ok1 = ref false and ok2 = ref false in
let _p1 = Thread.create (fun () -> produce buff1 0 10000) ()
and _p2 = Thread.create (fun () -> produce buff2 0 8000) ()
and c1 = Thread.create (fun () -> ok1 := consume buff1 0 10000) () in
ok2 := consume buff2 0 8000;
Thread.join c1;
if !ok1 && !ok2
then print_string "passed\n"
else print_string "FAILED\n"
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/lib-threads/prodcons.ml | ocaml | Test | Classic producer - consumer
type 'a prodcons =
{ buffer: 'a array;
lock: Mutex.t;
mutable readpos: int;
mutable writepos: int;
notempty: Condition.t;
notfull: Condition.t }
let create size init =
{ buffer = Array.make size init;
lock = Mutex.create();
readpos = 0;
writepos = 0;
notempty = Condition.create();
notfull = Condition.create() }
let put p data =
Mutex.lock p.lock;
while (p.writepos + 1) mod Array.length p.buffer = p.readpos do
Condition.wait p.notfull p.lock
done;
p.buffer.(p.writepos) <- data;
p.writepos <- (p.writepos + 1) mod Array.length p.buffer;
Condition.signal p.notempty;
Mutex.unlock p.lock
let get p =
Mutex.lock p.lock;
while p.writepos = p.readpos do
Condition.wait p.notempty p.lock
done;
let data = p.buffer.(p.readpos) in
p.readpos <- (p.readpos + 1) mod Array.length p.buffer;
Condition.signal p.notfull;
Mutex.unlock p.lock;
data
let rec produce buff n max =
put buff n;
if n < max then produce buff (n+1) max
let rec consume buff cur max =
let n = get buff in
if n <> cur then false
else if n = max then true
else consume buff (cur + 1) max
let _ =
let buff1 = create 20 0 and buff2 = create 30 0 in
let ok1 = ref false and ok2 = ref false in
let _p1 = Thread.create (fun () -> produce buff1 0 10000) ()
and _p2 = Thread.create (fun () -> produce buff2 0 8000) ()
and c1 = Thread.create (fun () -> ok1 := consume buff1 0 10000) () in
ok2 := consume buff2 0 8000;
Thread.join c1;
if !ok1 && !ok2
then print_string "passed\n"
else print_string "FAILED\n"
|
3a31ba6ba92b7696af29301d03e05a2bd18c3c0195734c9b54861e698137401f | FreeProving/free-compiler | TypeDecl.hs | -- | This module contains the definition of data type and type synonym
-- declarations of our intermediate language.
module FreeC.IR.Syntax.TypeDecl where
import FreeC.IR.SrcSpan
import FreeC.IR.Syntax.Name
import FreeC.IR.Syntax.Type
import FreeC.IR.Syntax.TypeVarDecl
import FreeC.Pretty
-------------------------------------------------------------------------------
-- Type Declarations --
-------------------------------------------------------------------------------
-- | A data type or type synonym declaration.
data TypeDecl
= DataDecl { typeDeclSrcSpan :: SrcSpan
, typeDeclIdent :: DeclIdent
, typeDeclArgs :: [TypeVarDecl]
, dataDeclCons :: [ConDecl]
}
| TypeSynDecl { typeDeclSrcSpan :: SrcSpan
, typeDeclIdent :: DeclIdent
, typeDeclArgs :: [TypeVarDecl]
, typeSynDeclRhs :: Type
}
deriving ( Eq, Show )
-- | Instance to get the name of a type synonym or data type declaration.
instance HasDeclIdent TypeDecl where
declIdent = typeDeclIdent
-- | Gets the qualified name of the given type declaration.
typeDeclQName :: TypeDecl -> QName
typeDeclQName = declIdentName . typeDeclIdent
-- | Gets the unqualified name of the given type declaration.
typeDeclName :: TypeDecl -> Name
typeDeclName = nameFromQName . typeDeclQName
-- | Pretty instance for type declarations.
instance Pretty TypeDecl where
pretty (DataDecl _ declIdent' typeVarDecls conDecls) = prettyString "data"
<+> pretty declIdent'
<+> hsep (map pretty typeVarDecls)
<+> align (vcat (zipWith prettyConDecl [0 ..] conDecls))
where
prettyConDecl :: Int -> ConDecl -> Doc
prettyConDecl i conDecl | i == 0 = equals <+> pretty conDecl
| otherwise = char '|' <+> pretty conDecl
pretty (TypeSynDecl _ declIdent' typeVarDecls typeExpr) = prettyString "type"
<+> pretty declIdent'
<+> hsep (map pretty typeVarDecls)
<+> equals
<+> pretty typeExpr
-------------------------------------------------------------------------------
-- Constructor Declarations --
-------------------------------------------------------------------------------
-- | A constructor declaration.
data ConDecl = ConDecl { conDeclSrcSpan :: SrcSpan
, conDeclIdent :: DeclIdent
, conDeclFields :: [Type]
}
deriving ( Eq, Show )
-- | Instance to get the name of a constructor declaration.
instance HasDeclIdent ConDecl where
declIdent = conDeclIdent
-- | Gets the qualified name of the given constructor declaration.
conDeclQName :: ConDecl -> QName
conDeclQName = declIdentName . conDeclIdent
-- | Gets the unqualified name of the given constructor declaration.
conDeclName :: ConDecl -> Name
conDeclName = nameFromQName . conDeclQName
-- | Pretty instance for data constructor declarations.
instance Pretty ConDecl where
pretty (ConDecl _ declIdent' types) = pretty declIdent'
<+> hsep (map pretty types)
| null | https://raw.githubusercontent.com/FreeProving/free-compiler/6931b9ca652a185a92dd824373f092823aea4ea9/src/lib/FreeC/IR/Syntax/TypeDecl.hs | haskell | | This module contains the definition of data type and type synonym
declarations of our intermediate language.
-----------------------------------------------------------------------------
Type Declarations --
-----------------------------------------------------------------------------
| A data type or type synonym declaration.
| Instance to get the name of a type synonym or data type declaration.
| Gets the qualified name of the given type declaration.
| Gets the unqualified name of the given type declaration.
| Pretty instance for type declarations.
-----------------------------------------------------------------------------
Constructor Declarations --
-----------------------------------------------------------------------------
| A constructor declaration.
| Instance to get the name of a constructor declaration.
| Gets the qualified name of the given constructor declaration.
| Gets the unqualified name of the given constructor declaration.
| Pretty instance for data constructor declarations. | module FreeC.IR.Syntax.TypeDecl where
import FreeC.IR.SrcSpan
import FreeC.IR.Syntax.Name
import FreeC.IR.Syntax.Type
import FreeC.IR.Syntax.TypeVarDecl
import FreeC.Pretty
data TypeDecl
= DataDecl { typeDeclSrcSpan :: SrcSpan
, typeDeclIdent :: DeclIdent
, typeDeclArgs :: [TypeVarDecl]
, dataDeclCons :: [ConDecl]
}
| TypeSynDecl { typeDeclSrcSpan :: SrcSpan
, typeDeclIdent :: DeclIdent
, typeDeclArgs :: [TypeVarDecl]
, typeSynDeclRhs :: Type
}
deriving ( Eq, Show )
instance HasDeclIdent TypeDecl where
declIdent = typeDeclIdent
typeDeclQName :: TypeDecl -> QName
typeDeclQName = declIdentName . typeDeclIdent
typeDeclName :: TypeDecl -> Name
typeDeclName = nameFromQName . typeDeclQName
instance Pretty TypeDecl where
pretty (DataDecl _ declIdent' typeVarDecls conDecls) = prettyString "data"
<+> pretty declIdent'
<+> hsep (map pretty typeVarDecls)
<+> align (vcat (zipWith prettyConDecl [0 ..] conDecls))
where
prettyConDecl :: Int -> ConDecl -> Doc
prettyConDecl i conDecl | i == 0 = equals <+> pretty conDecl
| otherwise = char '|' <+> pretty conDecl
pretty (TypeSynDecl _ declIdent' typeVarDecls typeExpr) = prettyString "type"
<+> pretty declIdent'
<+> hsep (map pretty typeVarDecls)
<+> equals
<+> pretty typeExpr
data ConDecl = ConDecl { conDeclSrcSpan :: SrcSpan
, conDeclIdent :: DeclIdent
, conDeclFields :: [Type]
}
deriving ( Eq, Show )
instance HasDeclIdent ConDecl where
declIdent = conDeclIdent
conDeclQName :: ConDecl -> QName
conDeclQName = declIdentName . conDeclIdent
conDeclName :: ConDecl -> Name
conDeclName = nameFromQName . conDeclQName
instance Pretty ConDecl where
pretty (ConDecl _ declIdent' types) = pretty declIdent'
<+> hsep (map pretty types)
|
c72355445368dcf5378d7bc9a2549ae2a9c7bfc321aa506cfbdd4fad3ea44a3b | logicblocks/salutem | project.clj | (defproject io.logicblocks/salutem.core "0.1.8-RC4"
:description "A health check library for sync / async health checks."
:parent-project {:path "../parent/project.clj"
:inherit [:scm
:url
:license
:plugins
[:profiles :parent-shared]
[:profiles :parent-reveal]
[:profiles :parent-dev]
[:profiles :parent-unit]
[:profiles :parent-performance]
:deploy-repositories
:managed-dependencies
:cloverage
:bikeshed
:cljfmt
:eastwood]}
:plugins [[lein-parent "0.3.8"]]
:dependencies [[org.clojure/core.async]
[io.logicblocks/cartus.core]
[io.logicblocks/cartus.null]
[tick]]
:profiles {:shared {:dependencies [[tortue/spy]]}
:reveal [:parent-reveal]
:dev [:parent-dev :shared]
:unit [:parent-unit :shared]
:performance [:parent-performance :shared]}
:test-paths ["test/shared"
"test/unit"
"test/performance"]
:resource-paths [])
| null | https://raw.githubusercontent.com/logicblocks/salutem/c648d9aeafc2cf38578b5e7e693994d2655fb5b8/core/project.clj | clojure | (defproject io.logicblocks/salutem.core "0.1.8-RC4"
:description "A health check library for sync / async health checks."
:parent-project {:path "../parent/project.clj"
:inherit [:scm
:url
:license
:plugins
[:profiles :parent-shared]
[:profiles :parent-reveal]
[:profiles :parent-dev]
[:profiles :parent-unit]
[:profiles :parent-performance]
:deploy-repositories
:managed-dependencies
:cloverage
:bikeshed
:cljfmt
:eastwood]}
:plugins [[lein-parent "0.3.8"]]
:dependencies [[org.clojure/core.async]
[io.logicblocks/cartus.core]
[io.logicblocks/cartus.null]
[tick]]
:profiles {:shared {:dependencies [[tortue/spy]]}
:reveal [:parent-reveal]
:dev [:parent-dev :shared]
:unit [:parent-unit :shared]
:performance [:parent-performance :shared]}
:test-paths ["test/shared"
"test/unit"
"test/performance"]
:resource-paths [])
| |
86ca6095b119783306adda248878c356a44714e4c30883e394e7b2acce648fbb | emqx/emqx-lwm2m | emqx_lwm2m_tlv.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_lwm2m_tlv).
-export([ parse/1
, encode/1
]).
-include("emqx_lwm2m.hrl").
-define(LOG(Level, Format, Args), logger:Level("LWM2M-TLV: " ++ Format, Args)).
-define(TLV_TYPE_OBJECT_INSTANCE, 0).
-define(TLV_TYPE_RESOURCE_INSTANCE, 1).
-define(TLV_TYPE_MULTIPLE_RESOURCE, 2).
-define(TLV_TYPE_RESOURCE_WITH_VALUE, 3).
-define(TLV_NO_LENGTH_FIELD, 0).
-define(TLV_LEGNTH_8_BIT, 1).
-define(TLV_LEGNTH_16_BIT, 2).
-define(TLV_LEGNTH_24_BIT, 3).
%----------------------------------------------------------------------------------------------------------------------------------------
[ # { tlv_object_instance : = Id11 , value : , # { tlv_object_instance : = Id12 , value : = Value12 } , ... ]
where and Value12 is a list :
[ # { tlv_resource_with_value = > Id21 , value = > Value21 } , # { tlv_multiple_resource = > Id22 , value = Value22 } , ... ]
% where Value21 is a binary
Value22 is a list :
% [#{tlv_resource_instance => Id31, value => Value31}, #{tlv_resource_instance => Id32, value => Value32}, ...]
where Value31 and Value32 is a binary
%
correspond to three levels :
1 ) Object Instance Level
2 ) Resource Level
3 ) Resource Instance Level
%
NOTE : TLV does not has object level , only has object instance level . It implies TLV can not represent multiple objects
%----------------------------------------------------------------------------------------------------------------------------------------
parse(Data) ->
parse_loop(Data, []).
parse_loop(<<>>, Acc)->
lists:reverse(Acc);
parse_loop(Data, Acc) ->
{New, Rest} = parse_step1(Data),
parse_loop(Rest, [New|Acc]).
parse_step1(<<?TLV_TYPE_OBJECT_INSTANCE:2, IdLength:1, LengthType:2, InlineLength:3, Rest/binary>>) ->
{Id, Value, Rest2} = parse_step2(id_length_bit_width(IdLength), LengthType, InlineLength, Rest),
{#{tlv_object_instance => Id, value => parse_loop(Value, [])}, Rest2};
parse_step1(<<?TLV_TYPE_RESOURCE_INSTANCE:2, IdLength:1, LengthType:2, InlineLength:3, Rest/binary>>) ->
{Id, Value, Rest2} = parse_step2(id_length_bit_width(IdLength), LengthType, InlineLength, Rest),
{#{tlv_resource_instance => Id, value => Value}, Rest2};
parse_step1(<<?TLV_TYPE_MULTIPLE_RESOURCE:2, IdLength:1, LengthType:2, InlineLength:3, Rest/binary>>) ->
{Id, Value, Rest2} = parse_step2(id_length_bit_width(IdLength), LengthType, InlineLength, Rest),
{#{tlv_multiple_resource => Id, value => parse_loop(Value, [])}, Rest2};
parse_step1(<<?TLV_TYPE_RESOURCE_WITH_VALUE:2, IdLength:1, LengthType:2, InlineLength:3, Rest/binary>>) ->
{Id, Value, Rest2} = parse_step2(id_length_bit_width(IdLength), LengthType, InlineLength, Rest),
{#{tlv_resource_with_value => Id, value => Value}, Rest2}.
parse_step2(IdLength, ?TLV_NO_LENGTH_FIELD, Length, Data) ->
<<Id:IdLength, Value:Length/binary, Rest/binary>> = Data,
{Id, Value, Rest};
parse_step2(IdLength, ?TLV_LEGNTH_8_BIT, _, Data) ->
<<Id:IdLength, Length:8, Rest/binary>> = Data,
parse_step3(Id, Length, Rest);
parse_step2(IdLength, ?TLV_LEGNTH_16_BIT, _, Data) ->
<<Id:IdLength, Length:16, Rest/binary>> = Data,
parse_step3(Id, Length, Rest);
parse_step2(IdLength, ?TLV_LEGNTH_24_BIT, _, Data) ->
<<Id:IdLength, Length:24, Rest/binary>> = Data,
parse_step3(Id, Length, Rest).
parse_step3(Id, Length, Data) ->
<<Value:Length/binary, Rest/binary>> = Data,
{Id, Value, Rest}.
id_length_bit_width(0) -> 8;
id_length_bit_width(1) -> 16.
encode(TlvList) ->
encode(TlvList, <<>>).
encode([], Acc) ->
Acc;
encode([#{tlv_object_instance := Id, value := Value}|T], Acc) ->
SubItems = encode(Value, <<>>),
NewBinary = encode_body(?TLV_TYPE_OBJECT_INSTANCE, Id, SubItems),
encode(T, <<Acc/binary, NewBinary/binary>>);
encode([#{tlv_resource_instance := Id, value := Value}|T], Acc) ->
ValBinary = encode_value(Value),
NewBinary = encode_body(?TLV_TYPE_RESOURCE_INSTANCE, Id, ValBinary),
encode(T, <<Acc/binary, NewBinary/binary>>);
encode([#{tlv_multiple_resource := Id, value := Value}|T], Acc) ->
SubItems = encode(Value, <<>>),
NewBinary = encode_body(?TLV_TYPE_MULTIPLE_RESOURCE, Id, SubItems),
encode(T, <<Acc/binary, NewBinary/binary>>);
encode([#{tlv_resource_with_value := Id, value := Value}|T], Acc) ->
ValBinary = encode_value(Value),
NewBinary = encode_body(?TLV_TYPE_RESOURCE_WITH_VALUE, Id, ValBinary),
encode(T, <<Acc/binary, NewBinary/binary>>).
encode_body(Type, Id, Value) ->
Size = byte_size(Value),
{IdLength, IdBinarySize, IdBinary} = if
Id < 256 -> {0, 1, <<Id:8>>};
true -> {1, 2, <<Id:16>>}
end,
if
Size < 8 -> <<Type:2, IdLength:1, ?TLV_NO_LENGTH_FIELD:2, Size:3, IdBinary:IdBinarySize/binary, Value:Size/binary>>;
Size < 256 -> <<Type:2, IdLength:1, ?TLV_LEGNTH_8_BIT:2, 0:3, IdBinary:IdBinarySize/binary, Size:8, Value:Size/binary>>;
Size < 65536 -> <<Type:2, IdLength:1, ?TLV_LEGNTH_16_BIT:2, 0:3, IdBinary:IdBinarySize/binary, Size:16, Value:Size/binary>>;
true -> <<Type:2, IdLength:1, ?TLV_LEGNTH_24_BIT:2, 0:3, IdBinary:IdBinarySize/binary, Size:24, Value:Size/binary>>
end.
encode_value(Value) when is_binary(Value) ->
Value;
encode_value(Value) when is_list(Value) ->
list_to_binary(Value);
encode_value(true) ->
<<1>>;
encode_value(false) ->
<<0>>;
encode_value(Value) when is_integer(Value) ->
if
Value > -128, Value < 128 -> <<Value>>;
Value > -32768, Value < 32768 -> <<Value:16>>;
true -> <<Value:24>>
end;
encode_value(Value) when is_float(Value) ->
<<Value:32/float>>;
encode_value(Value) ->
error(io_lib:format("unsupport format ~p", [Value])).
-ifdef(TEST).
binary_to_hex_string(Data) ->
lists:flatten([io_lib:format("~2.16.0B ",[X]) || <<X:8>> <= Data ]).
-endif.
| null | https://raw.githubusercontent.com/emqx/emqx-lwm2m/6b02495beebe3b3596c75f730f4e64f3e92dd3a2/src/emqx_lwm2m_tlv.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.
--------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------
where Value21 is a binary
[#{tlv_resource_instance => Id31, value => Value31}, #{tlv_resource_instance => Id32, value => Value32}, ...]
---------------------------------------------------------------------------------------------------------------------------------------- | Copyright ( c ) 2020 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_lwm2m_tlv).
-export([ parse/1
, encode/1
]).
-include("emqx_lwm2m.hrl").
-define(LOG(Level, Format, Args), logger:Level("LWM2M-TLV: " ++ Format, Args)).
-define(TLV_TYPE_OBJECT_INSTANCE, 0).
-define(TLV_TYPE_RESOURCE_INSTANCE, 1).
-define(TLV_TYPE_MULTIPLE_RESOURCE, 2).
-define(TLV_TYPE_RESOURCE_WITH_VALUE, 3).
-define(TLV_NO_LENGTH_FIELD, 0).
-define(TLV_LEGNTH_8_BIT, 1).
-define(TLV_LEGNTH_16_BIT, 2).
-define(TLV_LEGNTH_24_BIT, 3).
[ # { tlv_object_instance : = Id11 , value : , # { tlv_object_instance : = Id12 , value : = Value12 } , ... ]
where and Value12 is a list :
[ # { tlv_resource_with_value = > Id21 , value = > Value21 } , # { tlv_multiple_resource = > Id22 , value = Value22 } , ... ]
Value22 is a list :
where Value31 and Value32 is a binary
correspond to three levels :
1 ) Object Instance Level
2 ) Resource Level
3 ) Resource Instance Level
NOTE : TLV does not has object level , only has object instance level . It implies TLV can not represent multiple objects
parse(Data) ->
parse_loop(Data, []).
parse_loop(<<>>, Acc)->
lists:reverse(Acc);
parse_loop(Data, Acc) ->
{New, Rest} = parse_step1(Data),
parse_loop(Rest, [New|Acc]).
parse_step1(<<?TLV_TYPE_OBJECT_INSTANCE:2, IdLength:1, LengthType:2, InlineLength:3, Rest/binary>>) ->
{Id, Value, Rest2} = parse_step2(id_length_bit_width(IdLength), LengthType, InlineLength, Rest),
{#{tlv_object_instance => Id, value => parse_loop(Value, [])}, Rest2};
parse_step1(<<?TLV_TYPE_RESOURCE_INSTANCE:2, IdLength:1, LengthType:2, InlineLength:3, Rest/binary>>) ->
{Id, Value, Rest2} = parse_step2(id_length_bit_width(IdLength), LengthType, InlineLength, Rest),
{#{tlv_resource_instance => Id, value => Value}, Rest2};
parse_step1(<<?TLV_TYPE_MULTIPLE_RESOURCE:2, IdLength:1, LengthType:2, InlineLength:3, Rest/binary>>) ->
{Id, Value, Rest2} = parse_step2(id_length_bit_width(IdLength), LengthType, InlineLength, Rest),
{#{tlv_multiple_resource => Id, value => parse_loop(Value, [])}, Rest2};
parse_step1(<<?TLV_TYPE_RESOURCE_WITH_VALUE:2, IdLength:1, LengthType:2, InlineLength:3, Rest/binary>>) ->
{Id, Value, Rest2} = parse_step2(id_length_bit_width(IdLength), LengthType, InlineLength, Rest),
{#{tlv_resource_with_value => Id, value => Value}, Rest2}.
parse_step2(IdLength, ?TLV_NO_LENGTH_FIELD, Length, Data) ->
<<Id:IdLength, Value:Length/binary, Rest/binary>> = Data,
{Id, Value, Rest};
parse_step2(IdLength, ?TLV_LEGNTH_8_BIT, _, Data) ->
<<Id:IdLength, Length:8, Rest/binary>> = Data,
parse_step3(Id, Length, Rest);
parse_step2(IdLength, ?TLV_LEGNTH_16_BIT, _, Data) ->
<<Id:IdLength, Length:16, Rest/binary>> = Data,
parse_step3(Id, Length, Rest);
parse_step2(IdLength, ?TLV_LEGNTH_24_BIT, _, Data) ->
<<Id:IdLength, Length:24, Rest/binary>> = Data,
parse_step3(Id, Length, Rest).
parse_step3(Id, Length, Data) ->
<<Value:Length/binary, Rest/binary>> = Data,
{Id, Value, Rest}.
id_length_bit_width(0) -> 8;
id_length_bit_width(1) -> 16.
encode(TlvList) ->
encode(TlvList, <<>>).
encode([], Acc) ->
Acc;
encode([#{tlv_object_instance := Id, value := Value}|T], Acc) ->
SubItems = encode(Value, <<>>),
NewBinary = encode_body(?TLV_TYPE_OBJECT_INSTANCE, Id, SubItems),
encode(T, <<Acc/binary, NewBinary/binary>>);
encode([#{tlv_resource_instance := Id, value := Value}|T], Acc) ->
ValBinary = encode_value(Value),
NewBinary = encode_body(?TLV_TYPE_RESOURCE_INSTANCE, Id, ValBinary),
encode(T, <<Acc/binary, NewBinary/binary>>);
encode([#{tlv_multiple_resource := Id, value := Value}|T], Acc) ->
SubItems = encode(Value, <<>>),
NewBinary = encode_body(?TLV_TYPE_MULTIPLE_RESOURCE, Id, SubItems),
encode(T, <<Acc/binary, NewBinary/binary>>);
encode([#{tlv_resource_with_value := Id, value := Value}|T], Acc) ->
ValBinary = encode_value(Value),
NewBinary = encode_body(?TLV_TYPE_RESOURCE_WITH_VALUE, Id, ValBinary),
encode(T, <<Acc/binary, NewBinary/binary>>).
encode_body(Type, Id, Value) ->
Size = byte_size(Value),
{IdLength, IdBinarySize, IdBinary} = if
Id < 256 -> {0, 1, <<Id:8>>};
true -> {1, 2, <<Id:16>>}
end,
if
Size < 8 -> <<Type:2, IdLength:1, ?TLV_NO_LENGTH_FIELD:2, Size:3, IdBinary:IdBinarySize/binary, Value:Size/binary>>;
Size < 256 -> <<Type:2, IdLength:1, ?TLV_LEGNTH_8_BIT:2, 0:3, IdBinary:IdBinarySize/binary, Size:8, Value:Size/binary>>;
Size < 65536 -> <<Type:2, IdLength:1, ?TLV_LEGNTH_16_BIT:2, 0:3, IdBinary:IdBinarySize/binary, Size:16, Value:Size/binary>>;
true -> <<Type:2, IdLength:1, ?TLV_LEGNTH_24_BIT:2, 0:3, IdBinary:IdBinarySize/binary, Size:24, Value:Size/binary>>
end.
encode_value(Value) when is_binary(Value) ->
Value;
encode_value(Value) when is_list(Value) ->
list_to_binary(Value);
encode_value(true) ->
<<1>>;
encode_value(false) ->
<<0>>;
encode_value(Value) when is_integer(Value) ->
if
Value > -128, Value < 128 -> <<Value>>;
Value > -32768, Value < 32768 -> <<Value:16>>;
true -> <<Value:24>>
end;
encode_value(Value) when is_float(Value) ->
<<Value:32/float>>;
encode_value(Value) ->
error(io_lib:format("unsupport format ~p", [Value])).
-ifdef(TEST).
binary_to_hex_string(Data) ->
lists:flatten([io_lib:format("~2.16.0B ",[X]) || <<X:8>> <= Data ]).
-endif.
|
9f084d39bee2a35bfd7df3b2280daba9ae170a9c2518a2b11bb5e7048d5609d3 | expede/rescue | Types.hs | # LANGUAGE ApplicativeDo #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
-- | The 'RescueT' transformer
module Control.Monad.Trans.Rescue.Types
( RescueT (..)
, Rescue
, runRescue
) where
import Control.Monad.Base
import Control.Monad.Catch
import Control.Monad.Cont
import Control.Monad.Fix
import Control.Monad.Reader
import Control.Monad.Rescue
import Control.Monad.Trans.Error.Class
import Data.Functor.Identity
import Data.WorldPeace
-- | Add type-directed error handling abilities to a 'Monad'
newtype RescueT errs m a
= RescueT { runRescueT :: m (Either (OpenUnion errs) a) }
| A specialized version of ' RescueT ' to be used without a transfromer stack
type Rescue errs = RescueT errs Identity
runRescue :: Rescue errs a -> Either (OpenUnion errs) a
runRescue = runIdentity . runRescueT
mapRescueT
:: ( n (Either (OpenUnion errs) a)
-> m (Either (OpenUnion errs') b)
)
-> RescueT errs n a
-> RescueT errs' m b
mapRescueT f (RescueT n) = RescueT $ f n
instance Eq (m (Either (OpenUnion errs) a)) => Eq (RescueT errs m a) where
RescueT a == RescueT b = a == b
instance Show (m (Either (OpenUnion errs) a)) => Show (RescueT errs m a) where
show (RescueT inner) = "RescueT (" <> show inner <> ")"
instance Functor m => Functor (RescueT errs m) where
fmap f (RescueT inner) = RescueT $ fmap (fmap f) inner
instance Applicative m => Applicative (RescueT errs m) where
pure = RescueT . pure . pure
(RescueT fs) <*> (RescueT xs) = RescueT $ do
innerFs <- fs
innerXs <- xs
return (innerFs <*> innerXs)
instance Monad m => Monad (RescueT errs m) where
RescueT action >>= k = RescueT $ action >>= \case
Left err -> return (Left err)
Right val -> runRescueT (k val)
instance MonadTrans (RescueT errs) where
lift action = RescueT (Right <$> action)
instance Monad m => MonadTransError RescueT errs m where
onRaise f (RescueT inner) =
RescueT $
inner >>= \case
Left err -> runRescueT $ f err
Right val -> return $ Right val
instance MonadBase b m => MonadBase b (RescueT errs m) where
liftBase = liftBaseDefault
instance MonadIO m => MonadIO (RescueT errs m) where
liftIO io = RescueT $ do
action <- liftIO io
return (Right action)
instance MonadFix m => MonadFix (RescueT errs m) where
mfix f = RescueT . mfix $ \a ->
runRescueT . f $ case a of
Right r -> r
_ -> error "Empty mfix argument" -- absurd
instance Foldable m => Foldable (RescueT errs m) where
foldMap f (RescueT m) = foldMap (foldMapEither f) m where
foldMapEither g (Right a) = g a
foldMapEither _ (Left _) = mempty
instance (Monad m, Traversable m) => Traversable (RescueT errs m) where
traverse f (RescueT m) = RescueT <$> traverse (traverseEither f) m
where
traverseEither g (Right val) = Right <$> g val
traverseEither _ (Left err) = pure (Left err)
instance Monad m => MonadRaise (RescueT errs m) where
type Errors (RescueT errs m) = errs
raise err = RescueT . pure $ raise err
instance Monad m => MonadRescue (RescueT errs m) where
attempt (RescueT inner) =
RescueT $
inner >>= \case
Left err -> return . Right $ Left err
Right val -> return . Right $ Right val
instance MonadThrow m => MonadThrow (RescueT errs m) where
throwM = lift . throwM
instance MonadCatch m => MonadCatch (RescueT errs m) where
catch (RescueT m) f = RescueT $ catch m (runRescueT . f)
instance MonadReader cfg m => MonadReader cfg (RescueT errs m) where
ask = lift ask
local = mapRescueT . local
reader = lift . reader
| null | https://raw.githubusercontent.com/expede/rescue/5f460a4cd9a01ac84e669a50711375c8f8dcba75/library/Control/Monad/Trans/Rescue/Types.hs | haskell | # LANGUAGE LambdaCase #
| The 'RescueT' transformer
| Add type-directed error handling abilities to a 'Monad'
absurd | # LANGUAGE ApplicativeDo #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Control.Monad.Trans.Rescue.Types
( RescueT (..)
, Rescue
, runRescue
) where
import Control.Monad.Base
import Control.Monad.Catch
import Control.Monad.Cont
import Control.Monad.Fix
import Control.Monad.Reader
import Control.Monad.Rescue
import Control.Monad.Trans.Error.Class
import Data.Functor.Identity
import Data.WorldPeace
newtype RescueT errs m a
= RescueT { runRescueT :: m (Either (OpenUnion errs) a) }
| A specialized version of ' RescueT ' to be used without a transfromer stack
type Rescue errs = RescueT errs Identity
runRescue :: Rescue errs a -> Either (OpenUnion errs) a
runRescue = runIdentity . runRescueT
mapRescueT
:: ( n (Either (OpenUnion errs) a)
-> m (Either (OpenUnion errs') b)
)
-> RescueT errs n a
-> RescueT errs' m b
mapRescueT f (RescueT n) = RescueT $ f n
instance Eq (m (Either (OpenUnion errs) a)) => Eq (RescueT errs m a) where
RescueT a == RescueT b = a == b
instance Show (m (Either (OpenUnion errs) a)) => Show (RescueT errs m a) where
show (RescueT inner) = "RescueT (" <> show inner <> ")"
instance Functor m => Functor (RescueT errs m) where
fmap f (RescueT inner) = RescueT $ fmap (fmap f) inner
instance Applicative m => Applicative (RescueT errs m) where
pure = RescueT . pure . pure
(RescueT fs) <*> (RescueT xs) = RescueT $ do
innerFs <- fs
innerXs <- xs
return (innerFs <*> innerXs)
instance Monad m => Monad (RescueT errs m) where
RescueT action >>= k = RescueT $ action >>= \case
Left err -> return (Left err)
Right val -> runRescueT (k val)
instance MonadTrans (RescueT errs) where
lift action = RescueT (Right <$> action)
instance Monad m => MonadTransError RescueT errs m where
onRaise f (RescueT inner) =
RescueT $
inner >>= \case
Left err -> runRescueT $ f err
Right val -> return $ Right val
instance MonadBase b m => MonadBase b (RescueT errs m) where
liftBase = liftBaseDefault
instance MonadIO m => MonadIO (RescueT errs m) where
liftIO io = RescueT $ do
action <- liftIO io
return (Right action)
instance MonadFix m => MonadFix (RescueT errs m) where
mfix f = RescueT . mfix $ \a ->
runRescueT . f $ case a of
Right r -> r
instance Foldable m => Foldable (RescueT errs m) where
foldMap f (RescueT m) = foldMap (foldMapEither f) m where
foldMapEither g (Right a) = g a
foldMapEither _ (Left _) = mempty
instance (Monad m, Traversable m) => Traversable (RescueT errs m) where
traverse f (RescueT m) = RescueT <$> traverse (traverseEither f) m
where
traverseEither g (Right val) = Right <$> g val
traverseEither _ (Left err) = pure (Left err)
instance Monad m => MonadRaise (RescueT errs m) where
type Errors (RescueT errs m) = errs
raise err = RescueT . pure $ raise err
instance Monad m => MonadRescue (RescueT errs m) where
attempt (RescueT inner) =
RescueT $
inner >>= \case
Left err -> return . Right $ Left err
Right val -> return . Right $ Right val
instance MonadThrow m => MonadThrow (RescueT errs m) where
throwM = lift . throwM
instance MonadCatch m => MonadCatch (RescueT errs m) where
catch (RescueT m) f = RescueT $ catch m (runRescueT . f)
instance MonadReader cfg m => MonadReader cfg (RescueT errs m) where
ask = lift ask
local = mapRescueT . local
reader = lift . reader
|
7ef5b4becd0f8755c3803232af148771e3251724f7d05dcfef93d3f8fba0edc3 | day8/re-frame | settings.cljc | (ns re-frame.settings
(:require
[re-frame.interop :as interop]
[re-frame.loggers :refer [console]]))
(def defaults
{:loaded? false
:global-interceptors interop/empty-queue})
(def store
(atom defaults))
(interop/on-load
#(swap! store (fn [m] (assoc m :loaded? true))))
(defn loaded?
[]
(:loaded? @store))
(defn -replace-global-interceptor
[global-interceptors interceptor]
(reduce
(fn [ret existing-interceptor]
(if (= (:id interceptor)
(:id existing-interceptor))
(do
(when interop/debug-enabled?
(when (not (loaded?))
(console :warn "re-frame: replacing duplicate global interceptor id: " (:id interceptor))))
(conj ret interceptor))
(conj ret existing-interceptor)))
interop/empty-queue
global-interceptors))
(defn reg-global-interceptor
[{:keys [id] :as interceptor}]
(swap! store update :global-interceptors
(fn [global-interceptors]
(let [ids (map :id global-interceptors)]
(if (some #{id} ids)
;; If the id already exists we replace it in-place to maintain the ordering of
;; global interceptors esp during hot-code reloading in development.
(-replace-global-interceptor global-interceptors interceptor)
(conj global-interceptors interceptor))))))
(defn get-global-interceptors
[]
(:global-interceptors @store))
(defn clear-global-interceptors
([]
(swap! store assoc :global-interceptors interop/empty-queue))
([id]
(swap! store update :global-interceptors
(fn [global-interceptors]
(into interop/empty-queue (remove #(= id (:id %)) global-interceptors))))))
| null | https://raw.githubusercontent.com/day8/re-frame/ecb756e66fe30efca896879369a420df1e271605/src/re_frame/settings.cljc | clojure | If the id already exists we replace it in-place to maintain the ordering of
global interceptors esp during hot-code reloading in development. | (ns re-frame.settings
(:require
[re-frame.interop :as interop]
[re-frame.loggers :refer [console]]))
(def defaults
{:loaded? false
:global-interceptors interop/empty-queue})
(def store
(atom defaults))
(interop/on-load
#(swap! store (fn [m] (assoc m :loaded? true))))
(defn loaded?
[]
(:loaded? @store))
(defn -replace-global-interceptor
[global-interceptors interceptor]
(reduce
(fn [ret existing-interceptor]
(if (= (:id interceptor)
(:id existing-interceptor))
(do
(when interop/debug-enabled?
(when (not (loaded?))
(console :warn "re-frame: replacing duplicate global interceptor id: " (:id interceptor))))
(conj ret interceptor))
(conj ret existing-interceptor)))
interop/empty-queue
global-interceptors))
(defn reg-global-interceptor
[{:keys [id] :as interceptor}]
(swap! store update :global-interceptors
(fn [global-interceptors]
(let [ids (map :id global-interceptors)]
(if (some #{id} ids)
(-replace-global-interceptor global-interceptors interceptor)
(conj global-interceptors interceptor))))))
(defn get-global-interceptors
[]
(:global-interceptors @store))
(defn clear-global-interceptors
([]
(swap! store assoc :global-interceptors interop/empty-queue))
([id]
(swap! store update :global-interceptors
(fn [global-interceptors]
(into interop/empty-queue (remove #(= id (:id %)) global-interceptors))))))
|
0de5397f7608201c54aa0f88f84c3d844119dc83ed4f7fbd63d17e22e8dfd676 | flyspeck/flyspeck | canon.ml | (* ========================================================================= *)
(* Reasonably efficient conversions for various canonical forms. *)
(* *)
, University of Cambridge Computer Laboratory
(* *)
( c ) Copyright , University of Cambridge 1998
( c ) Copyright , 1998 - 2007
(* ========================================================================= *)
open Parser
include Trivia
(* ------------------------------------------------------------------------- *)
(* Pre-simplification. *)
(* ------------------------------------------------------------------------- *)
let PRESIMP_CONV =
GEN_REWRITE_CONV TOP_DEPTH_CONV
[NOT_CLAUSES; AND_CLAUSES; OR_CLAUSES; IMP_CLAUSES; EQ_CLAUSES;
FORALL_SIMP; EXISTS_SIMP; EXISTS_OR_THM; FORALL_AND_THM;
LEFT_EXISTS_AND_THM; RIGHT_EXISTS_AND_THM;
LEFT_FORALL_OR_THM; RIGHT_FORALL_OR_THM];;
(* ------------------------------------------------------------------------- *)
ACI rearrangements of conjunctions and disjunctions . This is much faster
(* than AC xxx_ACI on large problems, as well as being more controlled. *)
(* ------------------------------------------------------------------------- *)
let CONJ_ACI_RULE =
let rec mk_fun th fn =
let tm = concl th in
if is_conj tm then
let th1,th2 = CONJ_PAIR th in
mk_fun th1 (mk_fun th2 fn)
else (tm |-> th) fn
and use_fun fn tm =
if is_conj tm then
let l,r = dest_conj tm in CONJ (use_fun fn l) (use_fun fn r)
else apply fn tm in
fun fm ->
let p,p' = dest_eq fm in
if p = p' then REFL p else
let th = use_fun (mk_fun (ASSUME p) undefined) p'
and th' = use_fun (mk_fun (ASSUME p') undefined) p in
IMP_ANTISYM_RULE (DISCH_ALL th) (DISCH_ALL th');;
let DISJ_ACI_RULE =
let pth_left = UNDISCH(TAUT `~(a \/ b) ==> ~a`)
and pth_right = UNDISCH(TAUT `~(a \/ b) ==> ~b`)
and pth = repeat UNDISCH (TAUT `~a ==> ~b ==> ~(a \/ b)`)
and pth_neg = UNDISCH(TAUT `(~a <=> ~b) ==> (a <=> b)`)
and a_tm = `a:bool` and b_tm = `b:bool` in
let NOT_DISJ_PAIR th =
let p,q = dest_disj(rand(concl th)) in
let ilist = [p,a_tm; q,b_tm] in
PROVE_HYP th (INST ilist pth_left),
PROVE_HYP th (INST ilist pth_right)
and NOT_DISJ th1 th2 =
let th3 = INST [rand(concl th1),a_tm; rand(concl th2),b_tm] pth in
PROVE_HYP th1 (PROVE_HYP th2 th3) in
let rec mk_fun th fn =
let tm = rand(concl th) in
if is_disj tm then
let th1,th2 = NOT_DISJ_PAIR th in
mk_fun th1 (mk_fun th2 fn)
else (tm |-> th) fn
and use_fun fn tm =
if is_disj tm then
let l,r = dest_disj tm in NOT_DISJ (use_fun fn l) (use_fun fn r)
else apply fn tm in
fun fm ->
let p,p' = dest_eq fm in
if p = p' then REFL p else
let th = use_fun (mk_fun (ASSUME(mk_neg p)) undefined) p'
and th' = use_fun (mk_fun (ASSUME(mk_neg p')) undefined) p in
let th1 = IMP_ANTISYM_RULE (DISCH_ALL th) (DISCH_ALL th') in
PROVE_HYP th1 (INST [p,a_tm; p',b_tm] pth_neg);;
(* ------------------------------------------------------------------------- *)
(* Order canonically, right-associate and remove duplicates. *)
(* ------------------------------------------------------------------------- *)
let CONJ_CANON_CONV tm =
let tm' = list_mk_conj(setify(conjuncts tm)) in
CONJ_ACI_RULE(mk_eq(tm,tm'));;
let DISJ_CANON_CONV tm =
let tm' = list_mk_disj(setify(disjuncts tm)) in
DISJ_ACI_RULE(mk_eq(tm,tm'));;
(* ------------------------------------------------------------------------- *)
General NNF conversion . The user supplies some conversion to be applied
(* to atomic formulas. *)
(* *)
(* "Iff"s are split conjunctively or disjunctively according to the flag *)
(* argument (conjuctively = true) until a universal quantifier (modulo *)
(* current parity) is passed; after that they are split conjunctively. This *)
(* is appropriate when the result is passed to a disjunctive splitter *)
followed by a clausal form inner core , such as .
(* *)
(* To avoid some duplicate computation, this function will in general *)
enter a recursion where it simultaneously computes NNF representations
(* for "p" and "~p", so the user needs to supply an atomic "conversion" *)
(* that does the same. *)
(* ------------------------------------------------------------------------- *)
let (GEN_NNF_CONV:bool->conv*(term->thm*thm)->conv) =
let and_tm = `(/\)` and or_tm = `(\/)` and not_tm = `(~)`
and pth_not_not = TAUT `~ ~ p = p`
and pth_not_and = TAUT `~(p /\ q) <=> ~p \/ ~q`
and pth_not_or = TAUT `~(p \/ q) <=> ~p /\ ~q`
and pth_imp = TAUT `p ==> q <=> ~p \/ q`
and pth_not_imp = TAUT `~(p ==> q) <=> p /\ ~q`
and pth_eq = TAUT `(p <=> q) <=> p /\ q \/ ~p /\ ~q`
and pth_not_eq = TAUT `~(p <=> q) <=> p /\ ~q \/ ~p /\ q`
and pth_eq' = TAUT `(p <=> q) <=> (p \/ ~q) /\ (~p \/ q)`
and pth_not_eq' = TAUT `~(p <=> q) <=> (p \/ q) /\ (~p \/ ~q)`
and [pth_not_forall; pth_not_exists; pth_not_exu] =
(CONJUNCTS o prove)
(`(~((!) P) <=> ?x:A. ~(P x)) /\
(~((?) P) <=> !x:A. ~(P x)) /\
(~((?!) P) <=> (!x:A. ~(P x)) \/ ?x y. P x /\ P y /\ ~(y = x))`,
REPEAT CONJ_TAC THEN
GEN_REWRITE_TAC (LAND_CONV o funpow 2 RAND_CONV) [GSYM ETA_AX] THEN
REWRITE_TAC[NOT_EXISTS_THM; NOT_FORALL_THM; EXISTS_UNIQUE_DEF;
DE_MORGAN_THM; NOT_IMP] THEN
REWRITE_TAC[CONJ_ASSOC; EQ_SYM_EQ])
and pth_exu = prove
(`((?!) P) <=> (?x:A. P x) /\ !x y. ~(P x) \/ ~(P y) \/ (y = x)`,
GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [GSYM ETA_AX] THEN
REWRITE_TAC[EXISTS_UNIQUE_DEF; TAUT `a /\ b ==> c <=> ~a \/ ~b \/ c`] THEN
REWRITE_TAC[EQ_SYM_EQ])
and p_tm = `p:bool` and q_tm = `q:bool` in
let rec NNF_DCONV cf baseconvs tm =
match tm with
Comb(Comb(Const("/\\",_),l),r) ->
let th_lp,th_ln = NNF_DCONV cf baseconvs l
and th_rp,th_rn = NNF_DCONV cf baseconvs r in
MK_COMB(AP_TERM and_tm th_lp,th_rp),
TRANS (INST [l,p_tm; r,q_tm] pth_not_and)
(MK_COMB(AP_TERM or_tm th_ln,th_rn))
| Comb(Comb(Const("\\/",_),l),r) ->
let th_lp,th_ln = NNF_DCONV cf baseconvs l
and th_rp,th_rn = NNF_DCONV cf baseconvs r in
MK_COMB(AP_TERM or_tm th_lp,th_rp),
TRANS (INST [l,p_tm; r,q_tm] pth_not_or)
(MK_COMB(AP_TERM and_tm th_ln,th_rn))
| Comb(Comb(Const("==>",_),l),r) ->
let th_lp,th_ln = NNF_DCONV cf baseconvs l
and th_rp,th_rn = NNF_DCONV cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_imp)
(MK_COMB(AP_TERM or_tm th_ln,th_rp)),
TRANS (INST [l,p_tm; r,q_tm] pth_not_imp)
(MK_COMB(AP_TERM and_tm th_lp,th_rn))
| Comb(Comb(Const("=",Tyapp("fun",Tyapp("bool",_)::_)),l),r) ->
let th_lp,th_ln = NNF_DCONV cf baseconvs l
and th_rp,th_rn = NNF_DCONV cf baseconvs r in
if cf then
TRANS (INST [l,p_tm; r,q_tm] pth_eq')
(MK_COMB(AP_TERM and_tm (MK_COMB(AP_TERM or_tm th_lp,th_rn)),
MK_COMB(AP_TERM or_tm th_ln,th_rp))),
TRANS (INST [l,p_tm; r,q_tm] pth_not_eq')
(MK_COMB(AP_TERM and_tm (MK_COMB(AP_TERM or_tm th_lp,th_rp)),
MK_COMB(AP_TERM or_tm th_ln,th_rn)))
else
TRANS (INST [l,p_tm; r,q_tm] pth_eq)
(MK_COMB(AP_TERM or_tm (MK_COMB(AP_TERM and_tm th_lp,th_rp)),
MK_COMB(AP_TERM and_tm th_ln,th_rn))),
TRANS (INST [l,p_tm; r,q_tm] pth_not_eq)
(MK_COMB(AP_TERM or_tm (MK_COMB(AP_TERM and_tm th_lp,th_rn)),
MK_COMB(AP_TERM and_tm th_ln,th_rp)))
| Comb(Const("!",Tyapp("fun",Tyapp("fun",ty::_)::_)) as q,
(Abs(x,t) as bod)) ->
let th_p,th_n = NNF_DCONV true baseconvs t in
AP_TERM q (ABS x th_p),
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_forall)
and th2 = TRANS (AP_TERM not_tm (BETA(mk_comb(bod,x)))) th_n in
TRANS th1 (MK_EXISTS x th2)
| Comb(Const("?",Tyapp("fun",Tyapp("fun",ty::_)::_)) as q,
(Abs(x,t) as bod)) ->
let th_p,th_n = NNF_DCONV cf baseconvs t in
AP_TERM q (ABS x th_p),
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_exists)
and th2 = TRANS (AP_TERM not_tm (BETA(mk_comb(bod,x)))) th_n in
TRANS th1 (MK_FORALL x th2)
| Comb(Const("?!",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let y = variant (x::frees t) x
and th_p,th_n = NNF_DCONV cf baseconvs t in
let eq = mk_eq(y,x) in
let eth_p,eth_n = baseconvs eq
and bth = BETA (mk_comb(bod,x))
and bth' = BETA_CONV(mk_comb(bod,y)) in
let th_p' = INST [y,x] th_p and th_n' = INST [y,x] th_n in
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_exu)
and th1' = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_exu)
and th2 =
MK_COMB(AP_TERM and_tm
(MK_EXISTS x (TRANS bth th_p)),
MK_FORALL x (MK_FORALL y
(MK_COMB(AP_TERM or_tm (TRANS (AP_TERM not_tm bth) th_n),
MK_COMB(AP_TERM or_tm
(TRANS (AP_TERM not_tm bth') th_n'),
eth_p)))))
and th2' =
MK_COMB(AP_TERM or_tm
(MK_FORALL x (TRANS (AP_TERM not_tm bth) th_n)),
MK_EXISTS x (MK_EXISTS y
(MK_COMB(AP_TERM and_tm (TRANS bth th_p),
MK_COMB(AP_TERM and_tm (TRANS bth' th_p'),
eth_n))))) in
TRANS th1 th2,TRANS th1' th2'
| Comb(Const("~",_),t) ->
let th1,th2 = NNF_DCONV cf baseconvs t in
th2,TRANS (INST [t,p_tm] pth_not_not) th1
| _ -> try baseconvs tm
with Failure _ -> REFL tm,REFL(mk_neg tm) in
let rec NNF_CONV cf (base1,base2 as baseconvs) tm =
match tm with
Comb(Comb(Const("/\\",_),l),r) ->
let th_lp = NNF_CONV cf baseconvs l
and th_rp = NNF_CONV cf baseconvs r in
MK_COMB(AP_TERM and_tm th_lp,th_rp)
| Comb(Comb(Const("\\/",_),l),r) ->
let th_lp = NNF_CONV cf baseconvs l
and th_rp = NNF_CONV cf baseconvs r in
MK_COMB(AP_TERM or_tm th_lp,th_rp)
| Comb(Comb(Const("==>",_),l),r) ->
let th_ln = NNF_CONV' cf baseconvs l
and th_rp = NNF_CONV cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_imp)
(MK_COMB(AP_TERM or_tm th_ln,th_rp))
| Comb(Comb(Const("=",Tyapp("fun",Tyapp("bool",_)::_)),l),r) ->
let th_lp,th_ln = NNF_DCONV cf base2 l
and th_rp,th_rn = NNF_DCONV cf base2 r in
if cf then
TRANS (INST [l,p_tm; r,q_tm] pth_eq')
(MK_COMB(AP_TERM and_tm (MK_COMB(AP_TERM or_tm th_lp,th_rn)),
MK_COMB(AP_TERM or_tm th_ln,th_rp)))
else
TRANS (INST [l,p_tm; r,q_tm] pth_eq)
(MK_COMB(AP_TERM or_tm (MK_COMB(AP_TERM and_tm th_lp,th_rp)),
MK_COMB(AP_TERM and_tm th_ln,th_rn)))
| Comb(Const("!",Tyapp("fun",Tyapp("fun",ty::_)::_)) as q,
(Abs(x,t))) ->
let th_p = NNF_CONV true baseconvs t in
AP_TERM q (ABS x th_p)
| Comb(Const("?",Tyapp("fun",Tyapp("fun",ty::_)::_)) as q,
(Abs(x,t))) ->
let th_p = NNF_CONV cf baseconvs t in
AP_TERM q (ABS x th_p)
| Comb(Const("?!",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let y = variant (x::frees t) x
and th_p,th_n = NNF_DCONV cf base2 t in
let eq = mk_eq(y,x) in
let eth_p,eth_n = base2 eq
and bth = BETA (mk_comb(bod,x))
and bth' = BETA_CONV(mk_comb(bod,y)) in
let th_n' = INST [y,x] th_n in
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_exu)
and th2 =
MK_COMB(AP_TERM and_tm
(MK_EXISTS x (TRANS bth th_p)),
MK_FORALL x (MK_FORALL y
(MK_COMB(AP_TERM or_tm (TRANS (AP_TERM not_tm bth) th_n),
MK_COMB(AP_TERM or_tm
(TRANS (AP_TERM not_tm bth') th_n'),
eth_p))))) in
TRANS th1 th2
| Comb(Const("~",_),t) -> NNF_CONV' cf baseconvs t
| _ -> try base1 tm with Failure _ -> REFL tm
and NNF_CONV' cf (base1,base2 as baseconvs) tm =
match tm with
Comb(Comb(Const("/\\",_),l),r) ->
let th_ln = NNF_CONV' cf baseconvs l
and th_rn = NNF_CONV' cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_not_and)
(MK_COMB(AP_TERM or_tm th_ln,th_rn))
| Comb(Comb(Const("\\/",_),l),r) ->
let th_ln = NNF_CONV' cf baseconvs l
and th_rn = NNF_CONV' cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_not_or)
(MK_COMB(AP_TERM and_tm th_ln,th_rn))
| Comb(Comb(Const("==>",_),l),r) ->
let th_lp = NNF_CONV cf baseconvs l
and th_rn = NNF_CONV' cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_not_imp)
(MK_COMB(AP_TERM and_tm th_lp,th_rn))
| Comb(Comb(Const("=",Tyapp("fun",Tyapp("bool",_)::_)),l),r) ->
let th_lp,th_ln = NNF_DCONV cf base2 l
and th_rp,th_rn = NNF_DCONV cf base2 r in
if cf then
TRANS (INST [l,p_tm; r,q_tm] pth_not_eq')
(MK_COMB(AP_TERM and_tm (MK_COMB(AP_TERM or_tm th_lp,th_rp)),
MK_COMB(AP_TERM or_tm th_ln,th_rn)))
else
TRANS (INST [l,p_tm; r,q_tm] pth_not_eq)
(MK_COMB(AP_TERM or_tm (MK_COMB(AP_TERM and_tm th_lp,th_rn)),
MK_COMB(AP_TERM and_tm th_ln,th_rp)))
| Comb(Const("!",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let th_n = NNF_CONV' cf baseconvs t in
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_forall)
and th2 = TRANS (AP_TERM not_tm (BETA(mk_comb(bod,x)))) th_n in
TRANS th1 (MK_EXISTS x th2)
| Comb(Const("?",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let th_n = NNF_CONV' true baseconvs t in
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_exists)
and th2 = TRANS (AP_TERM not_tm (BETA(mk_comb(bod,x)))) th_n in
TRANS th1 (MK_FORALL x th2)
| Comb(Const("?!",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let y = variant (x::frees t) x
and th_p,th_n = NNF_DCONV cf base2 t in
let eq = mk_eq(y,x) in
let eth_p,eth_n = base2 eq
and bth = BETA (mk_comb(bod,x))
and bth' = BETA_CONV(mk_comb(bod,y)) in
let th_p' = INST [y,x] th_p in
let th1' = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_exu)
and th2' =
MK_COMB(AP_TERM or_tm
(MK_FORALL x (TRANS (AP_TERM not_tm bth) th_n)),
MK_EXISTS x (MK_EXISTS y
(MK_COMB(AP_TERM and_tm (TRANS bth th_p),
MK_COMB(AP_TERM and_tm (TRANS bth' th_p'),
eth_n))))) in
TRANS th1' th2'
| Comb(Const("~",_),t) ->
let th1 = NNF_CONV cf baseconvs t in
TRANS (INST [t,p_tm] pth_not_not) th1
| _ -> let tm' = mk_neg tm in try base1 tm' with Failure _ -> REFL tm' in
NNF_CONV;;
(* ------------------------------------------------------------------------- *)
(* Some common special cases. *)
(* ------------------------------------------------------------------------- *)
let NNF_CONV =
(GEN_NNF_CONV false (ALL_CONV,fun t -> REFL t,REFL(mk_neg t)) :conv);;
let NNFC_CONV =
(GEN_NNF_CONV true (ALL_CONV,fun t -> REFL t,REFL(mk_neg t)) :conv);;
(* ------------------------------------------------------------------------- *)
Skolemize a term already in NNF ( does n't matter if it 's not prenex ) .
(* ------------------------------------------------------------------------- *)
let SKOLEM_CONV =
GEN_REWRITE_CONV TOP_DEPTH_CONV
[EXISTS_OR_THM; LEFT_EXISTS_AND_THM; RIGHT_EXISTS_AND_THM;
FORALL_AND_THM; LEFT_FORALL_OR_THM; RIGHT_FORALL_OR_THM;
FORALL_SIMP; EXISTS_SIMP] THENC
GEN_REWRITE_CONV REDEPTH_CONV
[RIGHT_AND_EXISTS_THM;
LEFT_AND_EXISTS_THM;
OR_EXISTS_THM;
RIGHT_OR_EXISTS_THM;
LEFT_OR_EXISTS_THM;
SKOLEM_THM];;
(* ------------------------------------------------------------------------- *)
Put a term already in NNF into prenex form .
(* ------------------------------------------------------------------------- *)
let PRENEX_CONV =
GEN_REWRITE_CONV REDEPTH_CONV
[AND_FORALL_THM; LEFT_AND_FORALL_THM; RIGHT_AND_FORALL_THM;
LEFT_OR_FORALL_THM; RIGHT_OR_FORALL_THM;
OR_EXISTS_THM; LEFT_OR_EXISTS_THM; RIGHT_OR_EXISTS_THM;
LEFT_AND_EXISTS_THM; RIGHT_AND_EXISTS_THM];;
(* ------------------------------------------------------------------------- *)
(* Weak and normal DNF conversion. The "weak" form gives a disjunction of *)
(* conjunctions, but has no particular associativity at either level and *)
(* may contain duplicates. The regular forms give canonical right-associate *)
(* lists without duplicates, but do not remove subsumed disjuncts. *)
(* *)
In both cases the input term is supposed to be in NNF already . We do go
(* inside quantifiers and transform their body, but don't move them. *)
(* ------------------------------------------------------------------------- *)
let WEAK_DNF_CONV,DNF_CONV =
let pth1 = TAUT `a /\ (b \/ c) <=> a /\ b \/ a /\ c`
and pth2 = TAUT `(a \/ b) /\ c <=> a /\ c \/ b /\ c`
and a_tm = `a:bool` and b_tm = `b:bool` and c_tm = `c:bool` in
let rec distribute tm =
match tm with
Comb(Comb(Const("/\\",_),a),Comb(Comb(Const("\\/",_),b),c)) ->
let th = INST [a,a_tm; b,b_tm; c,c_tm] pth1 in
TRANS th (BINOP_CONV distribute (rand(concl th)))
| Comb(Comb(Const("/\\",_),Comb(Comb(Const("\\/",_),a),b)),c) ->
let th = INST [a,a_tm; b,b_tm; c,c_tm] pth2 in
TRANS th (BINOP_CONV distribute (rand(concl th)))
| _ -> REFL tm in
let strengthen =
DEPTH_BINOP_CONV `(\/)` CONJ_CANON_CONV THENC DISJ_CANON_CONV in
let rec weakdnf tm =
match tm with
Comb(Const("!",_),Abs(_,_))
| Comb(Const("?",_),Abs(_,_)) -> BINDER_CONV weakdnf tm
| Comb(Comb(Const("\\/",_),_),_) -> BINOP_CONV weakdnf tm
| Comb(Comb(Const("/\\",_) as op,l),r) ->
let th = MK_COMB(AP_TERM op (weakdnf l),weakdnf r) in
TRANS th (distribute(rand(concl th)))
| _ -> REFL tm
and substrongdnf tm =
match tm with
Comb(Const("!",_),Abs(_,_))
| Comb(Const("?",_),Abs(_,_)) -> BINDER_CONV strongdnf tm
| Comb(Comb(Const("\\/",_),_),_) -> BINOP_CONV substrongdnf tm
| Comb(Comb(Const("/\\",_) as op,l),r) ->
let th = MK_COMB(AP_TERM op (substrongdnf l),substrongdnf r) in
TRANS th (distribute(rand(concl th)))
| _ -> REFL tm
and strongdnf tm =
let th = substrongdnf tm in
TRANS th (strengthen(rand(concl th))) in
weakdnf,strongdnf;;
(* ------------------------------------------------------------------------- *)
Likewise for CNF .
(* ------------------------------------------------------------------------- *)
let WEAK_CNF_CONV,CNF_CONV =
let pth1 = TAUT `a \/ (b /\ c) <=> (a \/ b) /\ (a \/ c)`
and pth2 = TAUT `(a /\ b) \/ c <=> (a \/ c) /\ (b \/ c)`
and a_tm = `a:bool` and b_tm = `b:bool` and c_tm = `c:bool` in
let rec distribute tm =
match tm with
Comb(Comb(Const("\\/",_),a),Comb(Comb(Const("/\\",_),b),c)) ->
let th = INST [a,a_tm; b,b_tm; c,c_tm] pth1 in
TRANS th (BINOP_CONV distribute (rand(concl th)))
| Comb(Comb(Const("\\/",_),Comb(Comb(Const("/\\",_),a),b)),c) ->
let th = INST [a,a_tm; b,b_tm; c,c_tm] pth2 in
TRANS th (BINOP_CONV distribute (rand(concl th)))
| _ -> REFL tm in
let strengthen =
DEPTH_BINOP_CONV `(/\)` DISJ_CANON_CONV THENC CONJ_CANON_CONV in
let rec weakcnf tm =
match tm with
Comb(Const("!",_),Abs(_,_))
| Comb(Const("?",_),Abs(_,_)) -> BINDER_CONV weakcnf tm
| Comb(Comb(Const("/\\",_),_),_) -> BINOP_CONV weakcnf tm
| Comb(Comb(Const("\\/",_) as op,l),r) ->
let th = MK_COMB(AP_TERM op (weakcnf l),weakcnf r) in
TRANS th (distribute(rand(concl th)))
| _ -> REFL tm
and substrongcnf tm =
match tm with
Comb(Const("!",_),Abs(_,_))
| Comb(Const("?",_),Abs(_,_)) -> BINDER_CONV strongcnf tm
| Comb(Comb(Const("/\\",_),_),_) -> BINOP_CONV substrongcnf tm
| Comb(Comb(Const("\\/",_) as op,l),r) ->
let th = MK_COMB(AP_TERM op (substrongcnf l),substrongcnf r) in
TRANS th (distribute(rand(concl th)))
| _ -> REFL tm
and strongcnf tm =
let th = substrongcnf tm in
TRANS th (strengthen(rand(concl th))) in
weakcnf,strongcnf;;
(* ------------------------------------------------------------------------- *)
(* Simply right-associate w.r.t. a binary operator. *)
(* ------------------------------------------------------------------------- *)
let ASSOC_CONV th =
let th' = SYM(SPEC_ALL th) in
let opx,yopz = dest_comb(rhs(concl th')) in
let op,x = dest_comb opx in
let y = lhand yopz and z = rand yopz in
let rec distrib tm =
match tm with
Comb(Comb(op',Comb(Comb(op'',p),q)),r) when op' = op & op'' = op ->
let th1 = INST [p,x; q,y; r,z] th' in
let l,r' = dest_comb(rand(concl th1)) in
let th2 = AP_TERM l (distrib r') in
let th3 = distrib(rand(concl th2)) in
TRANS th1 (TRANS th2 th3)
| _ -> REFL tm in
let rec assoc tm =
match tm with
Comb(Comb(op',p) as l,q) when op' = op ->
let th = AP_TERM l (assoc q) in
TRANS th (distrib(rand(concl th)))
| _ -> REFL tm in
assoc;;
(* ------------------------------------------------------------------------- *)
Eliminate select terms from a goal .
(* ------------------------------------------------------------------------- *)
let SELECT_ELIM_TAC =
let SELECT_ELIM_CONV =
let SELECT_ELIM_THM =
let pth = prove
(`(P:A->bool)((@) P) <=> (?) P`,
REWRITE_TAC[EXISTS_THM] THEN BETA_TAC THEN REFL_TAC)
and ptm = `P:A->bool` in
fun tm -> let stm,atm = dest_comb tm in
if is_const stm & fst(dest_const stm) = "@" then
CONV_RULE(LAND_CONV BETA_CONV)
(PINST [type_of(bndvar atm),aty] [atm,ptm] pth)
else failwith "SELECT_ELIM_THM: not a select-term" in
fun tm ->
PURE_REWRITE_CONV (map SELECT_ELIM_THM (find_terms is_select tm)) tm in
let SELECT_ELIM_ICONV =
let SELECT_AX_THM =
let pth = ISPEC `P:A->bool` SELECT_AX
and ptm = `P:A->bool` in
fun tm -> let stm,atm = dest_comb tm in
if is_const stm & fst(dest_const stm) = "@" then
let fvs = frees atm in
let th1 = PINST [type_of(bndvar atm),aty] [atm,ptm] pth in
let th2 = CONV_RULE(BINDER_CONV (BINOP_CONV BETA_CONV)) th1 in
GENL fvs th2
else failwith "SELECT_AX_THM: not a select-term" in
let SELECT_ELIM_ICONV tm =
let t = find_term is_select tm in
let th1 = SELECT_AX_THM t in
let itm = mk_imp(concl th1,tm) in
let th2 = DISCH_ALL (MP (ASSUME itm) th1) in
let fvs = frees t in
let fty = itlist (mk_fun_ty o type_of) fvs (type_of t) in
let fn = genvar fty
and atm = list_mk_abs(fvs,t) in
let rawdef = mk_eq(fn,atm) in
let def = GENL fvs (SYM(RIGHT_BETAS fvs (ASSUME rawdef))) in
let th3 = PURE_REWRITE_CONV[def] (lhand(concl th2)) in
let gtm = mk_forall(fn,rand(concl th3)) in
let th4 = EQ_MP (SYM th3) (SPEC fn (ASSUME gtm)) in
let th5 = IMP_TRANS (DISCH gtm th4) th2 in
MP (INST [atm,fn] (DISCH rawdef th5)) (REFL atm) in
let rec SELECT_ELIMS_ICONV tm =
try let th = SELECT_ELIM_ICONV tm in
let tm' = lhand(concl th) in
IMP_TRANS (SELECT_ELIMS_ICONV tm') th
with Failure _ -> DISCH tm (ASSUME tm) in
SELECT_ELIMS_ICONV in
CONV_TAC SELECT_ELIM_CONV THEN W(MATCH_MP_TAC o SELECT_ELIM_ICONV o snd);;
(* ------------------------------------------------------------------------- *)
(* Eliminate all lambda-terms except those part of quantifiers. *)
(* ------------------------------------------------------------------------- *)
let LAMBDA_ELIM_CONV =
let HALF_MK_ABS_CONV =
let pth = prove
(`(s = \x. t x) <=> (!x. s x = t x)`,
REWRITE_TAC[FUN_EQ_THM]) in
let rec conv vs tm =
if vs = [] then REFL tm else
(GEN_REWRITE_CONV I [pth] THENC BINDER_CONV(conv (tl vs))) tm in
conv in
let rec find_lambda tm =
if is_abs tm then tm
else if is_var tm or is_const tm then failwith "find_lambda"
else if is_abs tm then tm else
if is_forall tm or is_exists tm or is_uexists tm
then find_lambda (body(rand tm)) else
let l,r = dest_comb tm in
try find_lambda l with Failure _ -> find_lambda r in
let rec ELIM_LAMBDA conv tm =
try conv tm with Failure _ ->
if is_abs tm then ABS_CONV (ELIM_LAMBDA conv) tm
else if is_var tm or is_const tm then REFL tm else
if is_forall tm or is_exists tm or is_uexists tm
then BINDER_CONV (ELIM_LAMBDA conv) tm
else COMB_CONV (ELIM_LAMBDA conv) tm in
let APPLY_PTH =
let pth = prove
(`(!a. (a = c) ==> (P = Q a)) ==> (P <=> !a. (a = c) ==> Q a)`,
SIMP_TAC[LEFT_FORALL_IMP_THM; EXISTS_REFL]) in
MATCH_MP pth in
let LAMB1_CONV tm =
let atm = find_lambda tm in
let v,bod = dest_abs atm in
let vs = frees atm in
let vs' = vs @ [v] in
let aatm = list_mk_abs(vs,atm) in
let f = genvar(type_of aatm) in
let eq = mk_eq(f,aatm) in
let th1 = SYM(RIGHT_BETAS vs (ASSUME eq)) in
let th2 = ELIM_LAMBDA(GEN_REWRITE_CONV I [th1]) tm in
let th3 = APPLY_PTH (GEN f (DISCH_ALL th2)) in
CONV_RULE(RAND_CONV(BINDER_CONV(LAND_CONV (HALF_MK_ABS_CONV vs')))) th3 in
let rec conv tm =
try (LAMB1_CONV THENC conv) tm with Failure _ -> REFL tm in
conv;;
(* ------------------------------------------------------------------------- *)
Eliminate conditionals ; CONDS_ELIM_CONV aims for disjunctive splitting ,
for refutation procedures , and CONDS_CELIM_CONV for conjunctive .
(* Both switch modes "sensibly" when going through a quantifier. *)
(* ------------------------------------------------------------------------- *)
let CONDS_ELIM_CONV,CONDS_CELIM_CONV =
let th_cond = prove
(`((b <=> F) ==> x = x0) /\ ((b <=> T) ==> x = x1)
==> x = (b /\ x1 \/ ~b /\ x0)`,
BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[])
and th_cond' = prove
(`((b <=> F) ==> x = x0) /\ ((b <=> T) ==> x = x1)
==> x = ((~b \/ x1) /\ (b \/ x0))`,
BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[])
and propsimps = basic_net()
and false_tm = `F` and true_tm = `T` in
let match_th = MATCH_MP th_cond and match_th' = MATCH_MP th_cond'
and propsimp_conv = DEPTH_CONV(REWRITES_CONV propsimps)
and proptsimp_conv =
let cnv = TRY_CONV(REWRITES_CONV propsimps) in
BINOP_CONV cnv THENC cnv in
let rec find_conditional fvs tm =
match tm with
Comb(s,t) ->
if is_cond tm & intersect (frees(lhand s)) fvs = [] then tm
else (try (find_conditional fvs s)
with Failure _ -> find_conditional fvs t)
| Abs(x,t) -> find_conditional (x::fvs) t
| _ -> failwith "find_conditional" in
let rec CONDS_ELIM_CONV dfl tm =
try let t = find_conditional [] tm in
let p = lhand(rator t) in
let th_new =
if p = false_tm or p = true_tm then propsimp_conv tm else
let asm_0 = mk_eq(p,false_tm) and asm_1 = mk_eq(p,true_tm) in
let simp_0 = net_of_thm false (ASSUME asm_0) propsimps
and simp_1 = net_of_thm false (ASSUME asm_1) propsimps in
let th_0 = DISCH asm_0 (DEPTH_CONV(REWRITES_CONV simp_0) tm)
and th_1 = DISCH asm_1 (DEPTH_CONV(REWRITES_CONV simp_1) tm) in
let th_2 = CONJ th_0 th_1 in
let th_3 = if dfl then match_th th_2 else match_th' th_2 in
TRANS th_3 (proptsimp_conv(rand(concl th_3))) in
CONV_RULE (RAND_CONV (CONDS_ELIM_CONV dfl)) th_new
with Failure _ ->
if is_neg tm then
RAND_CONV (CONDS_ELIM_CONV (not dfl)) tm
else if is_conj tm or is_disj tm then
BINOP_CONV (CONDS_ELIM_CONV dfl) tm
else if is_imp tm or is_iff tm then
COMB2_CONV (RAND_CONV (CONDS_ELIM_CONV (not dfl)))
(CONDS_ELIM_CONV dfl) tm
else if is_forall tm then
BINDER_CONV (CONDS_ELIM_CONV false) tm
else if is_exists tm or is_uexists tm then
BINDER_CONV (CONDS_ELIM_CONV true) tm
else REFL tm in
CONDS_ELIM_CONV true,CONDS_ELIM_CONV false;;
(* ------------------------------------------------------------------------- *)
Fix up all head arities to be consistent , in " first order logic " style .
Applied to the assumptions ( not conclusion ) in a goal .
(* ------------------------------------------------------------------------- *)
let ASM_FOL_TAC =
let rec get_heads lconsts tm (cheads,vheads as sofar) =
try let v,bod = dest_forall tm in
get_heads (subtract lconsts [v]) bod sofar
with Failure _ -> try
let l,r = try dest_conj tm with Failure _ -> dest_disj tm in
get_heads lconsts l (get_heads lconsts r sofar)
with Failure _ -> try
let tm' = dest_neg tm in
get_heads lconsts tm' sofar
with Failure _ ->
let hop,args = strip_comb tm in
let len = length args in
let newheads =
if is_const hop or mem hop lconsts
then (insert (hop,len) cheads,vheads)
else if len > 0 then (cheads,insert (hop,len) vheads) else sofar in
itlist (get_heads lconsts) args newheads in
let get_thm_heads th sofar =
get_heads (freesl(hyp th)) (concl th) sofar in
let APP_CONV =
let th = prove
(`!(f:A->B) x. f x = I f x`,
REWRITE_TAC[I_THM]) in
REWR_CONV th in
let rec APP_N_CONV n tm =
if n = 1 then APP_CONV tm
else (RATOR_CONV (APP_N_CONV (n - 1)) THENC APP_CONV) tm in
let rec FOL_CONV hddata tm =
if is_forall tm then BINDER_CONV (FOL_CONV hddata) tm
else if is_conj tm or is_disj tm then BINOP_CONV (FOL_CONV hddata) tm else
let op,args = strip_comb tm in
let th = rev_itlist (C (curry MK_COMB))
(map (FOL_CONV hddata) args) (REFL op) in
let tm' = rand(concl th) in
let n = try length args - assoc op hddata with Failure _ -> 0 in
if n = 0 then th
else TRANS th (APP_N_CONV n tm') in
let GEN_FOL_CONV (cheads,vheads) =
let hddata =
if vheads = [] then
let hops = setify (map fst cheads) in
let getmin h =
let ns = mapfilter
(fun (k,n) -> if k = h then n else fail()) cheads in
if length ns < 2 then fail() else h,end_itlist min ns in
mapfilter getmin hops
else
map (fun t -> if is_const t & fst(dest_const t) = "="
then t,2 else t,0)
(setify (map fst (vheads @ cheads))) in
FOL_CONV hddata in
fun (asl,w as gl) ->
let headsp = itlist (get_thm_heads o snd) asl ([],[]) in
RULE_ASSUM_TAC(CONV_RULE(GEN_FOL_CONV headsp)) gl;;
(* ------------------------------------------------------------------------- *)
Depth conversion to apply at " atomic " formulas in " first - order " term .
(* ------------------------------------------------------------------------- *)
let rec PROP_ATOM_CONV conv tm =
match tm with
Comb((Const("!",_) | Const("?",_) | Const("?!",_)),Abs(_,_))
-> BINDER_CONV (PROP_ATOM_CONV conv) tm
| Comb(Comb
((Const("/\\",_) | Const("\\/",_) | Const("==>",_) |
(Const("=",Tyapp("fun",[Tyapp("bool",[]);_])))),_),_)
-> BINOP_CONV (PROP_ATOM_CONV conv) tm
| Comb(Const("~",_),_) -> RAND_CONV (PROP_ATOM_CONV conv) tm
| _ -> TRY_CONV conv tm;;
print_endline "canon.ml loaded"
| null | https://raw.githubusercontent.com/flyspeck/flyspeck/05bd66666b4b641f49e5131a37830f4881f39db9/azure/hol-light-nat/canon.ml | ocaml | =========================================================================
Reasonably efficient conversions for various canonical forms.
=========================================================================
-------------------------------------------------------------------------
Pre-simplification.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
than AC xxx_ACI on large problems, as well as being more controlled.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Order canonically, right-associate and remove duplicates.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
to atomic formulas.
"Iff"s are split conjunctively or disjunctively according to the flag
argument (conjuctively = true) until a universal quantifier (modulo
current parity) is passed; after that they are split conjunctively. This
is appropriate when the result is passed to a disjunctive splitter
To avoid some duplicate computation, this function will in general
for "p" and "~p", so the user needs to supply an atomic "conversion"
that does the same.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Some common special cases.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Weak and normal DNF conversion. The "weak" form gives a disjunction of
conjunctions, but has no particular associativity at either level and
may contain duplicates. The regular forms give canonical right-associate
lists without duplicates, but do not remove subsumed disjuncts.
inside quantifiers and transform their body, but don't move them.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Simply right-associate w.r.t. a binary operator.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Eliminate all lambda-terms except those part of quantifiers.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Both switch modes "sensibly" when going through a quantifier.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
------------------------------------------------------------------------- | , University of Cambridge Computer Laboratory
( c ) Copyright , University of Cambridge 1998
( c ) Copyright , 1998 - 2007
open Parser
include Trivia
let PRESIMP_CONV =
GEN_REWRITE_CONV TOP_DEPTH_CONV
[NOT_CLAUSES; AND_CLAUSES; OR_CLAUSES; IMP_CLAUSES; EQ_CLAUSES;
FORALL_SIMP; EXISTS_SIMP; EXISTS_OR_THM; FORALL_AND_THM;
LEFT_EXISTS_AND_THM; RIGHT_EXISTS_AND_THM;
LEFT_FORALL_OR_THM; RIGHT_FORALL_OR_THM];;
ACI rearrangements of conjunctions and disjunctions . This is much faster
let CONJ_ACI_RULE =
let rec mk_fun th fn =
let tm = concl th in
if is_conj tm then
let th1,th2 = CONJ_PAIR th in
mk_fun th1 (mk_fun th2 fn)
else (tm |-> th) fn
and use_fun fn tm =
if is_conj tm then
let l,r = dest_conj tm in CONJ (use_fun fn l) (use_fun fn r)
else apply fn tm in
fun fm ->
let p,p' = dest_eq fm in
if p = p' then REFL p else
let th = use_fun (mk_fun (ASSUME p) undefined) p'
and th' = use_fun (mk_fun (ASSUME p') undefined) p in
IMP_ANTISYM_RULE (DISCH_ALL th) (DISCH_ALL th');;
let DISJ_ACI_RULE =
let pth_left = UNDISCH(TAUT `~(a \/ b) ==> ~a`)
and pth_right = UNDISCH(TAUT `~(a \/ b) ==> ~b`)
and pth = repeat UNDISCH (TAUT `~a ==> ~b ==> ~(a \/ b)`)
and pth_neg = UNDISCH(TAUT `(~a <=> ~b) ==> (a <=> b)`)
and a_tm = `a:bool` and b_tm = `b:bool` in
let NOT_DISJ_PAIR th =
let p,q = dest_disj(rand(concl th)) in
let ilist = [p,a_tm; q,b_tm] in
PROVE_HYP th (INST ilist pth_left),
PROVE_HYP th (INST ilist pth_right)
and NOT_DISJ th1 th2 =
let th3 = INST [rand(concl th1),a_tm; rand(concl th2),b_tm] pth in
PROVE_HYP th1 (PROVE_HYP th2 th3) in
let rec mk_fun th fn =
let tm = rand(concl th) in
if is_disj tm then
let th1,th2 = NOT_DISJ_PAIR th in
mk_fun th1 (mk_fun th2 fn)
else (tm |-> th) fn
and use_fun fn tm =
if is_disj tm then
let l,r = dest_disj tm in NOT_DISJ (use_fun fn l) (use_fun fn r)
else apply fn tm in
fun fm ->
let p,p' = dest_eq fm in
if p = p' then REFL p else
let th = use_fun (mk_fun (ASSUME(mk_neg p)) undefined) p'
and th' = use_fun (mk_fun (ASSUME(mk_neg p')) undefined) p in
let th1 = IMP_ANTISYM_RULE (DISCH_ALL th) (DISCH_ALL th') in
PROVE_HYP th1 (INST [p,a_tm; p',b_tm] pth_neg);;
let CONJ_CANON_CONV tm =
let tm' = list_mk_conj(setify(conjuncts tm)) in
CONJ_ACI_RULE(mk_eq(tm,tm'));;
let DISJ_CANON_CONV tm =
let tm' = list_mk_disj(setify(disjuncts tm)) in
DISJ_ACI_RULE(mk_eq(tm,tm'));;
General NNF conversion . The user supplies some conversion to be applied
followed by a clausal form inner core , such as .
enter a recursion where it simultaneously computes NNF representations
let (GEN_NNF_CONV:bool->conv*(term->thm*thm)->conv) =
let and_tm = `(/\)` and or_tm = `(\/)` and not_tm = `(~)`
and pth_not_not = TAUT `~ ~ p = p`
and pth_not_and = TAUT `~(p /\ q) <=> ~p \/ ~q`
and pth_not_or = TAUT `~(p \/ q) <=> ~p /\ ~q`
and pth_imp = TAUT `p ==> q <=> ~p \/ q`
and pth_not_imp = TAUT `~(p ==> q) <=> p /\ ~q`
and pth_eq = TAUT `(p <=> q) <=> p /\ q \/ ~p /\ ~q`
and pth_not_eq = TAUT `~(p <=> q) <=> p /\ ~q \/ ~p /\ q`
and pth_eq' = TAUT `(p <=> q) <=> (p \/ ~q) /\ (~p \/ q)`
and pth_not_eq' = TAUT `~(p <=> q) <=> (p \/ q) /\ (~p \/ ~q)`
and [pth_not_forall; pth_not_exists; pth_not_exu] =
(CONJUNCTS o prove)
(`(~((!) P) <=> ?x:A. ~(P x)) /\
(~((?) P) <=> !x:A. ~(P x)) /\
(~((?!) P) <=> (!x:A. ~(P x)) \/ ?x y. P x /\ P y /\ ~(y = x))`,
REPEAT CONJ_TAC THEN
GEN_REWRITE_TAC (LAND_CONV o funpow 2 RAND_CONV) [GSYM ETA_AX] THEN
REWRITE_TAC[NOT_EXISTS_THM; NOT_FORALL_THM; EXISTS_UNIQUE_DEF;
DE_MORGAN_THM; NOT_IMP] THEN
REWRITE_TAC[CONJ_ASSOC; EQ_SYM_EQ])
and pth_exu = prove
(`((?!) P) <=> (?x:A. P x) /\ !x y. ~(P x) \/ ~(P y) \/ (y = x)`,
GEN_REWRITE_TAC (LAND_CONV o RAND_CONV) [GSYM ETA_AX] THEN
REWRITE_TAC[EXISTS_UNIQUE_DEF; TAUT `a /\ b ==> c <=> ~a \/ ~b \/ c`] THEN
REWRITE_TAC[EQ_SYM_EQ])
and p_tm = `p:bool` and q_tm = `q:bool` in
let rec NNF_DCONV cf baseconvs tm =
match tm with
Comb(Comb(Const("/\\",_),l),r) ->
let th_lp,th_ln = NNF_DCONV cf baseconvs l
and th_rp,th_rn = NNF_DCONV cf baseconvs r in
MK_COMB(AP_TERM and_tm th_lp,th_rp),
TRANS (INST [l,p_tm; r,q_tm] pth_not_and)
(MK_COMB(AP_TERM or_tm th_ln,th_rn))
| Comb(Comb(Const("\\/",_),l),r) ->
let th_lp,th_ln = NNF_DCONV cf baseconvs l
and th_rp,th_rn = NNF_DCONV cf baseconvs r in
MK_COMB(AP_TERM or_tm th_lp,th_rp),
TRANS (INST [l,p_tm; r,q_tm] pth_not_or)
(MK_COMB(AP_TERM and_tm th_ln,th_rn))
| Comb(Comb(Const("==>",_),l),r) ->
let th_lp,th_ln = NNF_DCONV cf baseconvs l
and th_rp,th_rn = NNF_DCONV cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_imp)
(MK_COMB(AP_TERM or_tm th_ln,th_rp)),
TRANS (INST [l,p_tm; r,q_tm] pth_not_imp)
(MK_COMB(AP_TERM and_tm th_lp,th_rn))
| Comb(Comb(Const("=",Tyapp("fun",Tyapp("bool",_)::_)),l),r) ->
let th_lp,th_ln = NNF_DCONV cf baseconvs l
and th_rp,th_rn = NNF_DCONV cf baseconvs r in
if cf then
TRANS (INST [l,p_tm; r,q_tm] pth_eq')
(MK_COMB(AP_TERM and_tm (MK_COMB(AP_TERM or_tm th_lp,th_rn)),
MK_COMB(AP_TERM or_tm th_ln,th_rp))),
TRANS (INST [l,p_tm; r,q_tm] pth_not_eq')
(MK_COMB(AP_TERM and_tm (MK_COMB(AP_TERM or_tm th_lp,th_rp)),
MK_COMB(AP_TERM or_tm th_ln,th_rn)))
else
TRANS (INST [l,p_tm; r,q_tm] pth_eq)
(MK_COMB(AP_TERM or_tm (MK_COMB(AP_TERM and_tm th_lp,th_rp)),
MK_COMB(AP_TERM and_tm th_ln,th_rn))),
TRANS (INST [l,p_tm; r,q_tm] pth_not_eq)
(MK_COMB(AP_TERM or_tm (MK_COMB(AP_TERM and_tm th_lp,th_rn)),
MK_COMB(AP_TERM and_tm th_ln,th_rp)))
| Comb(Const("!",Tyapp("fun",Tyapp("fun",ty::_)::_)) as q,
(Abs(x,t) as bod)) ->
let th_p,th_n = NNF_DCONV true baseconvs t in
AP_TERM q (ABS x th_p),
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_forall)
and th2 = TRANS (AP_TERM not_tm (BETA(mk_comb(bod,x)))) th_n in
TRANS th1 (MK_EXISTS x th2)
| Comb(Const("?",Tyapp("fun",Tyapp("fun",ty::_)::_)) as q,
(Abs(x,t) as bod)) ->
let th_p,th_n = NNF_DCONV cf baseconvs t in
AP_TERM q (ABS x th_p),
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_exists)
and th2 = TRANS (AP_TERM not_tm (BETA(mk_comb(bod,x)))) th_n in
TRANS th1 (MK_FORALL x th2)
| Comb(Const("?!",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let y = variant (x::frees t) x
and th_p,th_n = NNF_DCONV cf baseconvs t in
let eq = mk_eq(y,x) in
let eth_p,eth_n = baseconvs eq
and bth = BETA (mk_comb(bod,x))
and bth' = BETA_CONV(mk_comb(bod,y)) in
let th_p' = INST [y,x] th_p and th_n' = INST [y,x] th_n in
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_exu)
and th1' = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_exu)
and th2 =
MK_COMB(AP_TERM and_tm
(MK_EXISTS x (TRANS bth th_p)),
MK_FORALL x (MK_FORALL y
(MK_COMB(AP_TERM or_tm (TRANS (AP_TERM not_tm bth) th_n),
MK_COMB(AP_TERM or_tm
(TRANS (AP_TERM not_tm bth') th_n'),
eth_p)))))
and th2' =
MK_COMB(AP_TERM or_tm
(MK_FORALL x (TRANS (AP_TERM not_tm bth) th_n)),
MK_EXISTS x (MK_EXISTS y
(MK_COMB(AP_TERM and_tm (TRANS bth th_p),
MK_COMB(AP_TERM and_tm (TRANS bth' th_p'),
eth_n))))) in
TRANS th1 th2,TRANS th1' th2'
| Comb(Const("~",_),t) ->
let th1,th2 = NNF_DCONV cf baseconvs t in
th2,TRANS (INST [t,p_tm] pth_not_not) th1
| _ -> try baseconvs tm
with Failure _ -> REFL tm,REFL(mk_neg tm) in
let rec NNF_CONV cf (base1,base2 as baseconvs) tm =
match tm with
Comb(Comb(Const("/\\",_),l),r) ->
let th_lp = NNF_CONV cf baseconvs l
and th_rp = NNF_CONV cf baseconvs r in
MK_COMB(AP_TERM and_tm th_lp,th_rp)
| Comb(Comb(Const("\\/",_),l),r) ->
let th_lp = NNF_CONV cf baseconvs l
and th_rp = NNF_CONV cf baseconvs r in
MK_COMB(AP_TERM or_tm th_lp,th_rp)
| Comb(Comb(Const("==>",_),l),r) ->
let th_ln = NNF_CONV' cf baseconvs l
and th_rp = NNF_CONV cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_imp)
(MK_COMB(AP_TERM or_tm th_ln,th_rp))
| Comb(Comb(Const("=",Tyapp("fun",Tyapp("bool",_)::_)),l),r) ->
let th_lp,th_ln = NNF_DCONV cf base2 l
and th_rp,th_rn = NNF_DCONV cf base2 r in
if cf then
TRANS (INST [l,p_tm; r,q_tm] pth_eq')
(MK_COMB(AP_TERM and_tm (MK_COMB(AP_TERM or_tm th_lp,th_rn)),
MK_COMB(AP_TERM or_tm th_ln,th_rp)))
else
TRANS (INST [l,p_tm; r,q_tm] pth_eq)
(MK_COMB(AP_TERM or_tm (MK_COMB(AP_TERM and_tm th_lp,th_rp)),
MK_COMB(AP_TERM and_tm th_ln,th_rn)))
| Comb(Const("!",Tyapp("fun",Tyapp("fun",ty::_)::_)) as q,
(Abs(x,t))) ->
let th_p = NNF_CONV true baseconvs t in
AP_TERM q (ABS x th_p)
| Comb(Const("?",Tyapp("fun",Tyapp("fun",ty::_)::_)) as q,
(Abs(x,t))) ->
let th_p = NNF_CONV cf baseconvs t in
AP_TERM q (ABS x th_p)
| Comb(Const("?!",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let y = variant (x::frees t) x
and th_p,th_n = NNF_DCONV cf base2 t in
let eq = mk_eq(y,x) in
let eth_p,eth_n = base2 eq
and bth = BETA (mk_comb(bod,x))
and bth' = BETA_CONV(mk_comb(bod,y)) in
let th_n' = INST [y,x] th_n in
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_exu)
and th2 =
MK_COMB(AP_TERM and_tm
(MK_EXISTS x (TRANS bth th_p)),
MK_FORALL x (MK_FORALL y
(MK_COMB(AP_TERM or_tm (TRANS (AP_TERM not_tm bth) th_n),
MK_COMB(AP_TERM or_tm
(TRANS (AP_TERM not_tm bth') th_n'),
eth_p))))) in
TRANS th1 th2
| Comb(Const("~",_),t) -> NNF_CONV' cf baseconvs t
| _ -> try base1 tm with Failure _ -> REFL tm
and NNF_CONV' cf (base1,base2 as baseconvs) tm =
match tm with
Comb(Comb(Const("/\\",_),l),r) ->
let th_ln = NNF_CONV' cf baseconvs l
and th_rn = NNF_CONV' cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_not_and)
(MK_COMB(AP_TERM or_tm th_ln,th_rn))
| Comb(Comb(Const("\\/",_),l),r) ->
let th_ln = NNF_CONV' cf baseconvs l
and th_rn = NNF_CONV' cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_not_or)
(MK_COMB(AP_TERM and_tm th_ln,th_rn))
| Comb(Comb(Const("==>",_),l),r) ->
let th_lp = NNF_CONV cf baseconvs l
and th_rn = NNF_CONV' cf baseconvs r in
TRANS (INST [l,p_tm; r,q_tm] pth_not_imp)
(MK_COMB(AP_TERM and_tm th_lp,th_rn))
| Comb(Comb(Const("=",Tyapp("fun",Tyapp("bool",_)::_)),l),r) ->
let th_lp,th_ln = NNF_DCONV cf base2 l
and th_rp,th_rn = NNF_DCONV cf base2 r in
if cf then
TRANS (INST [l,p_tm; r,q_tm] pth_not_eq')
(MK_COMB(AP_TERM and_tm (MK_COMB(AP_TERM or_tm th_lp,th_rp)),
MK_COMB(AP_TERM or_tm th_ln,th_rn)))
else
TRANS (INST [l,p_tm; r,q_tm] pth_not_eq)
(MK_COMB(AP_TERM or_tm (MK_COMB(AP_TERM and_tm th_lp,th_rn)),
MK_COMB(AP_TERM and_tm th_ln,th_rp)))
| Comb(Const("!",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let th_n = NNF_CONV' cf baseconvs t in
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_forall)
and th2 = TRANS (AP_TERM not_tm (BETA(mk_comb(bod,x)))) th_n in
TRANS th1 (MK_EXISTS x th2)
| Comb(Const("?",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let th_n = NNF_CONV' true baseconvs t in
let th1 = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_exists)
and th2 = TRANS (AP_TERM not_tm (BETA(mk_comb(bod,x)))) th_n in
TRANS th1 (MK_FORALL x th2)
| Comb(Const("?!",Tyapp("fun",Tyapp("fun",ty::_)::_)),
(Abs(x,t) as bod)) ->
let y = variant (x::frees t) x
and th_p,th_n = NNF_DCONV cf base2 t in
let eq = mk_eq(y,x) in
let eth_p,eth_n = base2 eq
and bth = BETA (mk_comb(bod,x))
and bth' = BETA_CONV(mk_comb(bod,y)) in
let th_p' = INST [y,x] th_p in
let th1' = INST [bod,mk_var("P",mk_fun_ty ty bool_ty)]
(INST_TYPE [ty,aty] pth_not_exu)
and th2' =
MK_COMB(AP_TERM or_tm
(MK_FORALL x (TRANS (AP_TERM not_tm bth) th_n)),
MK_EXISTS x (MK_EXISTS y
(MK_COMB(AP_TERM and_tm (TRANS bth th_p),
MK_COMB(AP_TERM and_tm (TRANS bth' th_p'),
eth_n))))) in
TRANS th1' th2'
| Comb(Const("~",_),t) ->
let th1 = NNF_CONV cf baseconvs t in
TRANS (INST [t,p_tm] pth_not_not) th1
| _ -> let tm' = mk_neg tm in try base1 tm' with Failure _ -> REFL tm' in
NNF_CONV;;
let NNF_CONV =
(GEN_NNF_CONV false (ALL_CONV,fun t -> REFL t,REFL(mk_neg t)) :conv);;
let NNFC_CONV =
(GEN_NNF_CONV true (ALL_CONV,fun t -> REFL t,REFL(mk_neg t)) :conv);;
Skolemize a term already in NNF ( does n't matter if it 's not prenex ) .
let SKOLEM_CONV =
GEN_REWRITE_CONV TOP_DEPTH_CONV
[EXISTS_OR_THM; LEFT_EXISTS_AND_THM; RIGHT_EXISTS_AND_THM;
FORALL_AND_THM; LEFT_FORALL_OR_THM; RIGHT_FORALL_OR_THM;
FORALL_SIMP; EXISTS_SIMP] THENC
GEN_REWRITE_CONV REDEPTH_CONV
[RIGHT_AND_EXISTS_THM;
LEFT_AND_EXISTS_THM;
OR_EXISTS_THM;
RIGHT_OR_EXISTS_THM;
LEFT_OR_EXISTS_THM;
SKOLEM_THM];;
Put a term already in NNF into prenex form .
let PRENEX_CONV =
GEN_REWRITE_CONV REDEPTH_CONV
[AND_FORALL_THM; LEFT_AND_FORALL_THM; RIGHT_AND_FORALL_THM;
LEFT_OR_FORALL_THM; RIGHT_OR_FORALL_THM;
OR_EXISTS_THM; LEFT_OR_EXISTS_THM; RIGHT_OR_EXISTS_THM;
LEFT_AND_EXISTS_THM; RIGHT_AND_EXISTS_THM];;
In both cases the input term is supposed to be in NNF already . We do go
let WEAK_DNF_CONV,DNF_CONV =
let pth1 = TAUT `a /\ (b \/ c) <=> a /\ b \/ a /\ c`
and pth2 = TAUT `(a \/ b) /\ c <=> a /\ c \/ b /\ c`
and a_tm = `a:bool` and b_tm = `b:bool` and c_tm = `c:bool` in
let rec distribute tm =
match tm with
Comb(Comb(Const("/\\",_),a),Comb(Comb(Const("\\/",_),b),c)) ->
let th = INST [a,a_tm; b,b_tm; c,c_tm] pth1 in
TRANS th (BINOP_CONV distribute (rand(concl th)))
| Comb(Comb(Const("/\\",_),Comb(Comb(Const("\\/",_),a),b)),c) ->
let th = INST [a,a_tm; b,b_tm; c,c_tm] pth2 in
TRANS th (BINOP_CONV distribute (rand(concl th)))
| _ -> REFL tm in
let strengthen =
DEPTH_BINOP_CONV `(\/)` CONJ_CANON_CONV THENC DISJ_CANON_CONV in
let rec weakdnf tm =
match tm with
Comb(Const("!",_),Abs(_,_))
| Comb(Const("?",_),Abs(_,_)) -> BINDER_CONV weakdnf tm
| Comb(Comb(Const("\\/",_),_),_) -> BINOP_CONV weakdnf tm
| Comb(Comb(Const("/\\",_) as op,l),r) ->
let th = MK_COMB(AP_TERM op (weakdnf l),weakdnf r) in
TRANS th (distribute(rand(concl th)))
| _ -> REFL tm
and substrongdnf tm =
match tm with
Comb(Const("!",_),Abs(_,_))
| Comb(Const("?",_),Abs(_,_)) -> BINDER_CONV strongdnf tm
| Comb(Comb(Const("\\/",_),_),_) -> BINOP_CONV substrongdnf tm
| Comb(Comb(Const("/\\",_) as op,l),r) ->
let th = MK_COMB(AP_TERM op (substrongdnf l),substrongdnf r) in
TRANS th (distribute(rand(concl th)))
| _ -> REFL tm
and strongdnf tm =
let th = substrongdnf tm in
TRANS th (strengthen(rand(concl th))) in
weakdnf,strongdnf;;
Likewise for CNF .
let WEAK_CNF_CONV,CNF_CONV =
let pth1 = TAUT `a \/ (b /\ c) <=> (a \/ b) /\ (a \/ c)`
and pth2 = TAUT `(a /\ b) \/ c <=> (a \/ c) /\ (b \/ c)`
and a_tm = `a:bool` and b_tm = `b:bool` and c_tm = `c:bool` in
let rec distribute tm =
match tm with
Comb(Comb(Const("\\/",_),a),Comb(Comb(Const("/\\",_),b),c)) ->
let th = INST [a,a_tm; b,b_tm; c,c_tm] pth1 in
TRANS th (BINOP_CONV distribute (rand(concl th)))
| Comb(Comb(Const("\\/",_),Comb(Comb(Const("/\\",_),a),b)),c) ->
let th = INST [a,a_tm; b,b_tm; c,c_tm] pth2 in
TRANS th (BINOP_CONV distribute (rand(concl th)))
| _ -> REFL tm in
let strengthen =
DEPTH_BINOP_CONV `(/\)` DISJ_CANON_CONV THENC CONJ_CANON_CONV in
let rec weakcnf tm =
match tm with
Comb(Const("!",_),Abs(_,_))
| Comb(Const("?",_),Abs(_,_)) -> BINDER_CONV weakcnf tm
| Comb(Comb(Const("/\\",_),_),_) -> BINOP_CONV weakcnf tm
| Comb(Comb(Const("\\/",_) as op,l),r) ->
let th = MK_COMB(AP_TERM op (weakcnf l),weakcnf r) in
TRANS th (distribute(rand(concl th)))
| _ -> REFL tm
and substrongcnf tm =
match tm with
Comb(Const("!",_),Abs(_,_))
| Comb(Const("?",_),Abs(_,_)) -> BINDER_CONV strongcnf tm
| Comb(Comb(Const("/\\",_),_),_) -> BINOP_CONV substrongcnf tm
| Comb(Comb(Const("\\/",_) as op,l),r) ->
let th = MK_COMB(AP_TERM op (substrongcnf l),substrongcnf r) in
TRANS th (distribute(rand(concl th)))
| _ -> REFL tm
and strongcnf tm =
let th = substrongcnf tm in
TRANS th (strengthen(rand(concl th))) in
weakcnf,strongcnf;;
let ASSOC_CONV th =
let th' = SYM(SPEC_ALL th) in
let opx,yopz = dest_comb(rhs(concl th')) in
let op,x = dest_comb opx in
let y = lhand yopz and z = rand yopz in
let rec distrib tm =
match tm with
Comb(Comb(op',Comb(Comb(op'',p),q)),r) when op' = op & op'' = op ->
let th1 = INST [p,x; q,y; r,z] th' in
let l,r' = dest_comb(rand(concl th1)) in
let th2 = AP_TERM l (distrib r') in
let th3 = distrib(rand(concl th2)) in
TRANS th1 (TRANS th2 th3)
| _ -> REFL tm in
let rec assoc tm =
match tm with
Comb(Comb(op',p) as l,q) when op' = op ->
let th = AP_TERM l (assoc q) in
TRANS th (distrib(rand(concl th)))
| _ -> REFL tm in
assoc;;
Eliminate select terms from a goal .
let SELECT_ELIM_TAC =
let SELECT_ELIM_CONV =
let SELECT_ELIM_THM =
let pth = prove
(`(P:A->bool)((@) P) <=> (?) P`,
REWRITE_TAC[EXISTS_THM] THEN BETA_TAC THEN REFL_TAC)
and ptm = `P:A->bool` in
fun tm -> let stm,atm = dest_comb tm in
if is_const stm & fst(dest_const stm) = "@" then
CONV_RULE(LAND_CONV BETA_CONV)
(PINST [type_of(bndvar atm),aty] [atm,ptm] pth)
else failwith "SELECT_ELIM_THM: not a select-term" in
fun tm ->
PURE_REWRITE_CONV (map SELECT_ELIM_THM (find_terms is_select tm)) tm in
let SELECT_ELIM_ICONV =
let SELECT_AX_THM =
let pth = ISPEC `P:A->bool` SELECT_AX
and ptm = `P:A->bool` in
fun tm -> let stm,atm = dest_comb tm in
if is_const stm & fst(dest_const stm) = "@" then
let fvs = frees atm in
let th1 = PINST [type_of(bndvar atm),aty] [atm,ptm] pth in
let th2 = CONV_RULE(BINDER_CONV (BINOP_CONV BETA_CONV)) th1 in
GENL fvs th2
else failwith "SELECT_AX_THM: not a select-term" in
let SELECT_ELIM_ICONV tm =
let t = find_term is_select tm in
let th1 = SELECT_AX_THM t in
let itm = mk_imp(concl th1,tm) in
let th2 = DISCH_ALL (MP (ASSUME itm) th1) in
let fvs = frees t in
let fty = itlist (mk_fun_ty o type_of) fvs (type_of t) in
let fn = genvar fty
and atm = list_mk_abs(fvs,t) in
let rawdef = mk_eq(fn,atm) in
let def = GENL fvs (SYM(RIGHT_BETAS fvs (ASSUME rawdef))) in
let th3 = PURE_REWRITE_CONV[def] (lhand(concl th2)) in
let gtm = mk_forall(fn,rand(concl th3)) in
let th4 = EQ_MP (SYM th3) (SPEC fn (ASSUME gtm)) in
let th5 = IMP_TRANS (DISCH gtm th4) th2 in
MP (INST [atm,fn] (DISCH rawdef th5)) (REFL atm) in
let rec SELECT_ELIMS_ICONV tm =
try let th = SELECT_ELIM_ICONV tm in
let tm' = lhand(concl th) in
IMP_TRANS (SELECT_ELIMS_ICONV tm') th
with Failure _ -> DISCH tm (ASSUME tm) in
SELECT_ELIMS_ICONV in
CONV_TAC SELECT_ELIM_CONV THEN W(MATCH_MP_TAC o SELECT_ELIM_ICONV o snd);;
let LAMBDA_ELIM_CONV =
let HALF_MK_ABS_CONV =
let pth = prove
(`(s = \x. t x) <=> (!x. s x = t x)`,
REWRITE_TAC[FUN_EQ_THM]) in
let rec conv vs tm =
if vs = [] then REFL tm else
(GEN_REWRITE_CONV I [pth] THENC BINDER_CONV(conv (tl vs))) tm in
conv in
let rec find_lambda tm =
if is_abs tm then tm
else if is_var tm or is_const tm then failwith "find_lambda"
else if is_abs tm then tm else
if is_forall tm or is_exists tm or is_uexists tm
then find_lambda (body(rand tm)) else
let l,r = dest_comb tm in
try find_lambda l with Failure _ -> find_lambda r in
let rec ELIM_LAMBDA conv tm =
try conv tm with Failure _ ->
if is_abs tm then ABS_CONV (ELIM_LAMBDA conv) tm
else if is_var tm or is_const tm then REFL tm else
if is_forall tm or is_exists tm or is_uexists tm
then BINDER_CONV (ELIM_LAMBDA conv) tm
else COMB_CONV (ELIM_LAMBDA conv) tm in
let APPLY_PTH =
let pth = prove
(`(!a. (a = c) ==> (P = Q a)) ==> (P <=> !a. (a = c) ==> Q a)`,
SIMP_TAC[LEFT_FORALL_IMP_THM; EXISTS_REFL]) in
MATCH_MP pth in
let LAMB1_CONV tm =
let atm = find_lambda tm in
let v,bod = dest_abs atm in
let vs = frees atm in
let vs' = vs @ [v] in
let aatm = list_mk_abs(vs,atm) in
let f = genvar(type_of aatm) in
let eq = mk_eq(f,aatm) in
let th1 = SYM(RIGHT_BETAS vs (ASSUME eq)) in
let th2 = ELIM_LAMBDA(GEN_REWRITE_CONV I [th1]) tm in
let th3 = APPLY_PTH (GEN f (DISCH_ALL th2)) in
CONV_RULE(RAND_CONV(BINDER_CONV(LAND_CONV (HALF_MK_ABS_CONV vs')))) th3 in
let rec conv tm =
try (LAMB1_CONV THENC conv) tm with Failure _ -> REFL tm in
conv;;
Eliminate conditionals ; CONDS_ELIM_CONV aims for disjunctive splitting ,
for refutation procedures , and CONDS_CELIM_CONV for conjunctive .
let CONDS_ELIM_CONV,CONDS_CELIM_CONV =
let th_cond = prove
(`((b <=> F) ==> x = x0) /\ ((b <=> T) ==> x = x1)
==> x = (b /\ x1 \/ ~b /\ x0)`,
BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[])
and th_cond' = prove
(`((b <=> F) ==> x = x0) /\ ((b <=> T) ==> x = x1)
==> x = ((~b \/ x1) /\ (b \/ x0))`,
BOOL_CASES_TAC `b:bool` THEN ASM_REWRITE_TAC[])
and propsimps = basic_net()
and false_tm = `F` and true_tm = `T` in
let match_th = MATCH_MP th_cond and match_th' = MATCH_MP th_cond'
and propsimp_conv = DEPTH_CONV(REWRITES_CONV propsimps)
and proptsimp_conv =
let cnv = TRY_CONV(REWRITES_CONV propsimps) in
BINOP_CONV cnv THENC cnv in
let rec find_conditional fvs tm =
match tm with
Comb(s,t) ->
if is_cond tm & intersect (frees(lhand s)) fvs = [] then tm
else (try (find_conditional fvs s)
with Failure _ -> find_conditional fvs t)
| Abs(x,t) -> find_conditional (x::fvs) t
| _ -> failwith "find_conditional" in
let rec CONDS_ELIM_CONV dfl tm =
try let t = find_conditional [] tm in
let p = lhand(rator t) in
let th_new =
if p = false_tm or p = true_tm then propsimp_conv tm else
let asm_0 = mk_eq(p,false_tm) and asm_1 = mk_eq(p,true_tm) in
let simp_0 = net_of_thm false (ASSUME asm_0) propsimps
and simp_1 = net_of_thm false (ASSUME asm_1) propsimps in
let th_0 = DISCH asm_0 (DEPTH_CONV(REWRITES_CONV simp_0) tm)
and th_1 = DISCH asm_1 (DEPTH_CONV(REWRITES_CONV simp_1) tm) in
let th_2 = CONJ th_0 th_1 in
let th_3 = if dfl then match_th th_2 else match_th' th_2 in
TRANS th_3 (proptsimp_conv(rand(concl th_3))) in
CONV_RULE (RAND_CONV (CONDS_ELIM_CONV dfl)) th_new
with Failure _ ->
if is_neg tm then
RAND_CONV (CONDS_ELIM_CONV (not dfl)) tm
else if is_conj tm or is_disj tm then
BINOP_CONV (CONDS_ELIM_CONV dfl) tm
else if is_imp tm or is_iff tm then
COMB2_CONV (RAND_CONV (CONDS_ELIM_CONV (not dfl)))
(CONDS_ELIM_CONV dfl) tm
else if is_forall tm then
BINDER_CONV (CONDS_ELIM_CONV false) tm
else if is_exists tm or is_uexists tm then
BINDER_CONV (CONDS_ELIM_CONV true) tm
else REFL tm in
CONDS_ELIM_CONV true,CONDS_ELIM_CONV false;;
Fix up all head arities to be consistent , in " first order logic " style .
Applied to the assumptions ( not conclusion ) in a goal .
let ASM_FOL_TAC =
let rec get_heads lconsts tm (cheads,vheads as sofar) =
try let v,bod = dest_forall tm in
get_heads (subtract lconsts [v]) bod sofar
with Failure _ -> try
let l,r = try dest_conj tm with Failure _ -> dest_disj tm in
get_heads lconsts l (get_heads lconsts r sofar)
with Failure _ -> try
let tm' = dest_neg tm in
get_heads lconsts tm' sofar
with Failure _ ->
let hop,args = strip_comb tm in
let len = length args in
let newheads =
if is_const hop or mem hop lconsts
then (insert (hop,len) cheads,vheads)
else if len > 0 then (cheads,insert (hop,len) vheads) else sofar in
itlist (get_heads lconsts) args newheads in
let get_thm_heads th sofar =
get_heads (freesl(hyp th)) (concl th) sofar in
let APP_CONV =
let th = prove
(`!(f:A->B) x. f x = I f x`,
REWRITE_TAC[I_THM]) in
REWR_CONV th in
let rec APP_N_CONV n tm =
if n = 1 then APP_CONV tm
else (RATOR_CONV (APP_N_CONV (n - 1)) THENC APP_CONV) tm in
let rec FOL_CONV hddata tm =
if is_forall tm then BINDER_CONV (FOL_CONV hddata) tm
else if is_conj tm or is_disj tm then BINOP_CONV (FOL_CONV hddata) tm else
let op,args = strip_comb tm in
let th = rev_itlist (C (curry MK_COMB))
(map (FOL_CONV hddata) args) (REFL op) in
let tm' = rand(concl th) in
let n = try length args - assoc op hddata with Failure _ -> 0 in
if n = 0 then th
else TRANS th (APP_N_CONV n tm') in
let GEN_FOL_CONV (cheads,vheads) =
let hddata =
if vheads = [] then
let hops = setify (map fst cheads) in
let getmin h =
let ns = mapfilter
(fun (k,n) -> if k = h then n else fail()) cheads in
if length ns < 2 then fail() else h,end_itlist min ns in
mapfilter getmin hops
else
map (fun t -> if is_const t & fst(dest_const t) = "="
then t,2 else t,0)
(setify (map fst (vheads @ cheads))) in
FOL_CONV hddata in
fun (asl,w as gl) ->
let headsp = itlist (get_thm_heads o snd) asl ([],[]) in
RULE_ASSUM_TAC(CONV_RULE(GEN_FOL_CONV headsp)) gl;;
Depth conversion to apply at " atomic " formulas in " first - order " term .
let rec PROP_ATOM_CONV conv tm =
match tm with
Comb((Const("!",_) | Const("?",_) | Const("?!",_)),Abs(_,_))
-> BINDER_CONV (PROP_ATOM_CONV conv) tm
| Comb(Comb
((Const("/\\",_) | Const("\\/",_) | Const("==>",_) |
(Const("=",Tyapp("fun",[Tyapp("bool",[]);_])))),_),_)
-> BINOP_CONV (PROP_ATOM_CONV conv) tm
| Comb(Const("~",_),_) -> RAND_CONV (PROP_ATOM_CONV conv) tm
| _ -> TRY_CONV conv tm;;
print_endline "canon.ml loaded"
|
dcf69fb016c04b923d93244f6741ead47827a05b3b64ed970a1b6ce688c3ec1e | isovector/containers-good-graph | Good.hs | # OPTIONS_GHC -Wall #
module Data.Graph.Good
( Graph
, graphFromEdges
, vertices
, edges
, outdegree
, indegree
, transposeG
, dfs
, dff
, topSort
, reverseTopSort
, components
, scc
, bcc
, reachable
, path
) where
import Control.Applicative (empty)
import Control.Arrow ((***))
import Control.Monad ((<=<))
import Data.Array (Ix, Array)
import qualified Data.Array as A
import qualified Data.Graph as G
import Data.Maybe (mapMaybe, fromMaybe)
data Graph v = Graph
{ g_graph :: G.Graph
, g_from_vert :: G.Vertex -> v
, g_to_vert :: v -> Maybe G.Vertex
}
graphFromEdges :: Ord v => [(v, [v])] -> Graph v
graphFromEdges vs =
let (g, v_func, l) = G.graphFromEdges $ fmap (\(v, es) -> (v, v, es)) vs
in Graph g (\vert -> let (v, _, _) = v_func vert in v) l
vertices :: Graph v -> [v]
vertices g = fromVertices g $ overGraph G.vertices g
edges :: Graph v -> [(v, v)]
edges g = fmap (g_from_vert g *** g_from_vert g) $ overGraph G.edges g
overGraph :: (G.Graph -> r) -> Graph v -> r
overGraph f = f . g_graph
lookupArr :: Ix k => Array k v -> k -> Maybe v
lookupArr arr ix =
let (lo, hi) = A.bounds arr
in case (lo <= ix && ix <= hi) of
True -> Just $ arr A.! ix
False -> Nothing
outdegree :: Graph v -> v -> Maybe Int
outdegree g = lookupArr arr <=< g_to_vert g
where
arr = overGraph G.outdegree g
indegree :: Graph v -> v -> Maybe Int
indegree g = lookupArr arr <=< g_to_vert g
where
arr = overGraph G.indegree g
transposeG :: Graph v -> Graph v
transposeG g = g { g_graph = overGraph G.transposeG g }
fromVertices :: Functor f => Graph v -> f G.Vertex -> f v
fromVertices = fmap . g_from_vert
dfs :: Graph v -> [v] -> G.Forest v
dfs g vs =
let verts = mapMaybe (g_to_vert g) vs
in fmap (fromVertices g) $ overGraph G.dfs g verts
dff :: Graph v -> G.Forest v
dff g = fmap (fromVertices g) $ overGraph G.dff g
topSort :: Graph v -> [v]
topSort g = fromVertices g $ overGraph G.topSort g
reverseTopSort :: Graph v -> [v]
reverseTopSort = reverse . topSort
components :: Graph v -> G.Forest v
components g = fmap (fromVertices g) $ overGraph G.components g
scc :: Graph v -> G.Forest v
scc g = fmap (fromVertices g) $ overGraph G.scc g
bcc :: Graph v -> G.Forest [v]
bcc g = fmap (fmap $ fromVertices g) $ overGraph G.bcc g
reachable :: Graph v -> v -> [v]
reachable g v = case g_to_vert g v of
Nothing -> empty
Just vert -> fromVertices g $ overGraph G.reachable g vert
path :: Graph v -> v -> v -> Bool
path g v1 v2 = fromMaybe False $ do
vert1 <- g_to_vert g v1
vert2 <- g_to_vert g v2
pure $ overGraph G.path g vert1 vert2
| null | https://raw.githubusercontent.com/isovector/containers-good-graph/92281a6e841fc4679edf46cad8b011e0c2c7ff7f/src/Data/Graph/Good.hs | haskell | # OPTIONS_GHC -Wall #
module Data.Graph.Good
( Graph
, graphFromEdges
, vertices
, edges
, outdegree
, indegree
, transposeG
, dfs
, dff
, topSort
, reverseTopSort
, components
, scc
, bcc
, reachable
, path
) where
import Control.Applicative (empty)
import Control.Arrow ((***))
import Control.Monad ((<=<))
import Data.Array (Ix, Array)
import qualified Data.Array as A
import qualified Data.Graph as G
import Data.Maybe (mapMaybe, fromMaybe)
data Graph v = Graph
{ g_graph :: G.Graph
, g_from_vert :: G.Vertex -> v
, g_to_vert :: v -> Maybe G.Vertex
}
graphFromEdges :: Ord v => [(v, [v])] -> Graph v
graphFromEdges vs =
let (g, v_func, l) = G.graphFromEdges $ fmap (\(v, es) -> (v, v, es)) vs
in Graph g (\vert -> let (v, _, _) = v_func vert in v) l
vertices :: Graph v -> [v]
vertices g = fromVertices g $ overGraph G.vertices g
edges :: Graph v -> [(v, v)]
edges g = fmap (g_from_vert g *** g_from_vert g) $ overGraph G.edges g
overGraph :: (G.Graph -> r) -> Graph v -> r
overGraph f = f . g_graph
lookupArr :: Ix k => Array k v -> k -> Maybe v
lookupArr arr ix =
let (lo, hi) = A.bounds arr
in case (lo <= ix && ix <= hi) of
True -> Just $ arr A.! ix
False -> Nothing
outdegree :: Graph v -> v -> Maybe Int
outdegree g = lookupArr arr <=< g_to_vert g
where
arr = overGraph G.outdegree g
indegree :: Graph v -> v -> Maybe Int
indegree g = lookupArr arr <=< g_to_vert g
where
arr = overGraph G.indegree g
transposeG :: Graph v -> Graph v
transposeG g = g { g_graph = overGraph G.transposeG g }
fromVertices :: Functor f => Graph v -> f G.Vertex -> f v
fromVertices = fmap . g_from_vert
dfs :: Graph v -> [v] -> G.Forest v
dfs g vs =
let verts = mapMaybe (g_to_vert g) vs
in fmap (fromVertices g) $ overGraph G.dfs g verts
dff :: Graph v -> G.Forest v
dff g = fmap (fromVertices g) $ overGraph G.dff g
topSort :: Graph v -> [v]
topSort g = fromVertices g $ overGraph G.topSort g
reverseTopSort :: Graph v -> [v]
reverseTopSort = reverse . topSort
components :: Graph v -> G.Forest v
components g = fmap (fromVertices g) $ overGraph G.components g
scc :: Graph v -> G.Forest v
scc g = fmap (fromVertices g) $ overGraph G.scc g
bcc :: Graph v -> G.Forest [v]
bcc g = fmap (fmap $ fromVertices g) $ overGraph G.bcc g
reachable :: Graph v -> v -> [v]
reachable g v = case g_to_vert g v of
Nothing -> empty
Just vert -> fromVertices g $ overGraph G.reachable g vert
path :: Graph v -> v -> v -> Bool
path g v1 v2 = fromMaybe False $ do
vert1 <- g_to_vert g v1
vert2 <- g_to_vert g v2
pure $ overGraph G.path g vert1 vert2
| |
ca48833ec20d2032b293644b0c1c6f070fbe8fc3a226096e8913bed5c2758c02 | simmsb/calamity | MiscRoutes.hs | -- | Miscellaneous routes
module Calamity.HTTP.MiscRoutes where
import Calamity.HTTP.Internal.Request
import Calamity.HTTP.Internal.Route
import Calamity.HTTP.Internal.Types
import Data.Function ((&))
data MiscRequest a where
GetGateway :: MiscRequest GatewayResponse
GetGatewayBot :: MiscRequest BotGatewayResponse
instance Request (MiscRequest a) where
type Result (MiscRequest a) = a
route GetGateway =
mkRouteBuilder // S "gateway"
& buildRoute
route GetGatewayBot =
mkRouteBuilder // S "gateway" // S "bot"
& buildRoute
action GetGateway = getWith
action GetGatewayBot = getWith
| null | https://raw.githubusercontent.com/simmsb/calamity/1cdcace44eab62c03350c055e2db045d8a902c2e/calamity/Calamity/HTTP/MiscRoutes.hs | haskell | | Miscellaneous routes | module Calamity.HTTP.MiscRoutes where
import Calamity.HTTP.Internal.Request
import Calamity.HTTP.Internal.Route
import Calamity.HTTP.Internal.Types
import Data.Function ((&))
data MiscRequest a where
GetGateway :: MiscRequest GatewayResponse
GetGatewayBot :: MiscRequest BotGatewayResponse
instance Request (MiscRequest a) where
type Result (MiscRequest a) = a
route GetGateway =
mkRouteBuilder // S "gateway"
& buildRoute
route GetGatewayBot =
mkRouteBuilder // S "gateway" // S "bot"
& buildRoute
action GetGateway = getWith
action GetGatewayBot = getWith
|
f72a569442f1229ce4161120c2b8934722c2375977b89cfd57594bcf24917f11 | cyga/real-world-haskell | BloomFilter.hs | file : ch26 / BloomFilter.hs
module BloomFilter
(
Bloom
, length
, elem
, notElem
, fromList
) where
import BloomFilter.Internal
import BloomFilter.Mutable (insert, new)
import Data.Array.ST (runSTUArray)
import Data.Array.IArray ((!), bounds)
import Data.Word (Word32)
import Prelude hiding (elem, length, notElem)
length :: Bloom a -> Int
length = fromIntegral . len
len :: Bloom a -> Word32
len = succ . snd . bounds . blmArray
elem :: a -> Bloom a -> Bool
elt `elem` filt = all test (blmHash filt elt)
where test hash = blmArray filt ! (hash `mod` len filt)
notElem :: a -> Bloom a -> Bool
elt `notElem` filt = not (elt `elem` filt)
file : ch26 / BloomFilter.hs
fromList :: (a -> [Word32]) -- family of hash functions to use
-> Word32 -- number of bits in filter
-> [a] -- values to populate with
-> Bloom a
fromList hash numBits values =
B hash . runSTUArray $
do mb <- new hash numBits
mapM_ (insert mb) values
return (mutArray mb)
| null | https://raw.githubusercontent.com/cyga/real-world-haskell/4ed581af5b96c6ef03f20d763b8de26be69d43d9/ch26/BloomFilter.hs | haskell | family of hash functions to use
number of bits in filter
values to populate with | file : ch26 / BloomFilter.hs
module BloomFilter
(
Bloom
, length
, elem
, notElem
, fromList
) where
import BloomFilter.Internal
import BloomFilter.Mutable (insert, new)
import Data.Array.ST (runSTUArray)
import Data.Array.IArray ((!), bounds)
import Data.Word (Word32)
import Prelude hiding (elem, length, notElem)
length :: Bloom a -> Int
length = fromIntegral . len
len :: Bloom a -> Word32
len = succ . snd . bounds . blmArray
elem :: a -> Bloom a -> Bool
elt `elem` filt = all test (blmHash filt elt)
where test hash = blmArray filt ! (hash `mod` len filt)
notElem :: a -> Bloom a -> Bool
elt `notElem` filt = not (elt `elem` filt)
file : ch26 / BloomFilter.hs
-> Bloom a
fromList hash numBits values =
B hash . runSTUArray $
do mb <- new hash numBits
mapM_ (insert mb) values
return (mutArray mb)
|
179ab665c62d68a3675b8170613785abc6f2dbb015c9f199d9c1e86303fd3837 | wiseman/orbital-detector | project.clj | (defproject com.lemondronor/orbital-detector "0.1.0-SNAPSHOT"
:description "Detect orbiting rotorcraft."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[clj-time "0.12.2"]
[com.lemondronor.leaflet-gorilla "0.1.3"]
[com.lemonodor/gflags "0.7.3"]
[enlive "1.1.6"]
[factual/geo "1.0.0"]
[org.clojure/clojure "1.8.0"]
[org.clojure/data.csv "0.1.3"]
[org.clojure/data.json "0.2.6"]
[org.clojure/data.xml "0.0.8"]
[org.clojure/java.jdbc "0.6.1"]
[org.clojure/tools.logging "0.3.1"]
[org.postgis/postgis-jdbc "1.3.3" :exclusions [postgresql/postgresql]]
[org.xerial/sqlite-jdbc "3.8.11.2"]
[com.lemondronor/modesbeast "0.0.2"]
[org.clojure/core.async "0.2.374"]
[postgresql "9.3-1102.jdbc41"]]
:plugins [[lein-gorilla "0.3.5-SNAPSHOT" :exclusions [cider/cider-nrepl]]]
:main ^:skip-aot com.lemondronor.orbital-detector
:target-path "target/%s"
:profiles {:uberjar {:aot :all}}
:jvm-opts ["-server" "-Xmx1G"])
| null | https://raw.githubusercontent.com/wiseman/orbital-detector/21a029f979caa24c5d1ceeeedd67b8c2ea26d6e1/project.clj | clojure | (defproject com.lemondronor/orbital-detector "0.1.0-SNAPSHOT"
:description "Detect orbiting rotorcraft."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[clj-time "0.12.2"]
[com.lemondronor.leaflet-gorilla "0.1.3"]
[com.lemonodor/gflags "0.7.3"]
[enlive "1.1.6"]
[factual/geo "1.0.0"]
[org.clojure/clojure "1.8.0"]
[org.clojure/data.csv "0.1.3"]
[org.clojure/data.json "0.2.6"]
[org.clojure/data.xml "0.0.8"]
[org.clojure/java.jdbc "0.6.1"]
[org.clojure/tools.logging "0.3.1"]
[org.postgis/postgis-jdbc "1.3.3" :exclusions [postgresql/postgresql]]
[org.xerial/sqlite-jdbc "3.8.11.2"]
[com.lemondronor/modesbeast "0.0.2"]
[org.clojure/core.async "0.2.374"]
[postgresql "9.3-1102.jdbc41"]]
:plugins [[lein-gorilla "0.3.5-SNAPSHOT" :exclusions [cider/cider-nrepl]]]
:main ^:skip-aot com.lemondronor.orbital-detector
:target-path "target/%s"
:profiles {:uberjar {:aot :all}}
:jvm-opts ["-server" "-Xmx1G"])
| |
d4463ed39a8150effd86cf47c94c433b21114b51332a4ffdd06c479d61aceda8 | xray-tech/xorc-xray | pipeline.clj | (ns re.pipeline
"It specifies a control flow, where execution is running by propagating ctx
forth and back via pipeline. A pipeline consists of stages, each stage is a
map with keys :enter and/or :leave. ctx is a map with arbitrary keys.
:enter is a function of ctx which returns zero or more ctx for further stages.
If :enter returns zero ctx it means terminations of pipeline and we are
starting to rewind it
:leave is a function of ctxs where ctxs are all ctx generated by further
stages of the pipeline
Stages are free to assoc/dissoc ctx as well as doing side effects"
(:require [integrant.core :as ig]))
(comment
;; TODO tracing keys & spans
(tracing/set-tag :re/state (str state))
(tracing/set-tag :re/program (str (:id program))))
(defn terminate [ctx]
(assoc ctx ::queue nil))
(defn enter-all [{:keys [::queue] :as ctx}]
(if (empty? queue)
[ctx]
(let [{:keys [enter leave]} (peek queue)
ctx' (assoc ctx ::queue (pop queue))
res (if enter
(let [res (enter ctx')]
(if (empty? res)
[(terminate ctx)]
(mapcat enter-all res)))
(enter-all ctx'))]
(if leave
(leave res)
res))))
(defn enqueue
"Dynamically adds stages to the end of pipeline of ctx"
[ctx stages]
(update ctx ::queue into stages))
(defn execute
"Runs ctx through stages"
[ctx stages]
(let [queue (into clojure.lang.PersistentQueue/EMPTY stages)]
(map #(dissoc % ::queue) (enter-all (assoc ctx ::queue queue)))))
| null | https://raw.githubusercontent.com/xray-tech/xorc-xray/ee1c841067207c5952473dc8fb1f0b7d237976cb/src/re/pipeline.clj | clojure | TODO tracing keys & spans | (ns re.pipeline
"It specifies a control flow, where execution is running by propagating ctx
forth and back via pipeline. A pipeline consists of stages, each stage is a
map with keys :enter and/or :leave. ctx is a map with arbitrary keys.
:enter is a function of ctx which returns zero or more ctx for further stages.
If :enter returns zero ctx it means terminations of pipeline and we are
starting to rewind it
:leave is a function of ctxs where ctxs are all ctx generated by further
stages of the pipeline
Stages are free to assoc/dissoc ctx as well as doing side effects"
(:require [integrant.core :as ig]))
(comment
(tracing/set-tag :re/state (str state))
(tracing/set-tag :re/program (str (:id program))))
(defn terminate [ctx]
(assoc ctx ::queue nil))
(defn enter-all [{:keys [::queue] :as ctx}]
(if (empty? queue)
[ctx]
(let [{:keys [enter leave]} (peek queue)
ctx' (assoc ctx ::queue (pop queue))
res (if enter
(let [res (enter ctx')]
(if (empty? res)
[(terminate ctx)]
(mapcat enter-all res)))
(enter-all ctx'))]
(if leave
(leave res)
res))))
(defn enqueue
"Dynamically adds stages to the end of pipeline of ctx"
[ctx stages]
(update ctx ::queue into stages))
(defn execute
"Runs ctx through stages"
[ctx stages]
(let [queue (into clojure.lang.PersistentQueue/EMPTY stages)]
(map #(dissoc % ::queue) (enter-all (assoc ctx ::queue queue)))))
|
cdcd35e876ee37282de577293b9ad55404ef18ae8d89855b691684a3acd4b2a3 | jb55/elm-export-persistent | BackendKey.hs | -- |
-- Module : Elm.Export.Persist.Ent
Copyright : ( C ) 2016 - 17
License : MIT
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
-- Orphan instances needed for SQL keys
--
-- This is usually required, but optionally exported in case you have your own
-- already
# LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
# LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
module Elm.Export.Persist.BackendKey () where
import GHC.Generics
import Elm
import Database.Persist
import Database.Persist.Sql
deriving instance ElmType (BackendKey SqlBackend)
| null | https://raw.githubusercontent.com/jb55/elm-export-persistent/eabb242caa79f8c779388bb5b66c044838835c4b/src/Elm/Export/Persist/BackendKey.hs | haskell | |
Module : Elm.Export.Persist.Ent
Stability : experimental
Portability : non-portable
Orphan instances needed for SQL keys
This is usually required, but optionally exported in case you have your own
already | Copyright : ( C ) 2016 - 17
License : MIT
Maintainer : < >
# LANGUAGE FlexibleInstances #
# LANGUAGE StandaloneDeriving #
# LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
module Elm.Export.Persist.BackendKey () where
import GHC.Generics
import Elm
import Database.Persist
import Database.Persist.Sql
deriving instance ElmType (BackendKey SqlBackend)
|
4b3bdec4dee8968e2e55b74c4f29b268ad544a4f0c6fcd51c61e014bda395145 | philipcristiano/etsdb | etsdb_numbers.erl | -module(etsdb_numbers).
-export([to_float/1]).
to_float(X) when is_list(X)->
case string:to_float(X) of
{error, no_float} -> erlang:float(erlang:list_to_integer(X));
{Float, _Rest} -> Float
end;
to_float(X) when is_binary(X)->
to_float(erlang:binary_to_list(X)).
| null | https://raw.githubusercontent.com/philipcristiano/etsdb/f1c0d1d8baff8666d55a1f30e77a40652d173826/src/etsdb_numbers.erl | erlang | -module(etsdb_numbers).
-export([to_float/1]).
to_float(X) when is_list(X)->
case string:to_float(X) of
{error, no_float} -> erlang:float(erlang:list_to_integer(X));
{Float, _Rest} -> Float
end;
to_float(X) when is_binary(X)->
to_float(erlang:binary_to_list(X)).
| |
465ccd5eecfca369fb82652d01e7b3241b24a858e19c0c81e6999c3200f8964a | ChicagoBoss/ChicagoBoss | outgoing_mail_controller.erl | -module({{appid}}_outgoing_mail_controller).
-compile(export_all).
%% See -mail-controller.html for what should go in here
test_message(FromAddress, ToAddress, Subject) ->
Headers = [
{"Subject", Subject},
{"To", ToAddress},
{"From", FromAddress}
],
{ok, FromAddress, ToAddress, Headers, [{address, ToAddress}]}.
| null | https://raw.githubusercontent.com/ChicagoBoss/ChicagoBoss/113bac70c2f835c1e99c757170fd38abf09f5da2/skel/src/mail/outgoing_mail_controller.erl | erlang | See -mail-controller.html for what should go in here | -module({{appid}}_outgoing_mail_controller).
-compile(export_all).
test_message(FromAddress, ToAddress, Subject) ->
Headers = [
{"Subject", Subject},
{"To", ToAddress},
{"From", FromAddress}
],
{ok, FromAddress, ToAddress, Headers, [{address, ToAddress}]}.
|
100caca45b1f167cec3e10b31c736fddeb157d23aafa7a865ca718dd3d34445a | haskell-distributed/distributed-process | Explicit.hs | # LANGUAGE ScopedTypeVariables
, MultiParamTypeClasses
, FlexibleInstances
, FunctionalDependencies
, FlexibleContexts
, UndecidableInstances
, , GADTs
, EmptyDataDecls
, DeriveDataTypeable #
, MultiParamTypeClasses
, FlexibleInstances
, FunctionalDependencies
, FlexibleContexts
, UndecidableInstances
, KindSignatures
, GADTs
, EmptyDataDecls
, DeriveDataTypeable #-}
module Control.Distributed.Process.Internal.Closure.Explicit
(
RemoteRegister
, MkTDict(..)
, mkStaticVal
, mkClosureValSingle
, mkClosureVal
, call'
) where
import Control.Distributed.Static
import Control.Distributed.Process.Serializable
import Control.Distributed.Process.Internal.Closure.BuiltIn
( -- Static dictionaries and associated operations
staticDecode
)
import Control.Distributed.Process
import Data.Rank1Dynamic
import Data.Rank1Typeable
import Data.Binary(encode,put,get,Binary)
import qualified Data.ByteString.Lazy as B
| A RemoteRegister is a trasformer on a RemoteTable to register additional static values .
type RemoteRegister = RemoteTable -> RemoteTable
| This takes an explicit name and a value , and produces both a static reference to the name and a RemoteRegister for it .
mkStaticVal :: Serializable a => String -> a -> (Static a, RemoteRegister)
mkStaticVal n v = (staticLabel n_s, registerStatic n_s (toDynamic v))
where n_s = n
class MkTDict a where
mkTDict :: String -> a -> RemoteRegister
instance (Serializable b) => MkTDict (Process b) where
mkTDict _ _ = registerStatic (show (typeOf (undefined :: b)) ++ "__staticDict") (toDynamic (SerializableDict :: SerializableDict b))
instance MkTDict a where
mkTDict _ _ = id
-- | This takes an explicit name, a function of arity one, and creates a creates a function yielding a closure and a remote register for it.
mkClosureValSingle :: forall a b. (Serializable a, Typeable b, MkTDict b) => String -> (a -> b) -> (a -> Closure b, RemoteRegister)
mkClosureValSingle n v = (c, registerStatic n_s (toDynamic v) .
registerStatic n_sdict (toDynamic sdict) .
mkTDict n_tdict (undefined :: b)
) where
n_s = n
n_sdict = n ++ "__sdict"
n_tdict = n ++ "__tdict"
c = closure decoder . encode
decoder = (staticLabel n_s :: Static (a -> b)) `staticCompose` staticDecode (staticLabel n_sdict :: Static (SerializableDict a))
sdict :: (SerializableDict a)
sdict = SerializableDict
-- | This takes an explict name, a function of any arity, and creates a function yielding a closure and a remote register for it.
mkClosureVal :: forall func argTuple result closureFunction.
(Curry (argTuple -> Closure result) closureFunction,
MkTDict result,
Uncurry HTrue argTuple func result,
Typeable result, Serializable argTuple, IsFunction func HTrue) =>
String -> func -> (closureFunction, RemoteRegister)
mkClosureVal n v = (curryFun c, rtable)
where
uv :: argTuple -> result
uv = uncurry' reify v
n_s = n
n_sdict = n ++ "__sdict"
n_tdict = n ++ "__tdict"
c :: argTuple -> Closure result
c = closure decoder . encode
decoder :: Static (B.ByteString -> result)
decoder = (staticLabel n_s :: Static (argTuple -> result)) `staticCompose` staticDecode (staticLabel n_sdict :: Static (SerializableDict argTuple))
rtable = registerStatic n_s (toDynamic uv) .
registerStatic n_sdict (toDynamic sdict) .
mkTDict n_tdict (undefined :: result)
sdict :: (SerializableDict argTuple)
sdict = SerializableDict
-- | Works just like standard call, but with a simpler signature.
call' :: forall a. Serializable a => NodeId -> Closure (Process a) -> Process a
call' = call (staticLabel $ (show $ typeOf $ (undefined :: a)) ++ "__staticDict")
data EndOfTuple deriving Typeable
instance Binary EndOfTuple where
put _ = return ()
get = return undefined
-- This generic curry is straightforward
class Curry a b | a -> b where
curryFun :: a -> b
instance Curry ((a, EndOfTuple) -> b) (a -> b) where
curryFun f = \x -> f (x,undefined)
instance Curry (b -> c) r => Curry ((a,b) -> c) (a -> r) where
curryFun f = \x -> curryFun (\y -> (f (x,y)))
This generic uncurry courtesy
data HTrue
data HFalse
data Fun :: * -> * -> * -> * where
Done :: Fun EndOfTuple r r
Moar :: Fun xs f r -> Fun (x,xs) (x -> f) r
class Uncurry'' args func result | func -> args, func -> result, args result -> func where
reify :: Fun args func result
class Uncurry flag args func result | flag func -> args, flag func -> result, args result -> func where
reify' :: flag -> Fun args func result
instance Uncurry'' rest f r => Uncurry HTrue (a,rest) (a -> f) r where
reify' _ = Moar reify
instance Uncurry HFalse EndOfTuple a a where
reify' _ = Done
instance (IsFunction func b, Uncurry b args func result) => Uncurry'' args func result where
reify = reify' (undefined :: b)
uncurry' :: Fun args func result -> func -> args -> result
uncurry' Done r _ = r
uncurry' (Moar fun) f (x,xs) = uncurry' fun (f x) xs
class IsFunction t b | t -> b
instance (b ~ HTrue) => IsFunction (a -> c) b
instance (b ~ HFalse) => IsFunction a b
| null | https://raw.githubusercontent.com/haskell-distributed/distributed-process/ccc002c928d29335b5eb73be1d876007adaa0b53/src/Control/Distributed/Process/Internal/Closure/Explicit.hs | haskell | Static dictionaries and associated operations
| This takes an explicit name, a function of arity one, and creates a creates a function yielding a closure and a remote register for it.
| This takes an explict name, a function of any arity, and creates a function yielding a closure and a remote register for it.
| Works just like standard call, but with a simpler signature.
This generic curry is straightforward | # LANGUAGE ScopedTypeVariables
, MultiParamTypeClasses
, FlexibleInstances
, FunctionalDependencies
, FlexibleContexts
, UndecidableInstances
, , GADTs
, EmptyDataDecls
, DeriveDataTypeable #
, MultiParamTypeClasses
, FlexibleInstances
, FunctionalDependencies
, FlexibleContexts
, UndecidableInstances
, KindSignatures
, GADTs
, EmptyDataDecls
, DeriveDataTypeable #-}
module Control.Distributed.Process.Internal.Closure.Explicit
(
RemoteRegister
, MkTDict(..)
, mkStaticVal
, mkClosureValSingle
, mkClosureVal
, call'
) where
import Control.Distributed.Static
import Control.Distributed.Process.Serializable
import Control.Distributed.Process.Internal.Closure.BuiltIn
staticDecode
)
import Control.Distributed.Process
import Data.Rank1Dynamic
import Data.Rank1Typeable
import Data.Binary(encode,put,get,Binary)
import qualified Data.ByteString.Lazy as B
| A RemoteRegister is a trasformer on a RemoteTable to register additional static values .
type RemoteRegister = RemoteTable -> RemoteTable
| This takes an explicit name and a value , and produces both a static reference to the name and a RemoteRegister for it .
mkStaticVal :: Serializable a => String -> a -> (Static a, RemoteRegister)
mkStaticVal n v = (staticLabel n_s, registerStatic n_s (toDynamic v))
where n_s = n
class MkTDict a where
mkTDict :: String -> a -> RemoteRegister
instance (Serializable b) => MkTDict (Process b) where
mkTDict _ _ = registerStatic (show (typeOf (undefined :: b)) ++ "__staticDict") (toDynamic (SerializableDict :: SerializableDict b))
instance MkTDict a where
mkTDict _ _ = id
mkClosureValSingle :: forall a b. (Serializable a, Typeable b, MkTDict b) => String -> (a -> b) -> (a -> Closure b, RemoteRegister)
mkClosureValSingle n v = (c, registerStatic n_s (toDynamic v) .
registerStatic n_sdict (toDynamic sdict) .
mkTDict n_tdict (undefined :: b)
) where
n_s = n
n_sdict = n ++ "__sdict"
n_tdict = n ++ "__tdict"
c = closure decoder . encode
decoder = (staticLabel n_s :: Static (a -> b)) `staticCompose` staticDecode (staticLabel n_sdict :: Static (SerializableDict a))
sdict :: (SerializableDict a)
sdict = SerializableDict
mkClosureVal :: forall func argTuple result closureFunction.
(Curry (argTuple -> Closure result) closureFunction,
MkTDict result,
Uncurry HTrue argTuple func result,
Typeable result, Serializable argTuple, IsFunction func HTrue) =>
String -> func -> (closureFunction, RemoteRegister)
mkClosureVal n v = (curryFun c, rtable)
where
uv :: argTuple -> result
uv = uncurry' reify v
n_s = n
n_sdict = n ++ "__sdict"
n_tdict = n ++ "__tdict"
c :: argTuple -> Closure result
c = closure decoder . encode
decoder :: Static (B.ByteString -> result)
decoder = (staticLabel n_s :: Static (argTuple -> result)) `staticCompose` staticDecode (staticLabel n_sdict :: Static (SerializableDict argTuple))
rtable = registerStatic n_s (toDynamic uv) .
registerStatic n_sdict (toDynamic sdict) .
mkTDict n_tdict (undefined :: result)
sdict :: (SerializableDict argTuple)
sdict = SerializableDict
call' :: forall a. Serializable a => NodeId -> Closure (Process a) -> Process a
call' = call (staticLabel $ (show $ typeOf $ (undefined :: a)) ++ "__staticDict")
data EndOfTuple deriving Typeable
instance Binary EndOfTuple where
put _ = return ()
get = return undefined
class Curry a b | a -> b where
curryFun :: a -> b
instance Curry ((a, EndOfTuple) -> b) (a -> b) where
curryFun f = \x -> f (x,undefined)
instance Curry (b -> c) r => Curry ((a,b) -> c) (a -> r) where
curryFun f = \x -> curryFun (\y -> (f (x,y)))
This generic uncurry courtesy
data HTrue
data HFalse
data Fun :: * -> * -> * -> * where
Done :: Fun EndOfTuple r r
Moar :: Fun xs f r -> Fun (x,xs) (x -> f) r
class Uncurry'' args func result | func -> args, func -> result, args result -> func where
reify :: Fun args func result
class Uncurry flag args func result | flag func -> args, flag func -> result, args result -> func where
reify' :: flag -> Fun args func result
instance Uncurry'' rest f r => Uncurry HTrue (a,rest) (a -> f) r where
reify' _ = Moar reify
instance Uncurry HFalse EndOfTuple a a where
reify' _ = Done
instance (IsFunction func b, Uncurry b args func result) => Uncurry'' args func result where
reify = reify' (undefined :: b)
uncurry' :: Fun args func result -> func -> args -> result
uncurry' Done r _ = r
uncurry' (Moar fun) f (x,xs) = uncurry' fun (f x) xs
class IsFunction t b | t -> b
instance (b ~ HTrue) => IsFunction (a -> c) b
instance (b ~ HFalse) => IsFunction a b
|
0cc7ebf8ff10f5103becd1b23130c4dda60e981b354b665f77d2371603930221 | AdaCore/why3 | stackify.mli | (********************************************************************)
(* *)
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
General Public License version 2.1 , with the special exception
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
open Why3
open Cfg_ast
type labeled_block = label * block
type usage = Multi | One
type exp_tree =
| Scope of label * usage * exp_tree * exp_tree
| Loop of (Ptree.ident * Ptree.term) list * exp_tree
| Block of labeled_block
val entry : exp_tree -> labeled_block
val targets : cfg_term -> label list
val stackify : labeled_block list -> label -> exp_tree
| null | https://raw.githubusercontent.com/AdaCore/why3/4441127004d53cf2cb0f722fed4a930ccf040ee4/plugins/cfg/stackify.mli | ocaml | ******************************************************************
This software is distributed under the terms of the GNU Lesser
on linking described in file LICENSE.
****************************************************************** | The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University
General Public License version 2.1 , with the special exception
open Why3
open Cfg_ast
type labeled_block = label * block
type usage = Multi | One
type exp_tree =
| Scope of label * usage * exp_tree * exp_tree
| Loop of (Ptree.ident * Ptree.term) list * exp_tree
| Block of labeled_block
val entry : exp_tree -> labeled_block
val targets : cfg_term -> label list
val stackify : labeled_block list -> label -> exp_tree
|
ff9a69d58b3670d8dcfaa8cd0758993be33e1b4a35db46ddcf69ea8a97f3e0b5 | alex-hhh/ActivityLog2 | cp-test.rkt | #lang racket/base
;; cp-test.rkt -- test the critical power functionality
;;
;; This file is part of ActivityLog2 -- -hhh/ActivityLog2
Copyright ( c ) 2020 , 2022 < >
;;
;; This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option )
;; any later version.
;;
;; This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
;; more details.
;;
You should have received a copy of the GNU General Public License along
;; with this program. If not, see </>.
(require al2-test-runner
rackunit
"../rkt/utilities.rkt"
"../rkt/models/critical-power.rkt"
"../rkt/metrics.rkt")
send calls to stdout , so we can see them !
Use 1 worker thread , so we can determine when tasks finish ( See
;; `do-tc-check`)
(set-worker-thread-count 1)
(define ammax
'((2740 3769 10 422.25)
(2740 3764 15 414.27)
(2740 3758 30 388.3)
(2740 3755 36 375.99)
(2740 3754 43 362.81)
(2740 3755 45 358.62)
(2740 3755 52 350.76)
(2740 3747 60 332.95)
(2740 3746 62 328.02)
(2724 2981 74 296.44)
(2724 2981 75 295.86)
(2724 2977 89 288.99)
(2724 2977 90 288.48)
(2724 2973 107 280.35)
(2724 2968 120 273.84)
(2724 2967 128 268.91)
(2742 1203 154 257.01)
(2735 1864 180 254.64)
(2742 1251 185 253.22)
(2742 1214 222 253.66)
(2742 1218 266 249.6)
(2742 1204 300 249.03)
(2742 1186 319 242.39)
(2742 1805 383 226.19)
(2742 1805 460 225.68)
(2742 1805 552 225.46)
(2742 1805 600 224.96)
(2742 1804 662 224.52)
(2742 1804 794 223.99)
(2742 2102 900 223.83)
(2742 2050 953 223.74)
(2742 1805 1144 223.98)
(2742 1804 1200 224.53)
(2742 1632 1373 209.61)
(2742 1205 1648 206.48)
(2742 1204 1800 208.53)
(2742 1057 1948 203.04)
(2742 755 2248 197.6)
(2742 457 2548 192.87)
(2737 726 2700 192.86)
(2737 638 2848 189.86)
(2737 336 3148 185.19)
(2739 1687 3448 182.14)
(2739 1684 3600 183.24)
(2739 877 3748 183.12)
(2739 980 4048 183.93)
(2739 936 4348 185.45)
(2739 638 4648 179.83)
(2739 337 4948 179.47)
(2739 37 5248 176.1)
(2728 136 5400 174.22)
(2728 133 5548 173.76)
(2728 135 5848 169.73)
(2728 208 6148 168.53)
(2728 151 6448 168.14)
(2728 155 6748 167.67)
(2728 135 7048 167.06)
(2728 55 7200 166.39)
(2728 135 7348 165.75)
(2728 154 7648 165.29)
(2728 151 7948 164.42)
(2728 152 8248 164.34)
(2728 151 8548 163.28)
(2728 56 8848 162.37)
(2728 134 9148 161.48)
(2728 63 9448 160.58)
(2728 151 9748 160.33)
(2728 56 10048 160.13)
(2718 17 10348 157.24)))
neuromuscular range : 15 to 45 seconds
(define-values (nm-start nm-end) (values 15.0 45.0))
anaerobic range : 2 to 5 minutes
(define-values (an-start an-end) (values 120.0 300.0))
aerobic range 12 to 20 minutes
(define-values (ae-start ae-end) (values 720.0 1200.0))
(define mmax-fn (aggregate-mmax->spline-fn ammax))
(define critical-power-test-suite
(test-suite
"Critical Power"
(test-case "CP3 exhaustive search"
(define-values (cp3 cp3-results)
(cp3-fit mmax-fn nm-start nm-end an-start an-end ae-start ae-end))
(cp3-check-results cp3 cp3-results mmax-fn))
(test-case "CP3 exhaustive search with progress"
(define progress '())
(define (progress-cb val)
(set! progress (cons val progress)))
(define-values (cp3 cp3-results)
(cp3-fit mmax-fn nm-start nm-end an-start an-end ae-start ae-end progress-cb))
(cp3-check-results cp3 cp3-results mmax-fn)
(check-true (> (length progress) 0))
(for ([one (in-list progress)]
[two (in-list (cdr progress))])
(check >= one two)))
(test-case "CP2 exhaustive search"
(define-values (cp2 cp2-results)
(cp2-fit mmax-fn an-start an-end ae-start ae-end))
(cp2-check-results cp2 cp2-results mmax-fn))))
(module+ test
(run-tests #:package "cp-test"
#:results-file "test-results/cp-test.xml"
critical-power-test-suite))
| null | https://raw.githubusercontent.com/alex-hhh/ActivityLog2/a021adbd16f015e53da89858c2c3af0357bfdca4/test/cp-test.rkt | racket | cp-test.rkt -- test the critical power functionality
This file is part of ActivityLog2 -- -hhh/ActivityLog2
This program is free software: you can redistribute it and/or modify it
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
with this program. If not, see </>.
`do-tc-check`) | #lang racket/base
Copyright ( c ) 2020 , 2022 < >
under the terms of the GNU General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option )
You should have received a copy of the GNU General Public License along
(require al2-test-runner
rackunit
"../rkt/utilities.rkt"
"../rkt/models/critical-power.rkt"
"../rkt/metrics.rkt")
send calls to stdout , so we can see them !
Use 1 worker thread , so we can determine when tasks finish ( See
(set-worker-thread-count 1)
(define ammax
'((2740 3769 10 422.25)
(2740 3764 15 414.27)
(2740 3758 30 388.3)
(2740 3755 36 375.99)
(2740 3754 43 362.81)
(2740 3755 45 358.62)
(2740 3755 52 350.76)
(2740 3747 60 332.95)
(2740 3746 62 328.02)
(2724 2981 74 296.44)
(2724 2981 75 295.86)
(2724 2977 89 288.99)
(2724 2977 90 288.48)
(2724 2973 107 280.35)
(2724 2968 120 273.84)
(2724 2967 128 268.91)
(2742 1203 154 257.01)
(2735 1864 180 254.64)
(2742 1251 185 253.22)
(2742 1214 222 253.66)
(2742 1218 266 249.6)
(2742 1204 300 249.03)
(2742 1186 319 242.39)
(2742 1805 383 226.19)
(2742 1805 460 225.68)
(2742 1805 552 225.46)
(2742 1805 600 224.96)
(2742 1804 662 224.52)
(2742 1804 794 223.99)
(2742 2102 900 223.83)
(2742 2050 953 223.74)
(2742 1805 1144 223.98)
(2742 1804 1200 224.53)
(2742 1632 1373 209.61)
(2742 1205 1648 206.48)
(2742 1204 1800 208.53)
(2742 1057 1948 203.04)
(2742 755 2248 197.6)
(2742 457 2548 192.87)
(2737 726 2700 192.86)
(2737 638 2848 189.86)
(2737 336 3148 185.19)
(2739 1687 3448 182.14)
(2739 1684 3600 183.24)
(2739 877 3748 183.12)
(2739 980 4048 183.93)
(2739 936 4348 185.45)
(2739 638 4648 179.83)
(2739 337 4948 179.47)
(2739 37 5248 176.1)
(2728 136 5400 174.22)
(2728 133 5548 173.76)
(2728 135 5848 169.73)
(2728 208 6148 168.53)
(2728 151 6448 168.14)
(2728 155 6748 167.67)
(2728 135 7048 167.06)
(2728 55 7200 166.39)
(2728 135 7348 165.75)
(2728 154 7648 165.29)
(2728 151 7948 164.42)
(2728 152 8248 164.34)
(2728 151 8548 163.28)
(2728 56 8848 162.37)
(2728 134 9148 161.48)
(2728 63 9448 160.58)
(2728 151 9748 160.33)
(2728 56 10048 160.13)
(2718 17 10348 157.24)))
neuromuscular range : 15 to 45 seconds
(define-values (nm-start nm-end) (values 15.0 45.0))
anaerobic range : 2 to 5 minutes
(define-values (an-start an-end) (values 120.0 300.0))
aerobic range 12 to 20 minutes
(define-values (ae-start ae-end) (values 720.0 1200.0))
(define mmax-fn (aggregate-mmax->spline-fn ammax))
(define critical-power-test-suite
(test-suite
"Critical Power"
(test-case "CP3 exhaustive search"
(define-values (cp3 cp3-results)
(cp3-fit mmax-fn nm-start nm-end an-start an-end ae-start ae-end))
(cp3-check-results cp3 cp3-results mmax-fn))
(test-case "CP3 exhaustive search with progress"
(define progress '())
(define (progress-cb val)
(set! progress (cons val progress)))
(define-values (cp3 cp3-results)
(cp3-fit mmax-fn nm-start nm-end an-start an-end ae-start ae-end progress-cb))
(cp3-check-results cp3 cp3-results mmax-fn)
(check-true (> (length progress) 0))
(for ([one (in-list progress)]
[two (in-list (cdr progress))])
(check >= one two)))
(test-case "CP2 exhaustive search"
(define-values (cp2 cp2-results)
(cp2-fit mmax-fn an-start an-end ae-start ae-end))
(cp2-check-results cp2 cp2-results mmax-fn))))
(module+ test
(run-tests #:package "cp-test"
#:results-file "test-results/cp-test.xml"
critical-power-test-suite))
|
d7688fa572adeba171fcf1e486ffb0936127acefc3827383dd7cfa41ff1b9c17 | coq/coq | output.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 Common
open Index
(*s Low level output *)
let output_char c = output_char !out_channel c
let output_string s = output_string !out_channel s
let printf s = Printf.fprintf !out_channel s
let sprintf = Printf.sprintf
(*s Coq keywords *)
let build_table l =
let h = Hashtbl.create 101 in
List.iter (fun key ->Hashtbl.add h key ()) l;
function s -> try Hashtbl.find h s; true with Not_found -> false
let is_keyword =
build_table
[ "About"; "Axiom"; "Abort"; "Chapter"; "Check"; "Coercion"; "Compute"; "CoFixpoint";
"CoInductive"; "Corollary"; "Defined"; "Definition"; "End"; "Eval"; "Example";
"Export"; "Fact"; "Fix"; "Fixpoint"; "From"; "Function"; "Generalizable"; "Global"; "Grammar";
"Guarded"; "Goal"; "Hint"; "Debug"; "On";
"Hypothesis"; "Hypotheses";
"Resolve"; "Unfold"; "Immediate"; "Extern"; "Constructors"; "Rewrite";
"Implicit"; "Import"; "Inductive";
"Infix"; "Lemma"; "Let"; "Load"; "Local"; "Locate"; "Ltac";
"Module"; "Module Type"; "Declare Module"; "Include";
"Mutual"; "Parameter"; "Parameters"; "Print"; "Printing"; "All"; "Proof"; "Proof with"; "Qed";
"Record"; "Recursive"; "Remark"; "Require"; "Save"; "Scheme"; "Assumptions"; "Axioms"; "Universes";
"Induction"; "for"; "Sort"; "Section"; "Show"; "Structure"; "Syntactic"; "Syntax"; "Tactic"; "Theorem";
"Search"; "SearchPattern"; "SearchRewrite";
"Set"; "Types"; "Undo"; "Unset"; "Variable"; "Variables"; "Context";
"Notation"; "Reserved Notation"; "Tactic Notation"; "Number Notation"; "String Notation"; "Enable Notation"; "Disable Notation";
"Delimit"; "Bind"; "Open"; "Scope"; "Inline";
"Implicit Arguments"; "Add"; "Strict";
"Typeclasses"; "Instance"; "Global Instance"; "Class"; "Instantiation";
"goal"; "goals"; "vm_compute";
"Opaque"; "Transparent"; "Time";
"Extraction"; "Extract";
"Variant";
Program
"Program Definition"; "Program Example"; "Program Fixpoint"; "Program Lemma";
"Obligation"; "Obligations"; "Solve"; "using"; "Next Obligation"; "Next";
"Program Instance"; "Equations"; "Equations_nocomp";
(*i (* coq terms *) *)
"forall"; "match"; "as"; "in"; "return"; "with"; "end"; "let"; "fun";
"if"; "then"; "else"; "Prop"; "Set"; "Type"; ":="; "where"; "struct"; "wf"; "measure";
"fix"; "cofix"; "is";
(* Ltac *)
"before"; "after"; "constr"; "ltac"; "goal"; "context"; "beta"; "delta"; "iota"; "zeta"; "lazymatch"; "type"; "of"; "rec";
(* Notations *)
"level"; "associativity"; "no"
]
let is_tactic =
build_table
[ "intro"; "intros"; "apply"; "rewrite"; "refine"; "case"; "clear"; "injection";
"elimtype"; "progress"; "setoid_rewrite"; "left"; "right"; "constructor";
"econstructor"; "decide equality"; "abstract"; "exists"; "cbv"; "simple destruct";
"info"; "field"; "specialize"; "evar"; "solve"; "instantiate"; "info_auto"; "info_eauto";
"quote"; "eexact"; "autorewrite";
"destruct"; "destruction"; "destruct_call"; "dependent"; "elim"; "extensionality";
"f_equal"; "generalize"; "generalize_eqs"; "generalize_eqs_vars"; "induction"; "rename"; "move";
"set"; "assert"; "do"; "repeat";
"cut"; "assumption"; "exact"; "split"; "subst"; "try"; "discriminate";
"simpl"; "unfold"; "red"; "compute"; "at"; "in"; "by";
"reflexivity"; "symmetry"; "transitivity";
"replace"; "setoid_replace"; "inversion"; "inversion_clear";
"pattern"; "intuition"; "congruence"; "fail"; "fresh";
"trivial"; "tauto"; "firstorder"; "ring";
"clapply"; "program_simpl"; "program_simplify"; "eapply"; "auto"; "eauto";
"change"; "fold"; "hnf"; "lazy"; "simple"; "eexists"; "debug"; "idtac"; "first"; "type of"; "pose";
"eval"; "instantiate"; "until" ]
(*s Current Coq module *)
let current_module : (string * string option) ref = ref ("",None)
let get_module withsub =
let (m,sub) = !current_module in
if withsub then
match sub with
| None -> m
| Some sub -> m ^ ": " ^ sub
else
m
let set_module m sub = current_module := (m,sub);
page_title := get_module true
s Common to both LaTeX and HTML
let item_level = ref 0
let in_doc = ref false
(*s Customized and predefined pretty-print *)
let initialize_texmacs () =
let ensuremath x = sprintf "<with|mode|math|\\<%s\\>>" x in
List.fold_right (fun (s,t) tt -> Tokens.ttree_add tt s t)
[ "*", ensuremath "times";
"->", ensuremath "rightarrow";
"<-", ensuremath "leftarrow";
"<->", ensuremath "leftrightarrow";
"=>", ensuremath "Rightarrow";
"<=", ensuremath "le";
">=", ensuremath "ge";
"<>", ensuremath "noteq";
"~", ensuremath "lnot";
"/\\", ensuremath "land";
"\\/", ensuremath "lor";
"|-", ensuremath "vdash"
] Tokens.empty_ttree
let token_tree_texmacs = ref (initialize_texmacs ())
let token_tree_latex = ref Tokens.empty_ttree
let token_tree_html = ref Tokens.empty_ttree
let initialize_tex_html () =
let if_utf8 = if !prefs.encoding.utf8 then fun x -> Some x else fun _ -> None in
let (tree_latex, tree_html) = List.fold_right (fun (s,l,l') (tt,tt') ->
(Tokens.ttree_add tt s l,
match l' with None -> tt' | Some l' -> Tokens.ttree_add tt' s l'))
[ "*" , "\\ensuremath{\\times}", if_utf8 "×";
"|", "\\ensuremath{|}", None;
"->", "\\ensuremath{\\rightarrow}", if_utf8 "→";
"->~", "\\ensuremath{\\rightarrow\\lnot}", None;
"->~~", "\\ensuremath{\\rightarrow\\lnot\\lnot}", None;
"<-", "\\ensuremath{\\leftarrow}", None;
"<->", "\\ensuremath{\\leftrightarrow}", if_utf8 "↔";
"=>", "\\ensuremath{\\Rightarrow}", if_utf8 "⇒";
"<=", "\\ensuremath{\\le}", if_utf8 "≤";
">=", "\\ensuremath{\\ge}", if_utf8 "≥";
"<>", "\\ensuremath{\\not=}", if_utf8 "≠";
"~", "\\ensuremath{\\lnot}", if_utf8 "¬";
"/\\", "\\ensuremath{\\land}", if_utf8 "∧";
"\\/", "\\ensuremath{\\lor}", if_utf8 "∨";
"|-", "\\ensuremath{\\vdash}", None;
"forall", "\\ensuremath{\\forall}", if_utf8 "∀";
"exists", "\\ensuremath{\\exists}", if_utf8 "∃";
"Π", "\\ensuremath{\\Pi}", if_utf8 "Π";
"λ", "\\ensuremath{\\lambda}", if_utf8 "λ";
(* "fun", "\\ensuremath{\\lambda}" ? *)
] (Tokens.empty_ttree,Tokens.empty_ttree) in
token_tree_latex := tree_latex;
token_tree_html := tree_html
let add_printing_token s (t1,t2) =
(match t1 with None -> () | Some t1 ->
token_tree_latex := Tokens.ttree_add !token_tree_latex s t1);
(match t2 with None -> () | Some t2 ->
token_tree_html := Tokens.ttree_add !token_tree_html s t2)
let remove_printing_token s =
token_tree_latex := Tokens.ttree_remove !token_tree_latex s;
token_tree_html := Tokens.ttree_remove !token_tree_html s
(*s Table of contents *)
type toc_entry =
| Toc_library of string * string option
| Toc_section of int * (unit -> unit) * string
let (toc_q : toc_entry Queue.t) = Queue.create ()
let add_toc_entry e = Queue.add e toc_q
let new_label = let r = ref 0 in fun () -> incr r; "lab" ^ string_of_int !r
(*s LaTeX output *)
module Latex = struct
let in_title = ref false
(*s Latex preamble *)
let (preamble : string Queue.t) = Queue.create ()
let push_in_preamble s = Queue.add s preamble
let utf8x_extra_support () =
printf "\n";
printf "%%Warning: tipa declares many non-standard macros used by utf8x to\n";
printf "%%interpret utf8 characters but extra packages might have to be added\n";
printf "%%such as \"textgreek\" for Greek letters not already in tipa\n";
printf "%%or \"stmaryrd\" for mathematical symbols.\n";
printf "%%Utf8 codes missing a LaTeX interpretation can be defined by using\n";
printf "%%\\DeclareUnicodeCharacter{code}{interpretation}.\n";
printf "%%Use coqdoc's option -p to add new packages or declarations.\n";
printf "\\usepackage{tipa}\n";
printf "\n"
let header () =
if !prefs.header_trailer then begin
printf "\\documentclass[12pt]{report}\n";
if !prefs.encoding.inputenc != "" then
printf "\\usepackage[%s]{inputenc}\n" !prefs.encoding.inputenc;
if !prefs.encoding.inputenc = "utf8x" then utf8x_extra_support ();
printf "\\usepackage[T1]{fontenc}\n";
printf "\\usepackage{fullpage}\n";
printf "\\usepackage{coqdoc}\n";
printf "\\usepackage{amsmath,amssymb}\n";
printf "\\usepackage{url}\n";
(match !prefs.toc_depth with
| None -> ()
| Some n -> printf "\\setcounter{tocdepth}{%i}\n" n);
Queue.iter (fun s -> printf "%s\n" s) preamble;
printf "\\begin{document}\n"
end;
output_string
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
output_string
"%% This file has been automatically generated with the command\n";
output_string "%% ";
Array.iter (fun s -> printf "%s " s) Sys.argv;
printf "\n";
output_string
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
let trailer () =
if !prefs.header_trailer then begin
printf "\\end{document}\n"
end
(*s Latex low-level translation *)
let nbsp () = output_char '~'
let char c = match c with
| '\\' ->
printf "\\symbol{92}"
| '$' | '#' | '%' | '&' | '{' | '}' | '_' ->
output_char '\\'; output_char c
| '^' | '~' ->
output_char '\\'; output_char c; printf "{}"
| _ ->
output_char c
let label_char c = match c with
| '_' -> output_char ' '
| '\\' | '$' | '#' | '%' | '&' | '{' | '}'
| '^' | '~' -> printf "x%X" (Char.code c)
| _ -> if c >= '\x80' then printf "x%X" (Char.code c) else output_char c
let label_ident s =
for i = 0 to String.length s - 1 do label_char s.[i] done
let latex_char = output_char
let latex_string = output_string
let html_char _ = ()
let html_string _ = ()
(*s Latex char escaping *)
let escaped =
let buff = Buffer.create 5 in
fun s ->
Buffer.clear buff;
for i = 0 to String.length s - 1 do
match s.[i] with
| '\\' ->
Buffer.add_string buff "\\symbol{92}"
| '$' | '#' | '%' | '&' | '{' | '}' | '_' as c ->
Buffer.add_char buff '\\'; Buffer.add_char buff c
| '^' | '~' as c ->
Buffer.add_char buff '\\'; Buffer.add_char buff c;
Buffer.add_string buff "{}"
| '\'' ->
if i < String.length s - 1 && s.[i+1] = '\'' then begin
Buffer.add_char buff '\''; Buffer.add_char buff '{';
Buffer.add_char buff '}'
end else
Buffer.add_char buff '\''
| c ->
Buffer.add_char buff c
done;
Buffer.contents buff
(*s Latex reference and symbol translation *)
let start_module () =
let ln = !prefs.lib_name in
if not !prefs.short then begin
printf "\\coqlibrary{";
label_ident (get_module false);
printf "}{";
if ln <> "" then printf "%s " ln;
printf "}{%s}\n\n" (escaped (get_module true))
end
let start_latex_math () = output_char '$'
let stop_latex_math () = output_char '$'
let start_quote () = output_char '`'; output_char '`'
let stop_quote () = output_char '\''; output_char '\''
let start_verbatim inline =
if inline then printf "\\texttt{"
else printf "\\begin{verbatim}\n"
let stop_verbatim inline =
if inline then printf "}"
else printf "\\end{verbatim}\n"
let url addr name =
printf "%s\\footnote{\\url{%s}}"
(match name with
| None -> ""
| Some n -> n)
addr
let indentation n =
if n == 0 then
printf "\\coqdocnoindent\n"
else
let space = 0.5 *. (float n) in
printf "\\coqdocindent{%2.2fem}\n" space
let ident_ref m fid typ s =
let id = if fid <> "" then (m ^ "." ^ fid) else m in
match find_module m with
| Local ->
printf "\\coqref{"; label_ident id;
printf "}{\\coqdoc%s{%s}}" (type_name typ) s
| External m when !prefs.externals ->
printf "\\coqexternalref{"; label_ident fid;
printf "}{%s}{\\coqdoc%s{%s}}" (escaped m) (type_name typ) s
| External _ | Unknown ->
printf "\\coqdoc%s{%s}" (type_name typ) s
let defref m id ty s =
if ty <> Notation then
(printf "\\coqdef{"; label_ident (m ^ "." ^ id);
printf "}{%s}{\\coqdoc%s{%s}}" s (type_name ty) s)
else
Glob file still not able to say the exact extent of the definition
(* so we currently renounce to highlight the notation location *)
(printf "\\coqdef{"; label_ident (m ^ "." ^ id);
printf "}{%s}{%s}" s s)
let reference s = function
| Def (fullid,typ) ->
defref (get_module false) fullid typ s
| Ref (m,fullid,typ) ->
ident_ref m fullid typ s
s The sublexer buffers symbol characters and attached
uninterpreted ident and try to apply special translation such as ,
predefined , translation " - > " to " \ensuremath{\rightarrow } " or ,
virtually , a user - level translation from " = _ h " to " \ensuremath{=_{h } } "
uninterpreted ident and try to apply special translation such as,
predefined, translation "->" to "\ensuremath{\rightarrow}" or,
virtually, a user-level translation from "=_h" to "\ensuremath{=_{h}}" *)
let output_sublexer_string doescape issymbchar tag s =
let s = if doescape then escaped s else s in
match tag with
| Some ref -> reference s ref
| None -> if issymbchar then output_string s else printf "\\coqdocvar{%s}" s
let last_was_in = ref false
let sublexer c loc =
if c = '*' && !last_was_in then begin
Tokens.flush_sublexer ();
output_char '*'
end else begin
let tag =
try Some (Index.find (get_module false) loc) with Not_found -> None
in
Tokens.output_tagged_symbol_char tag c
end;
last_was_in := false
let sublexer_in_doc c =
if c = '*' && !last_was_in then begin
Tokens.flush_sublexer ();
output_char '*'
end else
Tokens.output_tagged_symbol_char None c;
last_was_in := false
let initialize () =
initialize_tex_html ();
Tokens.token_tree := token_tree_latex;
Tokens.outfun := output_sublexer_string
(*s Interpreting ident with fallback on sublexer if unknown ident *)
let translate s =
match Tokens.translate s with Some s -> s | None -> escaped s
let keyword s loc =
printf "\\coqdockw{%s}" (translate s)
let ident s loc =
last_was_in := s = "in";
try
match loc with
| None -> raise Not_found
| Some loc ->
let tag = Index.find (get_module false) loc in
reference (translate s) tag
with Not_found ->
if is_tactic s then
printf "\\coqdoctac{%s}" (translate s)
else if is_keyword s then
printf "\\coqdockw{%s}" (translate s)
else if !prefs.interpolate && !in_doc (* always a var otherwise *)
then
try
let tag = Index.find_string s in
reference (translate s) tag
with _ -> Tokens.output_tagged_ident_string s
else Tokens.output_tagged_ident_string s
let ident s l =
if !in_title then (
printf "\\texorpdfstring{\\protect";
ident s l;
printf "}{%s}" (translate s))
else
ident s l
(*s Translating structure *)
let proofbox () = printf "\\ensuremath{\\Box}"
let rec reach_item_level n =
if !item_level < n then begin
printf "\n\\begin{itemize}\n\\item "; incr item_level;
reach_item_level n
end else if !item_level > n then begin
printf "\n\\end{itemize}\n"; decr item_level;
reach_item_level n
end
let item n =
let old_level = !item_level in
reach_item_level n;
if n <= old_level then printf "\n\\item "
let stop_item () = reach_item_level 0
let start_doc () = in_doc := true
let end_doc () = in_doc := false; stop_item ()
(* This is broken if we are in math mode, but coqdoc currently isn't
tracking that *)
let start_emph () = printf "\\textit{"
let stop_emph () = printf "}"
let start_details _ = ()
let stop_details () = ()
let start_comment () = printf "\\begin{coqdoccomment}\n"
let end_comment () = printf "\\end{coqdoccomment}\n"
let start_coq () = printf "\\begin{coqdoccode}\n"
let end_coq () = printf "\\end{coqdoccode}\n"
let section_kind = function
| 1 -> "\\section{"
| 2 -> "\\subsection{"
| 3 -> "\\subsubsection{"
| 4 -> "\\paragraph{"
| _ -> assert false
let section lev f =
stop_item ();
output_string (section_kind lev);
in_title := true; f (); in_title := false;
printf "}\n\n"
let rule () =
printf "\\par\n\\noindent\\hrulefill\\par\n\\noindent{}"
let paragraph () = printf "\n\n"
let line_break () = printf "\\coqdoceol\n"
let empty_line_of_code () = printf "\\coqdocemptyline\n"
let start_inline_coq_block () = line_break (); empty_line_of_code ()
let end_inline_coq_block () = empty_line_of_code ()
let start_inline_coq () = ()
let end_inline_coq () = ()
let make_multi_index () = ()
let make_index () = ()
let make_toc () = printf "\\tableofcontents\n"
end
(*s HTML output *)
module Html = struct
let header () =
if !prefs.header_trailer then
if !prefs.header_file_spec then
let cin = open_in !prefs.header_file in
try
while true do
let s = input_line cin in
printf "%s\n" s
done
with End_of_file -> close_in cin
else
begin
printf "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n";
printf "\"-strict.dtd\">\n";
printf "<html xmlns=\"\">\n<head>\n";
printf "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\" />\n" !prefs.encoding.charset;
printf "<link href=\"coqdoc.css\" rel=\"stylesheet\" type=\"text/css\" />\n";
printf "<title>%s</title>\n</head>\n\n" !page_title;
printf "<body>\n\n<div id=\"page\">\n\n<div id=\"header\">\n</div>\n\n";
printf "<div id=\"main\">\n\n"
end
let trailer () =
if !prefs.header_trailer && !prefs.footer_file_spec then
let cin = open_in !prefs.footer_file in
try
while true do
let s = input_line cin in
printf "%s\n" s
done
with End_of_file -> close_in cin
else
begin
if !prefs.index && (get_module false) <> "Index" then
printf "</div>\n\n<div id=\"footer\">\n<hr/><a href=\"%s.html\">Index</a>" !prefs.index_name;
printf "<hr/>This page has been generated by ";
printf "<a href=\"%s\">coqdoc</a>\n" Coq_config.wwwcoq;
printf "</div>\n\n</div>\n\n</body>\n</html>"
end
let start_module () =
let ln = !prefs.lib_name in
if not !prefs.short then begin
let (m,sub) = !current_module in
add_toc_entry (Toc_library (m,sub));
if ln = "" then
printf "<h1 class=\"libtitle\">%s</h1>\n\n" (get_module true)
else
printf "<h1 class=\"libtitle\">%s %s</h1>\n\n" ln (get_module true)
end
let indentation n = for _i = 1 to n do printf " " done
let line_break () = printf "<br/>\n"
let empty_line_of_code () =
printf "\n<br/>\n"
let nbsp () = printf " "
let char = function
| '<' -> printf "<"
| '>' -> printf ">"
| '&' -> printf "&"
| c -> output_char c
let escaped =
let buff = Buffer.create 5 in
fun s ->
Buffer.clear buff;
for i = 0 to String.length s - 1 do
match s.[i] with
| '<' -> Buffer.add_string buff "<"
| '>' -> Buffer.add_string buff ">"
| '&' -> Buffer.add_string buff "&"
| '\"' -> Buffer.add_string buff """
| c -> Buffer.add_char buff c
done;
Buffer.contents buff
let sanitize_name s =
let rec loop esc i =
if i < 0 then if esc then escaped s else s
else match s.[i] with
| 'a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '_' -> loop esc (i-1)
| '<' | '>' | '&' | '\'' | '\"' -> loop true (i-1)
| '-' | ':' -> loop esc (i-1) (* should be safe in HTML5 attribute name syntax *)
| _ ->
(* This name contains complex characters:
this is probably a notation string, we simply hash it. *)
Digest.to_hex (Digest.string s)
in loop false (String.length s - 1)
let latex_char _ = ()
let latex_string _ = ()
let html_char = output_char
let html_string = output_string
let start_latex_math () = ()
let stop_latex_math () = ()
let start_quote () = char '"'
let stop_quote () = start_quote ()
let start_verbatim inline =
if inline then printf "<code>"
else printf "<pre>\n"
let stop_verbatim inline =
if inline then printf "</code>"
else printf "</pre>\n"
let url addr name =
printf "<a href=\"%s\">%s</a>" addr
(match name with
| Some n -> n
| None -> addr)
let ident_ref m fid typ s =
match find_module m with
| Local ->
printf "<a class=\"idref\" href=\"%s.html#%s\">" m (sanitize_name fid);
printf "<span class=\"id\" title=\"%s\">%s</span></a>" typ s
| External m when !prefs.externals ->
printf "<a class=\"idref\" href=\"%s.html#%s\">" m (sanitize_name fid);
printf "<span class=\"id\" title=\"%s\">%s</span></a>" typ s
| External _ | Unknown ->
printf "<span class=\"id\" title=\"%s\">%s</span>" typ s
let reference s r =
match r with
| Def (fullid,ty) ->
let s' = sanitize_name fullid in
printf "<a id=\"%s\" class=\"idref\" href=\"#%s\">" s' s';
printf "<span class=\"id\" title=\"%s\">%s</span></a>" (type_name ty) s
| Ref (m,fullid,ty) ->
ident_ref m fullid (type_name ty) s
let output_sublexer_string doescape issymbchar tag s =
let s = if doescape then escaped s else s in
match tag with
| Some ref -> reference s ref
| None ->
if issymbchar then output_string s
else printf "<span class=\"id\" title=\"var\">%s</span>" s
let sublexer c loc =
let tag =
try Some (Index.find (get_module false) loc) with Not_found -> None
in
Tokens.output_tagged_symbol_char tag c
let sublexer_in_doc c =
Tokens.output_tagged_symbol_char None c
let initialize () =
initialize_tex_html();
Tokens.token_tree := token_tree_html;
Tokens.outfun := output_sublexer_string
let translate s =
match Tokens.translate s with Some s -> s | None -> escaped s
let keyword s loc =
printf "<span class=\"id\" title=\"keyword\">%s</span>" (translate s)
let ident s loc =
try
match loc with
| None -> raise Not_found
| Some loc ->
reference (translate s) (Index.find (get_module false) loc)
with Not_found ->
if is_tactic s then
printf "<span class=\"id\" title=\"tactic\">%s</span>" (translate s)
else if is_keyword s then
printf "<span class=\"id\" title=\"keyword\">%s</span>" (translate s)
else if !prefs.interpolate && !in_doc (* always a var otherwise *) then
try reference (translate s) (Index.find_string s)
with Not_found -> Tokens.output_tagged_ident_string s
else
Tokens.output_tagged_ident_string s
let proofbox () = printf "<font size=-2>☐</font>"
let rec reach_item_level n =
if !item_level < n then begin
printf "<ul class=\"doclist\">\n<li>"; incr item_level;
reach_item_level n
end else if !item_level > n then begin
printf "\n</li>\n</ul>\n"; decr item_level;
reach_item_level n
end
let item n =
let old_level = !item_level in
reach_item_level n;
if n <= old_level then printf "\n</li>\n<li>"
let stop_item () = reach_item_level 0
let start_coq () = if not !prefs.raw_comments then printf "<div class=\"code\">\n"
let end_coq () = if not !prefs.raw_comments then printf "</div>\n"
let start_doc () = in_doc := true;
if not !prefs.raw_comments then
printf "\n<div class=\"doc\">\n"
let end_doc () = in_doc := false;
stop_item ();
if not !prefs.raw_comments then printf "</div>\n"
let start_emph () = printf "<i>"
let stop_emph () = printf "</i>"
let start_details = function
| Some s -> printf "<details><summary>%s</summary>" s
| _ -> printf "<details>"
let stop_details () = printf "</details>"
let start_comment () = printf "<span class=\"comment\">(*"
let end_comment () = printf "*)</span>"
let start_inline_coq () =
if !prefs.inline_notmono then printf "<span class=\"inlinecodenm\">"
else printf "<span class=\"inlinecode\">"
let end_inline_coq () = printf "</span>"
let start_inline_coq_block () = line_break (); start_inline_coq ()
let end_inline_coq_block () = end_inline_coq ()
let paragraph () = printf "\n<div class=\"paragraph\"> </div>\n\n"
(* inference rules *)
let inf_rule assumptions (_,_,midnm) conclusions =
this first function replaces any occurrence of 3 or more spaces
in a row with " & nbsp;"s . We do this to the assumptions so that
people can put multiple rules on a line with nice formatting
in a row with " "s. We do this to the assumptions so that
people can put multiple rules on a line with nice formatting *)
let replace_spaces str =
let rec copy a n = match n with 0 -> [] | n -> (a :: copy a (n - 1)) in
let results = Str.full_split (Str.regexp "[' '][' '][' ']+") str in
let strs = List.map (fun r -> match r with
| Str.Text s -> [s]
| Str.Delim s ->
copy " " (String.length s))
results
in
String.concat "" (List.concat strs)
in
let start_assumption line =
(printf "<tr class=\"infruleassumption\">\n";
printf " <td class=\"infrule\">%s</td>\n" (replace_spaces line)) in
let end_assumption () =
(printf " <td></td>\n";
printf "</tr>\n") in
let rec print_assumptions hyps =
match hyps with
| [] -> start_assumption " "
| [(_,hyp)] -> start_assumption hyp
| ((_,hyp) :: hyps') -> (start_assumption hyp;
end_assumption ();
print_assumptions hyps') in
printf "<center><table class=\"infrule\">\n";
print_assumptions assumptions;
printf " <td class=\"infrulenamecol\" rowspan=\"3\">\n";
(match midnm with
| None -> printf " \n </td>"
| Some s -> printf " %s \n </td>" s);
printf "</tr>\n";
printf "<tr class=\"infrulemiddle\">\n";
printf " <td class=\"infrule\"><hr /></td>\n";
printf "</tr>\n";
print_assumptions conclusions;
end_assumption ();
printf "</table></center>"
let section lev f =
let lab = new_label () in
let r = sprintf "%s.html#%s" (get_module false) lab in
(match !prefs.toc_depth with
| None -> add_toc_entry (Toc_section (lev, f, r))
| Some n -> if lev <= n then add_toc_entry (Toc_section (lev, f, r))
else ());
stop_item ();
printf "<a id=\"%s\"></a><h%d class=\"section\">" lab lev;
f ();
printf "</h%d>\n" lev
let rule () = printf "<hr/>\n"
(* make a HTML index from a list of triples (name,text,link) *)
let index_ref i c =
let idxc = sprintf "%s_%c" i.idx_name c in
!prefs.index_name ^ (if !prefs.multi_index then "_" ^ idxc ^ ".html" else ".html#" ^ idxc)
let letter_index category idx (c,l) =
if l <> [] then begin
let cat = if category && idx <> "global" then "(" ^ idx ^ ")" else "" in
printf "<a id=\"%s_%c\"></a><h2>%s %s</h2>\n" idx c (display_letter c) cat;
List.iter
(fun (id,(text,link,t)) ->
let id' = escaped (prepare_entry id t) in
printf "<a href=\"%s\">%s</a> %s<br/>\n" link id' text) l;
printf "<br/><br/>"
end
let all_letters i = List.iter (letter_index false i.idx_name) i.idx_entries
Construction d'une liste des index ( 1 index global , puis 1
index par catégorie )
index par catégorie) *)
let format_global_index =
Index.map
(fun s (m,t) ->
if t = Library then
let ln = !prefs.lib_name in
if ln <> "" then
"[" ^ String.lowercase_ascii ln ^ "]", m ^ ".html", t
else
"[library]", m ^ ".html", t
else
sprintf "[%s, in <a href=\"%s.html\">%s</a>]" (type_name t) m m ,
sprintf "%s.html#%s" m (sanitize_name s), t)
let format_bytype_index = function
| Library, idx ->
Index.map (fun id m -> "", m ^ ".html", Library) idx
| (t,idx) ->
Index.map
(fun s m ->
let text = sprintf "[in <a href=\"%s.html\">%s</a>]" m m in
(text, sprintf "%s.html#%s" m (sanitize_name s), t)) idx
Impression de la table d'index
let print_index_table_item i =
printf "<tr>\n<td>%s Index</td>\n" (String.capitalize_ascii i.idx_name);
List.iter
(fun (c,l) ->
if l <> [] then
printf "<td><a href=\"%s\">%s</a></td>\n" (index_ref i c)
(display_letter c)
else
printf "<td>%s</td>\n" (display_letter c))
i.idx_entries;
let n = i.idx_size in
printf "<td>(%d %s)</td>\n" n (if n > 1 then "entries" else "entry");
printf "</tr>\n"
let print_index_table idxl =
printf "<table>\n";
List.iter print_index_table_item idxl;
printf "</table>\n"
let make_one_multi_index prt_tbl i =
Attn : make_one_multi_index ...
let idx = i.idx_name in
let one_letter ((c,l) as cl) =
open_out_file (sprintf "%s_%s_%c.html" !prefs.index_name idx c);
if (!prefs.header_trailer) then header ();
prt_tbl (); printf "<hr/>";
letter_index true idx cl;
if List.length l > 30 then begin printf "<hr/>"; prt_tbl () end;
if (!prefs.header_trailer) then trailer ();
close_out_file ()
in
List.iter one_letter i.idx_entries
let make_multi_index () =
let all_index =
let glob,bt = Index.all_entries () in
(format_global_index glob) ::
(List.map format_bytype_index bt) in
let print_table () = print_index_table all_index in
List.iter (make_one_multi_index print_table) all_index
let make_index () =
let all_index =
let glob,bt = Index.all_entries () in
(format_global_index glob) ::
(List.map format_bytype_index bt) in
let print_table () = print_index_table all_index in
let print_one_index i =
if i.idx_size > 0 then begin
printf "<hr/>\n<h1>%s Index</h1>\n" (String.capitalize_ascii i.idx_name);
all_letters i
end
in
set_module "Index" None;
if !prefs.title <> "" then printf "<h1>%s</h1>\n" !prefs.title;
print_table ();
if not (!prefs.multi_index) then
begin
List.iter print_one_index all_index;
printf "<hr/>"; print_table ()
end
let make_toc () =
let ln = !prefs.lib_name in
let make_toc_entry = function
| Toc_library (m,sub) ->
stop_item ();
let ms = match sub with | None -> m | Some s -> m ^ ": " ^ s in
if ln = "" then
printf "<h2><a href=\"%s.html\">%s</a></h2>\n" m ms
else
printf "<h2><a href=\"%s.html\">%s %s</a></h2>\n" m ln ms
| Toc_section (n, f, r) ->
item n;
printf "<a href=\"%s\">" r; f (); printf "</a>\n"
in
printf "<div id=\"toc\">\n";
Queue.iter make_toc_entry toc_q;
stop_item ();
printf "</div>\n"
end
(*s TeXmacs-aware output *)
module TeXmacs = struct
(*s Latex preamble *)
let (_ : string Queue.t) =
in_doc := false; Queue.create ()
let header () =
output_string
"(*i This file has been automatically generated with the command \n";
output_string
" "; Array.iter (fun s -> printf "%s " s) Sys.argv; printf " *)\n"
let trailer () = ()
let nbsp () = output_char ' '
let char_true c = match c with
| '\\' -> printf "\\\\"
| '<' -> printf "\\<"
| '|' -> printf "\\|"
| '>' -> printf "\\>"
| _ -> output_char c
let char c = if !in_doc then char_true c else output_char c
let latex_char = char_true
let latex_string = String.iter latex_char
let html_char _ = ()
let html_string _ = ()
let raw_ident s =
for i = 0 to String.length s - 1 do char s.[i] done
let start_module () = ()
let start_latex_math () = printf "<with|mode|math|"
let stop_latex_math () = output_char '>'
let start_verbatim inline = in_doc := true; printf "<\\verbatim>"
let stop_verbatim inline = in_doc := false; printf "</verbatim>"
let url addr name =
printf "%s<\\footnote><\\url>%s</url></footnote>" addr
(match name with
| None -> ""
| Some n -> n)
let start_quote () = output_char '`'; output_char '`'
let stop_quote () = output_char '\''; output_char '\''
let indentation n = ()
let keyword s =
printf "<kw|"; raw_ident s; printf ">"
let ident_true s =
if is_keyword s then keyword s
else raw_ident s
let keyword s loc = keyword s
let ident s _ = if !in_doc then ident_true s else raw_ident s
let output_sublexer_string doescape issymbchar tag s =
if doescape then raw_ident s else output_string s
let sublexer c l =
if !in_doc then Tokens.output_tagged_symbol_char None c else char c
let sublexer_in_doc c =
char c
let initialize () =
Tokens.token_tree := token_tree_texmacs;
Tokens.outfun := output_sublexer_string
let proofbox () = printf "QED"
let rec reach_item_level n =
if !item_level < n then begin
printf "\n<\\itemize>\n<item>"; incr item_level;
reach_item_level n
end else if !item_level > n then begin
printf "\n</itemize>"; decr item_level;
reach_item_level n
end
let item n =
let old_level = !item_level in
reach_item_level n;
if n <= old_level then printf "\n\n<item>"
let stop_item () = reach_item_level 0
let start_doc () = in_doc := true; printf "(** texmacs: "
let end_doc () = stop_item (); in_doc := false; printf " *)"
let start_coq () = ()
let end_coq () = ()
let start_emph () = printf "<with|font shape|italic|"
let stop_emph () = printf ">"
let start_details _ = ()
let stop_details () = ()
let start_comment () = ()
let end_comment () = ()
let section_kind = function
| 1 -> "section"
| 2 -> "subsection"
| 3 -> "subsubsection"
| 4 -> "paragraph"
| _ -> assert false
let section lev f =
stop_item ();
printf "<"; output_string (section_kind lev); printf "|";
f (); printf ">\n\n"
let rule () =
printf "\n<hrule>\n"
let paragraph () = printf "\n\n"
let line_break () = printf "\n"
let empty_line_of_code () = printf "\n"
let start_inline_coq () = printf "<verbatim|["
let end_inline_coq () = printf "]>"
let start_inline_coq_block () = line_break (); start_inline_coq ()
let end_inline_coq_block () = end_inline_coq ()
let make_multi_index () = ()
let make_index () = ()
let make_toc () = ()
end
(*s Raw output *)
module Raw = struct
let header () = ()
let trailer () = ()
let nbsp () = output_char ' '
let char = output_char
let latex_char = output_char
let latex_string = output_string
let html_char _ = ()
let html_string _ = ()
let raw_ident s =
for i = 0 to String.length s - 1 do char s.[i] done
let start_module () = ()
let start_latex_math () = ()
let stop_latex_math () = ()
let start_verbatim inline = ()
let stop_verbatim inline = ()
let url addr name =
match name with
| Some n -> printf "%s (%s)" n addr
| None -> printf "%s" addr
let start_quote () = printf "\""
let stop_quote () = printf "\""
let indentation n =
for _i = 1 to n do printf " " done
let keyword s loc = raw_ident s
let ident s loc = raw_ident s
let sublexer c l = char c
let sublexer_in_doc c = char c
let initialize () =
Tokens.token_tree := ref Tokens.empty_ttree;
Tokens.outfun := (fun _ _ _ _ -> failwith "Useless")
let proofbox () = printf "[]"
let item n = printf "- "
let stop_item () = ()
let reach_item_level _ = ()
let start_doc () = printf "(** "
let end_doc () = printf " *)\n"
let start_emph () = printf "_"
let stop_emph () = printf "_"
let start_details _ = ()
let stop_details () = ()
let start_comment () = printf "(*"
let end_comment () = printf "*)"
let start_coq () = ()
let end_coq () = ()
let section_kind =
function
| 1 -> "* "
| 2 -> "** "
| 3 -> "*** "
| 4 -> "**** "
| _ -> assert false
let section lev f =
output_string (section_kind lev);
f ()
let rule () = ()
let paragraph () = printf "\n\n"
let line_break () = printf "\n"
let empty_line_of_code () = printf "\n"
let start_inline_coq () = ()
let end_inline_coq () = ()
let start_inline_coq_block () = line_break (); start_inline_coq ()
let end_inline_coq_block () = end_inline_coq ()
let make_multi_index () = ()
let make_index () = ()
let make_toc () = ()
end
(*s Generic output *)
let select f1 f2 f3 f4 x =
match !prefs.targetlang with LaTeX -> f1 x | HTML -> f2 x | TeXmacs -> f3 x | Raw -> f4 x
let push_in_preamble = Latex.push_in_preamble
let header = select Latex.header Html.header TeXmacs.header Raw.header
let trailer = select Latex.trailer Html.trailer TeXmacs.trailer Raw.trailer
let start_module =
select Latex.start_module Html.start_module TeXmacs.start_module Raw.start_module
let start_doc = select Latex.start_doc Html.start_doc TeXmacs.start_doc Raw.start_doc
let end_doc = select Latex.end_doc Html.end_doc TeXmacs.end_doc Raw.end_doc
let start_comment = select Latex.start_comment Html.start_comment TeXmacs.start_comment Raw.start_comment
let end_comment = select Latex.end_comment Html.end_comment TeXmacs.end_comment Raw.end_comment
let start_coq = select Latex.start_coq Html.start_coq TeXmacs.start_coq Raw.start_coq
let end_coq = select Latex.end_coq Html.end_coq TeXmacs.end_coq Raw.end_coq
let start_inline_coq =
select Latex.start_inline_coq Html.start_inline_coq TeXmacs.start_inline_coq Raw.start_inline_coq
let end_inline_coq =
select Latex.end_inline_coq Html.end_inline_coq TeXmacs.end_inline_coq Raw.end_inline_coq
let start_inline_coq_block =
select Latex.start_inline_coq_block Html.start_inline_coq_block
TeXmacs.start_inline_coq_block Raw.start_inline_coq_block
let end_inline_coq_block =
select Latex.end_inline_coq_block Html.end_inline_coq_block TeXmacs.end_inline_coq_block Raw.end_inline_coq_block
let indentation = select Latex.indentation Html.indentation TeXmacs.indentation Raw.indentation
let paragraph = select Latex.paragraph Html.paragraph TeXmacs.paragraph Raw.paragraph
let line_break = select Latex.line_break Html.line_break TeXmacs.line_break Raw.line_break
let empty_line_of_code = select
Latex.empty_line_of_code Html.empty_line_of_code TeXmacs.empty_line_of_code Raw.empty_line_of_code
let section = select Latex.section Html.section TeXmacs.section Raw.section
let item = select Latex.item Html.item TeXmacs.item Raw.item
let stop_item = select Latex.stop_item Html.stop_item TeXmacs.stop_item Raw.stop_item
let reach_item_level = select Latex.reach_item_level Html.reach_item_level TeXmacs.reach_item_level Raw.reach_item_level
let rule = select Latex.rule Html.rule TeXmacs.rule Raw.rule
let nbsp = select Latex.nbsp Html.nbsp TeXmacs.nbsp Raw.nbsp
let char = select Latex.char Html.char TeXmacs.char Raw.char
let keyword = select Latex.keyword Html.keyword TeXmacs.keyword Raw.keyword
let ident = select Latex.ident Html.ident TeXmacs.ident Raw.ident
let sublexer = select Latex.sublexer Html.sublexer TeXmacs.sublexer Raw.sublexer
let sublexer_in_doc = select Latex.sublexer_in_doc Html.sublexer_in_doc TeXmacs.sublexer_in_doc Raw.sublexer_in_doc
let initialize = select Latex.initialize Html.initialize TeXmacs.initialize Raw.initialize
let proofbox = select Latex.proofbox Html.proofbox TeXmacs.proofbox Raw.proofbox
let latex_char = select Latex.latex_char Html.latex_char TeXmacs.latex_char Raw.latex_char
let latex_string =
select Latex.latex_string Html.latex_string TeXmacs.latex_string Raw.latex_string
let html_char = select Latex.html_char Html.html_char TeXmacs.html_char Raw.html_char
let html_string =
select Latex.html_string Html.html_string TeXmacs.html_string Raw.html_string
let start_emph =
select Latex.start_emph Html.start_emph TeXmacs.start_emph Raw.start_emph
let stop_emph =
select Latex.stop_emph Html.stop_emph TeXmacs.stop_emph Raw.stop_emph
let start_details =
select Latex.start_details Html.start_details TeXmacs.start_details Raw.start_details
let stop_details =
select Latex.stop_details Html.stop_details TeXmacs.stop_details Raw.stop_details
let start_latex_math =
select Latex.start_latex_math Html.start_latex_math TeXmacs.start_latex_math Raw.start_latex_math
let stop_latex_math =
select Latex.stop_latex_math Html.stop_latex_math TeXmacs.stop_latex_math Raw.stop_latex_math
let start_verbatim =
select Latex.start_verbatim Html.start_verbatim TeXmacs.start_verbatim Raw.start_verbatim
let stop_verbatim =
select Latex.stop_verbatim Html.stop_verbatim TeXmacs.stop_verbatim Raw.stop_verbatim
let verbatim_char inline =
select (if inline then Latex.char else output_char) Html.char TeXmacs.char Raw.char
let hard_verbatim_char = output_char
let url =
select Latex.url Html.url TeXmacs.url Raw.url
let start_quote =
select Latex.start_quote Html.start_quote TeXmacs.start_quote Raw.start_quote
let stop_quote =
select Latex.stop_quote Html.stop_quote TeXmacs.stop_quote Raw.stop_quote
let inf_rule_dumb assumptions (midsp,midln,midnm) conclusions =
start_verbatim false;
let dumb_line =
function (sp,ln) -> (String.iter char ((String.make sp ' ') ^ ln);
char '\n')
in
(List.iter dumb_line assumptions;
dumb_line (midsp, midln ^ (match midnm with
| Some s -> " " ^ s
| None -> ""));
List.iter dumb_line conclusions);
stop_verbatim false
let inf_rule = select inf_rule_dumb Html.inf_rule inf_rule_dumb inf_rule_dumb
let make_multi_index = select Latex.make_multi_index Html.make_multi_index TeXmacs.make_multi_index Raw.make_multi_index
let make_index = select Latex.make_index Html.make_index TeXmacs.make_index Raw.make_index
let make_toc = select Latex.make_toc Html.make_toc TeXmacs.make_toc Raw.make_toc
| null | https://raw.githubusercontent.com/coq/coq/3dfa597540c0e4aa720c9af966f92b359a0c29f3/tools/coqdoc/output.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)
**********************************************************************
s Low level output
s Coq keywords
i (* coq terms
Ltac
Notations
s Current Coq module
s Customized and predefined pretty-print
"fun", "\\ensuremath{\\lambda}" ?
s Table of contents
s LaTeX output
s Latex preamble
s Latex low-level translation
s Latex char escaping
s Latex reference and symbol translation
so we currently renounce to highlight the notation location
s Interpreting ident with fallback on sublexer if unknown ident
always a var otherwise
s Translating structure
This is broken if we are in math mode, but coqdoc currently isn't
tracking that
s HTML output
should be safe in HTML5 attribute name syntax
This name contains complex characters:
this is probably a notation string, we simply hash it.
always a var otherwise
inference rules
make a HTML index from a list of triples (name,text,link)
s TeXmacs-aware output
s Latex preamble
s Raw output
s Generic output | 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 Common
open Index
let output_char c = output_char !out_channel c
let output_string s = output_string !out_channel s
let printf s = Printf.fprintf !out_channel s
let sprintf = Printf.sprintf
let build_table l =
let h = Hashtbl.create 101 in
List.iter (fun key ->Hashtbl.add h key ()) l;
function s -> try Hashtbl.find h s; true with Not_found -> false
let is_keyword =
build_table
[ "About"; "Axiom"; "Abort"; "Chapter"; "Check"; "Coercion"; "Compute"; "CoFixpoint";
"CoInductive"; "Corollary"; "Defined"; "Definition"; "End"; "Eval"; "Example";
"Export"; "Fact"; "Fix"; "Fixpoint"; "From"; "Function"; "Generalizable"; "Global"; "Grammar";
"Guarded"; "Goal"; "Hint"; "Debug"; "On";
"Hypothesis"; "Hypotheses";
"Resolve"; "Unfold"; "Immediate"; "Extern"; "Constructors"; "Rewrite";
"Implicit"; "Import"; "Inductive";
"Infix"; "Lemma"; "Let"; "Load"; "Local"; "Locate"; "Ltac";
"Module"; "Module Type"; "Declare Module"; "Include";
"Mutual"; "Parameter"; "Parameters"; "Print"; "Printing"; "All"; "Proof"; "Proof with"; "Qed";
"Record"; "Recursive"; "Remark"; "Require"; "Save"; "Scheme"; "Assumptions"; "Axioms"; "Universes";
"Induction"; "for"; "Sort"; "Section"; "Show"; "Structure"; "Syntactic"; "Syntax"; "Tactic"; "Theorem";
"Search"; "SearchPattern"; "SearchRewrite";
"Set"; "Types"; "Undo"; "Unset"; "Variable"; "Variables"; "Context";
"Notation"; "Reserved Notation"; "Tactic Notation"; "Number Notation"; "String Notation"; "Enable Notation"; "Disable Notation";
"Delimit"; "Bind"; "Open"; "Scope"; "Inline";
"Implicit Arguments"; "Add"; "Strict";
"Typeclasses"; "Instance"; "Global Instance"; "Class"; "Instantiation";
"goal"; "goals"; "vm_compute";
"Opaque"; "Transparent"; "Time";
"Extraction"; "Extract";
"Variant";
Program
"Program Definition"; "Program Example"; "Program Fixpoint"; "Program Lemma";
"Obligation"; "Obligations"; "Solve"; "using"; "Next Obligation"; "Next";
"Program Instance"; "Equations"; "Equations_nocomp";
"forall"; "match"; "as"; "in"; "return"; "with"; "end"; "let"; "fun";
"if"; "then"; "else"; "Prop"; "Set"; "Type"; ":="; "where"; "struct"; "wf"; "measure";
"fix"; "cofix"; "is";
"before"; "after"; "constr"; "ltac"; "goal"; "context"; "beta"; "delta"; "iota"; "zeta"; "lazymatch"; "type"; "of"; "rec";
"level"; "associativity"; "no"
]
let is_tactic =
build_table
[ "intro"; "intros"; "apply"; "rewrite"; "refine"; "case"; "clear"; "injection";
"elimtype"; "progress"; "setoid_rewrite"; "left"; "right"; "constructor";
"econstructor"; "decide equality"; "abstract"; "exists"; "cbv"; "simple destruct";
"info"; "field"; "specialize"; "evar"; "solve"; "instantiate"; "info_auto"; "info_eauto";
"quote"; "eexact"; "autorewrite";
"destruct"; "destruction"; "destruct_call"; "dependent"; "elim"; "extensionality";
"f_equal"; "generalize"; "generalize_eqs"; "generalize_eqs_vars"; "induction"; "rename"; "move";
"set"; "assert"; "do"; "repeat";
"cut"; "assumption"; "exact"; "split"; "subst"; "try"; "discriminate";
"simpl"; "unfold"; "red"; "compute"; "at"; "in"; "by";
"reflexivity"; "symmetry"; "transitivity";
"replace"; "setoid_replace"; "inversion"; "inversion_clear";
"pattern"; "intuition"; "congruence"; "fail"; "fresh";
"trivial"; "tauto"; "firstorder"; "ring";
"clapply"; "program_simpl"; "program_simplify"; "eapply"; "auto"; "eauto";
"change"; "fold"; "hnf"; "lazy"; "simple"; "eexists"; "debug"; "idtac"; "first"; "type of"; "pose";
"eval"; "instantiate"; "until" ]
let current_module : (string * string option) ref = ref ("",None)
let get_module withsub =
let (m,sub) = !current_module in
if withsub then
match sub with
| None -> m
| Some sub -> m ^ ": " ^ sub
else
m
let set_module m sub = current_module := (m,sub);
page_title := get_module true
s Common to both LaTeX and HTML
let item_level = ref 0
let in_doc = ref false
let initialize_texmacs () =
let ensuremath x = sprintf "<with|mode|math|\\<%s\\>>" x in
List.fold_right (fun (s,t) tt -> Tokens.ttree_add tt s t)
[ "*", ensuremath "times";
"->", ensuremath "rightarrow";
"<-", ensuremath "leftarrow";
"<->", ensuremath "leftrightarrow";
"=>", ensuremath "Rightarrow";
"<=", ensuremath "le";
">=", ensuremath "ge";
"<>", ensuremath "noteq";
"~", ensuremath "lnot";
"/\\", ensuremath "land";
"\\/", ensuremath "lor";
"|-", ensuremath "vdash"
] Tokens.empty_ttree
let token_tree_texmacs = ref (initialize_texmacs ())
let token_tree_latex = ref Tokens.empty_ttree
let token_tree_html = ref Tokens.empty_ttree
let initialize_tex_html () =
let if_utf8 = if !prefs.encoding.utf8 then fun x -> Some x else fun _ -> None in
let (tree_latex, tree_html) = List.fold_right (fun (s,l,l') (tt,tt') ->
(Tokens.ttree_add tt s l,
match l' with None -> tt' | Some l' -> Tokens.ttree_add tt' s l'))
[ "*" , "\\ensuremath{\\times}", if_utf8 "×";
"|", "\\ensuremath{|}", None;
"->", "\\ensuremath{\\rightarrow}", if_utf8 "→";
"->~", "\\ensuremath{\\rightarrow\\lnot}", None;
"->~~", "\\ensuremath{\\rightarrow\\lnot\\lnot}", None;
"<-", "\\ensuremath{\\leftarrow}", None;
"<->", "\\ensuremath{\\leftrightarrow}", if_utf8 "↔";
"=>", "\\ensuremath{\\Rightarrow}", if_utf8 "⇒";
"<=", "\\ensuremath{\\le}", if_utf8 "≤";
">=", "\\ensuremath{\\ge}", if_utf8 "≥";
"<>", "\\ensuremath{\\not=}", if_utf8 "≠";
"~", "\\ensuremath{\\lnot}", if_utf8 "¬";
"/\\", "\\ensuremath{\\land}", if_utf8 "∧";
"\\/", "\\ensuremath{\\lor}", if_utf8 "∨";
"|-", "\\ensuremath{\\vdash}", None;
"forall", "\\ensuremath{\\forall}", if_utf8 "∀";
"exists", "\\ensuremath{\\exists}", if_utf8 "∃";
"Π", "\\ensuremath{\\Pi}", if_utf8 "Π";
"λ", "\\ensuremath{\\lambda}", if_utf8 "λ";
] (Tokens.empty_ttree,Tokens.empty_ttree) in
token_tree_latex := tree_latex;
token_tree_html := tree_html
let add_printing_token s (t1,t2) =
(match t1 with None -> () | Some t1 ->
token_tree_latex := Tokens.ttree_add !token_tree_latex s t1);
(match t2 with None -> () | Some t2 ->
token_tree_html := Tokens.ttree_add !token_tree_html s t2)
let remove_printing_token s =
token_tree_latex := Tokens.ttree_remove !token_tree_latex s;
token_tree_html := Tokens.ttree_remove !token_tree_html s
type toc_entry =
| Toc_library of string * string option
| Toc_section of int * (unit -> unit) * string
let (toc_q : toc_entry Queue.t) = Queue.create ()
let add_toc_entry e = Queue.add e toc_q
let new_label = let r = ref 0 in fun () -> incr r; "lab" ^ string_of_int !r
module Latex = struct
let in_title = ref false
let (preamble : string Queue.t) = Queue.create ()
let push_in_preamble s = Queue.add s preamble
let utf8x_extra_support () =
printf "\n";
printf "%%Warning: tipa declares many non-standard macros used by utf8x to\n";
printf "%%interpret utf8 characters but extra packages might have to be added\n";
printf "%%such as \"textgreek\" for Greek letters not already in tipa\n";
printf "%%or \"stmaryrd\" for mathematical symbols.\n";
printf "%%Utf8 codes missing a LaTeX interpretation can be defined by using\n";
printf "%%\\DeclareUnicodeCharacter{code}{interpretation}.\n";
printf "%%Use coqdoc's option -p to add new packages or declarations.\n";
printf "\\usepackage{tipa}\n";
printf "\n"
let header () =
if !prefs.header_trailer then begin
printf "\\documentclass[12pt]{report}\n";
if !prefs.encoding.inputenc != "" then
printf "\\usepackage[%s]{inputenc}\n" !prefs.encoding.inputenc;
if !prefs.encoding.inputenc = "utf8x" then utf8x_extra_support ();
printf "\\usepackage[T1]{fontenc}\n";
printf "\\usepackage{fullpage}\n";
printf "\\usepackage{coqdoc}\n";
printf "\\usepackage{amsmath,amssymb}\n";
printf "\\usepackage{url}\n";
(match !prefs.toc_depth with
| None -> ()
| Some n -> printf "\\setcounter{tocdepth}{%i}\n" n);
Queue.iter (fun s -> printf "%s\n" s) preamble;
printf "\\begin{document}\n"
end;
output_string
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";
output_string
"%% This file has been automatically generated with the command\n";
output_string "%% ";
Array.iter (fun s -> printf "%s " s) Sys.argv;
printf "\n";
output_string
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
let trailer () =
if !prefs.header_trailer then begin
printf "\\end{document}\n"
end
let nbsp () = output_char '~'
let char c = match c with
| '\\' ->
printf "\\symbol{92}"
| '$' | '#' | '%' | '&' | '{' | '}' | '_' ->
output_char '\\'; output_char c
| '^' | '~' ->
output_char '\\'; output_char c; printf "{}"
| _ ->
output_char c
let label_char c = match c with
| '_' -> output_char ' '
| '\\' | '$' | '#' | '%' | '&' | '{' | '}'
| '^' | '~' -> printf "x%X" (Char.code c)
| _ -> if c >= '\x80' then printf "x%X" (Char.code c) else output_char c
let label_ident s =
for i = 0 to String.length s - 1 do label_char s.[i] done
let latex_char = output_char
let latex_string = output_string
let html_char _ = ()
let html_string _ = ()
let escaped =
let buff = Buffer.create 5 in
fun s ->
Buffer.clear buff;
for i = 0 to String.length s - 1 do
match s.[i] with
| '\\' ->
Buffer.add_string buff "\\symbol{92}"
| '$' | '#' | '%' | '&' | '{' | '}' | '_' as c ->
Buffer.add_char buff '\\'; Buffer.add_char buff c
| '^' | '~' as c ->
Buffer.add_char buff '\\'; Buffer.add_char buff c;
Buffer.add_string buff "{}"
| '\'' ->
if i < String.length s - 1 && s.[i+1] = '\'' then begin
Buffer.add_char buff '\''; Buffer.add_char buff '{';
Buffer.add_char buff '}'
end else
Buffer.add_char buff '\''
| c ->
Buffer.add_char buff c
done;
Buffer.contents buff
let start_module () =
let ln = !prefs.lib_name in
if not !prefs.short then begin
printf "\\coqlibrary{";
label_ident (get_module false);
printf "}{";
if ln <> "" then printf "%s " ln;
printf "}{%s}\n\n" (escaped (get_module true))
end
let start_latex_math () = output_char '$'
let stop_latex_math () = output_char '$'
let start_quote () = output_char '`'; output_char '`'
let stop_quote () = output_char '\''; output_char '\''
let start_verbatim inline =
if inline then printf "\\texttt{"
else printf "\\begin{verbatim}\n"
let stop_verbatim inline =
if inline then printf "}"
else printf "\\end{verbatim}\n"
let url addr name =
printf "%s\\footnote{\\url{%s}}"
(match name with
| None -> ""
| Some n -> n)
addr
let indentation n =
if n == 0 then
printf "\\coqdocnoindent\n"
else
let space = 0.5 *. (float n) in
printf "\\coqdocindent{%2.2fem}\n" space
let ident_ref m fid typ s =
let id = if fid <> "" then (m ^ "." ^ fid) else m in
match find_module m with
| Local ->
printf "\\coqref{"; label_ident id;
printf "}{\\coqdoc%s{%s}}" (type_name typ) s
| External m when !prefs.externals ->
printf "\\coqexternalref{"; label_ident fid;
printf "}{%s}{\\coqdoc%s{%s}}" (escaped m) (type_name typ) s
| External _ | Unknown ->
printf "\\coqdoc%s{%s}" (type_name typ) s
let defref m id ty s =
if ty <> Notation then
(printf "\\coqdef{"; label_ident (m ^ "." ^ id);
printf "}{%s}{\\coqdoc%s{%s}}" s (type_name ty) s)
else
Glob file still not able to say the exact extent of the definition
(printf "\\coqdef{"; label_ident (m ^ "." ^ id);
printf "}{%s}{%s}" s s)
let reference s = function
| Def (fullid,typ) ->
defref (get_module false) fullid typ s
| Ref (m,fullid,typ) ->
ident_ref m fullid typ s
s The sublexer buffers symbol characters and attached
uninterpreted ident and try to apply special translation such as ,
predefined , translation " - > " to " \ensuremath{\rightarrow } " or ,
virtually , a user - level translation from " = _ h " to " \ensuremath{=_{h } } "
uninterpreted ident and try to apply special translation such as,
predefined, translation "->" to "\ensuremath{\rightarrow}" or,
virtually, a user-level translation from "=_h" to "\ensuremath{=_{h}}" *)
let output_sublexer_string doescape issymbchar tag s =
let s = if doescape then escaped s else s in
match tag with
| Some ref -> reference s ref
| None -> if issymbchar then output_string s else printf "\\coqdocvar{%s}" s
let last_was_in = ref false
let sublexer c loc =
if c = '*' && !last_was_in then begin
Tokens.flush_sublexer ();
output_char '*'
end else begin
let tag =
try Some (Index.find (get_module false) loc) with Not_found -> None
in
Tokens.output_tagged_symbol_char tag c
end;
last_was_in := false
let sublexer_in_doc c =
if c = '*' && !last_was_in then begin
Tokens.flush_sublexer ();
output_char '*'
end else
Tokens.output_tagged_symbol_char None c;
last_was_in := false
let initialize () =
initialize_tex_html ();
Tokens.token_tree := token_tree_latex;
Tokens.outfun := output_sublexer_string
let translate s =
match Tokens.translate s with Some s -> s | None -> escaped s
let keyword s loc =
printf "\\coqdockw{%s}" (translate s)
let ident s loc =
last_was_in := s = "in";
try
match loc with
| None -> raise Not_found
| Some loc ->
let tag = Index.find (get_module false) loc in
reference (translate s) tag
with Not_found ->
if is_tactic s then
printf "\\coqdoctac{%s}" (translate s)
else if is_keyword s then
printf "\\coqdockw{%s}" (translate s)
then
try
let tag = Index.find_string s in
reference (translate s) tag
with _ -> Tokens.output_tagged_ident_string s
else Tokens.output_tagged_ident_string s
let ident s l =
if !in_title then (
printf "\\texorpdfstring{\\protect";
ident s l;
printf "}{%s}" (translate s))
else
ident s l
let proofbox () = printf "\\ensuremath{\\Box}"
let rec reach_item_level n =
if !item_level < n then begin
printf "\n\\begin{itemize}\n\\item "; incr item_level;
reach_item_level n
end else if !item_level > n then begin
printf "\n\\end{itemize}\n"; decr item_level;
reach_item_level n
end
let item n =
let old_level = !item_level in
reach_item_level n;
if n <= old_level then printf "\n\\item "
let stop_item () = reach_item_level 0
let start_doc () = in_doc := true
let end_doc () = in_doc := false; stop_item ()
let start_emph () = printf "\\textit{"
let stop_emph () = printf "}"
let start_details _ = ()
let stop_details () = ()
let start_comment () = printf "\\begin{coqdoccomment}\n"
let end_comment () = printf "\\end{coqdoccomment}\n"
let start_coq () = printf "\\begin{coqdoccode}\n"
let end_coq () = printf "\\end{coqdoccode}\n"
let section_kind = function
| 1 -> "\\section{"
| 2 -> "\\subsection{"
| 3 -> "\\subsubsection{"
| 4 -> "\\paragraph{"
| _ -> assert false
let section lev f =
stop_item ();
output_string (section_kind lev);
in_title := true; f (); in_title := false;
printf "}\n\n"
let rule () =
printf "\\par\n\\noindent\\hrulefill\\par\n\\noindent{}"
let paragraph () = printf "\n\n"
let line_break () = printf "\\coqdoceol\n"
let empty_line_of_code () = printf "\\coqdocemptyline\n"
let start_inline_coq_block () = line_break (); empty_line_of_code ()
let end_inline_coq_block () = empty_line_of_code ()
let start_inline_coq () = ()
let end_inline_coq () = ()
let make_multi_index () = ()
let make_index () = ()
let make_toc () = printf "\\tableofcontents\n"
end
module Html = struct
let header () =
if !prefs.header_trailer then
if !prefs.header_file_spec then
let cin = open_in !prefs.header_file in
try
while true do
let s = input_line cin in
printf "%s\n" s
done
with End_of_file -> close_in cin
else
begin
printf "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n";
printf "\"-strict.dtd\">\n";
printf "<html xmlns=\"\">\n<head>\n";
printf "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=%s\" />\n" !prefs.encoding.charset;
printf "<link href=\"coqdoc.css\" rel=\"stylesheet\" type=\"text/css\" />\n";
printf "<title>%s</title>\n</head>\n\n" !page_title;
printf "<body>\n\n<div id=\"page\">\n\n<div id=\"header\">\n</div>\n\n";
printf "<div id=\"main\">\n\n"
end
let trailer () =
if !prefs.header_trailer && !prefs.footer_file_spec then
let cin = open_in !prefs.footer_file in
try
while true do
let s = input_line cin in
printf "%s\n" s
done
with End_of_file -> close_in cin
else
begin
if !prefs.index && (get_module false) <> "Index" then
printf "</div>\n\n<div id=\"footer\">\n<hr/><a href=\"%s.html\">Index</a>" !prefs.index_name;
printf "<hr/>This page has been generated by ";
printf "<a href=\"%s\">coqdoc</a>\n" Coq_config.wwwcoq;
printf "</div>\n\n</div>\n\n</body>\n</html>"
end
let start_module () =
let ln = !prefs.lib_name in
if not !prefs.short then begin
let (m,sub) = !current_module in
add_toc_entry (Toc_library (m,sub));
if ln = "" then
printf "<h1 class=\"libtitle\">%s</h1>\n\n" (get_module true)
else
printf "<h1 class=\"libtitle\">%s %s</h1>\n\n" ln (get_module true)
end
let indentation n = for _i = 1 to n do printf " " done
let line_break () = printf "<br/>\n"
let empty_line_of_code () =
printf "\n<br/>\n"
let nbsp () = printf " "
let char = function
| '<' -> printf "<"
| '>' -> printf ">"
| '&' -> printf "&"
| c -> output_char c
let escaped =
let buff = Buffer.create 5 in
fun s ->
Buffer.clear buff;
for i = 0 to String.length s - 1 do
match s.[i] with
| '<' -> Buffer.add_string buff "<"
| '>' -> Buffer.add_string buff ">"
| '&' -> Buffer.add_string buff "&"
| '\"' -> Buffer.add_string buff """
| c -> Buffer.add_char buff c
done;
Buffer.contents buff
let sanitize_name s =
let rec loop esc i =
if i < 0 then if esc then escaped s else s
else match s.[i] with
| 'a'..'z' | 'A'..'Z' | '0'..'9' | '.' | '_' -> loop esc (i-1)
| '<' | '>' | '&' | '\'' | '\"' -> loop true (i-1)
| _ ->
Digest.to_hex (Digest.string s)
in loop false (String.length s - 1)
let latex_char _ = ()
let latex_string _ = ()
let html_char = output_char
let html_string = output_string
let start_latex_math () = ()
let stop_latex_math () = ()
let start_quote () = char '"'
let stop_quote () = start_quote ()
let start_verbatim inline =
if inline then printf "<code>"
else printf "<pre>\n"
let stop_verbatim inline =
if inline then printf "</code>"
else printf "</pre>\n"
let url addr name =
printf "<a href=\"%s\">%s</a>" addr
(match name with
| Some n -> n
| None -> addr)
let ident_ref m fid typ s =
match find_module m with
| Local ->
printf "<a class=\"idref\" href=\"%s.html#%s\">" m (sanitize_name fid);
printf "<span class=\"id\" title=\"%s\">%s</span></a>" typ s
| External m when !prefs.externals ->
printf "<a class=\"idref\" href=\"%s.html#%s\">" m (sanitize_name fid);
printf "<span class=\"id\" title=\"%s\">%s</span></a>" typ s
| External _ | Unknown ->
printf "<span class=\"id\" title=\"%s\">%s</span>" typ s
let reference s r =
match r with
| Def (fullid,ty) ->
let s' = sanitize_name fullid in
printf "<a id=\"%s\" class=\"idref\" href=\"#%s\">" s' s';
printf "<span class=\"id\" title=\"%s\">%s</span></a>" (type_name ty) s
| Ref (m,fullid,ty) ->
ident_ref m fullid (type_name ty) s
let output_sublexer_string doescape issymbchar tag s =
let s = if doescape then escaped s else s in
match tag with
| Some ref -> reference s ref
| None ->
if issymbchar then output_string s
else printf "<span class=\"id\" title=\"var\">%s</span>" s
let sublexer c loc =
let tag =
try Some (Index.find (get_module false) loc) with Not_found -> None
in
Tokens.output_tagged_symbol_char tag c
let sublexer_in_doc c =
Tokens.output_tagged_symbol_char None c
let initialize () =
initialize_tex_html();
Tokens.token_tree := token_tree_html;
Tokens.outfun := output_sublexer_string
let translate s =
match Tokens.translate s with Some s -> s | None -> escaped s
let keyword s loc =
printf "<span class=\"id\" title=\"keyword\">%s</span>" (translate s)
let ident s loc =
try
match loc with
| None -> raise Not_found
| Some loc ->
reference (translate s) (Index.find (get_module false) loc)
with Not_found ->
if is_tactic s then
printf "<span class=\"id\" title=\"tactic\">%s</span>" (translate s)
else if is_keyword s then
printf "<span class=\"id\" title=\"keyword\">%s</span>" (translate s)
try reference (translate s) (Index.find_string s)
with Not_found -> Tokens.output_tagged_ident_string s
else
Tokens.output_tagged_ident_string s
let proofbox () = printf "<font size=-2>☐</font>"
let rec reach_item_level n =
if !item_level < n then begin
printf "<ul class=\"doclist\">\n<li>"; incr item_level;
reach_item_level n
end else if !item_level > n then begin
printf "\n</li>\n</ul>\n"; decr item_level;
reach_item_level n
end
let item n =
let old_level = !item_level in
reach_item_level n;
if n <= old_level then printf "\n</li>\n<li>"
let stop_item () = reach_item_level 0
let start_coq () = if not !prefs.raw_comments then printf "<div class=\"code\">\n"
let end_coq () = if not !prefs.raw_comments then printf "</div>\n"
let start_doc () = in_doc := true;
if not !prefs.raw_comments then
printf "\n<div class=\"doc\">\n"
let end_doc () = in_doc := false;
stop_item ();
if not !prefs.raw_comments then printf "</div>\n"
let start_emph () = printf "<i>"
let stop_emph () = printf "</i>"
let start_details = function
| Some s -> printf "<details><summary>%s</summary>" s
| _ -> printf "<details>"
let stop_details () = printf "</details>"
let start_comment () = printf "<span class=\"comment\">(*"
let end_comment () = printf "*)</span>"
let start_inline_coq () =
if !prefs.inline_notmono then printf "<span class=\"inlinecodenm\">"
else printf "<span class=\"inlinecode\">"
let end_inline_coq () = printf "</span>"
let start_inline_coq_block () = line_break (); start_inline_coq ()
let end_inline_coq_block () = end_inline_coq ()
let paragraph () = printf "\n<div class=\"paragraph\"> </div>\n\n"
let inf_rule assumptions (_,_,midnm) conclusions =
this first function replaces any occurrence of 3 or more spaces
in a row with " & nbsp;"s . We do this to the assumptions so that
people can put multiple rules on a line with nice formatting
in a row with " "s. We do this to the assumptions so that
people can put multiple rules on a line with nice formatting *)
let replace_spaces str =
let rec copy a n = match n with 0 -> [] | n -> (a :: copy a (n - 1)) in
let results = Str.full_split (Str.regexp "[' '][' '][' ']+") str in
let strs = List.map (fun r -> match r with
| Str.Text s -> [s]
| Str.Delim s ->
copy " " (String.length s))
results
in
String.concat "" (List.concat strs)
in
let start_assumption line =
(printf "<tr class=\"infruleassumption\">\n";
printf " <td class=\"infrule\">%s</td>\n" (replace_spaces line)) in
let end_assumption () =
(printf " <td></td>\n";
printf "</tr>\n") in
let rec print_assumptions hyps =
match hyps with
| [] -> start_assumption " "
| [(_,hyp)] -> start_assumption hyp
| ((_,hyp) :: hyps') -> (start_assumption hyp;
end_assumption ();
print_assumptions hyps') in
printf "<center><table class=\"infrule\">\n";
print_assumptions assumptions;
printf " <td class=\"infrulenamecol\" rowspan=\"3\">\n";
(match midnm with
| None -> printf " \n </td>"
| Some s -> printf " %s \n </td>" s);
printf "</tr>\n";
printf "<tr class=\"infrulemiddle\">\n";
printf " <td class=\"infrule\"><hr /></td>\n";
printf "</tr>\n";
print_assumptions conclusions;
end_assumption ();
printf "</table></center>"
let section lev f =
let lab = new_label () in
let r = sprintf "%s.html#%s" (get_module false) lab in
(match !prefs.toc_depth with
| None -> add_toc_entry (Toc_section (lev, f, r))
| Some n -> if lev <= n then add_toc_entry (Toc_section (lev, f, r))
else ());
stop_item ();
printf "<a id=\"%s\"></a><h%d class=\"section\">" lab lev;
f ();
printf "</h%d>\n" lev
let rule () = printf "<hr/>\n"
let index_ref i c =
let idxc = sprintf "%s_%c" i.idx_name c in
!prefs.index_name ^ (if !prefs.multi_index then "_" ^ idxc ^ ".html" else ".html#" ^ idxc)
let letter_index category idx (c,l) =
if l <> [] then begin
let cat = if category && idx <> "global" then "(" ^ idx ^ ")" else "" in
printf "<a id=\"%s_%c\"></a><h2>%s %s</h2>\n" idx c (display_letter c) cat;
List.iter
(fun (id,(text,link,t)) ->
let id' = escaped (prepare_entry id t) in
printf "<a href=\"%s\">%s</a> %s<br/>\n" link id' text) l;
printf "<br/><br/>"
end
let all_letters i = List.iter (letter_index false i.idx_name) i.idx_entries
Construction d'une liste des index ( 1 index global , puis 1
index par catégorie )
index par catégorie) *)
let format_global_index =
Index.map
(fun s (m,t) ->
if t = Library then
let ln = !prefs.lib_name in
if ln <> "" then
"[" ^ String.lowercase_ascii ln ^ "]", m ^ ".html", t
else
"[library]", m ^ ".html", t
else
sprintf "[%s, in <a href=\"%s.html\">%s</a>]" (type_name t) m m ,
sprintf "%s.html#%s" m (sanitize_name s), t)
let format_bytype_index = function
| Library, idx ->
Index.map (fun id m -> "", m ^ ".html", Library) idx
| (t,idx) ->
Index.map
(fun s m ->
let text = sprintf "[in <a href=\"%s.html\">%s</a>]" m m in
(text, sprintf "%s.html#%s" m (sanitize_name s), t)) idx
Impression de la table d'index
let print_index_table_item i =
printf "<tr>\n<td>%s Index</td>\n" (String.capitalize_ascii i.idx_name);
List.iter
(fun (c,l) ->
if l <> [] then
printf "<td><a href=\"%s\">%s</a></td>\n" (index_ref i c)
(display_letter c)
else
printf "<td>%s</td>\n" (display_letter c))
i.idx_entries;
let n = i.idx_size in
printf "<td>(%d %s)</td>\n" n (if n > 1 then "entries" else "entry");
printf "</tr>\n"
let print_index_table idxl =
printf "<table>\n";
List.iter print_index_table_item idxl;
printf "</table>\n"
let make_one_multi_index prt_tbl i =
Attn : make_one_multi_index ...
let idx = i.idx_name in
let one_letter ((c,l) as cl) =
open_out_file (sprintf "%s_%s_%c.html" !prefs.index_name idx c);
if (!prefs.header_trailer) then header ();
prt_tbl (); printf "<hr/>";
letter_index true idx cl;
if List.length l > 30 then begin printf "<hr/>"; prt_tbl () end;
if (!prefs.header_trailer) then trailer ();
close_out_file ()
in
List.iter one_letter i.idx_entries
let make_multi_index () =
let all_index =
let glob,bt = Index.all_entries () in
(format_global_index glob) ::
(List.map format_bytype_index bt) in
let print_table () = print_index_table all_index in
List.iter (make_one_multi_index print_table) all_index
let make_index () =
let all_index =
let glob,bt = Index.all_entries () in
(format_global_index glob) ::
(List.map format_bytype_index bt) in
let print_table () = print_index_table all_index in
let print_one_index i =
if i.idx_size > 0 then begin
printf "<hr/>\n<h1>%s Index</h1>\n" (String.capitalize_ascii i.idx_name);
all_letters i
end
in
set_module "Index" None;
if !prefs.title <> "" then printf "<h1>%s</h1>\n" !prefs.title;
print_table ();
if not (!prefs.multi_index) then
begin
List.iter print_one_index all_index;
printf "<hr/>"; print_table ()
end
let make_toc () =
let ln = !prefs.lib_name in
let make_toc_entry = function
| Toc_library (m,sub) ->
stop_item ();
let ms = match sub with | None -> m | Some s -> m ^ ": " ^ s in
if ln = "" then
printf "<h2><a href=\"%s.html\">%s</a></h2>\n" m ms
else
printf "<h2><a href=\"%s.html\">%s %s</a></h2>\n" m ln ms
| Toc_section (n, f, r) ->
item n;
printf "<a href=\"%s\">" r; f (); printf "</a>\n"
in
printf "<div id=\"toc\">\n";
Queue.iter make_toc_entry toc_q;
stop_item ();
printf "</div>\n"
end
module TeXmacs = struct
let (_ : string Queue.t) =
in_doc := false; Queue.create ()
let header () =
output_string
"(*i This file has been automatically generated with the command \n";
output_string
" "; Array.iter (fun s -> printf "%s " s) Sys.argv; printf " *)\n"
let trailer () = ()
let nbsp () = output_char ' '
let char_true c = match c with
| '\\' -> printf "\\\\"
| '<' -> printf "\\<"
| '|' -> printf "\\|"
| '>' -> printf "\\>"
| _ -> output_char c
let char c = if !in_doc then char_true c else output_char c
let latex_char = char_true
let latex_string = String.iter latex_char
let html_char _ = ()
let html_string _ = ()
let raw_ident s =
for i = 0 to String.length s - 1 do char s.[i] done
let start_module () = ()
let start_latex_math () = printf "<with|mode|math|"
let stop_latex_math () = output_char '>'
let start_verbatim inline = in_doc := true; printf "<\\verbatim>"
let stop_verbatim inline = in_doc := false; printf "</verbatim>"
let url addr name =
printf "%s<\\footnote><\\url>%s</url></footnote>" addr
(match name with
| None -> ""
| Some n -> n)
let start_quote () = output_char '`'; output_char '`'
let stop_quote () = output_char '\''; output_char '\''
let indentation n = ()
let keyword s =
printf "<kw|"; raw_ident s; printf ">"
let ident_true s =
if is_keyword s then keyword s
else raw_ident s
let keyword s loc = keyword s
let ident s _ = if !in_doc then ident_true s else raw_ident s
let output_sublexer_string doescape issymbchar tag s =
if doescape then raw_ident s else output_string s
let sublexer c l =
if !in_doc then Tokens.output_tagged_symbol_char None c else char c
let sublexer_in_doc c =
char c
let initialize () =
Tokens.token_tree := token_tree_texmacs;
Tokens.outfun := output_sublexer_string
let proofbox () = printf "QED"
let rec reach_item_level n =
if !item_level < n then begin
printf "\n<\\itemize>\n<item>"; incr item_level;
reach_item_level n
end else if !item_level > n then begin
printf "\n</itemize>"; decr item_level;
reach_item_level n
end
let item n =
let old_level = !item_level in
reach_item_level n;
if n <= old_level then printf "\n\n<item>"
let stop_item () = reach_item_level 0
let start_doc () = in_doc := true; printf "(** texmacs: "
let end_doc () = stop_item (); in_doc := false; printf " *)"
let start_coq () = ()
let end_coq () = ()
let start_emph () = printf "<with|font shape|italic|"
let stop_emph () = printf ">"
let start_details _ = ()
let stop_details () = ()
let start_comment () = ()
let end_comment () = ()
let section_kind = function
| 1 -> "section"
| 2 -> "subsection"
| 3 -> "subsubsection"
| 4 -> "paragraph"
| _ -> assert false
let section lev f =
stop_item ();
printf "<"; output_string (section_kind lev); printf "|";
f (); printf ">\n\n"
let rule () =
printf "\n<hrule>\n"
let paragraph () = printf "\n\n"
let line_break () = printf "\n"
let empty_line_of_code () = printf "\n"
let start_inline_coq () = printf "<verbatim|["
let end_inline_coq () = printf "]>"
let start_inline_coq_block () = line_break (); start_inline_coq ()
let end_inline_coq_block () = end_inline_coq ()
let make_multi_index () = ()
let make_index () = ()
let make_toc () = ()
end
module Raw = struct
let header () = ()
let trailer () = ()
let nbsp () = output_char ' '
let char = output_char
let latex_char = output_char
let latex_string = output_string
let html_char _ = ()
let html_string _ = ()
let raw_ident s =
for i = 0 to String.length s - 1 do char s.[i] done
let start_module () = ()
let start_latex_math () = ()
let stop_latex_math () = ()
let start_verbatim inline = ()
let stop_verbatim inline = ()
let url addr name =
match name with
| Some n -> printf "%s (%s)" n addr
| None -> printf "%s" addr
let start_quote () = printf "\""
let stop_quote () = printf "\""
let indentation n =
for _i = 1 to n do printf " " done
let keyword s loc = raw_ident s
let ident s loc = raw_ident s
let sublexer c l = char c
let sublexer_in_doc c = char c
let initialize () =
Tokens.token_tree := ref Tokens.empty_ttree;
Tokens.outfun := (fun _ _ _ _ -> failwith "Useless")
let proofbox () = printf "[]"
let item n = printf "- "
let stop_item () = ()
let reach_item_level _ = ()
let start_doc () = printf "(** "
let end_doc () = printf " *)\n"
let start_emph () = printf "_"
let stop_emph () = printf "_"
let start_details _ = ()
let stop_details () = ()
let start_comment () = printf "(*"
let end_comment () = printf "*)"
let start_coq () = ()
let end_coq () = ()
let section_kind =
function
| 1 -> "* "
| 2 -> "** "
| 3 -> "*** "
| 4 -> "**** "
| _ -> assert false
let section lev f =
output_string (section_kind lev);
f ()
let rule () = ()
let paragraph () = printf "\n\n"
let line_break () = printf "\n"
let empty_line_of_code () = printf "\n"
let start_inline_coq () = ()
let end_inline_coq () = ()
let start_inline_coq_block () = line_break (); start_inline_coq ()
let end_inline_coq_block () = end_inline_coq ()
let make_multi_index () = ()
let make_index () = ()
let make_toc () = ()
end
let select f1 f2 f3 f4 x =
match !prefs.targetlang with LaTeX -> f1 x | HTML -> f2 x | TeXmacs -> f3 x | Raw -> f4 x
let push_in_preamble = Latex.push_in_preamble
let header = select Latex.header Html.header TeXmacs.header Raw.header
let trailer = select Latex.trailer Html.trailer TeXmacs.trailer Raw.trailer
let start_module =
select Latex.start_module Html.start_module TeXmacs.start_module Raw.start_module
let start_doc = select Latex.start_doc Html.start_doc TeXmacs.start_doc Raw.start_doc
let end_doc = select Latex.end_doc Html.end_doc TeXmacs.end_doc Raw.end_doc
let start_comment = select Latex.start_comment Html.start_comment TeXmacs.start_comment Raw.start_comment
let end_comment = select Latex.end_comment Html.end_comment TeXmacs.end_comment Raw.end_comment
let start_coq = select Latex.start_coq Html.start_coq TeXmacs.start_coq Raw.start_coq
let end_coq = select Latex.end_coq Html.end_coq TeXmacs.end_coq Raw.end_coq
let start_inline_coq =
select Latex.start_inline_coq Html.start_inline_coq TeXmacs.start_inline_coq Raw.start_inline_coq
let end_inline_coq =
select Latex.end_inline_coq Html.end_inline_coq TeXmacs.end_inline_coq Raw.end_inline_coq
let start_inline_coq_block =
select Latex.start_inline_coq_block Html.start_inline_coq_block
TeXmacs.start_inline_coq_block Raw.start_inline_coq_block
let end_inline_coq_block =
select Latex.end_inline_coq_block Html.end_inline_coq_block TeXmacs.end_inline_coq_block Raw.end_inline_coq_block
let indentation = select Latex.indentation Html.indentation TeXmacs.indentation Raw.indentation
let paragraph = select Latex.paragraph Html.paragraph TeXmacs.paragraph Raw.paragraph
let line_break = select Latex.line_break Html.line_break TeXmacs.line_break Raw.line_break
let empty_line_of_code = select
Latex.empty_line_of_code Html.empty_line_of_code TeXmacs.empty_line_of_code Raw.empty_line_of_code
let section = select Latex.section Html.section TeXmacs.section Raw.section
let item = select Latex.item Html.item TeXmacs.item Raw.item
let stop_item = select Latex.stop_item Html.stop_item TeXmacs.stop_item Raw.stop_item
let reach_item_level = select Latex.reach_item_level Html.reach_item_level TeXmacs.reach_item_level Raw.reach_item_level
let rule = select Latex.rule Html.rule TeXmacs.rule Raw.rule
let nbsp = select Latex.nbsp Html.nbsp TeXmacs.nbsp Raw.nbsp
let char = select Latex.char Html.char TeXmacs.char Raw.char
let keyword = select Latex.keyword Html.keyword TeXmacs.keyword Raw.keyword
let ident = select Latex.ident Html.ident TeXmacs.ident Raw.ident
let sublexer = select Latex.sublexer Html.sublexer TeXmacs.sublexer Raw.sublexer
let sublexer_in_doc = select Latex.sublexer_in_doc Html.sublexer_in_doc TeXmacs.sublexer_in_doc Raw.sublexer_in_doc
let initialize = select Latex.initialize Html.initialize TeXmacs.initialize Raw.initialize
let proofbox = select Latex.proofbox Html.proofbox TeXmacs.proofbox Raw.proofbox
let latex_char = select Latex.latex_char Html.latex_char TeXmacs.latex_char Raw.latex_char
let latex_string =
select Latex.latex_string Html.latex_string TeXmacs.latex_string Raw.latex_string
let html_char = select Latex.html_char Html.html_char TeXmacs.html_char Raw.html_char
let html_string =
select Latex.html_string Html.html_string TeXmacs.html_string Raw.html_string
let start_emph =
select Latex.start_emph Html.start_emph TeXmacs.start_emph Raw.start_emph
let stop_emph =
select Latex.stop_emph Html.stop_emph TeXmacs.stop_emph Raw.stop_emph
let start_details =
select Latex.start_details Html.start_details TeXmacs.start_details Raw.start_details
let stop_details =
select Latex.stop_details Html.stop_details TeXmacs.stop_details Raw.stop_details
let start_latex_math =
select Latex.start_latex_math Html.start_latex_math TeXmacs.start_latex_math Raw.start_latex_math
let stop_latex_math =
select Latex.stop_latex_math Html.stop_latex_math TeXmacs.stop_latex_math Raw.stop_latex_math
let start_verbatim =
select Latex.start_verbatim Html.start_verbatim TeXmacs.start_verbatim Raw.start_verbatim
let stop_verbatim =
select Latex.stop_verbatim Html.stop_verbatim TeXmacs.stop_verbatim Raw.stop_verbatim
let verbatim_char inline =
select (if inline then Latex.char else output_char) Html.char TeXmacs.char Raw.char
let hard_verbatim_char = output_char
let url =
select Latex.url Html.url TeXmacs.url Raw.url
let start_quote =
select Latex.start_quote Html.start_quote TeXmacs.start_quote Raw.start_quote
let stop_quote =
select Latex.stop_quote Html.stop_quote TeXmacs.stop_quote Raw.stop_quote
let inf_rule_dumb assumptions (midsp,midln,midnm) conclusions =
start_verbatim false;
let dumb_line =
function (sp,ln) -> (String.iter char ((String.make sp ' ') ^ ln);
char '\n')
in
(List.iter dumb_line assumptions;
dumb_line (midsp, midln ^ (match midnm with
| Some s -> " " ^ s
| None -> ""));
List.iter dumb_line conclusions);
stop_verbatim false
let inf_rule = select inf_rule_dumb Html.inf_rule inf_rule_dumb inf_rule_dumb
let make_multi_index = select Latex.make_multi_index Html.make_multi_index TeXmacs.make_multi_index Raw.make_multi_index
let make_index = select Latex.make_index Html.make_index TeXmacs.make_index Raw.make_index
let make_toc = select Latex.make_toc Html.make_toc TeXmacs.make_toc Raw.make_toc
|
02227b9cc8e77b7d7159e577957dee09da1fa91d95d2c16826981a830de427bb | deadpendency/deadpendency | PackagistAllSpec.hs | # OPTIONS_GHC -fno - warn - orphans #
module Effect.FetchRegistryRepoInfo.Backend.LanguageRegistryFiles.Packagist.PackagistAllSpec (spec) where
import Common.Model.Dependency.DependencyName
import Common.Model.Dependency.Registry.DependencyRegistryInfo
import DF.Effect.FetchRegistryRepoInfo.Backend.LanguageRegistryFiles.Packagist.Packagist
import DF.Effect.FetchRegistryRepoInfo.Backend.Model.FetchDependencyRegistryError
import Effect.FetchRegistryRepoInfo.Backend.LanguageRegistryFiles.Packagist.PackagistIndex
import Streamly.Prelude qualified as S
import Test.Hspec
spec :: Spec
spec = parallel $
context "when parsing real registry input" $ do
xit "decodes the input correctly for some packages" $ do
packageNames <- fetchPackageNames 100 2000
result <- S.toList $ S.maxThreads 5 $ S.fromParallel $ S.mapM failOnNothingFetch $ S.fromFoldable packageNames
let resultLefts = fst $ partitionEithers result
resultLefts `shouldBe` []
failOnNothingFetch :: DependencyName -> IO (Either FetchDependencyRegistryError DependencyRegistryInfo)
failOnNothingFetch name = do
result <- fetchDependencyPackagist name
case result of
Right (Just a) -> pure $ Right a
Right Nothing -> error $ "failed to fetch: " <> name ^. #_ntText
Left b -> pure $ Left b
| null | https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/dependency-fetcher/test/Effect/FetchRegistryRepoInfo/Backend/LanguageRegistryFiles/Packagist/PackagistAllSpec.hs | haskell | # OPTIONS_GHC -fno - warn - orphans #
module Effect.FetchRegistryRepoInfo.Backend.LanguageRegistryFiles.Packagist.PackagistAllSpec (spec) where
import Common.Model.Dependency.DependencyName
import Common.Model.Dependency.Registry.DependencyRegistryInfo
import DF.Effect.FetchRegistryRepoInfo.Backend.LanguageRegistryFiles.Packagist.Packagist
import DF.Effect.FetchRegistryRepoInfo.Backend.Model.FetchDependencyRegistryError
import Effect.FetchRegistryRepoInfo.Backend.LanguageRegistryFiles.Packagist.PackagistIndex
import Streamly.Prelude qualified as S
import Test.Hspec
spec :: Spec
spec = parallel $
context "when parsing real registry input" $ do
xit "decodes the input correctly for some packages" $ do
packageNames <- fetchPackageNames 100 2000
result <- S.toList $ S.maxThreads 5 $ S.fromParallel $ S.mapM failOnNothingFetch $ S.fromFoldable packageNames
let resultLefts = fst $ partitionEithers result
resultLefts `shouldBe` []
failOnNothingFetch :: DependencyName -> IO (Either FetchDependencyRegistryError DependencyRegistryInfo)
failOnNothingFetch name = do
result <- fetchDependencyPackagist name
case result of
Right (Just a) -> pure $ Right a
Right Nothing -> error $ "failed to fetch: " <> name ^. #_ntText
Left b -> pure $ Left b
| |
5b550b5eccfb5815346e7dc6ee8cd62605e63358f337b32959421aea3926267a | dramforever/finlog | Type.hs | # LANGUAGE TemplateHaskell #
module Finlog.Frontend.Type where
import Control.Monad.Except
import Data.Foldable
import qualified Data.HashMap.Strict as HM
import Data.Maybe
import Finlog.Framework.DAG
import Finlog.Frontend.AST
import Finlog.Utils.Mark
import GHC.Stack
import Lens.Micro.Platform
literalType :: Literal -> Typ
literalType (IntLitL (IntLit _ intTy)) = IntType intTy
badUnaryOp :: BinOp -> Typ -> CompilerError
badUnaryOp op rhs =
CompilerError
("Bad unary operation:"
<+> codeAnn (viaShow op <+> viaShow rhs))
[]
badBinOp :: BinOp -> Typ -> Typ -> CompilerError
badBinOp op lhs rhs =
CompilerError
("Bad binary operation:"
<+> codeAnn (viaShow lhs <+> viaShow op <+> viaShow rhs))
[]
condDiffer :: Typ -> Typ -> CompilerError
condDiffer t1 t2 =
CompilerError
("Differing types in conditional" <+> codeAnn (viaShow t1)
<+> "and" <+> codeAnn (viaShow t2))
[]
-- TODO: Simplify this
combineInt :: Typ -> Typ -> Maybe IntType
combineInt (UnsignedTy s1) (UnsignedTy s2) = Just $ Unsigned (s1 `max` s2)
combineInt (UnsignedTy s1) (SignedTy s2) = Just $ Unsigned (s1 `max` s2)
combineInt (SignedTy s1) (UnsignedTy s2) = Just $ Unsigned (s1 `max` s2)
combineInt (SignedTy s1) (SignedTy s2) = Just $ Signed (s1 `max` s2)
combineInt _ _ = Nothing
inferBin :: BinOp -> Typ -> Typ -> Maybe Typ
inferBin BinArith lhs rhs = IntType <$> combineInt lhs rhs
inferBin BinBitComb BitTy BitTy = Just BitTy
inferBin BinBitComb lhs rhs = IntType <$> combineInt lhs rhs
inferBin BinComp lhs rhs
| lhs == rhs = Just BitTy
| otherwise = Nothing
inferBin BinLogic (IntType _) (IntType _) = Just BitTy
inferBin BinLogic _ _ = Nothing
inferExprF :: ExprF Typ -> Either CompilerError Typ
inferExprF (LitE lit) = Right $ literalType lit
inferExprF (InputE _ typ) = Right typ
inferExprF (UnaryE BNot rhs@(IntType _)) = Right rhs
inferExprF ( UnaryE op@BNot rhs ) = Left $ badUnaryOp op rhs
inferExprF (UnaryE LNot (IntType _)) = Right BitTy
inferExprF ( UnaryE op@LNot rhs ) = Left $ badUnaryOp op rhs
inferExprF (BinE op lhs rhs) =
case inferBin op lhs rhs of
Just ty -> Right ty
Nothing -> Left $ badBinOp op lhs rhs
inferExprF (CondE _cond lhs rhs) =
if lhs == rhs
then Right lhs
else Left $ condDiffer lhs rhs
TODO
assignable :: Typ -> Typ -> Bool
assignable = (==)
data TypeMap = TypeMap
{ _inameTypeMap :: HM.HashMap IName Typ
, _regTypeMap :: HM.HashMap Reg Typ
}
deriving (Show, Eq)
$(makeClassy ''TypeMap)
initialTypeMap :: TypeMap
initialTypeMap = TypeMap HM.empty HM.empty
inameType :: HasTypeMap s => IName -> Lens' s (Maybe Typ)
inameType iname = inameTypeMap . at iname
regType :: HasTypeMap s => Reg -> Lens' s (Maybe Typ)
regType reg = regTypeMap . at reg
data Task = Open IName | Close IName
deriving (Show)
infer :: (HasCallStack, _) => IName -> m Typ
infer iname = do
go [Open iname]
fromJust <$> use (inameType iname)
where
go [] = pure ()
go (Open i: rest) = do
use (inameType i) >>= \case
Just _ -> go rest
Nothing -> fromJust <$> use (fwdMap . at i) >>= \case
RegItem reg -> do
ty <- fromJust <$> use (regType reg)
inameType i ?= ty
go rest
ComplexItem exprf ->
go $ (Open <$> toList exprf) ++ Close i : rest
go (Close i : rest) = do
fromJust <$> use (fwdMap . at i) >>= \case
RegItem _ -> error "infer: Unexpected RegItem"
ComplexItem exprf -> do
ty <- traverse (fmap fromJust . use . inameType) exprf
res <- liftEither $ inferExprF ty
inameType i ?= res
go rest
| null | https://raw.githubusercontent.com/dramforever/finlog/ca642dfa7ea89b131ab13b6b267fabf317e12d9c/src/Finlog/Frontend/Type.hs | haskell | TODO: Simplify this | # LANGUAGE TemplateHaskell #
module Finlog.Frontend.Type where
import Control.Monad.Except
import Data.Foldable
import qualified Data.HashMap.Strict as HM
import Data.Maybe
import Finlog.Framework.DAG
import Finlog.Frontend.AST
import Finlog.Utils.Mark
import GHC.Stack
import Lens.Micro.Platform
literalType :: Literal -> Typ
literalType (IntLitL (IntLit _ intTy)) = IntType intTy
badUnaryOp :: BinOp -> Typ -> CompilerError
badUnaryOp op rhs =
CompilerError
("Bad unary operation:"
<+> codeAnn (viaShow op <+> viaShow rhs))
[]
badBinOp :: BinOp -> Typ -> Typ -> CompilerError
badBinOp op lhs rhs =
CompilerError
("Bad binary operation:"
<+> codeAnn (viaShow lhs <+> viaShow op <+> viaShow rhs))
[]
condDiffer :: Typ -> Typ -> CompilerError
condDiffer t1 t2 =
CompilerError
("Differing types in conditional" <+> codeAnn (viaShow t1)
<+> "and" <+> codeAnn (viaShow t2))
[]
combineInt :: Typ -> Typ -> Maybe IntType
combineInt (UnsignedTy s1) (UnsignedTy s2) = Just $ Unsigned (s1 `max` s2)
combineInt (UnsignedTy s1) (SignedTy s2) = Just $ Unsigned (s1 `max` s2)
combineInt (SignedTy s1) (UnsignedTy s2) = Just $ Unsigned (s1 `max` s2)
combineInt (SignedTy s1) (SignedTy s2) = Just $ Signed (s1 `max` s2)
combineInt _ _ = Nothing
inferBin :: BinOp -> Typ -> Typ -> Maybe Typ
inferBin BinArith lhs rhs = IntType <$> combineInt lhs rhs
inferBin BinBitComb BitTy BitTy = Just BitTy
inferBin BinBitComb lhs rhs = IntType <$> combineInt lhs rhs
inferBin BinComp lhs rhs
| lhs == rhs = Just BitTy
| otherwise = Nothing
inferBin BinLogic (IntType _) (IntType _) = Just BitTy
inferBin BinLogic _ _ = Nothing
inferExprF :: ExprF Typ -> Either CompilerError Typ
inferExprF (LitE lit) = Right $ literalType lit
inferExprF (InputE _ typ) = Right typ
inferExprF (UnaryE BNot rhs@(IntType _)) = Right rhs
inferExprF ( UnaryE op@BNot rhs ) = Left $ badUnaryOp op rhs
inferExprF (UnaryE LNot (IntType _)) = Right BitTy
inferExprF ( UnaryE op@LNot rhs ) = Left $ badUnaryOp op rhs
inferExprF (BinE op lhs rhs) =
case inferBin op lhs rhs of
Just ty -> Right ty
Nothing -> Left $ badBinOp op lhs rhs
inferExprF (CondE _cond lhs rhs) =
if lhs == rhs
then Right lhs
else Left $ condDiffer lhs rhs
TODO
assignable :: Typ -> Typ -> Bool
assignable = (==)
data TypeMap = TypeMap
{ _inameTypeMap :: HM.HashMap IName Typ
, _regTypeMap :: HM.HashMap Reg Typ
}
deriving (Show, Eq)
$(makeClassy ''TypeMap)
initialTypeMap :: TypeMap
initialTypeMap = TypeMap HM.empty HM.empty
inameType :: HasTypeMap s => IName -> Lens' s (Maybe Typ)
inameType iname = inameTypeMap . at iname
regType :: HasTypeMap s => Reg -> Lens' s (Maybe Typ)
regType reg = regTypeMap . at reg
data Task = Open IName | Close IName
deriving (Show)
infer :: (HasCallStack, _) => IName -> m Typ
infer iname = do
go [Open iname]
fromJust <$> use (inameType iname)
where
go [] = pure ()
go (Open i: rest) = do
use (inameType i) >>= \case
Just _ -> go rest
Nothing -> fromJust <$> use (fwdMap . at i) >>= \case
RegItem reg -> do
ty <- fromJust <$> use (regType reg)
inameType i ?= ty
go rest
ComplexItem exprf ->
go $ (Open <$> toList exprf) ++ Close i : rest
go (Close i : rest) = do
fromJust <$> use (fwdMap . at i) >>= \case
RegItem _ -> error "infer: Unexpected RegItem"
ComplexItem exprf -> do
ty <- traverse (fmap fromJust . use . inameType) exprf
res <- liftEither $ inferExprF ty
inameType i ?= res
go rest
|
e463cbd7d004491409279a6b4a93bf345106c551d191a492c995cec23e4a2926 | TorXakis/TorXakis | ModelDecl.hs |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
--------------------------------------------------------------------------------
-- |
Module : TorXakis . . ModelDecl
Copyright : ( c ) TNO and Radboud University
License : BSD3 ( see the file license.txt )
--
Maintainer : ( Embedded Systems Innovation by )
-- Stability : experimental
-- Portability : portable
--
Parser for model declarations .
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module TorXakis.Parser.ModelDecl
(modelDeclP)
where
import TorXakis.Parser.BExpDecl
import TorXakis.Parser.ChanRef
import TorXakis.Parser.Common
import TorXakis.Parser.Data
-- | Parser for model declarations.
modelDeclP :: TxsParser ModelDecl
modelDeclP = declP "MODELDEF" $ \n l -> do
is <- chansInDecl
os <- chansOutDecl
ys <- chansSyncDecl
txsSymbol "BEHAVIOUR"
mkModelDecl n l is os ys <$> bexpDeclP
| null | https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/sys/txs-compiler/src/TorXakis/Parser/ModelDecl.hs | haskell | ------------------------------------------------------------------------------
|
Stability : experimental
Portability : portable
------------------------------------------------------------------------------
# LANGUAGE OverloadedStrings #
| Parser for model declarations. |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
Module : TorXakis . . ModelDecl
Copyright : ( c ) TNO and Radboud University
License : BSD3 ( see the file license.txt )
Maintainer : ( Embedded Systems Innovation by )
Parser for model declarations .
module TorXakis.Parser.ModelDecl
(modelDeclP)
where
import TorXakis.Parser.BExpDecl
import TorXakis.Parser.ChanRef
import TorXakis.Parser.Common
import TorXakis.Parser.Data
modelDeclP :: TxsParser ModelDecl
modelDeclP = declP "MODELDEF" $ \n l -> do
is <- chansInDecl
os <- chansOutDecl
ys <- chansSyncDecl
txsSymbol "BEHAVIOUR"
mkModelDecl n l is os ys <$> bexpDeclP
|
f60667f0704df53bc637e1082234d0cd4cd146c59c7e6062c4bb62580e0b972c | basho/merge_index | mi_locks.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2007 - 2012 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
%% @odc A functional locking structure, used to make segment and
%% buffer locking more convient.
-module(mi_locks).
-include("merge_index.hrl").
-author("Rusty Klophaus <>").
-export([
new/0,
claim/2,
claim_many/2,
release/2,
when_free/3
]).
-record(lock, {
key,
count,
funs=[]
}).
new() -> [].
claim_many(Keys, Locks) ->
lists:foldl(fun claim/2, Locks, Keys).
claim(Key, Locks) ->
case lists:keyfind(Key, #lock.key, Locks) of
Lock = #lock { count=Count } ->
NewLock = Lock#lock { count=Count + 1 },
lists:keystore(Key, #lock.key, Locks, NewLock);
false ->
NewLock = #lock { key=Key, count=1, funs=[] },
lists:keystore(Key, #lock.key, Locks, NewLock)
end.
release(Key, Locks) ->
case lists:keyfind(Key, #lock.key, Locks) of
#lock { count=1, funs=Funs } ->
[X() || X <- Funs],
lists:keydelete(Key, #lock.key, Locks);
Lock = #lock { count=Count } ->
NewLock = Lock#lock { count = Count - 1 },
lists:keystore(Key, #lock.key, Locks, NewLock);
false ->
throw({lock_does_not_exist, Key})
end.
%% Run the provided function when the key is free. If the key is
%% currently free, then this is run immeditaely.
when_free(Key, Fun, Locks) ->
case lists:keyfind(Key, #lock.key, Locks) of
false ->
Fun(),
Locks;
#lock { count=0, funs=Funs } ->
[X() || X <- [Fun|Funs]],
lists:keydelete(Key, #lock.key, Locks);
Lock = #lock { funs=Funs} ->
NewLock = Lock#lock { funs=[Fun|Funs] },
lists:keystore(Key, #lock.key, Locks, NewLock)
end.
| null | https://raw.githubusercontent.com/basho/merge_index/b701dde5c28956c3b629411e5ff7e50cbb5cb4b3/src/mi_locks.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@odc A functional locking structure, used to make segment and
buffer locking more convient.
Run the provided function when the key is free. If the key is
currently free, then this is run immeditaely. | Copyright ( c ) 2007 - 2012 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(mi_locks).
-include("merge_index.hrl").
-author("Rusty Klophaus <>").
-export([
new/0,
claim/2,
claim_many/2,
release/2,
when_free/3
]).
-record(lock, {
key,
count,
funs=[]
}).
new() -> [].
claim_many(Keys, Locks) ->
lists:foldl(fun claim/2, Locks, Keys).
claim(Key, Locks) ->
case lists:keyfind(Key, #lock.key, Locks) of
Lock = #lock { count=Count } ->
NewLock = Lock#lock { count=Count + 1 },
lists:keystore(Key, #lock.key, Locks, NewLock);
false ->
NewLock = #lock { key=Key, count=1, funs=[] },
lists:keystore(Key, #lock.key, Locks, NewLock)
end.
release(Key, Locks) ->
case lists:keyfind(Key, #lock.key, Locks) of
#lock { count=1, funs=Funs } ->
[X() || X <- Funs],
lists:keydelete(Key, #lock.key, Locks);
Lock = #lock { count=Count } ->
NewLock = Lock#lock { count = Count - 1 },
lists:keystore(Key, #lock.key, Locks, NewLock);
false ->
throw({lock_does_not_exist, Key})
end.
when_free(Key, Fun, Locks) ->
case lists:keyfind(Key, #lock.key, Locks) of
false ->
Fun(),
Locks;
#lock { count=0, funs=Funs } ->
[X() || X <- [Fun|Funs]],
lists:keydelete(Key, #lock.key, Locks);
Lock = #lock { funs=Funs} ->
NewLock = Lock#lock { funs=[Fun|Funs] },
lists:keystore(Key, #lock.key, Locks, NewLock)
end.
|
f2989257a6a7f9a49299b2cc1eda1d42381b9c0321288fb7264a64c2de6bfc50 | hraberg/deuce | lists.clj | (ns deuce.test.lists
(:use [deuce.test.common]))
" 5 Lists"[1 ]
[ 1 ]
(with-fresh-emacs)
(repl predicates-on-lists
(listp '(1)) ⇒ true
(listp '()) ⇒ true
(null '(1)) ⇒ nil
(null '() ⇒ true))
(repl accessing-elements-on-lists
(car '(a b c)) ⇒ 'a
(cdr '()) ⇒ nil
(nth 2 '(1 2 3 4)) ⇒ 3
(nth 10 '(1 2 3 4)) ⇒ nil
(nth -3 '(1 2 3 4)) ⇒ 1
(nthcdr 1 '(1 2 3 4)) ⇒ '(2 3 4)
(nthcdr 10 '(1 2 3 4)) ⇒ nil
(nthcdr -3 '(1 2 3 4)) ⇒ '(1 2 3 4))
(repl building-cons-cells-and-lists
(cons 1 '(2)) ⇒ '(1 2)
(cons 1 '()) ⇒ '(1)
(cons 1 2) ⇒ '(1 . 2)
(list 1 2 3 4 5) ⇒ '(1 2 3 4 5)
(list 1 2 '(3 4 5) 'foo) ⇒ '(1 2 (3 4 5) foo)
(list) ⇒ nil
(make-list 3 'pigs) ⇒ '(pigs pigs pigs)
(make-list 0 'pigs) ⇒ nil
(setq l (make-list 3 '(a b))) ⇒ '((a b) (a b) (a b))
(defun cadr (x) (car (cdr x)))
(eq (car l) (cadr l)) ⇒ true
(setq trees '(pine oak)) ⇒ '(pine oak)
(setq more-trees (append '(maple birch) trees))
⇒ '(maple birch pine oak)
trees ⇒ '(pine oak)
more-trees ⇒ '(maple birch pine oak)
(eq trees (cdr (cdr more-trees)))
⇒ true
trees ⇒ '(pine oak)
(setq wood (append trees nil)) ⇒ '(pine oak)
wood ⇒ '(pine oak)
(eq wood trees) ⇒ true
(append #el/vec [a b] "cd" nil)
⇒ '(a b 99 100)
(apply 'append '((a b c) nil (x y z) nil))
⇒ '(a b c x y z)
(append) ⇒ nil
(append '(x y) 'z) ⇒ '(x y . z)
(append '(x y) #el/vec [z])
⇒ '(x y . #el/vec [z])
(setq x '(1 2 3 4)) ⇒ '(1 2 3 4)
(reverse x) ⇒ '(4 3 2 1)
x ⇒ '(1 2 3 4)) | null | https://raw.githubusercontent.com/hraberg/deuce/9d507adb6c68c0f5c19ad79fa6ded9593c082575/test/deuce/test/lists.clj | clojure | (ns deuce.test.lists
(:use [deuce.test.common]))
" 5 Lists"[1 ]
[ 1 ]
(with-fresh-emacs)
(repl predicates-on-lists
(listp '(1)) ⇒ true
(listp '()) ⇒ true
(null '(1)) ⇒ nil
(null '() ⇒ true))
(repl accessing-elements-on-lists
(car '(a b c)) ⇒ 'a
(cdr '()) ⇒ nil
(nth 2 '(1 2 3 4)) ⇒ 3
(nth 10 '(1 2 3 4)) ⇒ nil
(nth -3 '(1 2 3 4)) ⇒ 1
(nthcdr 1 '(1 2 3 4)) ⇒ '(2 3 4)
(nthcdr 10 '(1 2 3 4)) ⇒ nil
(nthcdr -3 '(1 2 3 4)) ⇒ '(1 2 3 4))
(repl building-cons-cells-and-lists
(cons 1 '(2)) ⇒ '(1 2)
(cons 1 '()) ⇒ '(1)
(cons 1 2) ⇒ '(1 . 2)
(list 1 2 3 4 5) ⇒ '(1 2 3 4 5)
(list 1 2 '(3 4 5) 'foo) ⇒ '(1 2 (3 4 5) foo)
(list) ⇒ nil
(make-list 3 'pigs) ⇒ '(pigs pigs pigs)
(make-list 0 'pigs) ⇒ nil
(setq l (make-list 3 '(a b))) ⇒ '((a b) (a b) (a b))
(defun cadr (x) (car (cdr x)))
(eq (car l) (cadr l)) ⇒ true
(setq trees '(pine oak)) ⇒ '(pine oak)
(setq more-trees (append '(maple birch) trees))
⇒ '(maple birch pine oak)
trees ⇒ '(pine oak)
more-trees ⇒ '(maple birch pine oak)
(eq trees (cdr (cdr more-trees)))
⇒ true
trees ⇒ '(pine oak)
(setq wood (append trees nil)) ⇒ '(pine oak)
wood ⇒ '(pine oak)
(eq wood trees) ⇒ true
(append #el/vec [a b] "cd" nil)
⇒ '(a b 99 100)
(apply 'append '((a b c) nil (x y z) nil))
⇒ '(a b c x y z)
(append) ⇒ nil
(append '(x y) 'z) ⇒ '(x y . z)
(append '(x y) #el/vec [z])
⇒ '(x y . #el/vec [z])
(setq x '(1 2 3 4)) ⇒ '(1 2 3 4)
(reverse x) ⇒ '(4 3 2 1)
x ⇒ '(1 2 3 4)) | |
de9208ca471fd9cbc2fd0425e03016f17a236e3ee064bb6edddf7a7c0d5f5008 | fulcro-legacy/semantic-ui-wrapper | ui_item.cljs | (ns fulcrologic.semantic-ui.views.item.ui-item
(:require
[fulcrologic.semantic-ui.factory-helpers :as h]
["semantic-ui-react/dist/commonjs/views/Item/Item" :default Item]))
(def ui-item
"An item view presents large collections of site content for display.
Props:
- as (custom): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- content (custom): Shorthand for ItemContent component.
- description (custom): Shorthand for ItemDescription component.
- extra (custom): Shorthand for ItemExtra component.
- header (custom): Shorthand for ItemHeader component.
- image (custom): Shorthand for ItemImage component.
- meta (custom): Shorthand for ItemMeta component."
(h/factory-apply Item))
| null | https://raw.githubusercontent.com/fulcro-legacy/semantic-ui-wrapper/b0473480ddfff18496df086bf506099ac897f18f/semantic-ui-wrappers-shadow/src/main/fulcrologic/semantic_ui/views/item/ui_item.cljs | clojure | (ns fulcrologic.semantic-ui.views.item.ui-item
(:require
[fulcrologic.semantic-ui.factory-helpers :as h]
["semantic-ui-react/dist/commonjs/views/Item/Item" :default Item]))
(def ui-item
"An item view presents large collections of site content for display.
Props:
- as (custom): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- content (custom): Shorthand for ItemContent component.
- description (custom): Shorthand for ItemDescription component.
- extra (custom): Shorthand for ItemExtra component.
- header (custom): Shorthand for ItemHeader component.
- image (custom): Shorthand for ItemImage component.
- meta (custom): Shorthand for ItemMeta component."
(h/factory-apply Item))
| |
7b694afa865584aa0905494494809a058c527c4d8685df4cc9932da7b116450d | Soyn/sicp | Ex2.41.rkt | #lang racket
;----------Support Function--------------------------------------
(define (accumulate op initial sequence)
(if (null? sequence)
initial
( op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (enumerate-interval low high)
(if (> low high)
null
(cons low (enumerate-interval (+ low 1) high))))
(define (flatmap proc seq)
(accumulate append null (map proc seq)))
(define (unique-pairs n) ;生成序列(i, j),其中j < i < n
(flatmap (lambda (i)
(map (lambda (j) (list i j))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n)))
(define (filter predicate sequence)
(cond ((null? sequence) null)
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
;----------Support Function End-------------------------------------
;------------Ex 2.41------------------------------------------------
(define (ordered-triples-sum n s)
(filter (lambda (list) ( = (accumulate + 0 list) s))
(flatmap
(lambda(i)
(flatmap (lambda (j)
(map (lambda (k) (list i j k))
(enumerate-interval 1 (- j 1))))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n))))
-----------Answer Test---------------------------
(ordered-triples-sum 10 6)
(enumerate-interval 2 10) | null | https://raw.githubusercontent.com/Soyn/sicp/d2aa6e3b053f6d4c8150ab1b033a18f61fca7e1b/CH2/CH2.2/Ex2.41.rkt | racket | ----------Support Function--------------------------------------
生成序列(i, j),其中j < i < n
----------Support Function End-------------------------------------
------------Ex 2.41------------------------------------------------ | #lang racket
(define (accumulate op initial sequence)
(if (null? sequence)
initial
( op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (enumerate-interval low high)
(if (> low high)
null
(cons low (enumerate-interval (+ low 1) high))))
(define (flatmap proc seq)
(accumulate append null (map proc seq)))
(flatmap (lambda (i)
(map (lambda (j) (list i j))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n)))
(define (filter predicate sequence)
(cond ((null? sequence) null)
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
(define (ordered-triples-sum n s)
(filter (lambda (list) ( = (accumulate + 0 list) s))
(flatmap
(lambda(i)
(flatmap (lambda (j)
(map (lambda (k) (list i j k))
(enumerate-interval 1 (- j 1))))
(enumerate-interval 1 (- i 1))))
(enumerate-interval 1 n))))
-----------Answer Test---------------------------
(ordered-triples-sum 10 6)
(enumerate-interval 2 10) |
5e02d32a537d1a183883e88e974eee1a962336aebe10a70c4c46ae8bfdd17459 | vlstill/hsExprTest | IO.hs | # LANGUAGE Safe , NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - orphans #
( c ) 2016 - 2018
module Test.Testable.IO (
* IO replacements
IO
, getLine
, getChar
, getContents
, interact
, readIO
, readLn
, putChar
, putStr
, putStrLn
, print
, readFile
, writeFile
, appendFile
-- * running
, runIOLines
, runIOLines'
) where
import Test.Testable.IO.Base
import Data.Functor ( Functor, fmap )
import Control.Applicative ( Applicative, pure, (<*>), liftA2 )
import Control.Monad ( Monad, (>>=) )
import Control.Monad.Fail ( MonadFail (..) )
import Data.Monoid ( Monoid, mempty, mappend )
import Data.Semigroup ( Semigroup, (<>) )
import Prelude ( error )
instance Functor IO where
fmap = fmapIO
instance Applicative IO where
pure = pureIO
(<*>) = appIO
instance Monad IO where
(>>=) = bindIO
instance Semigroup a => Semigroup (IO a) where
(<>) = liftA2 (<>)
instance (Semigroup a, Monoid a) => Monoid (IO a) where
mempty = pure mempty
mappend = (<>)
instance MonadFail IO where
fail = error
| null | https://raw.githubusercontent.com/vlstill/hsExprTest/0c7754979cf837d48f5740674639e2decb96e547/testlib/Test/Testable/IO.hs | haskell | * running | # LANGUAGE Safe , NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - orphans #
( c ) 2016 - 2018
module Test.Testable.IO (
* IO replacements
IO
, getLine
, getChar
, getContents
, interact
, readIO
, readLn
, putChar
, putStr
, putStrLn
, print
, readFile
, writeFile
, appendFile
, runIOLines
, runIOLines'
) where
import Test.Testable.IO.Base
import Data.Functor ( Functor, fmap )
import Control.Applicative ( Applicative, pure, (<*>), liftA2 )
import Control.Monad ( Monad, (>>=) )
import Control.Monad.Fail ( MonadFail (..) )
import Data.Monoid ( Monoid, mempty, mappend )
import Data.Semigroup ( Semigroup, (<>) )
import Prelude ( error )
instance Functor IO where
fmap = fmapIO
instance Applicative IO where
pure = pureIO
(<*>) = appIO
instance Monad IO where
(>>=) = bindIO
instance Semigroup a => Semigroup (IO a) where
(<>) = liftA2 (<>)
instance (Semigroup a, Monoid a) => Monoid (IO a) where
mempty = pure mempty
mappend = (<>)
instance MonadFail IO where
fail = error
|
df9903eabaa127e3c93bad5038ae55c4af753479064de9219907c4acb6c0f777 | facebook/pyre-check | callGraph.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
CallGraph : defines the call graph of a callable ( function or method ) , which
* stores the set of calles for each call site .
*
* This also implements the logic to statically compute the call graph , given a
* function definition .
*
* Note that the call graph is highly tuned for the taint analysis and might be
* unsound for other analyses .
* stores the set of calles for each call site.
*
* This also implements the logic to statically compute the call graph, given a
* function definition.
*
* Note that the call graph is highly tuned for the taint analysis and might be
* unsound for other analyses.
*)
open Core
open Data_structures
open Analysis
open Ast
open Statement
open Expression
open Pyre
(** Represents type information about the return type of a call. *)
module ReturnType = struct
type t = {
is_boolean: bool;
is_integer: bool;
is_float: bool;
is_enumeration: bool;
}
[@@deriving compare, eq]
let pp formatter { is_boolean; is_integer; is_float; is_enumeration } =
let add_if condition tag tags =
if condition then
tag :: tags
else
tags
in
[]
|> add_if is_enumeration "enum"
|> add_if is_float "float"
|> add_if is_integer "int"
|> add_if is_boolean "bool"
|> String.concat ~sep:"|"
|> Format.fprintf formatter "{%s}"
let show = Format.asprintf "%a" pp
let none = { is_boolean = false; is_integer = false; is_float = false; is_enumeration = false }
let any = none
let bool = { is_boolean = true; is_integer = false; is_float = false; is_enumeration = false }
let integer = { is_boolean = false; is_integer = true; is_float = true; is_enumeration = false }
let from_annotation ~resolution annotation =
let matches_at_leaves ~f annotation =
let rec matches_at_leaves ~f annotation =
match annotation with
| Type.Any
| Type.Bottom ->
false
| Type.Union [Type.NoneType; annotation]
| Type.Union [annotation; Type.NoneType]
| Type.Parametric { name = "typing.Awaitable"; parameters = [Single annotation] } ->
matches_at_leaves ~f annotation
| Type.Tuple (Concatenation concatenation) ->
Type.OrderedTypes.Concatenation.extract_sole_unbounded_annotation concatenation
>>| (fun element -> matches_at_leaves ~f element)
|> Option.value ~default:(f annotation)
| Type.Tuple (Type.OrderedTypes.Concrete annotations) ->
List.for_all annotations ~f:(matches_at_leaves ~f)
| annotation -> f annotation
in
matches_at_leaves ~f annotation
in
try
let is_boolean =
matches_at_leaves annotation ~f:(fun left ->
GlobalResolution.less_or_equal resolution ~left ~right:Type.bool)
in
let is_integer =
matches_at_leaves annotation ~f:(fun left ->
GlobalResolution.less_or_equal resolution ~left ~right:Type.integer)
in
let is_float =
matches_at_leaves annotation ~f:(fun left ->
GlobalResolution.less_or_equal resolution ~left ~right:Type.float)
in
let is_enumeration =
matches_at_leaves annotation ~f:(fun left ->
GlobalResolution.less_or_equal resolution ~left ~right:Type.enumeration)
in
{ is_boolean; is_integer; is_float; is_enumeration }
with
| Analysis.ClassHierarchy.Untracked untracked_type ->
Log.warning
"Found untracked type `%s` when checking the return type `%a` of a call. The return type \
will NOT be considered a scalar, which could lead to missing breadcrumbs."
untracked_type
Type.pp
annotation;
none
(* Try to infer the return type from the callable type, otherwise lazily fallback
* to the resolved return type. *)
let from_callable_with_fallback ~resolution ~callable_type ~return_type =
let annotation =
match callable_type with
| Type.Callable { implementation = { annotation; _ }; overloads = []; _ }
when Type.Variable.all_variables_are_resolved annotation ->
annotation
| _ -> Lazy.force return_type
in
from_annotation ~resolution:(Resolution.global_resolution resolution) annotation
end
(** A specific target of a given call, with extra information. *)
module CallTarget = struct
type t = {
target: Target.t;
(* True if the call has an implicit receiver.
* For instance, `x.foo()` should be treated as `C.foo(x)`. *)
implicit_self: bool;
(* True if this is an implicit call to the `__call__` method. *)
implicit_dunder_call: bool;
(* The textual order index of the call in the function. *)
index: int;
(* The return type of the call expression, or `None` for object targets. *)
return_type: ReturnType.t option;
(* The type of the receiver object at this call site, if any. *)
receiver_type: Type.t option;
}
[@@deriving compare, eq, show { with_path = false }]
let target { target; _ } = target
let equal_ignoring_indices left right = equal left { right with index = left.index }
let dedup_and_sort targets =
targets
|> List.sort ~compare
|> List.remove_consecutive_duplicates ~which_to_keep:`First ~equal:equal_ignoring_indices
let create
?(implicit_self = false)
?(implicit_dunder_call = false)
?(index = 0)
?(return_type = Some ReturnType.any)
?receiver_type
target
=
{ target; implicit_self; implicit_dunder_call; index; return_type; receiver_type }
let equal_ignoring_types
{
target = target_left;
implicit_self = implicit_self_left;
implicit_dunder_call = implicit_dunder_call_left;
index = index_left;
return_type = _;
receiver_type = _;
}
{
target = target_right;
implicit_self = implicit_self_right;
implicit_dunder_call = implicit_dunder_call_right;
index = index_right;
return_type = _;
receiver_type = _;
}
=
Target.equal target_left target_right
&& implicit_self_left == implicit_self_right
&& implicit_dunder_call_left == implicit_dunder_call_right
&& index_left == index_right
end
(** Information about an argument being a callable. *)
module HigherOrderParameter = struct
type t = {
index: int;
call_targets: CallTarget.t list;
True if at least one callee could not be resolved .
* Usually indicates missing type information at the call site .
* Usually indicates missing type information at the call site. *)
unresolved: bool;
}
[@@deriving eq, show { with_path = false }]
let all_targets { call_targets; _ } = List.map ~f:CallTarget.target call_targets
let equal_ignoring_types
{ index = index_left; call_targets = call_targets_left; unresolved = unresolved_left }
{ index = index_right; call_targets = call_targets_right; unresolved = unresolved_right }
=
index_left == index_right
&& List.equal CallTarget.equal_ignoring_types call_targets_left call_targets_right
&& unresolved_left == unresolved_right
let join
{ index; call_targets = call_targets_left; unresolved = unresolved_left }
{ index = _; call_targets = call_targets_right; unresolved = unresolved_right }
=
{
index;
call_targets = List.rev_append call_targets_left call_targets_right;
unresolved = unresolved_left || unresolved_right;
}
let deduplicate { index; call_targets; unresolved } =
{ index; call_targets = CallTarget.dedup_and_sort call_targets; unresolved }
end
* Mapping from a parameter index to its , if any .
module HigherOrderParameterMap = struct
module Map = SerializableMap.Make (Int)
type t = HigherOrderParameter.t Map.t
let empty = Map.empty
let is_empty = Map.is_empty
let pp = Map.pp HigherOrderParameter.pp
let show = Format.asprintf "%a" pp
let equal = Map.equal HigherOrderParameter.equal
let equal_ignoring_types = Map.equal HigherOrderParameter.equal_ignoring_types
let join left right =
Map.union (fun _ left right -> Some (HigherOrderParameter.join left right)) left right
let deduplicate map = Map.map HigherOrderParameter.deduplicate map
let all_targets map =
Map.fold
(fun _ higher_order_parameter targets ->
List.rev_append targets (HigherOrderParameter.all_targets higher_order_parameter))
map
[]
let add map ({ HigherOrderParameter.index; _ } as higher_order_parameter) =
Map.update
index
(function
| None -> Some higher_order_parameter
| Some existing -> Some (HigherOrderParameter.join existing higher_order_parameter))
map
let from_list list = List.fold list ~init:Map.empty ~f:add
let to_list map = Map.data map
let first_index map =
Map.min_binding_opt map >>| fun (_, higher_order_parameter) -> higher_order_parameter
end
(** An aggregate of all possible callees at a call site. *)
module CallCallees = struct
type t = {
(* Normal call targets. *)
call_targets: CallTarget.t list;
(* Call targets for calls to the `__new__` class method. *)
new_targets: CallTarget.t list;
(* Call targets for calls to the `__init__` instance method. *)
init_targets: CallTarget.t list;
Information about arguments that are , and possibly called .
higher_order_parameters: HigherOrderParameterMap.t;
True if at least one callee could not be resolved .
* Usually indicates missing type information at the call site .
* Usually indicates missing type information at the call site. *)
unresolved: bool;
}
[@@deriving eq, show { with_path = false }]
let create
?(call_targets = [])
?(new_targets = [])
?(init_targets = [])
?(higher_order_parameters = HigherOrderParameterMap.empty)
?(unresolved = false)
()
=
{ call_targets; new_targets; init_targets; higher_order_parameters; unresolved }
let unresolved =
{
call_targets = [];
new_targets = [];
init_targets = [];
higher_order_parameters = HigherOrderParameterMap.empty;
unresolved = true;
}
let is_partially_resolved = function
| { call_targets = _ :: _; _ } -> true
| { new_targets = _ :: _; _ } -> true
| { init_targets = _ :: _; _ } -> true
| _ -> false
let pp_option formatter = function
| None -> Format.fprintf formatter "None"
| Some callees -> pp formatter callees
let join
{
call_targets = left_call_targets;
new_targets = left_new_targets;
init_targets = left_init_targets;
higher_order_parameters = left_higher_order_parameters;
unresolved = left_unresolved;
}
{
call_targets = right_call_targets;
new_targets = right_new_targets;
init_targets = right_init_targets;
higher_order_parameters = right_higher_order_parameters;
unresolved = right_unresolved;
}
=
let call_targets = List.rev_append left_call_targets right_call_targets in
let new_targets = List.rev_append left_new_targets right_new_targets in
let init_targets = List.rev_append left_init_targets right_init_targets in
let higher_order_parameters =
HigherOrderParameterMap.join left_higher_order_parameters right_higher_order_parameters
in
let unresolved = left_unresolved || right_unresolved in
{ call_targets; new_targets; init_targets; higher_order_parameters; unresolved }
let deduplicate { call_targets; new_targets; init_targets; higher_order_parameters; unresolved } =
let call_targets = CallTarget.dedup_and_sort call_targets in
let new_targets = CallTarget.dedup_and_sort new_targets in
let init_targets = CallTarget.dedup_and_sort init_targets in
let higher_order_parameters = HigherOrderParameterMap.deduplicate higher_order_parameters in
{ call_targets; new_targets; init_targets; higher_order_parameters; unresolved }
let all_targets { call_targets; new_targets; init_targets; higher_order_parameters; _ } =
call_targets
|> List.rev_append new_targets
|> List.rev_append init_targets
|> List.map ~f:CallTarget.target
|> List.rev_append (HigherOrderParameterMap.all_targets higher_order_parameters)
let equal_ignoring_types
{
call_targets = call_targets_left;
new_targets = new_targets_left;
init_targets = init_targets_left;
higher_order_parameters = higher_order_parameter_lefts;
unresolved = unresolved_left;
}
{
call_targets = call_targets_right;
new_targets = new_targets_right;
init_targets = init_targets_right;
higher_order_parameters = higher_order_parameter_rights;
unresolved = unresolved_right;
}
=
List.equal CallTarget.equal_ignoring_types call_targets_left call_targets_right
&& List.equal CallTarget.equal_ignoring_types new_targets_left new_targets_right
&& List.equal CallTarget.equal_ignoring_types init_targets_left init_targets_right
&& HigherOrderParameterMap.equal_ignoring_types
higher_order_parameter_lefts
higher_order_parameter_rights
&& unresolved_left == unresolved_right
let is_method_of_class ~is_class_name callees =
let rec is_class_type = function
| Type.Primitive name -> is_class_name name
| Type.Parametric { name; _ } -> is_class_name name
| Type.Union [NoneType; annotation]
| Type.Union [annotation; NoneType] ->
is_class_type annotation
| Type.Union annotations -> List.for_all ~f:is_class_type annotations
| _ -> false
in
let is_call_target = function
| { CallTarget.target = Method { class_name; _ }; receiver_type; _ }
| { target = Override { class_name; _ }; receiver_type; _ } ->
(* Is it not enough to check the class name, since methods can be inherited.
* For instance, `__iter__` is not defined on `Mapping`, but is defined in the parent class `Iterable`. *)
is_class_name class_name || receiver_type >>| is_class_type |> Option.value ~default:false
| _ -> false
in
match callees with
| { call_targets = []; _ } -> false
| { call_targets; _ } -> List.for_all call_targets ~f:is_call_target
let is_mapping_method callees =
let is_class_name = function
| "dict"
| "typing.Mapping"
| "typing.MutableMapping"
| "TypedDictionary"
| "NonTotalTypedDictionary"
| "collections.OrderedDict"
| "collections.defaultdict" ->
true
| _ -> false
in
is_method_of_class ~is_class_name callees
let is_sequence_method callees =
let is_class_name = function
| "list"
| "typing.Sequence"
| "typing.MutableSequence"
| "collections.deque"
| "tuple" ->
true
| _ -> false
in
is_method_of_class ~is_class_name callees
let is_object_new = function
| [] -> (* Unresolved call, assume it's object.__new__ *) true
| [
{
CallTarget.target =
Target.Method { class_name = "object"; method_name = "__new__"; kind = Normal };
_;
};
] ->
true
| _ -> false
let is_object_init = function
| [] -> (* Unresolved call, assume it's object.__init__ *) true
| [
{
CallTarget.target =
Target.Method { class_name = "object"; method_name = "__init__"; kind = Normal };
_;
};
] ->
true
| _ -> false
end
(** An aggregrate of all possible callees for a given attribute access. *)
module AttributeAccessCallees = struct
type t = {
property_targets: CallTarget.t list;
global_targets: CallTarget.t list;
(* True if the attribute access should also be considered a regular attribute.
* For instance, if the object has type `Union[A, B]` where only `A` defines a property. *)
is_attribute: bool;
}
[@@deriving eq, show { with_path = false }]
let deduplicate { property_targets; global_targets; is_attribute } =
{
property_targets = CallTarget.dedup_and_sort property_targets;
global_targets = CallTarget.dedup_and_sort global_targets;
is_attribute;
}
let join
{
property_targets = left_property_targets;
global_targets = left_global_targets;
is_attribute = left_is_attribute;
}
{
property_targets = right_property_targets;
global_targets = right_global_targets;
is_attribute = right_is_attribute;
}
=
{
property_targets = List.rev_append left_property_targets right_property_targets;
global_targets = List.rev_append left_global_targets right_global_targets;
is_attribute = left_is_attribute || right_is_attribute;
}
let all_targets { property_targets; global_targets; _ } =
List.rev_append property_targets global_targets |> List.map ~f:CallTarget.target
let equal_ignoring_types
{
property_targets = property_targets_left;
global_targets = global_targets_left;
is_attribute = is_attribute_left;
}
{
property_targets = property_targets_right;
global_targets = global_targets_right;
is_attribute = is_attribute_right;
}
=
List.equal CallTarget.equal_ignoring_types property_targets_left property_targets_right
&& List.equal CallTarget.equal_ignoring_types global_targets_left global_targets_right
&& is_attribute_left == is_attribute_right
let empty = { property_targets = []; global_targets = []; is_attribute = true }
let is_empty attribute_access_callees = equal attribute_access_callees empty
end
(** An aggregate of all possible callees for a given identifier expression, i.e `foo`. *)
module IdentifierCallees = struct
type t = { global_targets: CallTarget.t list } [@@deriving eq, show { with_path = false }]
let deduplicate { global_targets } = { global_targets = CallTarget.dedup_and_sort global_targets }
let join { global_targets = left_global_targets } { global_targets = right_global_targets } =
{ global_targets = List.rev_append left_global_targets right_global_targets }
let all_targets { global_targets } = List.map ~f:CallTarget.target global_targets
end
(** An aggregate of callees for formatting strings. *)
module StringFormatCallees = struct
type t = {
(* Implicit callees for any expression that is stringified. *)
stringify_targets: CallTarget.t list;
(* Artificial callees for distinguishing f-strings within a function. *)
f_string_targets: CallTarget.t list;
}
[@@deriving eq, show { with_path = false }]
let deduplicate { stringify_targets; f_string_targets } =
{
stringify_targets = CallTarget.dedup_and_sort stringify_targets;
f_string_targets = CallTarget.dedup_and_sort f_string_targets;
}
let join
{ stringify_targets = left_stringify_targets; f_string_targets = left_f_string_targets }
{ stringify_targets = right_stringify_targets; f_string_targets = right_f_string_targets }
=
{
stringify_targets = List.rev_append left_stringify_targets right_stringify_targets;
f_string_targets = List.rev_append left_f_string_targets right_f_string_targets;
}
let all_targets { stringify_targets; f_string_targets } =
List.rev_append stringify_targets f_string_targets |> List.map ~f:CallTarget.target
let from_stringify_targets stringify_targets = { stringify_targets; f_string_targets = [] }
let from_f_string_targets f_string_targets = { stringify_targets = []; f_string_targets }
end
(** An aggregate of all possible callees for an arbitrary expression. *)
module ExpressionCallees = struct
type t = {
call: CallCallees.t option;
attribute_access: AttributeAccessCallees.t option;
identifier: IdentifierCallees.t option;
string_format: StringFormatCallees.t option;
}
[@@deriving eq, show { with_path = false }]
let from_call callees =
{ call = Some callees; attribute_access = None; identifier = None; string_format = None }
let from_call_with_empty_attribute callees =
{
call = Some callees;
attribute_access = Some AttributeAccessCallees.empty;
identifier = None;
string_format = None;
}
let from_attribute_access properties =
{ call = None; attribute_access = Some properties; identifier = None; string_format = None }
let from_identifier identifier =
{ call = None; attribute_access = None; identifier = Some identifier; string_format = None }
let from_string_format string_format =
{ call = None; attribute_access = None; identifier = None; string_format = Some string_format }
let join
{
call = left_call;
attribute_access = left_attribute_access;
identifier = left_identifier;
string_format = left_string_format;
}
{
call = right_call;
attribute_access = right_attribute_access;
identifier = right_identifier;
string_format = right_string_format;
}
=
{
call = Option.merge ~f:CallCallees.join left_call right_call;
attribute_access =
Option.merge ~f:AttributeAccessCallees.join left_attribute_access right_attribute_access;
identifier = Option.merge ~f:IdentifierCallees.join left_identifier right_identifier;
string_format =
Option.merge ~f:StringFormatCallees.join left_string_format right_string_format;
}
let deduplicate { call; attribute_access; identifier; string_format } =
{
call = call >>| CallCallees.deduplicate;
attribute_access = attribute_access >>| AttributeAccessCallees.deduplicate;
identifier = identifier >>| IdentifierCallees.deduplicate;
string_format = string_format >>| StringFormatCallees.deduplicate;
}
let all_targets { call; attribute_access; identifier; string_format } =
let call_targets = call >>| CallCallees.all_targets |> Option.value ~default:[] in
let attribute_access_targets =
attribute_access >>| AttributeAccessCallees.all_targets |> Option.value ~default:[]
in
let identifier_targets =
identifier >>| IdentifierCallees.all_targets |> Option.value ~default:[]
in
let string_format_targets =
string_format >>| StringFormatCallees.all_targets |> Option.value ~default:[]
in
call_targets
|> List.rev_append attribute_access_targets
|> List.rev_append identifier_targets
|> List.rev_append string_format_targets
let is_empty_attribute_access_callees = function
| {
call = None;
attribute_access = Some some_attribute_access;
identifier = None;
string_format = None;
} ->
AttributeAccessCallees.is_empty some_attribute_access
| _ -> false
let equal_ignoring_types
{
call = call_left;
attribute_access = attribute_access_left;
identifier = identifier_left;
string_format = string_format_left;
}
{
call = call_right;
attribute_access = attribute_access_right;
identifier = identifier_right;
string_format = string_format_right;
}
=
Option.equal CallCallees.equal_ignoring_types call_left call_right
&& Option.equal
AttributeAccessCallees.equal_ignoring_types
attribute_access_left
attribute_access_right
&& Option.equal IdentifierCallees.equal identifier_left identifier_right
&& Option.equal StringFormatCallees.equal string_format_left string_format_right
end
(** An aggregate of all possible callees for an arbitrary location.
Note that multiple expressions might have the same location. *)
module LocationCallees = struct
type t =
| Singleton of ExpressionCallees.t
| Compound of ExpressionCallees.t SerializableStringMap.t
[@@deriving eq]
let pp formatter = function
| Singleton callees -> Format.fprintf formatter "%a" ExpressionCallees.pp callees
| Compound map ->
SerializableStringMap.to_alist map
|> List.map ~f:(fun (key, value) -> Format.asprintf "%s: %a" key ExpressionCallees.pp value)
|> String.concat ~sep:", "
|> Format.fprintf formatter "%s"
let show callees = Format.asprintf "%a" pp callees
let all_targets = function
| Singleton raw_callees -> ExpressionCallees.all_targets raw_callees
| Compound map ->
SerializableStringMap.data map |> List.concat_map ~f:ExpressionCallees.all_targets
let equal_ignoring_types location_callees_left location_callees_right =
match location_callees_left, location_callees_right with
| Singleton callees_left, Singleton callees_right ->
ExpressionCallees.equal_ignoring_types callees_left callees_right
| Compound map_left, Compound map_right ->
SerializableStringMap.equal ExpressionCallees.equal_ignoring_types map_left map_right
| _ -> false
end
module UnprocessedLocationCallees = struct
type t = ExpressionCallees.t SerializableStringMap.t
let singleton ~expression_identifier ~callees =
SerializableStringMap.singleton expression_identifier callees
let add map ~expression_identifier ~callees =
SerializableStringMap.update
expression_identifier
(function
| Some existing_callees -> Some (ExpressionCallees.join existing_callees callees)
| None -> Some callees)
map
end
let call_identifier { Call.callee; _ } =
match Node.value callee with
| Name (Name.Attribute { attribute; _ }) -> attribute
| Name (Name.Identifier name) -> name
| _ ->
Fall back to something that hopefully identifies the call well .
Expression.show callee
let expression_identifier = function
| Expression.Call call -> Some (call_identifier call)
| Expression.Name (Name.Attribute { attribute; _ }) -> Some attribute
| _ -> (* not a valid call site. *) None
(** The call graph of a function or method definition. *)
module DefineCallGraph = struct
type t = LocationCallees.t Location.Map.Tree.t [@@deriving eq]
let pp formatter call_graph =
let pp_pair formatter (key, value) =
Format.fprintf formatter "@,%a -> %a" Location.pp key LocationCallees.pp value
in
let pp_pairs formatter = List.iter ~f:(pp_pair formatter) in
call_graph |> Location.Map.Tree.to_alist |> Format.fprintf formatter "{@[<v 2>%a@]@,}" pp_pairs
let show = Format.asprintf "%a" pp
let empty = Location.Map.Tree.empty
let add call_graph ~location ~callees =
Location.Map.Tree.set call_graph ~key:location ~data:callees
let resolve_expression call_graph ~location ~expression_identifier =
match Location.Map.Tree.find call_graph location with
| Some (LocationCallees.Singleton callees) -> Some callees
| Some (LocationCallees.Compound name_to_callees) ->
SerializableStringMap.find_opt expression_identifier name_to_callees
| None -> None
let resolve_call call_graph ~location ~call =
expression_identifier (Expression.Call call)
>>= fun expression_identifier ->
resolve_expression call_graph ~location ~expression_identifier >>= fun { call; _ } -> call
let resolve_attribute_access call_graph ~location ~attribute =
resolve_expression call_graph ~location ~expression_identifier:attribute
>>= fun { attribute_access; _ } -> attribute_access
let resolve_identifier call_graph ~location ~identifier =
resolve_expression call_graph ~location ~expression_identifier:identifier
>>= fun { identifier; _ } -> identifier
let string_format_expression_identifier = "$__str__$"
let resolve_string_format call_graph ~location =
resolve_expression
call_graph
~location
~expression_identifier:string_format_expression_identifier
>>= fun { string_format; _ } -> string_format
let equal_ignoring_types call_graph_left call_graph_right =
Location.Map.Tree.equal LocationCallees.equal_ignoring_types call_graph_left call_graph_right
(** Return all callees of the call graph, as a sorted list. *)
let all_targets call_graph =
Location.Map.Tree.data call_graph
|> List.concat_map ~f:LocationCallees.all_targets
|> List.dedup_and_sort ~compare:Target.compare
end
Produce call targets with a textual order index .
*
* The index is the number of times a given function or method was previously called ,
* respecting the execution flow .
*
* ` ` `
* def f ( ):
* a = source_with_hop ( ) # index=0
* = a ) # index=0
* sink_with_hop(y = a ) # index=1
* b = source_with_hop ( ) # index=1
* sink_with_hop(z = a ) # index=2
* ` ` `
*
* The index is the number of times a given function or method was previously called,
* respecting the execution flow.
*
* ```
* def f():
* a = source_with_hop() # index=0
* sink_with_hop(x=a) # index=0
* sink_with_hop(y=a) # index=1
* b = source_with_hop() # index=1
* sink_with_hop(z=a) # index=2
* ```
*)
module CallTargetIndexer = struct
type t = {
indices: int Target.HashMap.t;
mutable seen_targets: Target.Set.t;
}
let create () = { indices = Target.HashMap.create (); seen_targets = Target.Set.empty }
let generate_fresh_indices indexer =
Target.Set.iter (Target.HashMap.incr indexer.indices) indexer.seen_targets;
indexer.seen_targets <- Target.Set.empty
let create_target
indexer
~implicit_self
~implicit_dunder_call
~return_type
?receiver_type
original_target
=
let target_for_index = Target.override_to_method original_target in
let index = Target.HashMap.find indexer.indices target_for_index |> Option.value ~default:0 in
indexer.seen_targets <- Target.Set.add target_for_index indexer.seen_targets;
{
CallTarget.target = original_target;
implicit_self;
implicit_dunder_call;
index;
return_type;
receiver_type;
}
end
type callee_kind =
| Method of { is_direct_call: bool }
| Function
let is_local identifier = String.is_prefix ~prefix:"$" identifier
let rec is_all_names = function
| Expression.Name (Name.Identifier identifier) when not (is_local identifier) -> true
| Name (Name.Attribute { base; attribute; _ }) when not (is_local attribute) ->
is_all_names (Node.value base)
| _ -> false
let rec callee_kind ~resolution callee callee_type =
let is_super_call =
let rec is_super callee =
match Node.value callee with
| Expression.Call { callee = { Node.value = Name (Name.Identifier "super"); _ }; _ } -> true
| Call { callee; _ } -> is_super callee
| Name (Name.Attribute { base; _ }) -> is_super base
| _ -> false
in
is_super callee
in
match callee_type with
| _ when is_super_call -> Method { is_direct_call = true }
| Type.Parametric { name = "BoundMethod"; _ } ->
Method { is_direct_call = is_all_names (Node.value callee) }
| Type.Callable _ -> (
match Node.value callee with
| Expression.Name (Name.Attribute { base; _ }) ->
let parent_type = CallResolution.resolve_ignoring_optional ~resolution base in
let is_class () =
parent_type
|> GlobalResolution.class_summary (Resolution.global_resolution resolution)
|> Option.is_some
in
if Type.is_meta parent_type then
Method { is_direct_call = true }
else if is_class () then
Method { is_direct_call = false }
else
Function
| _ -> Function)
| Type.Union (callee_type :: _) -> callee_kind ~resolution callee callee_type
| _ ->
(* We must be dealing with a callable class. *)
Method { is_direct_call = false }
let strip_optional annotation = Type.optional_value annotation |> Option.value ~default:annotation
let strip_meta annotation =
if Type.is_meta annotation then
Type.single_parameter annotation
else
annotation
Figure out what target to pick for an indirect call that resolves to implementation_target .
E.g. , if the receiver type is A , and A derives from Base , and the target is Base.method , then
targeting the override tree of is wrong , as it would include all siblings for A.
* Instead , we have the following cases :
* a ) receiver type matches implementation_target 's declaring type - > override implementation_target
* b ) no implementation_target override entries are subclasses of A - > real implementation_target
* c ) some override entries are subclasses of A - > search upwards for actual implementation ,
* and override all those where the override name is
* 1 ) the override target if it exists in the override shared mem
* 2 ) the real target otherwise
E.g., if the receiver type is A, and A derives from Base, and the target is Base.method, then
targeting the override tree of Base.method is wrong, as it would include all siblings for A.
* Instead, we have the following cases:
* a) receiver type matches implementation_target's declaring type -> override implementation_target
* b) no implementation_target override entries are subclasses of A -> real implementation_target
* c) some override entries are subclasses of A -> search upwards for actual implementation,
* and override all those where the override name is
* 1) the override target if it exists in the override shared mem
* 2) the real target otherwise
*)
let compute_indirect_targets ~resolution ~override_graph ~receiver_type implementation_target =
Target name must be the resolved implementation target
let global_resolution = Resolution.global_resolution resolution in
let get_class_type = GlobalResolution.parse_reference global_resolution in
let get_actual_target method_name =
if OverrideGraph.SharedMemory.overrides_exist override_graph method_name then
Target.get_corresponding_override method_name
else
method_name
in
let receiver_type = receiver_type |> strip_meta |> strip_optional |> Type.weaken_literals in
let declaring_type, method_name, kind =
match implementation_target with
| Target.Method { class_name; method_name; kind } ->
Reference.create class_name, method_name, kind
| _ -> failwith "Unexpected target"
in
if Reference.equal declaring_type (Type.class_name receiver_type) then (* case a *)
[get_actual_target implementation_target]
else
match
OverrideGraph.SharedMemory.get_overriding_types override_graph ~member:implementation_target
with
| None ->
(* case b *)
[implementation_target]
| Some overriding_types ->
(* case c *)
let keep_subtypes candidate =
let candidate_type = get_class_type candidate in
try
GlobalResolution.less_or_equal
global_resolution
~left:candidate_type
~right:receiver_type
with
| Analysis.ClassHierarchy.Untracked untracked_type ->
Log.warning
"Found untracked type `%s` when comparing `%a` and `%a`. The class `%a` will be \
considered a subclass of `%a`, which could lead to false positives."
untracked_type
Type.pp
candidate_type
Type.pp
receiver_type
Type.pp
candidate_type
Type.pp
receiver_type;
true
in
let override_targets =
let create_override_target class_name =
get_actual_target
(Target.Method { class_name = Reference.show class_name; method_name; kind })
in
List.filter overriding_types ~f:keep_subtypes
|> fun subtypes -> List.map subtypes ~f:create_override_target
in
implementation_target :: override_targets
let rec resolve_callees_from_type
~resolution
~override_graph
~call_indexer
?(dunder_call = false)
?receiver_type
~return_type
~callee_kind
callable_type
=
let resolve_callees_from_type ?(dunder_call = dunder_call) =
resolve_callees_from_type ~dunder_call
in
match callable_type with
| Type.Callable { kind = Named name; _ } -> (
let return_type =
ReturnType.from_callable_with_fallback ~resolution ~callable_type ~return_type
in
match receiver_type with
| Some receiver_type ->
let targets =
match callee_kind with
| Method { is_direct_call = true } -> [Target.create_method name]
| _ ->
compute_indirect_targets
~resolution
~override_graph
~receiver_type
(Target.create_method name)
in
let targets =
List.map
~f:(fun target ->
CallTargetIndexer.create_target
call_indexer
~implicit_self:true
~implicit_dunder_call:dunder_call
~return_type:(Some return_type)
~receiver_type
target)
targets
in
CallCallees.create ~call_targets:targets ()
| None ->
let target =
match callee_kind with
| Method _ -> Target.create_method name
| _ -> Target.create_function name
in
CallCallees.create
~call_targets:
[
CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:dunder_call
~return_type:(Some return_type)
?receiver_type
target;
]
())
| Type.Callable { kind = Anonymous; _ } -> CallCallees.unresolved
| Type.Parametric { name = "BoundMethod"; parameters = [Single callable; Single receiver_type] }
->
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~receiver_type
~return_type
~callee_kind
callable
| Type.Union (element :: elements) ->
let first_targets =
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~callee_kind
?receiver_type
~return_type
element
in
List.fold elements ~init:first_targets ~f:(fun combined_targets new_target ->
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
?receiver_type
~return_type
~callee_kind
new_target
|> CallCallees.join combined_targets)
| Type.Parametric { name = "type"; parameters = [Single class_type] } ->
resolve_constructor_callee ~resolution ~override_graph ~call_indexer class_type
|> Option.value ~default:CallCallees.unresolved
| callable_type -> (
(* Handle callable classes. `typing.Type` interacts specially with __call__, so we choose to
ignore it for now to make sure our constructor logic via `cls()` still works. *)
match
CallResolution.resolve_attribute_access_ignoring_untracked
~resolution
~base_type:callable_type
~attribute:"__call__"
with
| Type.Any
| Type.Top ->
CallCallees.unresolved
(* Callable protocol. *)
| Type.Callable { kind = Anonymous; _ } as resolved_dunder_call ->
Type.primitive_name callable_type
>>| (fun primitive_callable_name ->
let return_type =
ReturnType.from_callable_with_fallback
~resolution
~callable_type:resolved_dunder_call
~return_type
in
let target =
Target.Method
{
Target.class_name = primitive_callable_name;
method_name = "__call__";
kind = Normal;
}
in
CallCallees.create
~call_targets:
[
CallTargetIndexer.create_target
call_indexer
~implicit_self:true
~implicit_dunder_call:true
~return_type:(Some return_type)
?receiver_type
target;
]
())
|> Option.value ~default:CallCallees.unresolved
| annotation ->
if not dunder_call then
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~return_type
~dunder_call:true
~callee_kind
annotation
else
CallCallees.unresolved)
and resolve_constructor_callee ~resolution ~override_graph ~call_indexer class_type =
let meta_type = Type.meta class_type in
match
( CallResolution.resolve_attribute_access_ignoring_untracked
~resolution
~base_type:meta_type
~attribute:"__new__",
CallResolution.resolve_attribute_access_ignoring_untracked
~resolution
~base_type:meta_type
~attribute:"__init__" )
with
| Type.Any, _
| Type.Top, _
| _, Type.Any
| _, Type.Top ->
None
| new_callable_type, init_callable_type ->
let new_callees =
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~receiver_type:meta_type
~return_type:(lazy class_type)
~callee_kind:(Method { is_direct_call = true })
new_callable_type
in
let init_callees =
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~receiver_type:meta_type
~return_type:(lazy Type.none)
~callee_kind:(Method { is_direct_call = true })
init_callable_type
in
(* Technically, `object.__new__` returns `object` and `C.__init__` returns None.
* In practice, we actually want to use the class type. *)
let return_type =
ReturnType.from_annotation ~resolution:(Resolution.global_resolution resolution) class_type
in
let set_return_type call_target =
{ call_target with CallTarget.return_type = Some return_type }
in
Some
(CallCallees.create
~new_targets:(List.map ~f:set_return_type new_callees.call_targets)
~init_targets:(List.map ~f:set_return_type init_callees.call_targets)
~unresolved:(new_callees.unresolved || init_callees.unresolved)
())
let resolve_callee_from_defining_expression
~resolution
~override_graph
~call_indexer
~callee:{ Node.value = callee; _ }
~return_type
~implementing_class
=
match implementing_class, callee with
| Type.Top, Expression.Name name when is_all_names callee ->
(* If implementing_class is unknown, this must be a function rather than a method. We can use
global resolution on the callee. *)
GlobalResolution.global
(Resolution.global_resolution resolution)
(Ast.Expression.name_to_reference_exn name)
>>= fun { AttributeResolution.Global.undecorated_signature; _ } ->
undecorated_signature
>>| fun undecorated_signature ->
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~return_type
~callee_kind:Function
(Type.Callable undecorated_signature)
| _ -> (
let implementing_class_name =
if Type.is_meta implementing_class then
Type.parameters implementing_class
>>= fun parameters ->
List.nth parameters 0
>>= function
| Single implementing_class -> Some implementing_class
| _ -> None
else
Some implementing_class
in
match implementing_class_name with
| Some implementing_class_name ->
let class_primitive =
match implementing_class_name with
| Parametric { name; _ } -> Some name
| Primitive name -> Some name
| _ -> None
in
let method_name =
match callee with
| Expression.Name (Name.Attribute { attribute; _ }) -> Some attribute
| _ -> None
in
method_name
>>= (fun method_name ->
class_primitive >>| fun class_name -> Format.sprintf "%s.%s" class_name method_name)
>>| Reference.create
Here , we blindly reconstruct the callable instead of going through the global
resolution , as Pyre does n't have an API to get the undecorated signature of methods .
resolution, as Pyre doesn't have an API to get the undecorated signature of methods. *)
>>= fun name ->
let callable_type =
Type.Callable
{
Type.Callable.kind = Named name;
implementation =
{ annotation = Lazy.force return_type; parameters = Type.Callable.Defined [] };
overloads = [];
}
in
Some
(resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~return_type
~receiver_type:implementing_class
~callee_kind:(Method { is_direct_call = false })
callable_type)
| _ -> None)
(* Rewrite certain calls for the interprocedural analysis (e.g, pysa).
* This may or may not be sound depending on the analysis performed. *)
let transform_special_calls ~resolution { Call.callee; arguments } =
let attribute_access base method_name =
{
Node.value =
Expression.Name (Name.Attribute { base; attribute = method_name; special = true });
location = Node.location callee;
}
in
match Node.value callee, arguments with
| Name (Name.Identifier "iter"), [{ Call.Argument.value; _ }] ->
(* Only handle `iter` with a single argument here. *)
Some { Call.callee = attribute_access value "__iter__"; arguments = [] }
| Name (Name.Identifier "next"), [{ Call.Argument.value; _ }] ->
(* Only handle `next` with a single argument here. *)
Some { Call.callee = attribute_access value "__next__"; arguments = [] }
| Name (Name.Identifier "anext"), [{ Call.Argument.value; _ }] ->
(* Only handle `anext` with a single argument here. *)
Some { Call.callee = attribute_access value "__anext__"; arguments = [] }
| ( Expression.Name
(Name.Attribute
{
base = { Node.value = Expression.Name (Name.Identifier "functools"); _ };
attribute = "partial";
_;
}),
{ Call.Argument.value = actual_callable; _ } :: actual_arguments ) ->
Some { Call.callee = actual_callable; arguments = actual_arguments }
| ( Expression.Name
(Name.Attribute
{
base = { Node.value = Expression.Name (Name.Identifier "multiprocessing"); _ };
attribute = "Process";
_;
}),
[
{ Call.Argument.value = process_callee; name = Some { Node.value = "$parameter$target"; _ } };
{
Call.Argument.value = { Node.value = Expression.Tuple process_arguments; _ };
name = Some { Node.value = "$parameter$args"; _ };
};
] ) ->
Some
{
Call.callee = process_callee;
arguments =
List.map process_arguments ~f:(fun value -> { Call.Argument.value; name = None });
}
| _ -> SpecialCallResolution.redirect ~resolution { Call.callee; arguments }
let redirect_special_calls ~resolution call =
match transform_special_calls ~resolution call with
| Some call -> call
| None ->
(* Rewrite certain calls using the same logic used in the type checker.
* This should be sound for most analyses. *)
Annotated.Call.redirect_special_calls ~resolution call
let resolve_recognized_callees
~resolution
~override_graph
~call_indexer
~callee
~return_type
~callee_type
=
(* Special treatment for a set of hardcoded decorators returning callable classes. *)
match Node.value callee, callee_type with
| ( _,
Type.Parametric
{
name = "BoundMethod";
parameters = [Single (Parametric { name; _ }); Single implementing_class];
} )
when Set.mem Recognized.allowlisted_callable_class_decorators name ->
resolve_callee_from_defining_expression
~resolution
~override_graph
~call_indexer
~callee
~return_type
~implementing_class
| Expression.Name (Name.Attribute { base; _ }), Parametric { name; _ }
when Set.mem Recognized.allowlisted_callable_class_decorators name ->
Because of the special class , we do n't get a bound method & lose the self argument for
non - classmethod LRU cache wrappers . Reconstruct self in this case .
non-classmethod LRU cache wrappers. Reconstruct self in this case. *)
CallResolution.resolve_ignoring_optional ~resolution base
|> fun implementing_class ->
resolve_callee_from_defining_expression
~resolution
~override_graph
~call_indexer
~callee
~return_type
~implementing_class
| Expression.Name name, _
when is_all_names (Node.value callee)
&& Type.Set.mem SpecialCallResolution.recognized_callable_target_types callee_type ->
Ast.Expression.name_to_reference name
>>| Reference.show
>>| fun name ->
let return_type =
ReturnType.from_annotation
~resolution:(Resolution.global_resolution resolution)
(Lazy.force return_type)
in
CallCallees.create
~call_targets:
[
CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:(Some return_type)
(Target.Function { name; kind = Normal });
]
()
| _ -> None
let resolve_callee_ignoring_decorators ~resolution ~call_indexer ~return_type callee =
let global_resolution = Resolution.global_resolution resolution in
let open UnannotatedGlobalEnvironment in
let return_type () =
ReturnType.from_annotation
~resolution:(Resolution.global_resolution resolution)
(Lazy.force return_type)
in
match Node.value callee with
| Expression.Name name when is_all_names (Node.value callee) -> (
(* Resolving expressions that do not reference local variables or parameters. *)
let name = Ast.Expression.name_to_reference_exn name in
match GlobalResolution.resolve_exports global_resolution name with
| Some
(ResolvedReference.ModuleAttribute
{ export = ResolvedReference.Exported (Module.Export.Name.Define _); remaining = []; _ })
->
Some
(CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:(Some (return_type ()))
(Target.Function { name = Reference.show name; kind = Normal }))
| Some
(ResolvedReference.ModuleAttribute
{
from;
name;
export = ResolvedReference.Exported Module.Export.Name.Class;
remaining = [attribute];
_;
}) -> (
let class_name = Reference.create ~prefix:from name |> Reference.show in
GlobalResolution.class_summary global_resolution (Type.Primitive class_name)
>>| Node.value
>>| ClassSummary.attributes
>>= Identifier.SerializableMap.find_opt attribute
>>| Node.value
>>= function
| { kind = Method { static; _ }; _ } ->
Some
(CallTargetIndexer.create_target
call_indexer
~implicit_self:(not static)
~implicit_dunder_call:false
~return_type:(Some (return_type ()))
(Target.Method { Target.class_name; method_name = attribute; kind = Normal }))
| _ -> None)
| _ -> None)
| Expression.Name (Name.Attribute { base; attribute; _ }) -> (
Resolve ` base.attribute ` by looking up the type of ` base ` or the types of its parent
classes in the Method Resolution Order .
classes in the Method Resolution Order. *)
match CallResolution.resolve_ignoring_optional ~resolution base with
| Type.Primitive class_name
| Type.Parametric { name = "type"; parameters = [Single (Type.Primitive class_name)] } -> (
let find_attribute element =
match
GlobalResolution.class_summary global_resolution (Type.Primitive element)
>>| Node.value
>>| ClassSummary.attributes
>>= Identifier.SerializableMap.find_opt attribute
>>| Node.value
with
| Some { ClassSummary.Attribute.kind = Method _; _ } -> Some element
| _ -> None
in
let parent_classes_in_mro =
GlobalResolution.successors ~resolution:global_resolution class_name
in
match List.find_map (class_name :: parent_classes_in_mro) ~f:find_attribute with
| Some base_class ->
Some
(CallTargetIndexer.create_target
call_indexer
~implicit_self:true
~implicit_dunder_call:false
~return_type:(Some (return_type ()))
(Target.Method
{ Target.class_name = base_class; method_name = attribute; kind = Normal }))
| None -> None)
| _ -> None)
| _ -> None
let resolve_regular_callees ~resolution ~override_graph ~call_indexer ~return_type ~callee =
let callee_type = CallResolution.resolve_ignoring_optional ~resolution callee in
let recognized_callees =
resolve_recognized_callees
~resolution
~override_graph
~call_indexer
~callee
~return_type
~callee_type
|> Option.value ~default:CallCallees.unresolved
in
if CallCallees.is_partially_resolved recognized_callees then
recognized_callees
else
let callee_kind = callee_kind ~resolution callee callee_type in
let calleees_from_type =
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~return_type
~callee_kind
callee_type
in
if CallCallees.is_partially_resolved calleees_from_type then
calleees_from_type
else
resolve_callee_ignoring_decorators ~resolution ~call_indexer ~return_type callee
>>| (fun target -> CallCallees.create ~call_targets:[target] ())
|> Option.value ~default:CallCallees.unresolved
let resolve_callees
~resolution
~override_graph
~call_indexer
~call:({ Call.callee; arguments } as call)
=
let higher_order_parameters =
let get_higher_order_function_targets index { Call.Argument.value = argument; _ } =
let return_type =
lazy
(Expression.Call { callee = argument; arguments = [] }
|> Node.create_with_default_location
|> CallResolution.resolve_ignoring_untracked ~resolution)
in
match
( resolve_regular_callees
~resolution
~override_graph
~call_indexer
~return_type
~callee:argument,
argument )
with
| { CallCallees.call_targets = _ :: _ as regular_targets; unresolved; _ }, _ ->
Some { HigherOrderParameter.index; call_targets = regular_targets; unresolved }
| _, { Node.value = Expression.Lambda _; _ } ->
Some { HigherOrderParameter.index; call_targets = []; unresolved = true }
| _ -> None
in
List.filter_mapi arguments ~f:get_higher_order_function_targets
|> HigherOrderParameterMap.from_list
in
(* Resolving the return type can be costly, hence we prefer the annotation on the callee when
possible. When that does not work, we fallback to a full resolution of the call expression
(done lazily). *)
let return_type =
lazy
(Expression.Call call
|> Node.create_with_default_location
|> CallResolution.resolve_ignoring_untracked ~resolution)
in
let regular_callees =
resolve_regular_callees ~resolution ~override_graph ~call_indexer ~return_type ~callee
in
{ regular_callees with higher_order_parameters }
let get_defining_attributes ~resolution ~base_annotation ~attribute =
let rec get_defining_parents annotation =
match annotation with
| Type.Union annotations
| Type.Variable { Type.Variable.Unary.constraints = Type.Variable.Explicit annotations; _ } ->
List.concat_map annotations ~f:get_defining_parents
| _ -> [CallResolution.defining_attribute ~resolution annotation attribute]
in
base_annotation |> strip_meta |> strip_optional |> get_defining_parents
type attribute_access_properties = {
property_targets: CallTarget.t list;
is_attribute: bool;
}
let resolve_attribute_access_properties
~resolution
~override_graph
~call_indexer
~base_annotation
~attribute
~setter
=
let property_targets_of_attribute property =
let return_type =
if setter then
ReturnType.none
else
Annotated.Attribute.annotation property
|> Annotation.annotation
|> ReturnType.from_annotation ~resolution:(Resolution.global_resolution resolution)
in
let parent = Annotated.Attribute.parent property |> Reference.create in
let property_targets =
let kind = if setter then Target.PropertySetter else Target.Normal in
if Type.is_meta base_annotation then
[Target.create_method ~kind (Reference.create ~prefix:parent attribute)]
else
let callee = Target.create_method ~kind (Reference.create ~prefix:parent attribute) in
compute_indirect_targets ~resolution ~override_graph ~receiver_type:base_annotation callee
in
List.map
~f:
(CallTargetIndexer.create_target
call_indexer
~implicit_self:true
~implicit_dunder_call:false
~return_type:(Some return_type))
property_targets
in
let attributes = get_defining_attributes ~resolution ~base_annotation ~attribute in
let properties, non_properties =
List.partition_map
~f:(function
| Some property when Annotated.Attribute.property property -> Either.First property
| attribute -> Either.Second attribute)
attributes
in
let property_targets = List.concat_map ~f:property_targets_of_attribute properties in
let is_attribute = (not (List.is_empty non_properties)) || List.is_empty attributes in
{ property_targets; is_attribute }
let as_global_reference ~resolution expression =
match Node.value expression with
| Expression.Name (Name.Identifier identifier) ->
let reference = Reference.delocalize (Reference.create identifier) in
if Resolution.is_global resolution ~reference then
Some reference
else
None
| Name name -> (
name_to_reference name
>>= fun reference ->
GlobalResolution.resolve_exports (Resolution.global_resolution resolution) reference
>>= function
| UnannotatedGlobalEnvironment.ResolvedReference.ModuleAttribute
{ from; name; remaining = []; _ } ->
Some (Reference.combine from (Reference.create name))
| _ -> None)
| _ -> None
let resolve_attribute_access_global_targets ~resolution ~base_annotation ~base ~attribute ~special =
let expression =
Expression.Name (Name.Attribute { Name.Attribute.base; attribute; special })
|> Node.create_with_default_location
in
match as_global_reference ~resolution expression with
| Some global -> [global]
| None ->
let global_resolution = Resolution.global_resolution resolution in
let rec find_targets targets = function
| Type.Union annotations -> List.fold ~init:targets ~f:find_targets annotations
| Parametric { name = "type"; parameters = [Single annotation] } ->
Access on a class , i.e ` Foo.bar ` , translated into ` Foo.__class__.bar ` .
let parent =
let attribute =
Type.split annotation
|> fst
|> Type.primitive_name
>>= GlobalResolution.attribute_from_class_name
~transitive:true
~resolution:global_resolution
~name:attribute
~instantiated:annotation
in
match attribute with
| Some attribute when Annotated.Attribute.defined attribute ->
Type.Primitive (Annotated.Attribute.parent attribute) |> Type.class_name
| _ -> Type.class_name annotation
in
let attribute = Format.sprintf "__class__.%s" attribute in
let target = Reference.create ~prefix:parent attribute in
target :: targets
| annotation ->
(* Access on an instance, i.e `self.foo`. *)
let parents =
let successors =
GlobalResolution.class_metadata (Resolution.global_resolution resolution) annotation
>>| (fun { ClassMetadataEnvironment.successors; _ } -> successors)
|> Option.value ~default:[]
|> List.map ~f:(fun name -> Type.Primitive name)
in
annotation :: successors
in
let add_target targets parent =
let target = Reference.create ~prefix:(Type.class_name parent) attribute in
target :: targets
in
List.fold ~init:targets ~f:add_target parents
in
find_targets [] base_annotation
let resolve_attribute_access
~resolution
~override_graph
~call_indexer
~attribute_targets
~base
~attribute
~special
~setter
=
let base_annotation = CallResolution.resolve_ignoring_optional ~resolution base in
let { property_targets; is_attribute } =
resolve_attribute_access_properties
~resolution
~override_graph
~call_indexer
~base_annotation
~attribute
~setter
in
let global_targets =
resolve_attribute_access_global_targets ~resolution ~base_annotation ~base ~attribute ~special
|> List.map ~f:Target.create_object
|> List.filter ~f:(Hash_set.mem attribute_targets)
|> List.map
~f:
(CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:None)
in
{ AttributeAccessCallees.property_targets; global_targets; is_attribute }
let resolve_identifier ~resolution ~call_indexer ~attribute_targets ~identifier =
Expression.Name (Name.Identifier identifier)
|> Node.create_with_default_location
|> as_global_reference ~resolution
>>| Target.create_object
|> Option.filter ~f:(Hash_set.mem attribute_targets)
>>| fun global ->
{
IdentifierCallees.global_targets =
[
CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:None
global;
];
}
(* This is a bit of a trick. The only place that knows where the local annotation map keys is the
fixpoint (shared across the type check and additional static analysis modules). By having a
fixpoint that always terminates (by having a state = unit), we re-use the fixpoint id's without
having to hackily recompute them. *)
module DefineCallGraphFixpoint (Context : sig
val global_resolution : GlobalResolution.t
val local_annotations : LocalAnnotationMap.ReadOnly.t option
val qualifier : Reference.t
val parent : Reference.t option
val callees_at_location : UnprocessedLocationCallees.t Location.Table.t
val override_graph : OverrideGraph.SharedMemory.t
val call_indexer : CallTargetIndexer.t
val is_missing_flow_type_analysis : bool
val attribute_targets : Target.HashSet.t
end) =
struct
type assignment_target = { location: Location.t }
type visitor_t = {
resolution: Resolution.t;
assignment_target: assignment_target option;
}
let override_graph = Context.override_graph
let call_indexer = Context.call_indexer
let attribute_targets = Context.attribute_targets
(* For the missing flow analysis (`--find-missing-flows=type`), we turn unresolved
* calls into sinks, so that we may find sources flowing into those calls. *)
let add_unknown_callee
~expression:{ Node.value; location }
({ CallCallees.unresolved; call_targets; _ } as callees)
=
if unresolved && Context.is_missing_flow_type_analysis then
(* TODO(T117715045): Move the target creation in `taint/missingFlow.ml`. *)
let callee =
match value with
| Expression.Call { callee = { Node.value = callee; _ }; _ } -> callee
| _ -> value
in
let target =
Format.asprintf
"unknown-callee:%a:%a:%a"
Reference.pp
Context.qualifier
Location.pp
location
Expression.pp
(callee |> Node.create_with_default_location |> Ast.Expression.delocalize)
in
let call_target =
{
CallTarget.target = Target.Object target;
implicit_self = false;
implicit_dunder_call = false;
index = 0;
return_type = Some ReturnType.any;
receiver_type = None;
}
in
{ callees with call_targets = call_target :: call_targets }
else
callees
module NodeVisitor = struct
type nonrec t = visitor_t
let expression_visitor
({ resolution; assignment_target } as state)
({ Node.value; location } as expression)
=
CallTargetIndexer.generate_fresh_indices call_indexer;
let register_targets ~expression_identifier ?(location = location) callees =
Location.Table.update Context.callees_at_location location ~f:(function
| None -> UnprocessedLocationCallees.singleton ~expression_identifier ~callees
| Some existing_callees ->
UnprocessedLocationCallees.add existing_callees ~expression_identifier ~callees)
in
let () =
match value with
| Expression.Call call ->
let call = redirect_special_calls ~resolution call in
resolve_callees ~resolution ~override_graph ~call_indexer ~call
|> add_unknown_callee ~expression
|> ExpressionCallees.from_call
|> register_targets ~expression_identifier:(call_identifier call)
| Expression.Name (Name.Attribute { Name.Attribute.base; attribute; special }) ->
let setter =
match assignment_target with
| Some { location = assignment_target_location } ->
Location.equal assignment_target_location location
| None -> false
in
resolve_attribute_access
~resolution
~override_graph
~call_indexer
~attribute_targets
~base
~attribute
~special
~setter
|> ExpressionCallees.from_attribute_access
|> register_targets ~expression_identifier:attribute
| Expression.Name (Name.Identifier identifier) ->
resolve_identifier ~resolution ~call_indexer ~attribute_targets ~identifier
>>| ExpressionCallees.from_identifier
>>| register_targets ~expression_identifier:identifier
|> ignore
| Expression.ComparisonOperator comparison -> (
match ComparisonOperator.override ~location comparison with
| Some { Node.value = Expression.Call call; _ } ->
let call = redirect_special_calls ~resolution call in
resolve_callees ~resolution ~override_graph ~call_indexer ~call
|> add_unknown_callee ~expression
|> ExpressionCallees.from_call
|> register_targets ~expression_identifier:(call_identifier call)
| _ -> ())
| Expression.FormatString substrings ->
let artificial_target =
CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:None
Target.StringCombineArtificialTargets.format_string
in
let callees =
ExpressionCallees.from_string_format
(StringFormatCallees.from_f_string_targets [artificial_target])
in
(* Use indexed artificial targets to distinguish format strings at different
locations. *)
register_targets
~expression_identifier:DefineCallGraph.string_format_expression_identifier
~location
callees;
List.iter substrings ~f:(function
| Substring.Literal _ -> ()
| Substring.Format ({ Node.location = expression_location; _ } as expression) ->
let { CallCallees.call_targets; _ } =
let callee =
let method_name =
Annotated.Call.resolve_stringify_call ~resolution expression
in
{
Node.value =
Expression.Name
(Name.Attribute
{ base = expression; attribute = method_name; special = false });
location = expression_location;
}
in
CallTargetIndexer.generate_fresh_indices call_indexer;
resolve_regular_callees
~resolution
~override_graph
~call_indexer
~return_type:(lazy Type.string)
~callee
in
if not (List.is_empty call_targets) then
let callees =
ExpressionCallees.from_string_format
(StringFormatCallees.from_stringify_targets call_targets)
in
register_targets
~expression_identifier:DefineCallGraph.string_format_expression_identifier
~location:expression_location
callees)
| _ -> ()
in
(* Special-case `getattr()` and `setattr()` for the taint analysis. *)
let () =
match value with
| Expression.Call
{
callee = { Node.value = Name (Name.Identifier "getattr"); _ };
arguments =
[
{ Call.Argument.value = base; _ };
{
Call.Argument.value =
{
Node.value =
Expression.Constant
(Constant.String { StringLiteral.value = attribute; _ });
_;
};
_;
};
{ Call.Argument.value = _; _ };
];
} ->
resolve_attribute_access
~resolution
~override_graph
~call_indexer
~attribute_targets
~base
~attribute
~special:false
~setter:false
|> ExpressionCallees.from_attribute_access
|> register_targets ~expression_identifier:attribute
| Expression.Call
{
callee =
{
Node.value =
Name
(Name.Attribute
{
base = { Node.value = Name (Name.Identifier "object"); _ };
attribute = "__setattr__";
_;
});
_;
};
arguments =
[
{ Call.Argument.value = self; name = None };
{
Call.Argument.value =
{
Node.value =
Expression.Constant (Constant.String { value = attribute; kind = String });
_;
};
name = None;
};
{ Call.Argument.value = _; name = None };
];
} ->
resolve_attribute_access
~resolution
~override_graph
~call_indexer
~attribute_targets
~base:self
~attribute
~special:true
~setter:true
|> ExpressionCallees.from_attribute_access
|> register_targets ~expression_identifier:attribute
| _ -> ()
in
state
let statement_visitor state _ = state
let generator_visitor ({ resolution; _ } as state) generator =
Since generators create variables that Pyre sees as scoped within the generator , handle
them by adding the generator 's bindings to the resolution .
them by adding the generator's bindings to the resolution. *)
let ({ Ast.Statement.Assign.target = _; value = { Node.value; location }; _ } as assignment) =
Ast.Statement.Statement.generator_assignment generator
in
(* Since the analysis views the generator as an assignment, we need to also register (extra)
calls that (are generated above and) appear within the right-hand-side of the assignment*)
let iter, iter_next =
match value with
| Expression.Await
{
Node.value =
Expression.Call
{
callee =
{
Node.value =
Name
(Name.Attribute
{
base =
{
Node.value =
Expression.Call
{
callee =
{
Node.value =
Name (Name.Attribute { attribute = "__aiter__"; _ });
_;
};
_;
} as aiter;
_;
};
attribute = "__anext__";
_;
});
_;
};
_;
} as aiter_anext;
_;
} ->
(* E.g., x async for x in y *) aiter, aiter_anext
| Expression.Call
{
callee =
{
Node.value =
Name
(Name.Attribute
{
base =
{
Node.value =
Expression.Call
{
callee =
{
Node.value =
Name (Name.Attribute { attribute = "__iter__"; _ });
_;
};
_;
} as iter;
_;
};
attribute = "__next__";
_;
});
_;
};
_;
} as iter_next ->
(* E.g., x for x in y *) iter, iter_next
| _ -> failwith "Expect generators to be treated as e.__iter__().__next__()"
in
let state = expression_visitor state { Node.value = iter; location } in
let state = expression_visitor state { Node.value = iter_next; location } in
{ state with resolution = Resolution.resolve_assignment resolution assignment }
let node state = function
| Visit.Expression expression -> expression_visitor state expression
| Visit.Statement statement -> statement_visitor state statement
| Visit.Generator generator -> generator_visitor state generator
| _ -> state
let visit_statement_children _ statement =
match Node.value statement with
| Statement.Assign _
| Statement.Define _
| Statement.Class _ ->
false
| _ -> true
let visit_expression_children _ _ = true
let visit_format_string_children _ _ = true
end
module CalleeVisitor = Visit.MakeNodeVisitor (NodeVisitor)
include Fixpoint.Make (struct
type t = unit [@@deriving show]
let bottom = ()
let less_or_equal ~left:_ ~right:_ = true
let join _ _ = ()
let widen ~previous:_ ~next:_ ~iteration:_ = ()
let forward_statement ~resolution ~statement =
match Node.value statement with
| Statement.Assign { Assign.target; value; _ } ->
CalleeVisitor.visit_expression
~state:
(ref { resolution; assignment_target = Some { location = Node.location target } })
target;
CalleeVisitor.visit_expression ~state:(ref { resolution; assignment_target = None }) value
| _ ->
CalleeVisitor.visit_statement
~state:(ref { resolution; assignment_target = None })
statement
let forward ~statement_key _ ~statement =
let resolution =
TypeCheck.resolution_with_key
~global_resolution:Context.global_resolution
~local_annotations:Context.local_annotations
~parent:Context.parent
~statement_key
(module TypeCheck.DummyContext)
in
forward_statement ~resolution ~statement
let backward ~statement_key:_ _ ~statement:_ = ()
end)
end
let call_graph_of_define
~static_analysis_configuration:{ Configuration.StaticAnalysis.find_missing_flows; _ }
~environment
~override_graph
~attribute_targets
~qualifier
~define:({ Define.signature = { Define.Signature.name; parent; _ }; _ } as define)
=
let timer = Timer.start () in
let callees_at_location = Location.Table.create () in
let module DefineFixpoint = DefineCallGraphFixpoint (struct
let global_resolution = TypeEnvironment.ReadOnly.global_resolution environment
let local_annotations = TypeEnvironment.ReadOnly.get_local_annotations environment name
let qualifier = qualifier
let parent = parent
let callees_at_location = callees_at_location
let override_graph = override_graph
let call_indexer = CallTargetIndexer.create ()
let attribute_targets = attribute_targets
let is_missing_flow_type_analysis =
Option.equal
Configuration.MissingFlowKind.equal
find_missing_flows
(Some Configuration.MissingFlowKind.Type)
end)
in
(* Handle parameters. *)
let () =
let resolution =
TypeCheck.resolution
(TypeEnvironment.ReadOnly.global_resolution environment)
(module TypeCheck.DummyContext)
in
List.iter
define.Ast.Statement.Define.signature.parameters
~f:(fun { Node.value = { Parameter.value; _ }; _ } ->
Option.iter value ~f:(fun value ->
DefineFixpoint.CalleeVisitor.visit_expression
~state:(ref { DefineFixpoint.resolution; assignment_target = None })
value))
in
DefineFixpoint.forward ~cfg:(Cfg.create define) ~initial:() |> ignore;
let call_graph =
Location.Table.to_alist callees_at_location
|> List.map ~f:(fun (location, unprocessed_callees) ->
match SerializableStringMap.to_alist unprocessed_callees with
| [] -> failwith "unreachable"
| [(_, callees)] ->
location, LocationCallees.Singleton (ExpressionCallees.deduplicate callees)
| _ ->
( location,
LocationCallees.Compound
(SerializableStringMap.map ExpressionCallees.deduplicate unprocessed_callees) ))
|> List.filter ~f:(fun (_, callees) ->
match callees with
| LocationCallees.Singleton singleton ->
not (ExpressionCallees.is_empty_attribute_access_callees singleton)
| LocationCallees.Compound compound ->
SerializableStringMap.exists
(fun _ callees ->
not (ExpressionCallees.is_empty_attribute_access_callees callees))
compound)
|> Location.Map.Tree.of_alist_exn
in
Statistics.performance
~randomly_log_every:1000
~always_log_time_threshold:1.0 (* Seconds *)
~name:"Call graph built"
~section:`DependencyGraph
~normals:["callable", Reference.show name]
~timer
();
call_graph
let call_graph_of_callable
~static_analysis_configuration
~environment
~override_graph
~attribute_targets
~callable
=
let resolution = Analysis.TypeEnvironment.ReadOnly.global_resolution environment in
match Target.get_module_and_definition callable ~resolution with
| None -> Format.asprintf "Found no definition for `%a`" Target.pp_pretty callable |> failwith
| Some (qualifier, define) ->
call_graph_of_define
~static_analysis_configuration
~environment
~override_graph
~attribute_targets
~qualifier
~define:(Node.value define)
* Call graphs of callables , stored in the shared memory . This is a mapping from a callable to its
` DefineCallGraph.t ` .
`DefineCallGraph.t`. *)
module DefineCallGraphSharedMemory = struct
include
Memory.WithCache.Make
(Target.SharedMemoryKey)
(struct
type t = LocationCallees.t Location.Map.Tree.t
let prefix = Prefix.make ()
let description = "call graphs of defines"
end)
type t = Handle
let set Handle ~callable ~call_graph = add callable call_graph
let get Handle ~callable = get callable
end
(** Whole-program call graph, stored in the ocaml heap. This is a mapping from a callable to all its
callees. *)
module WholeProgramCallGraph = struct
type t = Target.t list Target.Map.Tree.t
let empty = Target.Map.Tree.empty
let is_empty = Target.Map.Tree.is_empty
let of_alist_exn = Target.Map.Tree.of_alist_exn
let add_or_exn ~callable ~callees call_graph =
Target.Map.Tree.update call_graph callable ~f:(function
| None -> callees
| Some _ ->
Format.asprintf "Program call graph already has callees for `%a`" Target.pp callable
|> failwith)
let fold graph ~init ~f =
Target.Map.Tree.fold graph ~init ~f:(fun ~key:target ~data:callees -> f ~target ~callees)
let merge_disjoint left right =
Target.Map.Tree.merge_skewed
~combine:(fun ~key:_ _ _ -> failwith "call graphs are not disjoint")
left
right
let to_target_graph graph = graph
end
type call_graphs = {
whole_program_call_graph: WholeProgramCallGraph.t;
define_call_graphs: DefineCallGraphSharedMemory.t;
}
* Build the whole call graph of the program .
The overrides must be computed first because we depend on a global shared memory graph to
include overrides in the call graph . Without it , we 'll underanalyze and have an inconsistent
fixpoint .
The overrides must be computed first because we depend on a global shared memory graph to
include overrides in the call graph. Without it, we'll underanalyze and have an inconsistent
fixpoint. *)
let build_whole_program_call_graph
~scheduler
~static_analysis_configuration
~environment
~override_graph
~store_shared_memory
~attribute_targets
~skip_analysis_targets
~callables
=
let define_call_graphs = DefineCallGraphSharedMemory.Handle in
let whole_program_call_graph =
let build_call_graph whole_program_call_graph callable =
if Target.Set.mem callable skip_analysis_targets then
whole_program_call_graph
else
let callable_call_graph =
Metrics.with_alarm
~max_time_in_seconds:60
~event_name:"call graph building"
~callable
(fun () ->
call_graph_of_callable
~static_analysis_configuration
~environment
~override_graph
~attribute_targets
~callable)
()
in
let () =
if store_shared_memory then
DefineCallGraphSharedMemory.set
define_call_graphs
~callable
~call_graph:callable_call_graph
in
WholeProgramCallGraph.add_or_exn
whole_program_call_graph
~callable
~callees:(DefineCallGraph.all_targets callable_call_graph)
in
Scheduler.map_reduce
scheduler
~policy:
(Scheduler.Policy.fixed_chunk_size
~minimum_chunks_per_worker:1
~minimum_chunk_size:100
~preferred_chunk_size:2000
())
~initial:WholeProgramCallGraph.empty
~map:(fun _ callables ->
List.fold callables ~init:WholeProgramCallGraph.empty ~f:build_call_graph)
~reduce:WholeProgramCallGraph.merge_disjoint
~inputs:callables
()
in
let () =
match static_analysis_configuration.Configuration.StaticAnalysis.save_results_to with
| Some path ->
let path = PyrePath.append path ~element:"call-graph.json" in
Log.info "Writing the call graph to `%s`" (PyrePath.absolute path);
whole_program_call_graph |> WholeProgramCallGraph.to_target_graph |> TargetGraph.dump ~path
| None -> ()
in
let () =
match static_analysis_configuration.Configuration.StaticAnalysis.dump_call_graph with
| Some path ->
Log.warning "Emitting the contents of the call graph to `%s`" (PyrePath.absolute path);
whole_program_call_graph |> WholeProgramCallGraph.to_target_graph |> TargetGraph.dump ~path
| None -> ()
in
{ whole_program_call_graph; define_call_graphs }
| null | https://raw.githubusercontent.com/facebook/pyre-check/3032acd2ffe3567defa05211bd6344cc7b7b10b1/source/interprocedural/callGraph.ml | ocaml | * Represents type information about the return type of a call.
Try to infer the return type from the callable type, otherwise lazily fallback
* to the resolved return type.
* A specific target of a given call, with extra information.
True if the call has an implicit receiver.
* For instance, `x.foo()` should be treated as `C.foo(x)`.
True if this is an implicit call to the `__call__` method.
The textual order index of the call in the function.
The return type of the call expression, or `None` for object targets.
The type of the receiver object at this call site, if any.
* Information about an argument being a callable.
* An aggregate of all possible callees at a call site.
Normal call targets.
Call targets for calls to the `__new__` class method.
Call targets for calls to the `__init__` instance method.
Is it not enough to check the class name, since methods can be inherited.
* For instance, `__iter__` is not defined on `Mapping`, but is defined in the parent class `Iterable`.
Unresolved call, assume it's object.__new__
Unresolved call, assume it's object.__init__
* An aggregrate of all possible callees for a given attribute access.
True if the attribute access should also be considered a regular attribute.
* For instance, if the object has type `Union[A, B]` where only `A` defines a property.
* An aggregate of all possible callees for a given identifier expression, i.e `foo`.
* An aggregate of callees for formatting strings.
Implicit callees for any expression that is stringified.
Artificial callees for distinguishing f-strings within a function.
* An aggregate of all possible callees for an arbitrary expression.
* An aggregate of all possible callees for an arbitrary location.
Note that multiple expressions might have the same location.
not a valid call site.
* The call graph of a function or method definition.
* Return all callees of the call graph, as a sorted list.
We must be dealing with a callable class.
case a
case b
case c
Handle callable classes. `typing.Type` interacts specially with __call__, so we choose to
ignore it for now to make sure our constructor logic via `cls()` still works.
Callable protocol.
Technically, `object.__new__` returns `object` and `C.__init__` returns None.
* In practice, we actually want to use the class type.
If implementing_class is unknown, this must be a function rather than a method. We can use
global resolution on the callee.
Rewrite certain calls for the interprocedural analysis (e.g, pysa).
* This may or may not be sound depending on the analysis performed.
Only handle `iter` with a single argument here.
Only handle `next` with a single argument here.
Only handle `anext` with a single argument here.
Rewrite certain calls using the same logic used in the type checker.
* This should be sound for most analyses.
Special treatment for a set of hardcoded decorators returning callable classes.
Resolving expressions that do not reference local variables or parameters.
Resolving the return type can be costly, hence we prefer the annotation on the callee when
possible. When that does not work, we fallback to a full resolution of the call expression
(done lazily).
Access on an instance, i.e `self.foo`.
This is a bit of a trick. The only place that knows where the local annotation map keys is the
fixpoint (shared across the type check and additional static analysis modules). By having a
fixpoint that always terminates (by having a state = unit), we re-use the fixpoint id's without
having to hackily recompute them.
For the missing flow analysis (`--find-missing-flows=type`), we turn unresolved
* calls into sinks, so that we may find sources flowing into those calls.
TODO(T117715045): Move the target creation in `taint/missingFlow.ml`.
Use indexed artificial targets to distinguish format strings at different
locations.
Special-case `getattr()` and `setattr()` for the taint analysis.
Since the analysis views the generator as an assignment, we need to also register (extra)
calls that (are generated above and) appear within the right-hand-side of the assignment
E.g., x async for x in y
E.g., x for x in y
Handle parameters.
Seconds
* Whole-program call graph, stored in the ocaml heap. This is a mapping from a callable to all its
callees. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
CallGraph : defines the call graph of a callable ( function or method ) , which
* stores the set of calles for each call site .
*
* This also implements the logic to statically compute the call graph , given a
* function definition .
*
* Note that the call graph is highly tuned for the taint analysis and might be
* unsound for other analyses .
* stores the set of calles for each call site.
*
* This also implements the logic to statically compute the call graph, given a
* function definition.
*
* Note that the call graph is highly tuned for the taint analysis and might be
* unsound for other analyses.
*)
open Core
open Data_structures
open Analysis
open Ast
open Statement
open Expression
open Pyre
module ReturnType = struct
type t = {
is_boolean: bool;
is_integer: bool;
is_float: bool;
is_enumeration: bool;
}
[@@deriving compare, eq]
let pp formatter { is_boolean; is_integer; is_float; is_enumeration } =
let add_if condition tag tags =
if condition then
tag :: tags
else
tags
in
[]
|> add_if is_enumeration "enum"
|> add_if is_float "float"
|> add_if is_integer "int"
|> add_if is_boolean "bool"
|> String.concat ~sep:"|"
|> Format.fprintf formatter "{%s}"
let show = Format.asprintf "%a" pp
let none = { is_boolean = false; is_integer = false; is_float = false; is_enumeration = false }
let any = none
let bool = { is_boolean = true; is_integer = false; is_float = false; is_enumeration = false }
let integer = { is_boolean = false; is_integer = true; is_float = true; is_enumeration = false }
let from_annotation ~resolution annotation =
let matches_at_leaves ~f annotation =
let rec matches_at_leaves ~f annotation =
match annotation with
| Type.Any
| Type.Bottom ->
false
| Type.Union [Type.NoneType; annotation]
| Type.Union [annotation; Type.NoneType]
| Type.Parametric { name = "typing.Awaitable"; parameters = [Single annotation] } ->
matches_at_leaves ~f annotation
| Type.Tuple (Concatenation concatenation) ->
Type.OrderedTypes.Concatenation.extract_sole_unbounded_annotation concatenation
>>| (fun element -> matches_at_leaves ~f element)
|> Option.value ~default:(f annotation)
| Type.Tuple (Type.OrderedTypes.Concrete annotations) ->
List.for_all annotations ~f:(matches_at_leaves ~f)
| annotation -> f annotation
in
matches_at_leaves ~f annotation
in
try
let is_boolean =
matches_at_leaves annotation ~f:(fun left ->
GlobalResolution.less_or_equal resolution ~left ~right:Type.bool)
in
let is_integer =
matches_at_leaves annotation ~f:(fun left ->
GlobalResolution.less_or_equal resolution ~left ~right:Type.integer)
in
let is_float =
matches_at_leaves annotation ~f:(fun left ->
GlobalResolution.less_or_equal resolution ~left ~right:Type.float)
in
let is_enumeration =
matches_at_leaves annotation ~f:(fun left ->
GlobalResolution.less_or_equal resolution ~left ~right:Type.enumeration)
in
{ is_boolean; is_integer; is_float; is_enumeration }
with
| Analysis.ClassHierarchy.Untracked untracked_type ->
Log.warning
"Found untracked type `%s` when checking the return type `%a` of a call. The return type \
will NOT be considered a scalar, which could lead to missing breadcrumbs."
untracked_type
Type.pp
annotation;
none
let from_callable_with_fallback ~resolution ~callable_type ~return_type =
let annotation =
match callable_type with
| Type.Callable { implementation = { annotation; _ }; overloads = []; _ }
when Type.Variable.all_variables_are_resolved annotation ->
annotation
| _ -> Lazy.force return_type
in
from_annotation ~resolution:(Resolution.global_resolution resolution) annotation
end
module CallTarget = struct
type t = {
target: Target.t;
implicit_self: bool;
implicit_dunder_call: bool;
index: int;
return_type: ReturnType.t option;
receiver_type: Type.t option;
}
[@@deriving compare, eq, show { with_path = false }]
let target { target; _ } = target
let equal_ignoring_indices left right = equal left { right with index = left.index }
let dedup_and_sort targets =
targets
|> List.sort ~compare
|> List.remove_consecutive_duplicates ~which_to_keep:`First ~equal:equal_ignoring_indices
let create
?(implicit_self = false)
?(implicit_dunder_call = false)
?(index = 0)
?(return_type = Some ReturnType.any)
?receiver_type
target
=
{ target; implicit_self; implicit_dunder_call; index; return_type; receiver_type }
let equal_ignoring_types
{
target = target_left;
implicit_self = implicit_self_left;
implicit_dunder_call = implicit_dunder_call_left;
index = index_left;
return_type = _;
receiver_type = _;
}
{
target = target_right;
implicit_self = implicit_self_right;
implicit_dunder_call = implicit_dunder_call_right;
index = index_right;
return_type = _;
receiver_type = _;
}
=
Target.equal target_left target_right
&& implicit_self_left == implicit_self_right
&& implicit_dunder_call_left == implicit_dunder_call_right
&& index_left == index_right
end
module HigherOrderParameter = struct
type t = {
index: int;
call_targets: CallTarget.t list;
True if at least one callee could not be resolved .
* Usually indicates missing type information at the call site .
* Usually indicates missing type information at the call site. *)
unresolved: bool;
}
[@@deriving eq, show { with_path = false }]
let all_targets { call_targets; _ } = List.map ~f:CallTarget.target call_targets
let equal_ignoring_types
{ index = index_left; call_targets = call_targets_left; unresolved = unresolved_left }
{ index = index_right; call_targets = call_targets_right; unresolved = unresolved_right }
=
index_left == index_right
&& List.equal CallTarget.equal_ignoring_types call_targets_left call_targets_right
&& unresolved_left == unresolved_right
let join
{ index; call_targets = call_targets_left; unresolved = unresolved_left }
{ index = _; call_targets = call_targets_right; unresolved = unresolved_right }
=
{
index;
call_targets = List.rev_append call_targets_left call_targets_right;
unresolved = unresolved_left || unresolved_right;
}
let deduplicate { index; call_targets; unresolved } =
{ index; call_targets = CallTarget.dedup_and_sort call_targets; unresolved }
end
* Mapping from a parameter index to its , if any .
module HigherOrderParameterMap = struct
module Map = SerializableMap.Make (Int)
type t = HigherOrderParameter.t Map.t
let empty = Map.empty
let is_empty = Map.is_empty
let pp = Map.pp HigherOrderParameter.pp
let show = Format.asprintf "%a" pp
let equal = Map.equal HigherOrderParameter.equal
let equal_ignoring_types = Map.equal HigherOrderParameter.equal_ignoring_types
let join left right =
Map.union (fun _ left right -> Some (HigherOrderParameter.join left right)) left right
let deduplicate map = Map.map HigherOrderParameter.deduplicate map
let all_targets map =
Map.fold
(fun _ higher_order_parameter targets ->
List.rev_append targets (HigherOrderParameter.all_targets higher_order_parameter))
map
[]
let add map ({ HigherOrderParameter.index; _ } as higher_order_parameter) =
Map.update
index
(function
| None -> Some higher_order_parameter
| Some existing -> Some (HigherOrderParameter.join existing higher_order_parameter))
map
let from_list list = List.fold list ~init:Map.empty ~f:add
let to_list map = Map.data map
let first_index map =
Map.min_binding_opt map >>| fun (_, higher_order_parameter) -> higher_order_parameter
end
module CallCallees = struct
type t = {
call_targets: CallTarget.t list;
new_targets: CallTarget.t list;
init_targets: CallTarget.t list;
Information about arguments that are , and possibly called .
higher_order_parameters: HigherOrderParameterMap.t;
True if at least one callee could not be resolved .
* Usually indicates missing type information at the call site .
* Usually indicates missing type information at the call site. *)
unresolved: bool;
}
[@@deriving eq, show { with_path = false }]
let create
?(call_targets = [])
?(new_targets = [])
?(init_targets = [])
?(higher_order_parameters = HigherOrderParameterMap.empty)
?(unresolved = false)
()
=
{ call_targets; new_targets; init_targets; higher_order_parameters; unresolved }
let unresolved =
{
call_targets = [];
new_targets = [];
init_targets = [];
higher_order_parameters = HigherOrderParameterMap.empty;
unresolved = true;
}
let is_partially_resolved = function
| { call_targets = _ :: _; _ } -> true
| { new_targets = _ :: _; _ } -> true
| { init_targets = _ :: _; _ } -> true
| _ -> false
let pp_option formatter = function
| None -> Format.fprintf formatter "None"
| Some callees -> pp formatter callees
let join
{
call_targets = left_call_targets;
new_targets = left_new_targets;
init_targets = left_init_targets;
higher_order_parameters = left_higher_order_parameters;
unresolved = left_unresolved;
}
{
call_targets = right_call_targets;
new_targets = right_new_targets;
init_targets = right_init_targets;
higher_order_parameters = right_higher_order_parameters;
unresolved = right_unresolved;
}
=
let call_targets = List.rev_append left_call_targets right_call_targets in
let new_targets = List.rev_append left_new_targets right_new_targets in
let init_targets = List.rev_append left_init_targets right_init_targets in
let higher_order_parameters =
HigherOrderParameterMap.join left_higher_order_parameters right_higher_order_parameters
in
let unresolved = left_unresolved || right_unresolved in
{ call_targets; new_targets; init_targets; higher_order_parameters; unresolved }
let deduplicate { call_targets; new_targets; init_targets; higher_order_parameters; unresolved } =
let call_targets = CallTarget.dedup_and_sort call_targets in
let new_targets = CallTarget.dedup_and_sort new_targets in
let init_targets = CallTarget.dedup_and_sort init_targets in
let higher_order_parameters = HigherOrderParameterMap.deduplicate higher_order_parameters in
{ call_targets; new_targets; init_targets; higher_order_parameters; unresolved }
let all_targets { call_targets; new_targets; init_targets; higher_order_parameters; _ } =
call_targets
|> List.rev_append new_targets
|> List.rev_append init_targets
|> List.map ~f:CallTarget.target
|> List.rev_append (HigherOrderParameterMap.all_targets higher_order_parameters)
let equal_ignoring_types
{
call_targets = call_targets_left;
new_targets = new_targets_left;
init_targets = init_targets_left;
higher_order_parameters = higher_order_parameter_lefts;
unresolved = unresolved_left;
}
{
call_targets = call_targets_right;
new_targets = new_targets_right;
init_targets = init_targets_right;
higher_order_parameters = higher_order_parameter_rights;
unresolved = unresolved_right;
}
=
List.equal CallTarget.equal_ignoring_types call_targets_left call_targets_right
&& List.equal CallTarget.equal_ignoring_types new_targets_left new_targets_right
&& List.equal CallTarget.equal_ignoring_types init_targets_left init_targets_right
&& HigherOrderParameterMap.equal_ignoring_types
higher_order_parameter_lefts
higher_order_parameter_rights
&& unresolved_left == unresolved_right
let is_method_of_class ~is_class_name callees =
let rec is_class_type = function
| Type.Primitive name -> is_class_name name
| Type.Parametric { name; _ } -> is_class_name name
| Type.Union [NoneType; annotation]
| Type.Union [annotation; NoneType] ->
is_class_type annotation
| Type.Union annotations -> List.for_all ~f:is_class_type annotations
| _ -> false
in
let is_call_target = function
| { CallTarget.target = Method { class_name; _ }; receiver_type; _ }
| { target = Override { class_name; _ }; receiver_type; _ } ->
is_class_name class_name || receiver_type >>| is_class_type |> Option.value ~default:false
| _ -> false
in
match callees with
| { call_targets = []; _ } -> false
| { call_targets; _ } -> List.for_all call_targets ~f:is_call_target
let is_mapping_method callees =
let is_class_name = function
| "dict"
| "typing.Mapping"
| "typing.MutableMapping"
| "TypedDictionary"
| "NonTotalTypedDictionary"
| "collections.OrderedDict"
| "collections.defaultdict" ->
true
| _ -> false
in
is_method_of_class ~is_class_name callees
let is_sequence_method callees =
let is_class_name = function
| "list"
| "typing.Sequence"
| "typing.MutableSequence"
| "collections.deque"
| "tuple" ->
true
| _ -> false
in
is_method_of_class ~is_class_name callees
let is_object_new = function
| [
{
CallTarget.target =
Target.Method { class_name = "object"; method_name = "__new__"; kind = Normal };
_;
};
] ->
true
| _ -> false
let is_object_init = function
| [
{
CallTarget.target =
Target.Method { class_name = "object"; method_name = "__init__"; kind = Normal };
_;
};
] ->
true
| _ -> false
end
module AttributeAccessCallees = struct
type t = {
property_targets: CallTarget.t list;
global_targets: CallTarget.t list;
is_attribute: bool;
}
[@@deriving eq, show { with_path = false }]
let deduplicate { property_targets; global_targets; is_attribute } =
{
property_targets = CallTarget.dedup_and_sort property_targets;
global_targets = CallTarget.dedup_and_sort global_targets;
is_attribute;
}
let join
{
property_targets = left_property_targets;
global_targets = left_global_targets;
is_attribute = left_is_attribute;
}
{
property_targets = right_property_targets;
global_targets = right_global_targets;
is_attribute = right_is_attribute;
}
=
{
property_targets = List.rev_append left_property_targets right_property_targets;
global_targets = List.rev_append left_global_targets right_global_targets;
is_attribute = left_is_attribute || right_is_attribute;
}
let all_targets { property_targets; global_targets; _ } =
List.rev_append property_targets global_targets |> List.map ~f:CallTarget.target
let equal_ignoring_types
{
property_targets = property_targets_left;
global_targets = global_targets_left;
is_attribute = is_attribute_left;
}
{
property_targets = property_targets_right;
global_targets = global_targets_right;
is_attribute = is_attribute_right;
}
=
List.equal CallTarget.equal_ignoring_types property_targets_left property_targets_right
&& List.equal CallTarget.equal_ignoring_types global_targets_left global_targets_right
&& is_attribute_left == is_attribute_right
let empty = { property_targets = []; global_targets = []; is_attribute = true }
let is_empty attribute_access_callees = equal attribute_access_callees empty
end
module IdentifierCallees = struct
type t = { global_targets: CallTarget.t list } [@@deriving eq, show { with_path = false }]
let deduplicate { global_targets } = { global_targets = CallTarget.dedup_and_sort global_targets }
let join { global_targets = left_global_targets } { global_targets = right_global_targets } =
{ global_targets = List.rev_append left_global_targets right_global_targets }
let all_targets { global_targets } = List.map ~f:CallTarget.target global_targets
end
module StringFormatCallees = struct
type t = {
stringify_targets: CallTarget.t list;
f_string_targets: CallTarget.t list;
}
[@@deriving eq, show { with_path = false }]
let deduplicate { stringify_targets; f_string_targets } =
{
stringify_targets = CallTarget.dedup_and_sort stringify_targets;
f_string_targets = CallTarget.dedup_and_sort f_string_targets;
}
let join
{ stringify_targets = left_stringify_targets; f_string_targets = left_f_string_targets }
{ stringify_targets = right_stringify_targets; f_string_targets = right_f_string_targets }
=
{
stringify_targets = List.rev_append left_stringify_targets right_stringify_targets;
f_string_targets = List.rev_append left_f_string_targets right_f_string_targets;
}
let all_targets { stringify_targets; f_string_targets } =
List.rev_append stringify_targets f_string_targets |> List.map ~f:CallTarget.target
let from_stringify_targets stringify_targets = { stringify_targets; f_string_targets = [] }
let from_f_string_targets f_string_targets = { stringify_targets = []; f_string_targets }
end
module ExpressionCallees = struct
type t = {
call: CallCallees.t option;
attribute_access: AttributeAccessCallees.t option;
identifier: IdentifierCallees.t option;
string_format: StringFormatCallees.t option;
}
[@@deriving eq, show { with_path = false }]
let from_call callees =
{ call = Some callees; attribute_access = None; identifier = None; string_format = None }
let from_call_with_empty_attribute callees =
{
call = Some callees;
attribute_access = Some AttributeAccessCallees.empty;
identifier = None;
string_format = None;
}
let from_attribute_access properties =
{ call = None; attribute_access = Some properties; identifier = None; string_format = None }
let from_identifier identifier =
{ call = None; attribute_access = None; identifier = Some identifier; string_format = None }
let from_string_format string_format =
{ call = None; attribute_access = None; identifier = None; string_format = Some string_format }
let join
{
call = left_call;
attribute_access = left_attribute_access;
identifier = left_identifier;
string_format = left_string_format;
}
{
call = right_call;
attribute_access = right_attribute_access;
identifier = right_identifier;
string_format = right_string_format;
}
=
{
call = Option.merge ~f:CallCallees.join left_call right_call;
attribute_access =
Option.merge ~f:AttributeAccessCallees.join left_attribute_access right_attribute_access;
identifier = Option.merge ~f:IdentifierCallees.join left_identifier right_identifier;
string_format =
Option.merge ~f:StringFormatCallees.join left_string_format right_string_format;
}
let deduplicate { call; attribute_access; identifier; string_format } =
{
call = call >>| CallCallees.deduplicate;
attribute_access = attribute_access >>| AttributeAccessCallees.deduplicate;
identifier = identifier >>| IdentifierCallees.deduplicate;
string_format = string_format >>| StringFormatCallees.deduplicate;
}
let all_targets { call; attribute_access; identifier; string_format } =
let call_targets = call >>| CallCallees.all_targets |> Option.value ~default:[] in
let attribute_access_targets =
attribute_access >>| AttributeAccessCallees.all_targets |> Option.value ~default:[]
in
let identifier_targets =
identifier >>| IdentifierCallees.all_targets |> Option.value ~default:[]
in
let string_format_targets =
string_format >>| StringFormatCallees.all_targets |> Option.value ~default:[]
in
call_targets
|> List.rev_append attribute_access_targets
|> List.rev_append identifier_targets
|> List.rev_append string_format_targets
let is_empty_attribute_access_callees = function
| {
call = None;
attribute_access = Some some_attribute_access;
identifier = None;
string_format = None;
} ->
AttributeAccessCallees.is_empty some_attribute_access
| _ -> false
let equal_ignoring_types
{
call = call_left;
attribute_access = attribute_access_left;
identifier = identifier_left;
string_format = string_format_left;
}
{
call = call_right;
attribute_access = attribute_access_right;
identifier = identifier_right;
string_format = string_format_right;
}
=
Option.equal CallCallees.equal_ignoring_types call_left call_right
&& Option.equal
AttributeAccessCallees.equal_ignoring_types
attribute_access_left
attribute_access_right
&& Option.equal IdentifierCallees.equal identifier_left identifier_right
&& Option.equal StringFormatCallees.equal string_format_left string_format_right
end
module LocationCallees = struct
type t =
| Singleton of ExpressionCallees.t
| Compound of ExpressionCallees.t SerializableStringMap.t
[@@deriving eq]
let pp formatter = function
| Singleton callees -> Format.fprintf formatter "%a" ExpressionCallees.pp callees
| Compound map ->
SerializableStringMap.to_alist map
|> List.map ~f:(fun (key, value) -> Format.asprintf "%s: %a" key ExpressionCallees.pp value)
|> String.concat ~sep:", "
|> Format.fprintf formatter "%s"
let show callees = Format.asprintf "%a" pp callees
let all_targets = function
| Singleton raw_callees -> ExpressionCallees.all_targets raw_callees
| Compound map ->
SerializableStringMap.data map |> List.concat_map ~f:ExpressionCallees.all_targets
let equal_ignoring_types location_callees_left location_callees_right =
match location_callees_left, location_callees_right with
| Singleton callees_left, Singleton callees_right ->
ExpressionCallees.equal_ignoring_types callees_left callees_right
| Compound map_left, Compound map_right ->
SerializableStringMap.equal ExpressionCallees.equal_ignoring_types map_left map_right
| _ -> false
end
module UnprocessedLocationCallees = struct
type t = ExpressionCallees.t SerializableStringMap.t
let singleton ~expression_identifier ~callees =
SerializableStringMap.singleton expression_identifier callees
let add map ~expression_identifier ~callees =
SerializableStringMap.update
expression_identifier
(function
| Some existing_callees -> Some (ExpressionCallees.join existing_callees callees)
| None -> Some callees)
map
end
let call_identifier { Call.callee; _ } =
match Node.value callee with
| Name (Name.Attribute { attribute; _ }) -> attribute
| Name (Name.Identifier name) -> name
| _ ->
Fall back to something that hopefully identifies the call well .
Expression.show callee
let expression_identifier = function
| Expression.Call call -> Some (call_identifier call)
| Expression.Name (Name.Attribute { attribute; _ }) -> Some attribute
module DefineCallGraph = struct
type t = LocationCallees.t Location.Map.Tree.t [@@deriving eq]
let pp formatter call_graph =
let pp_pair formatter (key, value) =
Format.fprintf formatter "@,%a -> %a" Location.pp key LocationCallees.pp value
in
let pp_pairs formatter = List.iter ~f:(pp_pair formatter) in
call_graph |> Location.Map.Tree.to_alist |> Format.fprintf formatter "{@[<v 2>%a@]@,}" pp_pairs
let show = Format.asprintf "%a" pp
let empty = Location.Map.Tree.empty
let add call_graph ~location ~callees =
Location.Map.Tree.set call_graph ~key:location ~data:callees
let resolve_expression call_graph ~location ~expression_identifier =
match Location.Map.Tree.find call_graph location with
| Some (LocationCallees.Singleton callees) -> Some callees
| Some (LocationCallees.Compound name_to_callees) ->
SerializableStringMap.find_opt expression_identifier name_to_callees
| None -> None
let resolve_call call_graph ~location ~call =
expression_identifier (Expression.Call call)
>>= fun expression_identifier ->
resolve_expression call_graph ~location ~expression_identifier >>= fun { call; _ } -> call
let resolve_attribute_access call_graph ~location ~attribute =
resolve_expression call_graph ~location ~expression_identifier:attribute
>>= fun { attribute_access; _ } -> attribute_access
let resolve_identifier call_graph ~location ~identifier =
resolve_expression call_graph ~location ~expression_identifier:identifier
>>= fun { identifier; _ } -> identifier
let string_format_expression_identifier = "$__str__$"
let resolve_string_format call_graph ~location =
resolve_expression
call_graph
~location
~expression_identifier:string_format_expression_identifier
>>= fun { string_format; _ } -> string_format
let equal_ignoring_types call_graph_left call_graph_right =
Location.Map.Tree.equal LocationCallees.equal_ignoring_types call_graph_left call_graph_right
let all_targets call_graph =
Location.Map.Tree.data call_graph
|> List.concat_map ~f:LocationCallees.all_targets
|> List.dedup_and_sort ~compare:Target.compare
end
Produce call targets with a textual order index .
*
* The index is the number of times a given function or method was previously called ,
* respecting the execution flow .
*
* ` ` `
* def f ( ):
* a = source_with_hop ( ) # index=0
* = a ) # index=0
* sink_with_hop(y = a ) # index=1
* b = source_with_hop ( ) # index=1
* sink_with_hop(z = a ) # index=2
* ` ` `
*
* The index is the number of times a given function or method was previously called,
* respecting the execution flow.
*
* ```
* def f():
* a = source_with_hop() # index=0
* sink_with_hop(x=a) # index=0
* sink_with_hop(y=a) # index=1
* b = source_with_hop() # index=1
* sink_with_hop(z=a) # index=2
* ```
*)
module CallTargetIndexer = struct
type t = {
indices: int Target.HashMap.t;
mutable seen_targets: Target.Set.t;
}
let create () = { indices = Target.HashMap.create (); seen_targets = Target.Set.empty }
let generate_fresh_indices indexer =
Target.Set.iter (Target.HashMap.incr indexer.indices) indexer.seen_targets;
indexer.seen_targets <- Target.Set.empty
let create_target
indexer
~implicit_self
~implicit_dunder_call
~return_type
?receiver_type
original_target
=
let target_for_index = Target.override_to_method original_target in
let index = Target.HashMap.find indexer.indices target_for_index |> Option.value ~default:0 in
indexer.seen_targets <- Target.Set.add target_for_index indexer.seen_targets;
{
CallTarget.target = original_target;
implicit_self;
implicit_dunder_call;
index;
return_type;
receiver_type;
}
end
type callee_kind =
| Method of { is_direct_call: bool }
| Function
let is_local identifier = String.is_prefix ~prefix:"$" identifier
let rec is_all_names = function
| Expression.Name (Name.Identifier identifier) when not (is_local identifier) -> true
| Name (Name.Attribute { base; attribute; _ }) when not (is_local attribute) ->
is_all_names (Node.value base)
| _ -> false
let rec callee_kind ~resolution callee callee_type =
let is_super_call =
let rec is_super callee =
match Node.value callee with
| Expression.Call { callee = { Node.value = Name (Name.Identifier "super"); _ }; _ } -> true
| Call { callee; _ } -> is_super callee
| Name (Name.Attribute { base; _ }) -> is_super base
| _ -> false
in
is_super callee
in
match callee_type with
| _ when is_super_call -> Method { is_direct_call = true }
| Type.Parametric { name = "BoundMethod"; _ } ->
Method { is_direct_call = is_all_names (Node.value callee) }
| Type.Callable _ -> (
match Node.value callee with
| Expression.Name (Name.Attribute { base; _ }) ->
let parent_type = CallResolution.resolve_ignoring_optional ~resolution base in
let is_class () =
parent_type
|> GlobalResolution.class_summary (Resolution.global_resolution resolution)
|> Option.is_some
in
if Type.is_meta parent_type then
Method { is_direct_call = true }
else if is_class () then
Method { is_direct_call = false }
else
Function
| _ -> Function)
| Type.Union (callee_type :: _) -> callee_kind ~resolution callee callee_type
| _ ->
Method { is_direct_call = false }
let strip_optional annotation = Type.optional_value annotation |> Option.value ~default:annotation
let strip_meta annotation =
if Type.is_meta annotation then
Type.single_parameter annotation
else
annotation
Figure out what target to pick for an indirect call that resolves to implementation_target .
E.g. , if the receiver type is A , and A derives from Base , and the target is Base.method , then
targeting the override tree of is wrong , as it would include all siblings for A.
* Instead , we have the following cases :
* a ) receiver type matches implementation_target 's declaring type - > override implementation_target
* b ) no implementation_target override entries are subclasses of A - > real implementation_target
* c ) some override entries are subclasses of A - > search upwards for actual implementation ,
* and override all those where the override name is
* 1 ) the override target if it exists in the override shared mem
* 2 ) the real target otherwise
E.g., if the receiver type is A, and A derives from Base, and the target is Base.method, then
targeting the override tree of Base.method is wrong, as it would include all siblings for A.
* Instead, we have the following cases:
* a) receiver type matches implementation_target's declaring type -> override implementation_target
* b) no implementation_target override entries are subclasses of A -> real implementation_target
* c) some override entries are subclasses of A -> search upwards for actual implementation,
* and override all those where the override name is
* 1) the override target if it exists in the override shared mem
* 2) the real target otherwise
*)
let compute_indirect_targets ~resolution ~override_graph ~receiver_type implementation_target =
Target name must be the resolved implementation target
let global_resolution = Resolution.global_resolution resolution in
let get_class_type = GlobalResolution.parse_reference global_resolution in
let get_actual_target method_name =
if OverrideGraph.SharedMemory.overrides_exist override_graph method_name then
Target.get_corresponding_override method_name
else
method_name
in
let receiver_type = receiver_type |> strip_meta |> strip_optional |> Type.weaken_literals in
let declaring_type, method_name, kind =
match implementation_target with
| Target.Method { class_name; method_name; kind } ->
Reference.create class_name, method_name, kind
| _ -> failwith "Unexpected target"
in
[get_actual_target implementation_target]
else
match
OverrideGraph.SharedMemory.get_overriding_types override_graph ~member:implementation_target
with
| None ->
[implementation_target]
| Some overriding_types ->
let keep_subtypes candidate =
let candidate_type = get_class_type candidate in
try
GlobalResolution.less_or_equal
global_resolution
~left:candidate_type
~right:receiver_type
with
| Analysis.ClassHierarchy.Untracked untracked_type ->
Log.warning
"Found untracked type `%s` when comparing `%a` and `%a`. The class `%a` will be \
considered a subclass of `%a`, which could lead to false positives."
untracked_type
Type.pp
candidate_type
Type.pp
receiver_type
Type.pp
candidate_type
Type.pp
receiver_type;
true
in
let override_targets =
let create_override_target class_name =
get_actual_target
(Target.Method { class_name = Reference.show class_name; method_name; kind })
in
List.filter overriding_types ~f:keep_subtypes
|> fun subtypes -> List.map subtypes ~f:create_override_target
in
implementation_target :: override_targets
let rec resolve_callees_from_type
~resolution
~override_graph
~call_indexer
?(dunder_call = false)
?receiver_type
~return_type
~callee_kind
callable_type
=
let resolve_callees_from_type ?(dunder_call = dunder_call) =
resolve_callees_from_type ~dunder_call
in
match callable_type with
| Type.Callable { kind = Named name; _ } -> (
let return_type =
ReturnType.from_callable_with_fallback ~resolution ~callable_type ~return_type
in
match receiver_type with
| Some receiver_type ->
let targets =
match callee_kind with
| Method { is_direct_call = true } -> [Target.create_method name]
| _ ->
compute_indirect_targets
~resolution
~override_graph
~receiver_type
(Target.create_method name)
in
let targets =
List.map
~f:(fun target ->
CallTargetIndexer.create_target
call_indexer
~implicit_self:true
~implicit_dunder_call:dunder_call
~return_type:(Some return_type)
~receiver_type
target)
targets
in
CallCallees.create ~call_targets:targets ()
| None ->
let target =
match callee_kind with
| Method _ -> Target.create_method name
| _ -> Target.create_function name
in
CallCallees.create
~call_targets:
[
CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:dunder_call
~return_type:(Some return_type)
?receiver_type
target;
]
())
| Type.Callable { kind = Anonymous; _ } -> CallCallees.unresolved
| Type.Parametric { name = "BoundMethod"; parameters = [Single callable; Single receiver_type] }
->
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~receiver_type
~return_type
~callee_kind
callable
| Type.Union (element :: elements) ->
let first_targets =
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~callee_kind
?receiver_type
~return_type
element
in
List.fold elements ~init:first_targets ~f:(fun combined_targets new_target ->
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
?receiver_type
~return_type
~callee_kind
new_target
|> CallCallees.join combined_targets)
| Type.Parametric { name = "type"; parameters = [Single class_type] } ->
resolve_constructor_callee ~resolution ~override_graph ~call_indexer class_type
|> Option.value ~default:CallCallees.unresolved
| callable_type -> (
match
CallResolution.resolve_attribute_access_ignoring_untracked
~resolution
~base_type:callable_type
~attribute:"__call__"
with
| Type.Any
| Type.Top ->
CallCallees.unresolved
| Type.Callable { kind = Anonymous; _ } as resolved_dunder_call ->
Type.primitive_name callable_type
>>| (fun primitive_callable_name ->
let return_type =
ReturnType.from_callable_with_fallback
~resolution
~callable_type:resolved_dunder_call
~return_type
in
let target =
Target.Method
{
Target.class_name = primitive_callable_name;
method_name = "__call__";
kind = Normal;
}
in
CallCallees.create
~call_targets:
[
CallTargetIndexer.create_target
call_indexer
~implicit_self:true
~implicit_dunder_call:true
~return_type:(Some return_type)
?receiver_type
target;
]
())
|> Option.value ~default:CallCallees.unresolved
| annotation ->
if not dunder_call then
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~return_type
~dunder_call:true
~callee_kind
annotation
else
CallCallees.unresolved)
and resolve_constructor_callee ~resolution ~override_graph ~call_indexer class_type =
let meta_type = Type.meta class_type in
match
( CallResolution.resolve_attribute_access_ignoring_untracked
~resolution
~base_type:meta_type
~attribute:"__new__",
CallResolution.resolve_attribute_access_ignoring_untracked
~resolution
~base_type:meta_type
~attribute:"__init__" )
with
| Type.Any, _
| Type.Top, _
| _, Type.Any
| _, Type.Top ->
None
| new_callable_type, init_callable_type ->
let new_callees =
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~receiver_type:meta_type
~return_type:(lazy class_type)
~callee_kind:(Method { is_direct_call = true })
new_callable_type
in
let init_callees =
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~receiver_type:meta_type
~return_type:(lazy Type.none)
~callee_kind:(Method { is_direct_call = true })
init_callable_type
in
let return_type =
ReturnType.from_annotation ~resolution:(Resolution.global_resolution resolution) class_type
in
let set_return_type call_target =
{ call_target with CallTarget.return_type = Some return_type }
in
Some
(CallCallees.create
~new_targets:(List.map ~f:set_return_type new_callees.call_targets)
~init_targets:(List.map ~f:set_return_type init_callees.call_targets)
~unresolved:(new_callees.unresolved || init_callees.unresolved)
())
let resolve_callee_from_defining_expression
~resolution
~override_graph
~call_indexer
~callee:{ Node.value = callee; _ }
~return_type
~implementing_class
=
match implementing_class, callee with
| Type.Top, Expression.Name name when is_all_names callee ->
GlobalResolution.global
(Resolution.global_resolution resolution)
(Ast.Expression.name_to_reference_exn name)
>>= fun { AttributeResolution.Global.undecorated_signature; _ } ->
undecorated_signature
>>| fun undecorated_signature ->
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~return_type
~callee_kind:Function
(Type.Callable undecorated_signature)
| _ -> (
let implementing_class_name =
if Type.is_meta implementing_class then
Type.parameters implementing_class
>>= fun parameters ->
List.nth parameters 0
>>= function
| Single implementing_class -> Some implementing_class
| _ -> None
else
Some implementing_class
in
match implementing_class_name with
| Some implementing_class_name ->
let class_primitive =
match implementing_class_name with
| Parametric { name; _ } -> Some name
| Primitive name -> Some name
| _ -> None
in
let method_name =
match callee with
| Expression.Name (Name.Attribute { attribute; _ }) -> Some attribute
| _ -> None
in
method_name
>>= (fun method_name ->
class_primitive >>| fun class_name -> Format.sprintf "%s.%s" class_name method_name)
>>| Reference.create
Here , we blindly reconstruct the callable instead of going through the global
resolution , as Pyre does n't have an API to get the undecorated signature of methods .
resolution, as Pyre doesn't have an API to get the undecorated signature of methods. *)
>>= fun name ->
let callable_type =
Type.Callable
{
Type.Callable.kind = Named name;
implementation =
{ annotation = Lazy.force return_type; parameters = Type.Callable.Defined [] };
overloads = [];
}
in
Some
(resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~return_type
~receiver_type:implementing_class
~callee_kind:(Method { is_direct_call = false })
callable_type)
| _ -> None)
let transform_special_calls ~resolution { Call.callee; arguments } =
let attribute_access base method_name =
{
Node.value =
Expression.Name (Name.Attribute { base; attribute = method_name; special = true });
location = Node.location callee;
}
in
match Node.value callee, arguments with
| Name (Name.Identifier "iter"), [{ Call.Argument.value; _ }] ->
Some { Call.callee = attribute_access value "__iter__"; arguments = [] }
| Name (Name.Identifier "next"), [{ Call.Argument.value; _ }] ->
Some { Call.callee = attribute_access value "__next__"; arguments = [] }
| Name (Name.Identifier "anext"), [{ Call.Argument.value; _ }] ->
Some { Call.callee = attribute_access value "__anext__"; arguments = [] }
| ( Expression.Name
(Name.Attribute
{
base = { Node.value = Expression.Name (Name.Identifier "functools"); _ };
attribute = "partial";
_;
}),
{ Call.Argument.value = actual_callable; _ } :: actual_arguments ) ->
Some { Call.callee = actual_callable; arguments = actual_arguments }
| ( Expression.Name
(Name.Attribute
{
base = { Node.value = Expression.Name (Name.Identifier "multiprocessing"); _ };
attribute = "Process";
_;
}),
[
{ Call.Argument.value = process_callee; name = Some { Node.value = "$parameter$target"; _ } };
{
Call.Argument.value = { Node.value = Expression.Tuple process_arguments; _ };
name = Some { Node.value = "$parameter$args"; _ };
};
] ) ->
Some
{
Call.callee = process_callee;
arguments =
List.map process_arguments ~f:(fun value -> { Call.Argument.value; name = None });
}
| _ -> SpecialCallResolution.redirect ~resolution { Call.callee; arguments }
let redirect_special_calls ~resolution call =
match transform_special_calls ~resolution call with
| Some call -> call
| None ->
Annotated.Call.redirect_special_calls ~resolution call
let resolve_recognized_callees
~resolution
~override_graph
~call_indexer
~callee
~return_type
~callee_type
=
match Node.value callee, callee_type with
| ( _,
Type.Parametric
{
name = "BoundMethod";
parameters = [Single (Parametric { name; _ }); Single implementing_class];
} )
when Set.mem Recognized.allowlisted_callable_class_decorators name ->
resolve_callee_from_defining_expression
~resolution
~override_graph
~call_indexer
~callee
~return_type
~implementing_class
| Expression.Name (Name.Attribute { base; _ }), Parametric { name; _ }
when Set.mem Recognized.allowlisted_callable_class_decorators name ->
Because of the special class , we do n't get a bound method & lose the self argument for
non - classmethod LRU cache wrappers . Reconstruct self in this case .
non-classmethod LRU cache wrappers. Reconstruct self in this case. *)
CallResolution.resolve_ignoring_optional ~resolution base
|> fun implementing_class ->
resolve_callee_from_defining_expression
~resolution
~override_graph
~call_indexer
~callee
~return_type
~implementing_class
| Expression.Name name, _
when is_all_names (Node.value callee)
&& Type.Set.mem SpecialCallResolution.recognized_callable_target_types callee_type ->
Ast.Expression.name_to_reference name
>>| Reference.show
>>| fun name ->
let return_type =
ReturnType.from_annotation
~resolution:(Resolution.global_resolution resolution)
(Lazy.force return_type)
in
CallCallees.create
~call_targets:
[
CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:(Some return_type)
(Target.Function { name; kind = Normal });
]
()
| _ -> None
let resolve_callee_ignoring_decorators ~resolution ~call_indexer ~return_type callee =
let global_resolution = Resolution.global_resolution resolution in
let open UnannotatedGlobalEnvironment in
let return_type () =
ReturnType.from_annotation
~resolution:(Resolution.global_resolution resolution)
(Lazy.force return_type)
in
match Node.value callee with
| Expression.Name name when is_all_names (Node.value callee) -> (
let name = Ast.Expression.name_to_reference_exn name in
match GlobalResolution.resolve_exports global_resolution name with
| Some
(ResolvedReference.ModuleAttribute
{ export = ResolvedReference.Exported (Module.Export.Name.Define _); remaining = []; _ })
->
Some
(CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:(Some (return_type ()))
(Target.Function { name = Reference.show name; kind = Normal }))
| Some
(ResolvedReference.ModuleAttribute
{
from;
name;
export = ResolvedReference.Exported Module.Export.Name.Class;
remaining = [attribute];
_;
}) -> (
let class_name = Reference.create ~prefix:from name |> Reference.show in
GlobalResolution.class_summary global_resolution (Type.Primitive class_name)
>>| Node.value
>>| ClassSummary.attributes
>>= Identifier.SerializableMap.find_opt attribute
>>| Node.value
>>= function
| { kind = Method { static; _ }; _ } ->
Some
(CallTargetIndexer.create_target
call_indexer
~implicit_self:(not static)
~implicit_dunder_call:false
~return_type:(Some (return_type ()))
(Target.Method { Target.class_name; method_name = attribute; kind = Normal }))
| _ -> None)
| _ -> None)
| Expression.Name (Name.Attribute { base; attribute; _ }) -> (
Resolve ` base.attribute ` by looking up the type of ` base ` or the types of its parent
classes in the Method Resolution Order .
classes in the Method Resolution Order. *)
match CallResolution.resolve_ignoring_optional ~resolution base with
| Type.Primitive class_name
| Type.Parametric { name = "type"; parameters = [Single (Type.Primitive class_name)] } -> (
let find_attribute element =
match
GlobalResolution.class_summary global_resolution (Type.Primitive element)
>>| Node.value
>>| ClassSummary.attributes
>>= Identifier.SerializableMap.find_opt attribute
>>| Node.value
with
| Some { ClassSummary.Attribute.kind = Method _; _ } -> Some element
| _ -> None
in
let parent_classes_in_mro =
GlobalResolution.successors ~resolution:global_resolution class_name
in
match List.find_map (class_name :: parent_classes_in_mro) ~f:find_attribute with
| Some base_class ->
Some
(CallTargetIndexer.create_target
call_indexer
~implicit_self:true
~implicit_dunder_call:false
~return_type:(Some (return_type ()))
(Target.Method
{ Target.class_name = base_class; method_name = attribute; kind = Normal }))
| None -> None)
| _ -> None)
| _ -> None
let resolve_regular_callees ~resolution ~override_graph ~call_indexer ~return_type ~callee =
let callee_type = CallResolution.resolve_ignoring_optional ~resolution callee in
let recognized_callees =
resolve_recognized_callees
~resolution
~override_graph
~call_indexer
~callee
~return_type
~callee_type
|> Option.value ~default:CallCallees.unresolved
in
if CallCallees.is_partially_resolved recognized_callees then
recognized_callees
else
let callee_kind = callee_kind ~resolution callee callee_type in
let calleees_from_type =
resolve_callees_from_type
~resolution
~override_graph
~call_indexer
~return_type
~callee_kind
callee_type
in
if CallCallees.is_partially_resolved calleees_from_type then
calleees_from_type
else
resolve_callee_ignoring_decorators ~resolution ~call_indexer ~return_type callee
>>| (fun target -> CallCallees.create ~call_targets:[target] ())
|> Option.value ~default:CallCallees.unresolved
let resolve_callees
~resolution
~override_graph
~call_indexer
~call:({ Call.callee; arguments } as call)
=
let higher_order_parameters =
let get_higher_order_function_targets index { Call.Argument.value = argument; _ } =
let return_type =
lazy
(Expression.Call { callee = argument; arguments = [] }
|> Node.create_with_default_location
|> CallResolution.resolve_ignoring_untracked ~resolution)
in
match
( resolve_regular_callees
~resolution
~override_graph
~call_indexer
~return_type
~callee:argument,
argument )
with
| { CallCallees.call_targets = _ :: _ as regular_targets; unresolved; _ }, _ ->
Some { HigherOrderParameter.index; call_targets = regular_targets; unresolved }
| _, { Node.value = Expression.Lambda _; _ } ->
Some { HigherOrderParameter.index; call_targets = []; unresolved = true }
| _ -> None
in
List.filter_mapi arguments ~f:get_higher_order_function_targets
|> HigherOrderParameterMap.from_list
in
let return_type =
lazy
(Expression.Call call
|> Node.create_with_default_location
|> CallResolution.resolve_ignoring_untracked ~resolution)
in
let regular_callees =
resolve_regular_callees ~resolution ~override_graph ~call_indexer ~return_type ~callee
in
{ regular_callees with higher_order_parameters }
let get_defining_attributes ~resolution ~base_annotation ~attribute =
let rec get_defining_parents annotation =
match annotation with
| Type.Union annotations
| Type.Variable { Type.Variable.Unary.constraints = Type.Variable.Explicit annotations; _ } ->
List.concat_map annotations ~f:get_defining_parents
| _ -> [CallResolution.defining_attribute ~resolution annotation attribute]
in
base_annotation |> strip_meta |> strip_optional |> get_defining_parents
type attribute_access_properties = {
property_targets: CallTarget.t list;
is_attribute: bool;
}
let resolve_attribute_access_properties
~resolution
~override_graph
~call_indexer
~base_annotation
~attribute
~setter
=
let property_targets_of_attribute property =
let return_type =
if setter then
ReturnType.none
else
Annotated.Attribute.annotation property
|> Annotation.annotation
|> ReturnType.from_annotation ~resolution:(Resolution.global_resolution resolution)
in
let parent = Annotated.Attribute.parent property |> Reference.create in
let property_targets =
let kind = if setter then Target.PropertySetter else Target.Normal in
if Type.is_meta base_annotation then
[Target.create_method ~kind (Reference.create ~prefix:parent attribute)]
else
let callee = Target.create_method ~kind (Reference.create ~prefix:parent attribute) in
compute_indirect_targets ~resolution ~override_graph ~receiver_type:base_annotation callee
in
List.map
~f:
(CallTargetIndexer.create_target
call_indexer
~implicit_self:true
~implicit_dunder_call:false
~return_type:(Some return_type))
property_targets
in
let attributes = get_defining_attributes ~resolution ~base_annotation ~attribute in
let properties, non_properties =
List.partition_map
~f:(function
| Some property when Annotated.Attribute.property property -> Either.First property
| attribute -> Either.Second attribute)
attributes
in
let property_targets = List.concat_map ~f:property_targets_of_attribute properties in
let is_attribute = (not (List.is_empty non_properties)) || List.is_empty attributes in
{ property_targets; is_attribute }
let as_global_reference ~resolution expression =
match Node.value expression with
| Expression.Name (Name.Identifier identifier) ->
let reference = Reference.delocalize (Reference.create identifier) in
if Resolution.is_global resolution ~reference then
Some reference
else
None
| Name name -> (
name_to_reference name
>>= fun reference ->
GlobalResolution.resolve_exports (Resolution.global_resolution resolution) reference
>>= function
| UnannotatedGlobalEnvironment.ResolvedReference.ModuleAttribute
{ from; name; remaining = []; _ } ->
Some (Reference.combine from (Reference.create name))
| _ -> None)
| _ -> None
let resolve_attribute_access_global_targets ~resolution ~base_annotation ~base ~attribute ~special =
let expression =
Expression.Name (Name.Attribute { Name.Attribute.base; attribute; special })
|> Node.create_with_default_location
in
match as_global_reference ~resolution expression with
| Some global -> [global]
| None ->
let global_resolution = Resolution.global_resolution resolution in
let rec find_targets targets = function
| Type.Union annotations -> List.fold ~init:targets ~f:find_targets annotations
| Parametric { name = "type"; parameters = [Single annotation] } ->
Access on a class , i.e ` Foo.bar ` , translated into ` Foo.__class__.bar ` .
let parent =
let attribute =
Type.split annotation
|> fst
|> Type.primitive_name
>>= GlobalResolution.attribute_from_class_name
~transitive:true
~resolution:global_resolution
~name:attribute
~instantiated:annotation
in
match attribute with
| Some attribute when Annotated.Attribute.defined attribute ->
Type.Primitive (Annotated.Attribute.parent attribute) |> Type.class_name
| _ -> Type.class_name annotation
in
let attribute = Format.sprintf "__class__.%s" attribute in
let target = Reference.create ~prefix:parent attribute in
target :: targets
| annotation ->
let parents =
let successors =
GlobalResolution.class_metadata (Resolution.global_resolution resolution) annotation
>>| (fun { ClassMetadataEnvironment.successors; _ } -> successors)
|> Option.value ~default:[]
|> List.map ~f:(fun name -> Type.Primitive name)
in
annotation :: successors
in
let add_target targets parent =
let target = Reference.create ~prefix:(Type.class_name parent) attribute in
target :: targets
in
List.fold ~init:targets ~f:add_target parents
in
find_targets [] base_annotation
let resolve_attribute_access
~resolution
~override_graph
~call_indexer
~attribute_targets
~base
~attribute
~special
~setter
=
let base_annotation = CallResolution.resolve_ignoring_optional ~resolution base in
let { property_targets; is_attribute } =
resolve_attribute_access_properties
~resolution
~override_graph
~call_indexer
~base_annotation
~attribute
~setter
in
let global_targets =
resolve_attribute_access_global_targets ~resolution ~base_annotation ~base ~attribute ~special
|> List.map ~f:Target.create_object
|> List.filter ~f:(Hash_set.mem attribute_targets)
|> List.map
~f:
(CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:None)
in
{ AttributeAccessCallees.property_targets; global_targets; is_attribute }
let resolve_identifier ~resolution ~call_indexer ~attribute_targets ~identifier =
Expression.Name (Name.Identifier identifier)
|> Node.create_with_default_location
|> as_global_reference ~resolution
>>| Target.create_object
|> Option.filter ~f:(Hash_set.mem attribute_targets)
>>| fun global ->
{
IdentifierCallees.global_targets =
[
CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:None
global;
];
}
module DefineCallGraphFixpoint (Context : sig
val global_resolution : GlobalResolution.t
val local_annotations : LocalAnnotationMap.ReadOnly.t option
val qualifier : Reference.t
val parent : Reference.t option
val callees_at_location : UnprocessedLocationCallees.t Location.Table.t
val override_graph : OverrideGraph.SharedMemory.t
val call_indexer : CallTargetIndexer.t
val is_missing_flow_type_analysis : bool
val attribute_targets : Target.HashSet.t
end) =
struct
type assignment_target = { location: Location.t }
type visitor_t = {
resolution: Resolution.t;
assignment_target: assignment_target option;
}
let override_graph = Context.override_graph
let call_indexer = Context.call_indexer
let attribute_targets = Context.attribute_targets
let add_unknown_callee
~expression:{ Node.value; location }
({ CallCallees.unresolved; call_targets; _ } as callees)
=
if unresolved && Context.is_missing_flow_type_analysis then
let callee =
match value with
| Expression.Call { callee = { Node.value = callee; _ }; _ } -> callee
| _ -> value
in
let target =
Format.asprintf
"unknown-callee:%a:%a:%a"
Reference.pp
Context.qualifier
Location.pp
location
Expression.pp
(callee |> Node.create_with_default_location |> Ast.Expression.delocalize)
in
let call_target =
{
CallTarget.target = Target.Object target;
implicit_self = false;
implicit_dunder_call = false;
index = 0;
return_type = Some ReturnType.any;
receiver_type = None;
}
in
{ callees with call_targets = call_target :: call_targets }
else
callees
module NodeVisitor = struct
type nonrec t = visitor_t
let expression_visitor
({ resolution; assignment_target } as state)
({ Node.value; location } as expression)
=
CallTargetIndexer.generate_fresh_indices call_indexer;
let register_targets ~expression_identifier ?(location = location) callees =
Location.Table.update Context.callees_at_location location ~f:(function
| None -> UnprocessedLocationCallees.singleton ~expression_identifier ~callees
| Some existing_callees ->
UnprocessedLocationCallees.add existing_callees ~expression_identifier ~callees)
in
let () =
match value with
| Expression.Call call ->
let call = redirect_special_calls ~resolution call in
resolve_callees ~resolution ~override_graph ~call_indexer ~call
|> add_unknown_callee ~expression
|> ExpressionCallees.from_call
|> register_targets ~expression_identifier:(call_identifier call)
| Expression.Name (Name.Attribute { Name.Attribute.base; attribute; special }) ->
let setter =
match assignment_target with
| Some { location = assignment_target_location } ->
Location.equal assignment_target_location location
| None -> false
in
resolve_attribute_access
~resolution
~override_graph
~call_indexer
~attribute_targets
~base
~attribute
~special
~setter
|> ExpressionCallees.from_attribute_access
|> register_targets ~expression_identifier:attribute
| Expression.Name (Name.Identifier identifier) ->
resolve_identifier ~resolution ~call_indexer ~attribute_targets ~identifier
>>| ExpressionCallees.from_identifier
>>| register_targets ~expression_identifier:identifier
|> ignore
| Expression.ComparisonOperator comparison -> (
match ComparisonOperator.override ~location comparison with
| Some { Node.value = Expression.Call call; _ } ->
let call = redirect_special_calls ~resolution call in
resolve_callees ~resolution ~override_graph ~call_indexer ~call
|> add_unknown_callee ~expression
|> ExpressionCallees.from_call
|> register_targets ~expression_identifier:(call_identifier call)
| _ -> ())
| Expression.FormatString substrings ->
let artificial_target =
CallTargetIndexer.create_target
call_indexer
~implicit_self:false
~implicit_dunder_call:false
~return_type:None
Target.StringCombineArtificialTargets.format_string
in
let callees =
ExpressionCallees.from_string_format
(StringFormatCallees.from_f_string_targets [artificial_target])
in
register_targets
~expression_identifier:DefineCallGraph.string_format_expression_identifier
~location
callees;
List.iter substrings ~f:(function
| Substring.Literal _ -> ()
| Substring.Format ({ Node.location = expression_location; _ } as expression) ->
let { CallCallees.call_targets; _ } =
let callee =
let method_name =
Annotated.Call.resolve_stringify_call ~resolution expression
in
{
Node.value =
Expression.Name
(Name.Attribute
{ base = expression; attribute = method_name; special = false });
location = expression_location;
}
in
CallTargetIndexer.generate_fresh_indices call_indexer;
resolve_regular_callees
~resolution
~override_graph
~call_indexer
~return_type:(lazy Type.string)
~callee
in
if not (List.is_empty call_targets) then
let callees =
ExpressionCallees.from_string_format
(StringFormatCallees.from_stringify_targets call_targets)
in
register_targets
~expression_identifier:DefineCallGraph.string_format_expression_identifier
~location:expression_location
callees)
| _ -> ()
in
let () =
match value with
| Expression.Call
{
callee = { Node.value = Name (Name.Identifier "getattr"); _ };
arguments =
[
{ Call.Argument.value = base; _ };
{
Call.Argument.value =
{
Node.value =
Expression.Constant
(Constant.String { StringLiteral.value = attribute; _ });
_;
};
_;
};
{ Call.Argument.value = _; _ };
];
} ->
resolve_attribute_access
~resolution
~override_graph
~call_indexer
~attribute_targets
~base
~attribute
~special:false
~setter:false
|> ExpressionCallees.from_attribute_access
|> register_targets ~expression_identifier:attribute
| Expression.Call
{
callee =
{
Node.value =
Name
(Name.Attribute
{
base = { Node.value = Name (Name.Identifier "object"); _ };
attribute = "__setattr__";
_;
});
_;
};
arguments =
[
{ Call.Argument.value = self; name = None };
{
Call.Argument.value =
{
Node.value =
Expression.Constant (Constant.String { value = attribute; kind = String });
_;
};
name = None;
};
{ Call.Argument.value = _; name = None };
];
} ->
resolve_attribute_access
~resolution
~override_graph
~call_indexer
~attribute_targets
~base:self
~attribute
~special:true
~setter:true
|> ExpressionCallees.from_attribute_access
|> register_targets ~expression_identifier:attribute
| _ -> ()
in
state
let statement_visitor state _ = state
let generator_visitor ({ resolution; _ } as state) generator =
Since generators create variables that Pyre sees as scoped within the generator , handle
them by adding the generator 's bindings to the resolution .
them by adding the generator's bindings to the resolution. *)
let ({ Ast.Statement.Assign.target = _; value = { Node.value; location }; _ } as assignment) =
Ast.Statement.Statement.generator_assignment generator
in
let iter, iter_next =
match value with
| Expression.Await
{
Node.value =
Expression.Call
{
callee =
{
Node.value =
Name
(Name.Attribute
{
base =
{
Node.value =
Expression.Call
{
callee =
{
Node.value =
Name (Name.Attribute { attribute = "__aiter__"; _ });
_;
};
_;
} as aiter;
_;
};
attribute = "__anext__";
_;
});
_;
};
_;
} as aiter_anext;
_;
} ->
| Expression.Call
{
callee =
{
Node.value =
Name
(Name.Attribute
{
base =
{
Node.value =
Expression.Call
{
callee =
{
Node.value =
Name (Name.Attribute { attribute = "__iter__"; _ });
_;
};
_;
} as iter;
_;
};
attribute = "__next__";
_;
});
_;
};
_;
} as iter_next ->
| _ -> failwith "Expect generators to be treated as e.__iter__().__next__()"
in
let state = expression_visitor state { Node.value = iter; location } in
let state = expression_visitor state { Node.value = iter_next; location } in
{ state with resolution = Resolution.resolve_assignment resolution assignment }
let node state = function
| Visit.Expression expression -> expression_visitor state expression
| Visit.Statement statement -> statement_visitor state statement
| Visit.Generator generator -> generator_visitor state generator
| _ -> state
let visit_statement_children _ statement =
match Node.value statement with
| Statement.Assign _
| Statement.Define _
| Statement.Class _ ->
false
| _ -> true
let visit_expression_children _ _ = true
let visit_format_string_children _ _ = true
end
module CalleeVisitor = Visit.MakeNodeVisitor (NodeVisitor)
include Fixpoint.Make (struct
type t = unit [@@deriving show]
let bottom = ()
let less_or_equal ~left:_ ~right:_ = true
let join _ _ = ()
let widen ~previous:_ ~next:_ ~iteration:_ = ()
let forward_statement ~resolution ~statement =
match Node.value statement with
| Statement.Assign { Assign.target; value; _ } ->
CalleeVisitor.visit_expression
~state:
(ref { resolution; assignment_target = Some { location = Node.location target } })
target;
CalleeVisitor.visit_expression ~state:(ref { resolution; assignment_target = None }) value
| _ ->
CalleeVisitor.visit_statement
~state:(ref { resolution; assignment_target = None })
statement
let forward ~statement_key _ ~statement =
let resolution =
TypeCheck.resolution_with_key
~global_resolution:Context.global_resolution
~local_annotations:Context.local_annotations
~parent:Context.parent
~statement_key
(module TypeCheck.DummyContext)
in
forward_statement ~resolution ~statement
let backward ~statement_key:_ _ ~statement:_ = ()
end)
end
let call_graph_of_define
~static_analysis_configuration:{ Configuration.StaticAnalysis.find_missing_flows; _ }
~environment
~override_graph
~attribute_targets
~qualifier
~define:({ Define.signature = { Define.Signature.name; parent; _ }; _ } as define)
=
let timer = Timer.start () in
let callees_at_location = Location.Table.create () in
let module DefineFixpoint = DefineCallGraphFixpoint (struct
let global_resolution = TypeEnvironment.ReadOnly.global_resolution environment
let local_annotations = TypeEnvironment.ReadOnly.get_local_annotations environment name
let qualifier = qualifier
let parent = parent
let callees_at_location = callees_at_location
let override_graph = override_graph
let call_indexer = CallTargetIndexer.create ()
let attribute_targets = attribute_targets
let is_missing_flow_type_analysis =
Option.equal
Configuration.MissingFlowKind.equal
find_missing_flows
(Some Configuration.MissingFlowKind.Type)
end)
in
let () =
let resolution =
TypeCheck.resolution
(TypeEnvironment.ReadOnly.global_resolution environment)
(module TypeCheck.DummyContext)
in
List.iter
define.Ast.Statement.Define.signature.parameters
~f:(fun { Node.value = { Parameter.value; _ }; _ } ->
Option.iter value ~f:(fun value ->
DefineFixpoint.CalleeVisitor.visit_expression
~state:(ref { DefineFixpoint.resolution; assignment_target = None })
value))
in
DefineFixpoint.forward ~cfg:(Cfg.create define) ~initial:() |> ignore;
let call_graph =
Location.Table.to_alist callees_at_location
|> List.map ~f:(fun (location, unprocessed_callees) ->
match SerializableStringMap.to_alist unprocessed_callees with
| [] -> failwith "unreachable"
| [(_, callees)] ->
location, LocationCallees.Singleton (ExpressionCallees.deduplicate callees)
| _ ->
( location,
LocationCallees.Compound
(SerializableStringMap.map ExpressionCallees.deduplicate unprocessed_callees) ))
|> List.filter ~f:(fun (_, callees) ->
match callees with
| LocationCallees.Singleton singleton ->
not (ExpressionCallees.is_empty_attribute_access_callees singleton)
| LocationCallees.Compound compound ->
SerializableStringMap.exists
(fun _ callees ->
not (ExpressionCallees.is_empty_attribute_access_callees callees))
compound)
|> Location.Map.Tree.of_alist_exn
in
Statistics.performance
~randomly_log_every:1000
~name:"Call graph built"
~section:`DependencyGraph
~normals:["callable", Reference.show name]
~timer
();
call_graph
let call_graph_of_callable
~static_analysis_configuration
~environment
~override_graph
~attribute_targets
~callable
=
let resolution = Analysis.TypeEnvironment.ReadOnly.global_resolution environment in
match Target.get_module_and_definition callable ~resolution with
| None -> Format.asprintf "Found no definition for `%a`" Target.pp_pretty callable |> failwith
| Some (qualifier, define) ->
call_graph_of_define
~static_analysis_configuration
~environment
~override_graph
~attribute_targets
~qualifier
~define:(Node.value define)
* Call graphs of callables , stored in the shared memory . This is a mapping from a callable to its
` DefineCallGraph.t ` .
`DefineCallGraph.t`. *)
module DefineCallGraphSharedMemory = struct
include
Memory.WithCache.Make
(Target.SharedMemoryKey)
(struct
type t = LocationCallees.t Location.Map.Tree.t
let prefix = Prefix.make ()
let description = "call graphs of defines"
end)
type t = Handle
let set Handle ~callable ~call_graph = add callable call_graph
let get Handle ~callable = get callable
end
module WholeProgramCallGraph = struct
type t = Target.t list Target.Map.Tree.t
let empty = Target.Map.Tree.empty
let is_empty = Target.Map.Tree.is_empty
let of_alist_exn = Target.Map.Tree.of_alist_exn
let add_or_exn ~callable ~callees call_graph =
Target.Map.Tree.update call_graph callable ~f:(function
| None -> callees
| Some _ ->
Format.asprintf "Program call graph already has callees for `%a`" Target.pp callable
|> failwith)
let fold graph ~init ~f =
Target.Map.Tree.fold graph ~init ~f:(fun ~key:target ~data:callees -> f ~target ~callees)
let merge_disjoint left right =
Target.Map.Tree.merge_skewed
~combine:(fun ~key:_ _ _ -> failwith "call graphs are not disjoint")
left
right
let to_target_graph graph = graph
end
type call_graphs = {
whole_program_call_graph: WholeProgramCallGraph.t;
define_call_graphs: DefineCallGraphSharedMemory.t;
}
* Build the whole call graph of the program .
The overrides must be computed first because we depend on a global shared memory graph to
include overrides in the call graph . Without it , we 'll underanalyze and have an inconsistent
fixpoint .
The overrides must be computed first because we depend on a global shared memory graph to
include overrides in the call graph. Without it, we'll underanalyze and have an inconsistent
fixpoint. *)
let build_whole_program_call_graph
~scheduler
~static_analysis_configuration
~environment
~override_graph
~store_shared_memory
~attribute_targets
~skip_analysis_targets
~callables
=
let define_call_graphs = DefineCallGraphSharedMemory.Handle in
let whole_program_call_graph =
let build_call_graph whole_program_call_graph callable =
if Target.Set.mem callable skip_analysis_targets then
whole_program_call_graph
else
let callable_call_graph =
Metrics.with_alarm
~max_time_in_seconds:60
~event_name:"call graph building"
~callable
(fun () ->
call_graph_of_callable
~static_analysis_configuration
~environment
~override_graph
~attribute_targets
~callable)
()
in
let () =
if store_shared_memory then
DefineCallGraphSharedMemory.set
define_call_graphs
~callable
~call_graph:callable_call_graph
in
WholeProgramCallGraph.add_or_exn
whole_program_call_graph
~callable
~callees:(DefineCallGraph.all_targets callable_call_graph)
in
Scheduler.map_reduce
scheduler
~policy:
(Scheduler.Policy.fixed_chunk_size
~minimum_chunks_per_worker:1
~minimum_chunk_size:100
~preferred_chunk_size:2000
())
~initial:WholeProgramCallGraph.empty
~map:(fun _ callables ->
List.fold callables ~init:WholeProgramCallGraph.empty ~f:build_call_graph)
~reduce:WholeProgramCallGraph.merge_disjoint
~inputs:callables
()
in
let () =
match static_analysis_configuration.Configuration.StaticAnalysis.save_results_to with
| Some path ->
let path = PyrePath.append path ~element:"call-graph.json" in
Log.info "Writing the call graph to `%s`" (PyrePath.absolute path);
whole_program_call_graph |> WholeProgramCallGraph.to_target_graph |> TargetGraph.dump ~path
| None -> ()
in
let () =
match static_analysis_configuration.Configuration.StaticAnalysis.dump_call_graph with
| Some path ->
Log.warning "Emitting the contents of the call graph to `%s`" (PyrePath.absolute path);
whole_program_call_graph |> WholeProgramCallGraph.to_target_graph |> TargetGraph.dump ~path
| None -> ()
in
{ whole_program_call_graph; define_call_graphs }
|
8b867cfbe4cbe88d46d4d5c52fa344c4fdeeacaf757f00090a82e113b3be0308 | darrenldl/ProVerif-ATP | parser_components.mli | open MParser
type 'a stateless_p = ('a, unit) parser
val ignore_space : 'a stateless_p -> 'a stateless_p
val ident_p : string stateless_p
| null | https://raw.githubusercontent.com/darrenldl/ProVerif-ATP/7af6cfb9e0550ecdb072c471e15b8f22b07408bd/narrator/src/parser_components.mli | ocaml | open MParser
type 'a stateless_p = ('a, unit) parser
val ignore_space : 'a stateless_p -> 'a stateless_p
val ident_p : string stateless_p
| |
7c81b27df00a2ecb5135ccfdef7c6209b80ebc0d0e2041076268898d28f8026b | TheBestTvarynka/Lisp-SQL-Parser | table.lisp | ;;;; Simple table data structure.
Copyright ( c ) 2013 , All rights reserved ( see COPYING file for details ) .
(in-package :cl-simple-table)
(deftype row ()
"Table row type."
`(vector t *))
(deftype table ()
"Table type."
`(vector row *))
(defun make-table ()
"Creates a table."
(make-array 1 :element-type 'row :fill-pointer 0 :adjustable t))
(defun make-row ()
"Create a row."
(make-array 1 :fill-pointer 0 :adjustable t))
(defun add-to-table (row table)
"Appends a row to the table."
(vector-push-extend row table)
table)
(defun add-to-row (value row)
"Append a column to row and set it to the given value."
(vector-push-extend value row)
row)
(defun get-row (index table)
"Returns the row in the given index inside the table."
(elt table index))
(defun get-row-column (column row)
"Gets the value in the given column inside row."
(elt row column))
(defun set-row-column (column value row)
"Sets the value of the given column inside the row."
(setf (elt row column) value)
row)
(defun num-rows (table)
"Returns the number of rows in the table."
(length table))
(defun num-cols (row)
"Returns the number of elements in this row."
(length row))
(defun rectangular-table-p (table)
"Returns true if all the rows in the table have the same number of elements."
(or (= (num-rows table) 0)
(let ((cols (num-cols (get-row 0 table))))
(every (lambda (row)
(eql (num-cols row) cols))
table))))
(defun sequence->row (elements)
"Converts a sequence of elements into a table row."
(coerce elements 'row))
(defun row-sequence->table (rows)
"Converts a sequence of rows into a table."
(coerce rows 'table))
(defmacro with-rows ((table row-var &optional return-expression) &body body)
"Iterates the rows in the given table, row-var is the current row, returning return-expression."
(let ((iterator (gensym)))
`(dotimes (,iterator (num-rows ,table) ,return-expression)
(let ((,row-var (get-row ,iterator ,table)))
,@body))))
| null | https://raw.githubusercontent.com/TheBestTvarynka/Lisp-SQL-Parser/d8f1283fc00e394d76e4ac28e434c99d1bee72aa/src/cl-simple-table-master/table.lisp | lisp | Simple table data structure. | Copyright ( c ) 2013 , All rights reserved ( see COPYING file for details ) .
(in-package :cl-simple-table)
(deftype row ()
"Table row type."
`(vector t *))
(deftype table ()
"Table type."
`(vector row *))
(defun make-table ()
"Creates a table."
(make-array 1 :element-type 'row :fill-pointer 0 :adjustable t))
(defun make-row ()
"Create a row."
(make-array 1 :fill-pointer 0 :adjustable t))
(defun add-to-table (row table)
"Appends a row to the table."
(vector-push-extend row table)
table)
(defun add-to-row (value row)
"Append a column to row and set it to the given value."
(vector-push-extend value row)
row)
(defun get-row (index table)
"Returns the row in the given index inside the table."
(elt table index))
(defun get-row-column (column row)
"Gets the value in the given column inside row."
(elt row column))
(defun set-row-column (column value row)
"Sets the value of the given column inside the row."
(setf (elt row column) value)
row)
(defun num-rows (table)
"Returns the number of rows in the table."
(length table))
(defun num-cols (row)
"Returns the number of elements in this row."
(length row))
(defun rectangular-table-p (table)
"Returns true if all the rows in the table have the same number of elements."
(or (= (num-rows table) 0)
(let ((cols (num-cols (get-row 0 table))))
(every (lambda (row)
(eql (num-cols row) cols))
table))))
(defun sequence->row (elements)
"Converts a sequence of elements into a table row."
(coerce elements 'row))
(defun row-sequence->table (rows)
"Converts a sequence of rows into a table."
(coerce rows 'table))
(defmacro with-rows ((table row-var &optional return-expression) &body body)
"Iterates the rows in the given table, row-var is the current row, returning return-expression."
(let ((iterator (gensym)))
`(dotimes (,iterator (num-rows ,table) ,return-expression)
(let ((,row-var (get-row ,iterator ,table)))
,@body))))
|
1c05b1a2af440fe1db1b4369943f69e74c3514bd22b32f50d1a040949e916b61 | exoscale/clojure-kubernetes-client | v1_node.clj | (ns clojure-kubernetes-client.specs.v1-node
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-object-meta :refer :all]
[clojure-kubernetes-client.specs.v1-node-spec :refer :all]
[clojure-kubernetes-client.specs.v1-node-status :refer :all]
)
(:import (java.io File)))
(declare v1-node-data v1-node)
(def v1-node-data
{
(ds/opt :apiVersion) string?
(ds/opt :kind) string?
(ds/opt :metadata) v1-object-meta
(ds/opt :spec) v1-node-spec
(ds/opt :status) v1-node-status
})
(def v1-node
(ds/spec
{:name ::v1-node
:spec v1-node-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_node.clj | clojure | (ns clojure-kubernetes-client.specs.v1-node
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-object-meta :refer :all]
[clojure-kubernetes-client.specs.v1-node-spec :refer :all]
[clojure-kubernetes-client.specs.v1-node-status :refer :all]
)
(:import (java.io File)))
(declare v1-node-data v1-node)
(def v1-node-data
{
(ds/opt :apiVersion) string?
(ds/opt :kind) string?
(ds/opt :metadata) v1-object-meta
(ds/opt :spec) v1-node-spec
(ds/opt :status) v1-node-status
})
(def v1-node
(ds/spec
{:name ::v1-node
:spec v1-node-data}))
| |
6a39e278c7a33d989db77aa3b29558880196441f03284569a9b91cabc7d8efb9 | google/ormolu | bracket-declaration-out.hs | # LANGUAGE TemplateHaskell #
[d|data T a where Foo :: T ()|]
foo =
[d|
foo :: Int -> Char
bar = 42
|]
[d|
data T = T
deriving (Eq, Ord, Enum, Bounded, Show)
|]
$(do [d|baz = baz|])
$(singletons [d|data T = T deriving (Eq, Ord, Enum, Bounded, Show)|])
$( singletons
[d|
data T = T
deriving (Eq, Ord, Enum, Bounded, Show)
|]
)
| null | https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/data/examples/declaration/splice/bracket-declaration-out.hs | haskell | # LANGUAGE TemplateHaskell #
[d|data T a where Foo :: T ()|]
foo =
[d|
foo :: Int -> Char
bar = 42
|]
[d|
data T = T
deriving (Eq, Ord, Enum, Bounded, Show)
|]
$(do [d|baz = baz|])
$(singletons [d|data T = T deriving (Eq, Ord, Enum, Bounded, Show)|])
$( singletons
[d|
data T = T
deriving (Eq, Ord, Enum, Bounded, Show)
|]
)
| |
76ecf8e09192e20596b517b3612fea34c8bfba6e89e0d9cd843c79783cffb1d0 | scalaris-team/scalaris | leases_proto_sched_SUITE.erl | 2010 - 2014 Zuse Institute Berlin
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.
@author < >
%% @doc Unit tests for leases.
%% @end
%% @version $Id$
-module(leases_proto_sched_SUITE).
-author('').
-vsn('$Id').
-compile(export_all).
-include("scalaris.hrl").
-include("unittest.hrl").
-include("client_types.hrl").
groups() ->
[{join_tests, [sequence], [
test_single_join
]}
].
all() ->
[
{group, join_tests}
].
suite() -> [ {timetrap, {seconds, 300}} ].
group(join_tests) ->
[{timetrap, {seconds, 10}}];
group(_) ->
suite().
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_group(Group, Config) -> unittest_helper:init_per_group(Group, Config).
end_per_group(Group, Config) -> unittest_helper:end_per_group(Group, Config).
init_per_testcase(_TestCase, Config) ->
{priv_dir, PrivDir} = lists:keyfind(priv_dir, 1, Config),
unittest_helper:make_ring(4, [{config, [{log_path, PrivDir},
{leases, true}]}]),
[{stop_ring, true} | Config].
end_per_testcase(_TestCase, _Config) ->
ok.
-spec proto_sched_fun(start | stop) -> ok.
proto_sched_fun(start) ->
proto_sched:thread_begin();
proto_sched_fun(stop) ->
%% is a ring running?
case erlang:whereis(pid_groups) =:= undefined
orelse pid_groups:find_a(proto_sched) =:= failed of
true -> ok;
false ->
%% then finalize proto_sched run:
%% try to call thread_end(): if this
%% process was running the proto_sched
%% thats fine, otherwise thread_end()
%% will raise an exception
proto_sched:thread_end(),
proto_sched:wait_for_end()
end.
-spec proto_sched2_fun(setup, ThreadNum::pos_integer()) -> ok;
(cleanup, PIDs::[pid() | atom()]) -> ok.
proto_sched2_fun(setup, Arg) ->
proto_sched:thread_num(Arg);
proto_sched2_fun(cleanup, _Arg) ->
proto_sched:wait_for_end(),
unittest_helper:print_proto_sched_stats(at_end_if_failed),
proto_sched:cleanup().
test_single_join(_Config) ->
proto_sched2_fun(setup, 1),
proto_sched_fun(start),
{[_], []} = api_vm:add_nodes(1),
lease_helper:wait_for_ring_size(5),
proto_sched_fun(stop),
proto_sched2_fun(cleanup, []),
?assert(admin:check_leases()),
ok.
| null | https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/test/leases_proto_sched_SUITE.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.
@doc Unit tests for leases.
@end
@version $Id$
is a ring running?
then finalize proto_sched run:
try to call thread_end(): if this
process was running the proto_sched
thats fine, otherwise thread_end()
will raise an exception | 2010 - 2014 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
-module(leases_proto_sched_SUITE).
-author('').
-vsn('$Id').
-compile(export_all).
-include("scalaris.hrl").
-include("unittest.hrl").
-include("client_types.hrl").
groups() ->
[{join_tests, [sequence], [
test_single_join
]}
].
all() ->
[
{group, join_tests}
].
suite() -> [ {timetrap, {seconds, 300}} ].
group(join_tests) ->
[{timetrap, {seconds, 10}}];
group(_) ->
suite().
init_per_suite(Config) ->
Config.
end_per_suite(_Config) ->
ok.
init_per_group(Group, Config) -> unittest_helper:init_per_group(Group, Config).
end_per_group(Group, Config) -> unittest_helper:end_per_group(Group, Config).
init_per_testcase(_TestCase, Config) ->
{priv_dir, PrivDir} = lists:keyfind(priv_dir, 1, Config),
unittest_helper:make_ring(4, [{config, [{log_path, PrivDir},
{leases, true}]}]),
[{stop_ring, true} | Config].
end_per_testcase(_TestCase, _Config) ->
ok.
-spec proto_sched_fun(start | stop) -> ok.
proto_sched_fun(start) ->
proto_sched:thread_begin();
proto_sched_fun(stop) ->
case erlang:whereis(pid_groups) =:= undefined
orelse pid_groups:find_a(proto_sched) =:= failed of
true -> ok;
false ->
proto_sched:thread_end(),
proto_sched:wait_for_end()
end.
-spec proto_sched2_fun(setup, ThreadNum::pos_integer()) -> ok;
(cleanup, PIDs::[pid() | atom()]) -> ok.
proto_sched2_fun(setup, Arg) ->
proto_sched:thread_num(Arg);
proto_sched2_fun(cleanup, _Arg) ->
proto_sched:wait_for_end(),
unittest_helper:print_proto_sched_stats(at_end_if_failed),
proto_sched:cleanup().
test_single_join(_Config) ->
proto_sched2_fun(setup, 1),
proto_sched_fun(start),
{[_], []} = api_vm:add_nodes(1),
lease_helper:wait_for_ring_size(5),
proto_sched_fun(stop),
proto_sched2_fun(cleanup, []),
?assert(admin:check_leases()),
ok.
|
1a1bf427b5fe3408f2cd5a39c39d58deb4692d57f4a69d1986787ebb2a24b9be | colis-anr/morbig | morbigDriver.ml | (**************************************************************************)
(* -*- tuareg -*- *)
(* *)
Copyright ( C ) 2017 - 2021 , ,
.
(* *)
(* This is free software: you can redistribute it and/or modify it *)
under the terms of the GNU General Public License , version 3 .
(* *)
(* Additional terms apply, due to the reproduction of portions of *)
(* the POSIX standard. Please refer to the file COPYING for details. *)
(**************************************************************************)
open Morbig
let save input_filename (cst : CST.program) =
Options.(
if backend () = NoSerialisation
then
()
else
let cout = open_out (output_file_of_input_file input_filename) in
begin match backend () with
| Bin -> save_binary_cst cout cst
| Json -> save_json_cst cout cst
| SimpleJson -> JsonHelpers.save_as_json true cout cst
| Dot -> JsonHelpers.save_as_dot cout cst
| NoSerialisation -> assert false
end;
close_out cout
)
(** write the concrete syntax tree [cst] to the output file
corresponding to [input_filename]. The format and the name of the
output file are determined by the program options. *)
let save_error input_filename message =
let eout = open_out (input_filename ^ ".morbigerror") in
output_string eout message;
output_string eout "\n";
close_out eout
(** write string [message] to the error file corresponding to
[input_filename]. *)
let not_a_script input_filename =
Options.skip_nosh ()
&& (Scripts.(is_elf input_filename || is_other_script input_filename))
let nb_inputs = ref 0
let nb_inputs_skipped = ref 0
let nb_inputs_erroneous = ref 0
let show_stats () =
if Options.display_stats () then begin
Printf.printf "Number of input files: %i\n" !nb_inputs;
Printf.printf "Number of skipped files: %i\n" !nb_inputs_skipped;
Printf.printf "Number of rejected files: %i\n" !nb_inputs_erroneous
end
let parse_one_file input_filename =
Debug.printf "Trying to open: %s\n" input_filename;
incr nb_inputs;
if not_a_script input_filename then
incr nb_inputs_skipped
else
try
parse_file input_filename |> save input_filename
with e ->
incr nb_inputs_erroneous;
if Options.continue_after_error () then
save_error input_filename (Errors.string_of_error e)
else (
output_string stderr (Errors.string_of_error e ^ "\n");
exit 1
)
let parse_input_files_provided_via_stdin () =
try
while true do
parse_one_file (read_line ())
done
with End_of_file -> ()
let parse_input_files_provided_on_command_line () =
if List.length (Options.input_files ()) <= 0 then begin
Printf.eprintf "morbig: no input files.\n";
exit 1
end;
List.iter parse_one_file (Options.input_files ())
let parse_input_files () =
if Options.from_stdin () then
parse_input_files_provided_via_stdin ()
else
parse_input_files_provided_on_command_line ()
let main =
Options.analyze_command_line_arguments ();
parse_input_files ();
show_stats ()
| null | https://raw.githubusercontent.com/colis-anr/morbig/77c2ca402785979c4af351b412fe7be2d521838f/src/morbigDriver.ml | ocaml | ************************************************************************
-*- tuareg -*-
This is free software: you can redistribute it and/or modify it
Additional terms apply, due to the reproduction of portions of
the POSIX standard. Please refer to the file COPYING for details.
************************************************************************
* write the concrete syntax tree [cst] to the output file
corresponding to [input_filename]. The format and the name of the
output file are determined by the program options.
* write string [message] to the error file corresponding to
[input_filename]. | Copyright ( C ) 2017 - 2021 , ,
.
under the terms of the GNU General Public License , version 3 .
open Morbig
let save input_filename (cst : CST.program) =
Options.(
if backend () = NoSerialisation
then
()
else
let cout = open_out (output_file_of_input_file input_filename) in
begin match backend () with
| Bin -> save_binary_cst cout cst
| Json -> save_json_cst cout cst
| SimpleJson -> JsonHelpers.save_as_json true cout cst
| Dot -> JsonHelpers.save_as_dot cout cst
| NoSerialisation -> assert false
end;
close_out cout
)
let save_error input_filename message =
let eout = open_out (input_filename ^ ".morbigerror") in
output_string eout message;
output_string eout "\n";
close_out eout
let not_a_script input_filename =
Options.skip_nosh ()
&& (Scripts.(is_elf input_filename || is_other_script input_filename))
let nb_inputs = ref 0
let nb_inputs_skipped = ref 0
let nb_inputs_erroneous = ref 0
let show_stats () =
if Options.display_stats () then begin
Printf.printf "Number of input files: %i\n" !nb_inputs;
Printf.printf "Number of skipped files: %i\n" !nb_inputs_skipped;
Printf.printf "Number of rejected files: %i\n" !nb_inputs_erroneous
end
let parse_one_file input_filename =
Debug.printf "Trying to open: %s\n" input_filename;
incr nb_inputs;
if not_a_script input_filename then
incr nb_inputs_skipped
else
try
parse_file input_filename |> save input_filename
with e ->
incr nb_inputs_erroneous;
if Options.continue_after_error () then
save_error input_filename (Errors.string_of_error e)
else (
output_string stderr (Errors.string_of_error e ^ "\n");
exit 1
)
let parse_input_files_provided_via_stdin () =
try
while true do
parse_one_file (read_line ())
done
with End_of_file -> ()
let parse_input_files_provided_on_command_line () =
if List.length (Options.input_files ()) <= 0 then begin
Printf.eprintf "morbig: no input files.\n";
exit 1
end;
List.iter parse_one_file (Options.input_files ())
let parse_input_files () =
if Options.from_stdin () then
parse_input_files_provided_via_stdin ()
else
parse_input_files_provided_on_command_line ()
let main =
Options.analyze_command_line_arguments ();
parse_input_files ();
show_stats ()
|
eea3c4c8a9fc4f05f2e61964e2c2656515dccf2352816b3d31c99d1fbc1c5aff | namin/clpset-miniKanren | test-all.scm | (load "mktests.scm")
(load "clpset-tests.scm")
(load "lib-tests.scm")
(load "recordsub-tests.scm")
(load "tapl.scm")
| null | https://raw.githubusercontent.com/namin/clpset-miniKanren/c0cf0342431b36467cf217555a63a3d0477bd477/test-all.scm | scheme | (load "mktests.scm")
(load "clpset-tests.scm")
(load "lib-tests.scm")
(load "recordsub-tests.scm")
(load "tapl.scm")
| |
fb45e498acba820395e3cb7b28f0a6edd351746accffe60d3e14ee11cb59e1e9 | ghcjs/ghcjs-examples | threads.hs | # LANGUAGE QuasiQuotes , OverloadedStrings , ScopedTypeVariables #
start 10000 threads that each randomly update the color of a single cell in a table
start 10000 threads that each randomly update the color of a single cell in a table
-}
module Main where
import Control.Applicative
import Control.Concurrent
import Control.Monad
import System.Random
import GHCJS.Foreign.QQ
import GHCJS.Types
addStyle :: [JSString] -> IO ()
addStyle styles = do
(sh :: JSRef ()) <-
[jsu| var st = document.createElement('style');
st.appendChild(document.createTextNode(''));
document.head.appendChild(st);
$r = st.sheet;
|]
forM_ styles $ \s -> [jsu_| `sh.insertRule(`s, 0); |]
addChild :: JSRef () -> JSString -> IO (JSRef ())
addChild parent tagName =
[jsu| var elem = document.createElement(`tagName);
`parent.appendChild(elem);
$r = elem;
|]
setCol :: JSRef () -> Int -> IO ()
setCol elem col = [jsu_| `elem.className = 'col-' + `col; |]
main :: IO ()
main = do
let dim = 100
addStyle [ "body { background-color: #666; }"
, "table { border-collapse: collapse; }"
, "td { width: 7px; height: 7px; padding: 0; margin: 0; border: none; }"
, "td.col-0 { background-color: #000; }", "td.col-1 { background-color: #444; }"
, "td.col-2 { background-color: #888; }", "td.col-3 { background-color: #bbb; }"
, "td.col-4 { background-color: #fff; }"
]
table <- addChild [jsu'| document.body |] "table"
rows <- replicateM dim (addChild table "tr")
cells <- concat <$> forM rows (\r -> replicateM dim (addChild r "td"))
forM_ cells (void . forkIO . cellThread)
cellThread :: JSRef () -> IO a
cellThread elem = forever $ do
setCol elem =<< randomRIO (0,4)
threadDelay . (1000000+) =<< randomRIO (0,10000000)
| null | https://raw.githubusercontent.com/ghcjs/ghcjs-examples/217b7fd3816f57634977beac711452704c3ea688/threads/threads.hs | haskell | # LANGUAGE QuasiQuotes , OverloadedStrings , ScopedTypeVariables #
start 10000 threads that each randomly update the color of a single cell in a table
start 10000 threads that each randomly update the color of a single cell in a table
-}
module Main where
import Control.Applicative
import Control.Concurrent
import Control.Monad
import System.Random
import GHCJS.Foreign.QQ
import GHCJS.Types
addStyle :: [JSString] -> IO ()
addStyle styles = do
(sh :: JSRef ()) <-
[jsu| var st = document.createElement('style');
st.appendChild(document.createTextNode(''));
document.head.appendChild(st);
$r = st.sheet;
|]
forM_ styles $ \s -> [jsu_| `sh.insertRule(`s, 0); |]
addChild :: JSRef () -> JSString -> IO (JSRef ())
addChild parent tagName =
[jsu| var elem = document.createElement(`tagName);
`parent.appendChild(elem);
$r = elem;
|]
setCol :: JSRef () -> Int -> IO ()
setCol elem col = [jsu_| `elem.className = 'col-' + `col; |]
main :: IO ()
main = do
let dim = 100
addStyle [ "body { background-color: #666; }"
, "table { border-collapse: collapse; }"
, "td { width: 7px; height: 7px; padding: 0; margin: 0; border: none; }"
, "td.col-0 { background-color: #000; }", "td.col-1 { background-color: #444; }"
, "td.col-2 { background-color: #888; }", "td.col-3 { background-color: #bbb; }"
, "td.col-4 { background-color: #fff; }"
]
table <- addChild [jsu'| document.body |] "table"
rows <- replicateM dim (addChild table "tr")
cells <- concat <$> forM rows (\r -> replicateM dim (addChild r "td"))
forM_ cells (void . forkIO . cellThread)
cellThread :: JSRef () -> IO a
cellThread elem = forever $ do
setCol elem =<< randomRIO (0,4)
threadDelay . (1000000+) =<< randomRIO (0,10000000)
| |
eb2b2494b6fdc115a90d66a6407587f20d0b9aa000434ea7d08df53b02ad8ff9 | JonathanLorimer/weft | ResolverSpec.hs | module ResolverSpec where
import Control.Monad
import Data.Void
import qualified Data.Map as M
import Test.Hspec hiding (Arg)
import Weft.Generics.Resolve
import Weft.Internal.Types
import Weft.Internal.Utils
import Weft.Types
data Tester = Tester
{ testFoo :: Method '[ '("name", String) ] String
, testBar :: Int
} deriving Generic
testerResolver :: JHKD Tester 'Resolver
testerResolver =
buildResolver @Tester
(ToResolver $ pure . getArg)
(ToResolver $ pure 5)
spec :: Spec
spec = describe "resolver" $ do
it "should not crash with an impossible case" $ do
res <- resolve testerResolver $
buildQuery @Tester
( ToQuery $ M.empty )
( ToQuery $ M.singleton "bar" (ANil, ()) )
res `shouldBe2`
buildResponse @Tester
( ToResponse $ M.empty )
( ToResponse $ M.singleton "bar" 5 )
it "should resolve arg fields" $ do
res <- resolve testerResolver $
buildQuery @Tester
( ToQuery $ M.singleton "foo" (Arg "sandy":@@ ANil, ()) )
( ToQuery $ M.empty )
res `shouldBe2`
buildResponse @Tester
( ToResponse $ M.singleton "foo" "sandy" )
( ToResponse $ M.empty )
it "should resolve everything" $ do
res <- resolve testerResolver $
buildQuery @Tester
( ToQuery $ M.singleton "foo" (Arg "sandy":@@ ANil, ()) )
( ToQuery $ M.singleton "bar" (ANil, ()) )
res `shouldBe2`
buildResponse @Tester
( ToResponse $ M.singleton "foo" "sandy" )
( ToResponse $ M.singleton "bar" 5 )
shouldBe2
:: ( HasCallStack
, Eq (J record 'Response Void)
)
=> JHKD record 'Response
-> JHKD record 'Response
-> Expectation
actual `shouldBe2` expected =
expectTrue ("lame") $ runHKD actual == runHKD expected
expectTrue :: HasCallStack => String -> Bool -> Expectation
expectTrue msg b = unless b (expectationFailure msg)
| null | https://raw.githubusercontent.com/JonathanLorimer/weft/fc0396240905ab0202c5896019cf1e482d216f8d/test/ResolverSpec.hs | haskell | module ResolverSpec where
import Control.Monad
import Data.Void
import qualified Data.Map as M
import Test.Hspec hiding (Arg)
import Weft.Generics.Resolve
import Weft.Internal.Types
import Weft.Internal.Utils
import Weft.Types
data Tester = Tester
{ testFoo :: Method '[ '("name", String) ] String
, testBar :: Int
} deriving Generic
testerResolver :: JHKD Tester 'Resolver
testerResolver =
buildResolver @Tester
(ToResolver $ pure . getArg)
(ToResolver $ pure 5)
spec :: Spec
spec = describe "resolver" $ do
it "should not crash with an impossible case" $ do
res <- resolve testerResolver $
buildQuery @Tester
( ToQuery $ M.empty )
( ToQuery $ M.singleton "bar" (ANil, ()) )
res `shouldBe2`
buildResponse @Tester
( ToResponse $ M.empty )
( ToResponse $ M.singleton "bar" 5 )
it "should resolve arg fields" $ do
res <- resolve testerResolver $
buildQuery @Tester
( ToQuery $ M.singleton "foo" (Arg "sandy":@@ ANil, ()) )
( ToQuery $ M.empty )
res `shouldBe2`
buildResponse @Tester
( ToResponse $ M.singleton "foo" "sandy" )
( ToResponse $ M.empty )
it "should resolve everything" $ do
res <- resolve testerResolver $
buildQuery @Tester
( ToQuery $ M.singleton "foo" (Arg "sandy":@@ ANil, ()) )
( ToQuery $ M.singleton "bar" (ANil, ()) )
res `shouldBe2`
buildResponse @Tester
( ToResponse $ M.singleton "foo" "sandy" )
( ToResponse $ M.singleton "bar" 5 )
shouldBe2
:: ( HasCallStack
, Eq (J record 'Response Void)
)
=> JHKD record 'Response
-> JHKD record 'Response
-> Expectation
actual `shouldBe2` expected =
expectTrue ("lame") $ runHKD actual == runHKD expected
expectTrue :: HasCallStack => String -> Bool -> Expectation
expectTrue msg b = unless b (expectationFailure msg)
| |
78ca765e02f557e69e693435275ddb577e4c7af875b3f3de4ed692721ea1cc22 | issuu/broen | cookies_SUITE.erl | -module(cookies_SUITE).
-compile(nowarn_export_all).
-compile(export_all).
-include_lib("amqp_client/include/amqp_client.hrl").
-include_lib("common_test/include/ct.hrl").
suite() ->
[{timetrap, {seconds, 30}}].
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(broen),
{ok, ConnProps} = application:get_env(broen, amqp_connection),
ConnInfo = amqp_director:parse_connection_parameters(ConnProps),
WorkingUrl = start_server(ConnInfo, "routing_test.cookies", fun cookies/3),
OtherUrl = start_server(ConnInfo, "routing_test.cookies_other", fun cookies_other/3),
timer:sleep(1000),
[{url, WorkingUrl}, {other_url, OtherUrl} | Config].
end_per_suite(_Config) ->
ok.
all() ->
ct_helper:all_tests(?MODULE).
test_cookies(Config) ->
Url = ?config(url, Config),
{ok, {Resp, Props, Payload}} = httpc:request(get, {Url, []}, [], []),
{_, 200, _} = Resp,
"application/json" = proplists:get_value("content-type", Props),
"test_cookie=11; Version=1; Expires=Sat, 12-Jan-2030 13:34:56 GMT; " ++ Rest = proplists:get_value("set-cookie", Props),
["Max-Age=" ++ _, " Domain=mine; Path=/; Secure"] = string:split(Rest, ";"),
#{<<"message">> := <<"Hello!">>} = jsx:decode(list_to_binary(Payload), [return_maps]).
test_other_cookies(Config) ->
Url = ?config(other_url, Config),
{ok, {Resp, Props, Payload}} = httpc:request(get, {Url, []}, [], []),
{_, 200, _} = Resp,
"application/json" = proplists:get_value("content-type", Props),
"test_cookie=somevalue; Version=1; Expires=Sat, 12-Jan-2030 13:34:56 GMT; " ++ Rest = proplists:get_value("set-cookie", Props),
["Max-Age=" ++ _," Domain=some-other-domain; Path=/call/routing_test; HttpOnly"] = string:split(Rest, ";"),
#{<<"message">> := <<"Hello!">>} = jsx:decode(list_to_binary(Payload), [return_maps]).
start_server(ConnInfo, RoutingKey, Handler) ->
{ok, Hostname} = inet:gethostname(),
UrlBit = lists:flatten(string:replace(RoutingKey, ".", "/", all)),
QueueName = iolist_to_binary([RoutingKey, "-", Hostname]),
WorkingUrl = ":7083/call/" ++ UrlBit,
AmqpConfig = [{exchange, <<"http_exchange">>},
{consume_queue, QueueName},
no_ack,
{queue_definitions, [#'exchange.declare'{exchange = <<"http_exchange">>,
type = <<"topic">>},
#'queue.declare'{queue = QueueName,
exclusive = true,
auto_delete = true
},
#'queue.bind'{exchange = <<"http_exchange">>,
queue = QueueName,
routing_key = iolist_to_binary([RoutingKey, ".#"])}
]}],
{ok, Pid} = amqp_server_sup:start_link(list_to_atom(RoutingKey ++ "_test"), ConnInfo, AmqpConfig, Handler, 1),
unlink(Pid),
WorkingUrl.
cookies(Payload, <<"application/json">>, _Type) ->
Unpacked = jsx:decode(Payload, [return_maps]),
<<"GET">> = maps:get(<<"method">>, Unpacked),
{reply, jsx:encode(#{
media_type => <<"application/json">>,
cookies => #{<<"test_cookie">> => #{value => <<"11">>,
domain => <<"mine">>,
secure => true,
expires => iso8601:format({{2030, 1, 12}, {13, 34, 56}}),
path => <<"/">>}},
payload => jsx:encode(#{message => <<"Hello!">>})
}), <<"application/json">>}.
cookies_other(Payload, <<"application/json">>, _Type) ->
Unpacked = jsx:decode(Payload, [return_maps]),
<<"GET">> = maps:get(<<"method">>, Unpacked),
{reply, jsx:encode(#{
media_type => <<"application/json">>,
cookies => #{<<"test_cookie">> => #{value => <<"somevalue">>,
domain => <<"some-other-domain">>,
http_only => true,
expires => "Sat, 12 Jan 2030 13:34:56 GMT"}},
payload => jsx:encode(#{message => <<"Hello!">>})
}), <<"application/json">>}.
| null | https://raw.githubusercontent.com/issuu/broen/7d0e1ad9017b9e9907d924b54c3c63dd1d741c9c/test/cookies_SUITE.erl | erlang | -module(cookies_SUITE).
-compile(nowarn_export_all).
-compile(export_all).
-include_lib("amqp_client/include/amqp_client.hrl").
-include_lib("common_test/include/ct.hrl").
suite() ->
[{timetrap, {seconds, 30}}].
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(broen),
{ok, ConnProps} = application:get_env(broen, amqp_connection),
ConnInfo = amqp_director:parse_connection_parameters(ConnProps),
WorkingUrl = start_server(ConnInfo, "routing_test.cookies", fun cookies/3),
OtherUrl = start_server(ConnInfo, "routing_test.cookies_other", fun cookies_other/3),
timer:sleep(1000),
[{url, WorkingUrl}, {other_url, OtherUrl} | Config].
end_per_suite(_Config) ->
ok.
all() ->
ct_helper:all_tests(?MODULE).
test_cookies(Config) ->
Url = ?config(url, Config),
{ok, {Resp, Props, Payload}} = httpc:request(get, {Url, []}, [], []),
{_, 200, _} = Resp,
"application/json" = proplists:get_value("content-type", Props),
"test_cookie=11; Version=1; Expires=Sat, 12-Jan-2030 13:34:56 GMT; " ++ Rest = proplists:get_value("set-cookie", Props),
["Max-Age=" ++ _, " Domain=mine; Path=/; Secure"] = string:split(Rest, ";"),
#{<<"message">> := <<"Hello!">>} = jsx:decode(list_to_binary(Payload), [return_maps]).
test_other_cookies(Config) ->
Url = ?config(other_url, Config),
{ok, {Resp, Props, Payload}} = httpc:request(get, {Url, []}, [], []),
{_, 200, _} = Resp,
"application/json" = proplists:get_value("content-type", Props),
"test_cookie=somevalue; Version=1; Expires=Sat, 12-Jan-2030 13:34:56 GMT; " ++ Rest = proplists:get_value("set-cookie", Props),
["Max-Age=" ++ _," Domain=some-other-domain; Path=/call/routing_test; HttpOnly"] = string:split(Rest, ";"),
#{<<"message">> := <<"Hello!">>} = jsx:decode(list_to_binary(Payload), [return_maps]).
start_server(ConnInfo, RoutingKey, Handler) ->
{ok, Hostname} = inet:gethostname(),
UrlBit = lists:flatten(string:replace(RoutingKey, ".", "/", all)),
QueueName = iolist_to_binary([RoutingKey, "-", Hostname]),
WorkingUrl = ":7083/call/" ++ UrlBit,
AmqpConfig = [{exchange, <<"http_exchange">>},
{consume_queue, QueueName},
no_ack,
{queue_definitions, [#'exchange.declare'{exchange = <<"http_exchange">>,
type = <<"topic">>},
#'queue.declare'{queue = QueueName,
exclusive = true,
auto_delete = true
},
#'queue.bind'{exchange = <<"http_exchange">>,
queue = QueueName,
routing_key = iolist_to_binary([RoutingKey, ".#"])}
]}],
{ok, Pid} = amqp_server_sup:start_link(list_to_atom(RoutingKey ++ "_test"), ConnInfo, AmqpConfig, Handler, 1),
unlink(Pid),
WorkingUrl.
cookies(Payload, <<"application/json">>, _Type) ->
Unpacked = jsx:decode(Payload, [return_maps]),
<<"GET">> = maps:get(<<"method">>, Unpacked),
{reply, jsx:encode(#{
media_type => <<"application/json">>,
cookies => #{<<"test_cookie">> => #{value => <<"11">>,
domain => <<"mine">>,
secure => true,
expires => iso8601:format({{2030, 1, 12}, {13, 34, 56}}),
path => <<"/">>}},
payload => jsx:encode(#{message => <<"Hello!">>})
}), <<"application/json">>}.
cookies_other(Payload, <<"application/json">>, _Type) ->
Unpacked = jsx:decode(Payload, [return_maps]),
<<"GET">> = maps:get(<<"method">>, Unpacked),
{reply, jsx:encode(#{
media_type => <<"application/json">>,
cookies => #{<<"test_cookie">> => #{value => <<"somevalue">>,
domain => <<"some-other-domain">>,
http_only => true,
expires => "Sat, 12 Jan 2030 13:34:56 GMT"}},
payload => jsx:encode(#{message => <<"Hello!">>})
}), <<"application/json">>}.
| |
bd26de1b7e6fffd4aac1f76f2913ec251dac54534192799fd3eb3a05add2bb7d | quephird/fun-with-quil | flower.clj | (ns fun-with-quil.animations.flower
(:use quil.core))
(def screen-w 800)
(def screen-h 800)
(defn setup []
(smooth)
(no-stroke)
(blend-mode :exclusion)
(ellipse-mode :center)
(color-mode :hsb))
(defn draw []
(let [fc (frame-count)
r (+ 150 (* 150 (sin (/ (* fc PI) 70))))
θ (radians (/ (* 40 PI fc) 180))
h (map-range (mod (* 0.5 fc) 255) 0 255 0 255)
n 20
dθ (radians (/ 360 n))]
(background 0)
(translate (/ screen-w 2) (/ screen-h 2))
(rotate θ)
(doseq [i (range n)]
(fill h 255 255)
(ellipse 0 250 r r)
(rotate dθ))))
(sketch
:title "flower"
:setup setup
:draw draw
:renderer :p3d
:size [screen-w screen-h])
| null | https://raw.githubusercontent.com/quephird/fun-with-quil/3b3a6885771f5a1a4cffeb8379f05a28048a1616/src/fun_with_quil/animations/flower.clj | clojure | (ns fun-with-quil.animations.flower
(:use quil.core))
(def screen-w 800)
(def screen-h 800)
(defn setup []
(smooth)
(no-stroke)
(blend-mode :exclusion)
(ellipse-mode :center)
(color-mode :hsb))
(defn draw []
(let [fc (frame-count)
r (+ 150 (* 150 (sin (/ (* fc PI) 70))))
θ (radians (/ (* 40 PI fc) 180))
h (map-range (mod (* 0.5 fc) 255) 0 255 0 255)
n 20
dθ (radians (/ 360 n))]
(background 0)
(translate (/ screen-w 2) (/ screen-h 2))
(rotate θ)
(doseq [i (range n)]
(fill h 255 255)
(ellipse 0 250 r r)
(rotate dθ))))
(sketch
:title "flower"
:setup setup
:draw draw
:renderer :p3d
:size [screen-w screen-h])
| |
3438fd31c1f99a08d7a927ab7d94793ea1ab5250c32cab189a552a2b4cbf3dd3 | bendudson/py4cl | callpython.lisp | (in-package :py4cl)
(define-condition python-error (error)
((text :initarg :text :reader text))
(:report (lambda (condition stream)
(format stream "Python error: ~a" (text condition)))))
(defun dispatch-reply (stream value)
(write-char #\r stream)
(stream-write-value value stream)
(force-output stream))
(defun dispatch-messages (process)
"Read response from python, loop to handle any callbacks"
(let ((read-stream (uiop:process-info-output process))
(write-stream (uiop:process-info-input process)))
(loop
First character is type of message
;; Returned value
(#\r (return-from dispatch-messages
(stream-read-value read-stream)))
;; Error
(#\e (error 'python-error
:text (stream-read-string read-stream)))
Delete object . This is called when an UnknownLispObject is deleted
(#\d (free-handle (stream-read-value read-stream)))
;; Slot read
(#\s (destructuring-bind (handle slot-name) (stream-read-value read-stream)
(let ((object (lisp-object handle)))
;; User must register a function to handle slot access
(dispatch-reply write-stream
(restart-case
(python-getattr object slot-name)
;; Provide some restarts for missing handler or missing slot
(return-nil () nil)
(return-zero () 0)
(enter-value (return-value)
:report "Provide a value to return"
:interactive (lambda ()
(format t "Enter a value to return: ")
(list (read)))
return-value))))))
;; Slot write
(#\S (destructuring-bind (handle slot-name slot-value) (stream-read-value read-stream)
(let ((object (lisp-object handle)))
;; User must register a function to handle slot write
(python-setattr object slot-name slot-value)
(dispatch-reply write-stream nil))))
;; Callback. Value returned is a list, containing the function ID then the args
(#\c
(let ((call-value (stream-read-value read-stream)))
(let ((return-value (apply (lisp-object (first call-value)) (second call-value))))
;; Send a reply
(dispatch-reply write-stream return-value))))
;; Print stdout
(#\p
(let ((print-string (stream-read-value read-stream)))
(princ print-string)))
(otherwise (error "Unhandled message type"))))))
(defun python-eval* (cmd-char &rest args)
"Internal function, which converts ARGS into a string to be evaluated
This handles both EVAL and EXEC calls with CMD-CHAR being different
in the two cases.
Anything in ARGS which is not a string is passed through PYTHONIZE
"
(python-start-if-not-alive)
(let ((stream (uiop:process-info-input *python*))
(str (apply #'concatenate 'string (loop for val in args
collecting (if (typep val 'string)
val
(pythonize val))))))
;; Write "x" if exec, otherwise "e"
(write-char cmd-char stream)
(stream-write-string str stream)
(force-output stream)
;; Wait for response from Python
(dispatch-messages *python*)))
(defun python-eval (&rest args)
"Evaluate an expression in python, returning the result
Arguments ARGS can be strings, or other objects. Anything which
is not a string is converted to a python value
Examples:
(python-eval \"[i**2 for i in range(\" 4 \")]\") => #(0 1 4 9)
(let ((a 10) (b 2))
(py4cl:python-eval a "*" b)) => 20
"
(delete-freed-python-objects)
(apply #'python-eval* #\e args))
(defun (setf python-eval) (value &rest args)
"Set an expression to a value. Just adds \"=\" and the value
to the end of the expression. Note that the result is evaluated
with exec rather than eval.
Examples:
(setf (python-eval \"a\") 2) ; python \"a=2\"
"
(apply #'python-eval* #\x (append args (list "=" (py4cl::pythonize value))))
value)
(defun python-exec (&rest args)
"Execute (using exec) an expression in python.
This is used for statements rather than expressions.
"
(delete-freed-python-objects)
(apply #'python-eval* #\x args))
(defun python-call (fun-name &rest args)
"Call a python function, given the function name as a string
and additional arguments. Keywords are converted to keyword arguments."
(python-start-if-not-alive)
(let ((stream (uiop:process-info-input *python*)))
;; Write "f" to indicate function call
(write-char #\f stream)
(stream-write-value (list fun-name args) stream)
(force-output stream))
(dispatch-messages *python*))
(defun python-call-async (fun-name &rest args)
"Call a python function asynchronously.
Returns a lambda which when called returns the result."
(python-start-if-not-alive)
(let* ((process *python*)
(stream (uiop:process-info-input process)))
;; Write "a" to indicate asynchronous function call
(write-char #\a stream)
(stream-write-value (list fun-name args) stream)
(force-output stream)
(let ((handle (dispatch-messages process))
value)
(lambda ()
(if handle
;; Retrieve the value from python
(progn
(write-char #\R stream)
(stream-write-value handle stream)
(force-output stream)
(setf handle nil
value (dispatch-messages process)))
;; If no handle then already have the value
value)))))
(defun python-method (obj method-name &rest args)
"Call a given method on an object OBJ. METHOD-NAME can be a
symbol (converted to lower case) or a string.
Examples:
(python-method \"hello {0}\" 'format \"world\")
; => \"hello world\"
(python-method '(1 2 3) '__len__)
= > 3
"
(python-start-if-not-alive)
(py4cl:python-eval
(py4cl::pythonize obj)
(format nil ".~(~a~)" method-name)
(if args
(py4cl::pythonize args)
"()")))
(defun python-generator (function stop-value)
(python-call "_py4cl_generator" function stop-value))
(defun function-args (args)
"Internal function, intended to be called by the CHAIN macro.
Converts function arguments to a list of strings and (pythonize )
function calls. Handles keywords and insertion of commas.
Returns a list which can be passed to PYTHON-EVAL.
Examples:
(py4cl::function-args '(1 :test 2))
=> ((PY4CL::PYTHONIZE 1) \",\" \"test\" \"=\" (PY4CL::PYTHONIZE 2))
"
(if (not args)
'("")
(if (keywordp (first args))
(append
(list (string-downcase (first args))
"="
`(pythonize ,(second args)))
(if (cddr args)
(append '(",") (function-args (cddr args)))))
(append
(list `(pythonize ,(first args)))
(if (rest args)
(append '(",") (function-args (rest args))))))))
(defmacro chain (target &rest chain)
"Chain method calls, member access, and indexing operations
on objects. The operations in CHAIN are applied in order from
first to last to the TARGET object.
TARGET can be
cons -- a python function to call, returning an object to operate on
otherwise -- a value, to be converted to a python value
CHAIN can consist of
cons -- a method to call
symbol -- a member data variable
otherwise -- a value put between [] brackets to access an index
Keywords inside python function calls are converted to python keywords.
Functions can be specified using a symbol or a string. If a symbol is used
then it is converted to python using STRING-DOWNCASE.
Examples:
(chain \"hello {0}\" (format \"world\") (capitalize))
=> python: \"hello {0}\".format(\"world\").capitalize()
=> \"Hello world\"
(chain (range 3) stop)
=> python: range(3).stop
=> 3
(chain \"hello\" 4)
=> python: \"hello\"[4]
=> \"o\"
"
(python-start-if-not-alive)
`(py4cl:python-eval
TARGET
,@(if (consp target)
;; A list -> python function call
`(,(let ((func (first target))) ; The function name
(if (stringp func)
func ; Leave string unmodified
(string-downcase func))) ; Otherwise convert to lower-case string
"("
,@(function-args (rest target))
")")
;; A value
(list (list 'py4cl::pythonize target)))
;; CHAIN
,@(loop for link in chain
appending
(cond
((consp link)
;; A list. Usually a method to call, but [] indicates __getitem__
(if (string= (first link) "[]")
;; Calling the __getitem__ method
(list "[" (list 'py4cl::pythonize ; So that strings are escaped
(if (cddr link)
More than one - > wrap in list / tuple
(cadr link))) ; Only one -> no tuple
"]")
;; Calling a method
`("."
,(let ((func (first link)))
(if (stringp func)
func ; Leave string unmodified
(string-downcase func))) ; Otherwise convert to lower-case string
"("
,@(function-args (rest link))
")")))
((symbolp link) (list (format nil ".~(~a~)" link)))
(t (list "[" (list 'py4cl::pythonize link) "]"))))))
(defun python-setf (&rest args)
"Set python variables in ARGS (\"var1\" value1 \"var2\" value2 ...) "
;; pairs converts a list (a b c d) into a list of pairs ((a b) (c d))
(labels ((pairs (items)
(when items
(unless (stringp (first items))
(error "Python variable names must be strings"))
(unless (cdr items)
(error "Expected an even number of inputs"))
(cons (list (first items) (second items))
(pairs (cddr items))))))
(python-start-if-not-alive)
(let ((stream (uiop:process-info-input *python*)))
;; Write "s" to indicate setting variables
(write-char #\s stream)
(stream-write-value (pairs args) stream)
(force-output stream))
;; Should get T returned, might be error
(dispatch-messages *python*)))
(defmacro remote-objects (&body body)
"Ensures that all values returned by python functions
and methods are kept in python, and only handles returned to lisp.
This is useful if performing operations on large datasets."
`(progn
(python-start-if-not-alive)
(let ((stream (uiop:process-info-input *python*)))
;; Turn on remote objects
(write-char #\O stream)
(force-output stream)
(unwind-protect
(progn ,@body)
;; Turn off remote objects
(write-char #\o stream)
(force-output stream)))))
(defmacro remote-objects* (&body body)
"Ensures that all values returned by python functions
and methods are kept in python, and only handles returned to lisp.
This is useful if performing operations on large datasets.
This version evaluates the result, returning it as a lisp value if possible.
"
`(python-eval (remote-objects ,@body)))
| null | https://raw.githubusercontent.com/bendudson/py4cl/601ed206a43beb8504015be464c45be98dc856d0/src/callpython.lisp | lisp | Returned value
Error
Slot read
User must register a function to handle slot access
Provide some restarts for missing handler or missing slot
Slot write
User must register a function to handle slot write
Callback. Value returned is a list, containing the function ID then the args
Send a reply
Print stdout
Write "x" if exec, otherwise "e"
Wait for response from Python
python \"a=2\"
Write "f" to indicate function call
Write "a" to indicate asynchronous function call
Retrieve the value from python
If no handle then already have the value
=> \"hello world\"
A list -> python function call
The function name
Leave string unmodified
Otherwise convert to lower-case string
A value
CHAIN
A list. Usually a method to call, but [] indicates __getitem__
Calling the __getitem__ method
So that strings are escaped
Only one -> no tuple
Calling a method
Leave string unmodified
Otherwise convert to lower-case string
pairs converts a list (a b c d) into a list of pairs ((a b) (c d))
Write "s" to indicate setting variables
Should get T returned, might be error
Turn on remote objects
Turn off remote objects | (in-package :py4cl)
(define-condition python-error (error)
((text :initarg :text :reader text))
(:report (lambda (condition stream)
(format stream "Python error: ~a" (text condition)))))
(defun dispatch-reply (stream value)
(write-char #\r stream)
(stream-write-value value stream)
(force-output stream))
(defun dispatch-messages (process)
"Read response from python, loop to handle any callbacks"
(let ((read-stream (uiop:process-info-output process))
(write-stream (uiop:process-info-input process)))
(loop
First character is type of message
(#\r (return-from dispatch-messages
(stream-read-value read-stream)))
(#\e (error 'python-error
:text (stream-read-string read-stream)))
Delete object . This is called when an UnknownLispObject is deleted
(#\d (free-handle (stream-read-value read-stream)))
(#\s (destructuring-bind (handle slot-name) (stream-read-value read-stream)
(let ((object (lisp-object handle)))
(dispatch-reply write-stream
(restart-case
(python-getattr object slot-name)
(return-nil () nil)
(return-zero () 0)
(enter-value (return-value)
:report "Provide a value to return"
:interactive (lambda ()
(format t "Enter a value to return: ")
(list (read)))
return-value))))))
(#\S (destructuring-bind (handle slot-name slot-value) (stream-read-value read-stream)
(let ((object (lisp-object handle)))
(python-setattr object slot-name slot-value)
(dispatch-reply write-stream nil))))
(#\c
(let ((call-value (stream-read-value read-stream)))
(let ((return-value (apply (lisp-object (first call-value)) (second call-value))))
(dispatch-reply write-stream return-value))))
(#\p
(let ((print-string (stream-read-value read-stream)))
(princ print-string)))
(otherwise (error "Unhandled message type"))))))
(defun python-eval* (cmd-char &rest args)
"Internal function, which converts ARGS into a string to be evaluated
This handles both EVAL and EXEC calls with CMD-CHAR being different
in the two cases.
Anything in ARGS which is not a string is passed through PYTHONIZE
"
(python-start-if-not-alive)
(let ((stream (uiop:process-info-input *python*))
(str (apply #'concatenate 'string (loop for val in args
collecting (if (typep val 'string)
val
(pythonize val))))))
(write-char cmd-char stream)
(stream-write-string str stream)
(force-output stream)
(dispatch-messages *python*)))
(defun python-eval (&rest args)
"Evaluate an expression in python, returning the result
Arguments ARGS can be strings, or other objects. Anything which
is not a string is converted to a python value
Examples:
(python-eval \"[i**2 for i in range(\" 4 \")]\") => #(0 1 4 9)
(let ((a 10) (b 2))
(py4cl:python-eval a "*" b)) => 20
"
(delete-freed-python-objects)
(apply #'python-eval* #\e args))
(defun (setf python-eval) (value &rest args)
"Set an expression to a value. Just adds \"=\" and the value
to the end of the expression. Note that the result is evaluated
with exec rather than eval.
Examples:
"
(apply #'python-eval* #\x (append args (list "=" (py4cl::pythonize value))))
value)
(defun python-exec (&rest args)
"Execute (using exec) an expression in python.
This is used for statements rather than expressions.
"
(delete-freed-python-objects)
(apply #'python-eval* #\x args))
(defun python-call (fun-name &rest args)
"Call a python function, given the function name as a string
and additional arguments. Keywords are converted to keyword arguments."
(python-start-if-not-alive)
(let ((stream (uiop:process-info-input *python*)))
(write-char #\f stream)
(stream-write-value (list fun-name args) stream)
(force-output stream))
(dispatch-messages *python*))
(defun python-call-async (fun-name &rest args)
"Call a python function asynchronously.
Returns a lambda which when called returns the result."
(python-start-if-not-alive)
(let* ((process *python*)
(stream (uiop:process-info-input process)))
(write-char #\a stream)
(stream-write-value (list fun-name args) stream)
(force-output stream)
(let ((handle (dispatch-messages process))
value)
(lambda ()
(if handle
(progn
(write-char #\R stream)
(stream-write-value handle stream)
(force-output stream)
(setf handle nil
value (dispatch-messages process)))
value)))))
(defun python-method (obj method-name &rest args)
"Call a given method on an object OBJ. METHOD-NAME can be a
symbol (converted to lower case) or a string.
Examples:
(python-method \"hello {0}\" 'format \"world\")
(python-method '(1 2 3) '__len__)
= > 3
"
(python-start-if-not-alive)
(py4cl:python-eval
(py4cl::pythonize obj)
(format nil ".~(~a~)" method-name)
(if args
(py4cl::pythonize args)
"()")))
(defun python-generator (function stop-value)
(python-call "_py4cl_generator" function stop-value))
(defun function-args (args)
"Internal function, intended to be called by the CHAIN macro.
Converts function arguments to a list of strings and (pythonize )
function calls. Handles keywords and insertion of commas.
Returns a list which can be passed to PYTHON-EVAL.
Examples:
(py4cl::function-args '(1 :test 2))
=> ((PY4CL::PYTHONIZE 1) \",\" \"test\" \"=\" (PY4CL::PYTHONIZE 2))
"
(if (not args)
'("")
(if (keywordp (first args))
(append
(list (string-downcase (first args))
"="
`(pythonize ,(second args)))
(if (cddr args)
(append '(",") (function-args (cddr args)))))
(append
(list `(pythonize ,(first args)))
(if (rest args)
(append '(",") (function-args (rest args))))))))
(defmacro chain (target &rest chain)
"Chain method calls, member access, and indexing operations
on objects. The operations in CHAIN are applied in order from
first to last to the TARGET object.
TARGET can be
cons -- a python function to call, returning an object to operate on
otherwise -- a value, to be converted to a python value
CHAIN can consist of
cons -- a method to call
symbol -- a member data variable
otherwise -- a value put between [] brackets to access an index
Keywords inside python function calls are converted to python keywords.
Functions can be specified using a symbol or a string. If a symbol is used
then it is converted to python using STRING-DOWNCASE.
Examples:
(chain \"hello {0}\" (format \"world\") (capitalize))
=> python: \"hello {0}\".format(\"world\").capitalize()
=> \"Hello world\"
(chain (range 3) stop)
=> python: range(3).stop
=> 3
(chain \"hello\" 4)
=> python: \"hello\"[4]
=> \"o\"
"
(python-start-if-not-alive)
`(py4cl:python-eval
TARGET
,@(if (consp target)
(if (stringp func)
"("
,@(function-args (rest target))
")")
(list (list 'py4cl::pythonize target)))
,@(loop for link in chain
appending
(cond
((consp link)
(if (string= (first link) "[]")
(if (cddr link)
More than one - > wrap in list / tuple
"]")
`("."
,(let ((func (first link)))
(if (stringp func)
"("
,@(function-args (rest link))
")")))
((symbolp link) (list (format nil ".~(~a~)" link)))
(t (list "[" (list 'py4cl::pythonize link) "]"))))))
(defun python-setf (&rest args)
"Set python variables in ARGS (\"var1\" value1 \"var2\" value2 ...) "
(labels ((pairs (items)
(when items
(unless (stringp (first items))
(error "Python variable names must be strings"))
(unless (cdr items)
(error "Expected an even number of inputs"))
(cons (list (first items) (second items))
(pairs (cddr items))))))
(python-start-if-not-alive)
(let ((stream (uiop:process-info-input *python*)))
(write-char #\s stream)
(stream-write-value (pairs args) stream)
(force-output stream))
(dispatch-messages *python*)))
(defmacro remote-objects (&body body)
"Ensures that all values returned by python functions
and methods are kept in python, and only handles returned to lisp.
This is useful if performing operations on large datasets."
`(progn
(python-start-if-not-alive)
(let ((stream (uiop:process-info-input *python*)))
(write-char #\O stream)
(force-output stream)
(unwind-protect
(progn ,@body)
(write-char #\o stream)
(force-output stream)))))
(defmacro remote-objects* (&body body)
"Ensures that all values returned by python functions
and methods are kept in python, and only handles returned to lisp.
This is useful if performing operations on large datasets.
This version evaluates the result, returning it as a lisp value if possible.
"
`(python-eval (remote-objects ,@body)))
|
65f9ad6411756e5eef783b2cdc20f7816793c6d413f4a0f6de400aa680180083 | fission-codes/fission | Types.hs | -- | Application security
module Fission.Security.Types
( Secret (..)
, SecretDigest
) where
import Data.Swagger
import Fission.Prelude
-- | A text digest
type SecretDigest = Text
-- | An application secret
newtype Secret = Secret { unSecret :: Text }
deriving ( Eq
, Show
, Generic
)
deriving newtype ( FromJSON
, ToJSON
)
instance Arbitrary Secret where
arbitrary = Secret <$> arbitrary
instance ToSchema Secret where
declareNamedSchema _ =
mempty
|> type_ ?~ SwaggerString
|> example ?~ "U)mRvIvI6$L_MkYpme!lfzMte_92M5G912-NUfRmfxhRKx$Rr6aLUxqdqW"
|> description ?~ "User secret (used for authentication)"
|> NamedSchema (Just "Secret")
|> pure
| null | https://raw.githubusercontent.com/fission-codes/fission/ae177407dccc20be67948a901956b99f40d37ac8/fission-core/library/Fission/Security/Types.hs | haskell | | Application security
| A text digest
| An application secret | module Fission.Security.Types
( Secret (..)
, SecretDigest
) where
import Data.Swagger
import Fission.Prelude
type SecretDigest = Text
newtype Secret = Secret { unSecret :: Text }
deriving ( Eq
, Show
, Generic
)
deriving newtype ( FromJSON
, ToJSON
)
instance Arbitrary Secret where
arbitrary = Secret <$> arbitrary
instance ToSchema Secret where
declareNamedSchema _ =
mempty
|> type_ ?~ SwaggerString
|> example ?~ "U)mRvIvI6$L_MkYpme!lfzMte_92M5G912-NUfRmfxhRKx$Rr6aLUxqdqW"
|> description ?~ "User secret (used for authentication)"
|> NamedSchema (Just "Secret")
|> pure
|
89c37c9f3d582e0ae85624d03a32508ee1a0c2e0058e02a9dedb13f53d453046 | gfngfn/SATySFi | state.ml |
exception NotDuringPageBreak
type state = {
mutable during_page_break : bool;
}
let state = {
during_page_break = false;
}
let start_page_break () = state.during_page_break <- true
let during_page_break () = state.during_page_break
| null | https://raw.githubusercontent.com/gfngfn/SATySFi/9dbd61df0ab05943b3394830c371e927df45251a/src/frontend/state.ml | ocaml |
exception NotDuringPageBreak
type state = {
mutable during_page_break : bool;
}
let state = {
during_page_break = false;
}
let start_page_break () = state.during_page_break <- true
let during_page_break () = state.during_page_break
| |
a0576beff24f06ac61a9d5d1b98d399c7268fd79cbf27c083c7ee74c67d62c01 | Frechmatz/cl-synthesizer | example-2.lisp | (defpackage :cl-synthesizer-modules-vco-example-2
(:use :cl))
(in-package :cl-synthesizer-modules-vco-example-2)
(defun example ()
"A frequency modulated triangle"
(let ((rack (cl-synthesizer:make-rack :environment (cl-synthesizer:make-environment))))
(cl-synthesizer:add-module
rack "LFO"
#'cl-synthesizer-modules-vco:make-module :v-peak 5.0 :base-frequency 4.0)
(cl-synthesizer:add-module
rack "VCO"
#'cl-synthesizer-modules-vco:make-module :base-frequency 440.0 :v-peak 5.0 :cv-lin-hz-v 20.0)
(cl-synthesizer:add-patch rack "LFO" :triangle "VCO" :cv-lin)
(cl-synthesizer-monitor:add-monitor
rack
#'cl-synthesizer-monitor-wave-file-agent:make-backend
'(("VCO" :output-socket :triangle))
:filename "cl-synthesizer-examples/vco-example-2.wav"
:v-peak 5.0)
(cl-synthesizer-monitor:add-monitor
rack
#'cl-synthesizer-monitor-csv-file-agent:make-backend
'(("VCO" :state :frequency :name "Frequency"))
:filename "cl-synthesizer-examples/vco-example-2.csv")
rack))
(defun run-example ()
(let ((rack (example))) (cl-synthesizer:play-rack rack :duration-seconds 2)))
;; (run-example)
| null | https://raw.githubusercontent.com/Frechmatz/cl-synthesizer/ba2e4003448829078187013f6723eb5c8ce8adbc/src/modules/vco/example-2.lisp | lisp | (run-example) | (defpackage :cl-synthesizer-modules-vco-example-2
(:use :cl))
(in-package :cl-synthesizer-modules-vco-example-2)
(defun example ()
"A frequency modulated triangle"
(let ((rack (cl-synthesizer:make-rack :environment (cl-synthesizer:make-environment))))
(cl-synthesizer:add-module
rack "LFO"
#'cl-synthesizer-modules-vco:make-module :v-peak 5.0 :base-frequency 4.0)
(cl-synthesizer:add-module
rack "VCO"
#'cl-synthesizer-modules-vco:make-module :base-frequency 440.0 :v-peak 5.0 :cv-lin-hz-v 20.0)
(cl-synthesizer:add-patch rack "LFO" :triangle "VCO" :cv-lin)
(cl-synthesizer-monitor:add-monitor
rack
#'cl-synthesizer-monitor-wave-file-agent:make-backend
'(("VCO" :output-socket :triangle))
:filename "cl-synthesizer-examples/vco-example-2.wav"
:v-peak 5.0)
(cl-synthesizer-monitor:add-monitor
rack
#'cl-synthesizer-monitor-csv-file-agent:make-backend
'(("VCO" :state :frequency :name "Frequency"))
:filename "cl-synthesizer-examples/vco-example-2.csv")
rack))
(defun run-example ()
(let ((rack (example))) (cl-synthesizer:play-rack rack :duration-seconds 2)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.