_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 |
|---|---|---|---|---|---|---|---|---|
98f1d50e6039f723319e1137e7ff9d7281123295a349805ae74e7ad866acd8ee | kongo2002/statser | statser_api_tests.erl | -module(statser_api_tests).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-define(DEFAULT_HOST, ":8080").
setup() ->
setup(emergency).
setup(LogLevel) ->
Ctx = test_util:start_statser(LogLevel),
inets:start(),
Ctx.
teardown(State) ->
inets:stop(),
test_util:stop(State),
ok.
api_metrics_query_non_existing_target_test_() ->
{
"test for rendering non existing targets",
{
setup,
fun setup/0, fun teardown/1,
[
?_assertEqual([], metrics_request("does.not.exist")),
?_assertEqual([], metrics_request("does.not.*"))
]
}
}.
api_render_non_existing_target_test_() ->
{
"test for rendering non existing targets",
{
setup,
fun setup/0, fun teardown/1,
[
?_assertEqual([], render_request(["does.not.exist"])),
?_assertEqual([], render_request(["does.not.exist", "doesnt.exist.either"])),
?_assertEqual([], render_request(["does.not.*"]))
]
}
}.
api_render_functions_of_non_existing_target_test_() ->
{
"test for rendering function calls of non existing targets",
{
setup,
fun setup/0, fun teardown/1,
[
?_assertEqual([], render_request(["perSecond(does.not.exist)"])),
?_assertEqual([], render_request(["sumSeries(does.not.*)"]))
]
}
}.
api_render_sent_metric_test_() ->
{
"test for rendering metrics that were just sent",
{
setup,
fun setup/0, fun teardown/1,
[
% TODO: refine assertion
?_assert(non_empty_list(send_and_request_datapoints("foo.bar", 100)))
]
}
}.
non_empty_list([_ | _]) -> true;
non_empty_list([]) -> false.
send_and_request_datapoints(Metric, Value) ->
test_util:send_metric(Metric, Value),
timer:sleep(100),
[{Values}] = render_request([Metric]),
DataPoints = proplists:get_value(<<"datapoints">>, Values),
DataPoints.
get_request(Path) ->
Url = ?DEFAULT_HOST ++ Path,
{ok, Response} = httpc:request(Url),
Response.
form_post_request(Path, Body) ->
Url = ?DEFAULT_HOST ++ Path,
Request = {Url, [], "application/x-www-form-urlencoded", Body},
{ok, Response} = httpc:request(post, Request, [], []),
Response.
metrics_request(Path) ->
Url = "/metrics?query=" ++ Path,
{{_, 200, "OK"}, _, Body} = get_request(Url),
jiffy:decode(Body).
render_request(Targets) ->
Ts0 = lists:map(fun(T) -> "target=" ++ T end, Targets),
Ts = lists:flatten(lists:join("&", Ts0 ++ ["from=-15min"])),
{{_, 200, "OK"}, _, Body} = form_post_request("/render", Ts),
jiffy:decode(Body).
-endif.
| null | https://raw.githubusercontent.com/kongo2002/statser/1cb0498f56c97d8a010b979c5163dd2750064e98/test/statser_api_tests.erl | erlang | TODO: refine assertion | -module(statser_api_tests).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-define(DEFAULT_HOST, ":8080").
setup() ->
setup(emergency).
setup(LogLevel) ->
Ctx = test_util:start_statser(LogLevel),
inets:start(),
Ctx.
teardown(State) ->
inets:stop(),
test_util:stop(State),
ok.
api_metrics_query_non_existing_target_test_() ->
{
"test for rendering non existing targets",
{
setup,
fun setup/0, fun teardown/1,
[
?_assertEqual([], metrics_request("does.not.exist")),
?_assertEqual([], metrics_request("does.not.*"))
]
}
}.
api_render_non_existing_target_test_() ->
{
"test for rendering non existing targets",
{
setup,
fun setup/0, fun teardown/1,
[
?_assertEqual([], render_request(["does.not.exist"])),
?_assertEqual([], render_request(["does.not.exist", "doesnt.exist.either"])),
?_assertEqual([], render_request(["does.not.*"]))
]
}
}.
api_render_functions_of_non_existing_target_test_() ->
{
"test for rendering function calls of non existing targets",
{
setup,
fun setup/0, fun teardown/1,
[
?_assertEqual([], render_request(["perSecond(does.not.exist)"])),
?_assertEqual([], render_request(["sumSeries(does.not.*)"]))
]
}
}.
api_render_sent_metric_test_() ->
{
"test for rendering metrics that were just sent",
{
setup,
fun setup/0, fun teardown/1,
[
?_assert(non_empty_list(send_and_request_datapoints("foo.bar", 100)))
]
}
}.
non_empty_list([_ | _]) -> true;
non_empty_list([]) -> false.
send_and_request_datapoints(Metric, Value) ->
test_util:send_metric(Metric, Value),
timer:sleep(100),
[{Values}] = render_request([Metric]),
DataPoints = proplists:get_value(<<"datapoints">>, Values),
DataPoints.
get_request(Path) ->
Url = ?DEFAULT_HOST ++ Path,
{ok, Response} = httpc:request(Url),
Response.
form_post_request(Path, Body) ->
Url = ?DEFAULT_HOST ++ Path,
Request = {Url, [], "application/x-www-form-urlencoded", Body},
{ok, Response} = httpc:request(post, Request, [], []),
Response.
metrics_request(Path) ->
Url = "/metrics?query=" ++ Path,
{{_, 200, "OK"}, _, Body} = get_request(Url),
jiffy:decode(Body).
render_request(Targets) ->
Ts0 = lists:map(fun(T) -> "target=" ++ T end, Targets),
Ts = lists:flatten(lists:join("&", Ts0 ++ ["from=-15min"])),
{{_, 200, "OK"}, _, Body} = form_post_request("/render", Ts),
jiffy:decode(Body).
-endif.
|
4b00ded5f1d2381810995e7338fb339abfb9a473d7e4ffb5b479dddd38545bc5 | FranklinChen/hugs98-plus-Sep2006 | SrcDist.hs | # OPTIONS_GHC -cpp #
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.SrcDist
Copyright : 2004
--
Maintainer : < >
-- Stability : alpha
-- Portability : portable
--
Copyright ( c ) 2003 - 2004 ,
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are
met :
* Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above
copyright notice , this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution .
* Neither the name of nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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 .
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
-- NOTE: FIX: we don't have a great way of testing this module, since
-- we can't easily look inside a tarball once its created.
module Distribution.Simple.SrcDist (
sdist
#ifdef DEBUG
,hunitTests
#endif
) where
import Distribution.PackageDescription
(PackageDescription(..), BuildInfo(..), Executable(..), Library(..),
setupMessage, libModules)
import Distribution.Package (showPackageId, PackageIdentifier(pkgVersion))
import Distribution.Version (Version(versionBranch))
import Distribution.Simple.Utils
(smartCopySources, die, findPackageDesc, findFile, copyFileVerbose)
import Distribution.Setup (SDistFlags(..))
import Distribution.PreProcess (PPSuffixHandler, ppSuffixes, removePreprocessed)
import Control.Monad(when)
import Data.Char (isSpace, toLower)
import Data.List (isPrefixOf)
import System.Cmd (system)
import System.Time (getClockTime, toCalendarTime, CalendarTime(..))
import Distribution.Compat.Directory (doesFileExist, doesDirectoryExist,
getCurrentDirectory, createDirectoryIfMissing, removeDirectoryRecursive)
import Distribution.Compat.FilePath (joinFileName, splitFileName)
#ifdef DEBUG
import HUnit (Test)
#endif
-- |Create a source distribution. FIX: Calls tar directly (won't work
-- on windows).
sdist :: PackageDescription
-> SDistFlags -- verbose & snapshot
-> FilePath -- ^build prefix (temp dir)
-> FilePath -- ^TargetPrefix
-> [PPSuffixHandler] -- ^ extra preprocessors (includes suffixes)
-> IO ()
sdist pkg_descr_orig (SDistFlags snapshot verbose) tmpDir targetPref pps = do
time <- getClockTime
ct <- toCalendarTime time
let date = ctYear ct*10000 + (fromEnum (ctMonth ct) + 1)*100 + ctDay ct
let pkg_descr
| snapshot = updatePackage (updatePkgVersion
(updateVersionBranch (++ [date]))) pkg_descr_orig
| otherwise = pkg_descr_orig
setupMessage "Building source dist for" pkg_descr
ex <- doesDirectoryExist tmpDir
when ex (die $ "Source distribution already in place. please move: " ++ tmpDir)
let targetDir = tmpDir `joinFileName` (nameVersion pkg_descr)
createDirectoryIfMissing True targetDir
-- maybe move the library files into place
maybe (return ()) (\l -> prepareDir verbose targetDir pps (libModules pkg_descr) (libBuildInfo l))
(library pkg_descr)
-- move the executables into place
flip mapM_ (executables pkg_descr) $ \ (Executable _ mainPath exeBi) -> do
prepareDir verbose targetDir pps [] exeBi
srcMainFile <- findFile (hsSourceDirs exeBi) mainPath
copyFileTo verbose targetDir srcMainFile
flip mapM_ (dataFiles pkg_descr) $ \ file -> do
let (dir, _) = splitFileName file
createDirectoryIfMissing True (targetDir `joinFileName` dir)
copyFileVerbose verbose file (targetDir `joinFileName` file)
when (not (null (licenseFile pkg_descr))) $
copyFileTo verbose targetDir (licenseFile pkg_descr)
flip mapM_ (extraSrcFiles pkg_descr) $ \ fpath -> do
copyFileTo verbose targetDir fpath
-- setup isn't listed in the description file.
hsExists <- doesFileExist "Setup.hs"
lhsExists <- doesFileExist "Setup.lhs"
if hsExists then copyFileTo verbose targetDir "Setup.hs"
else if lhsExists then copyFileTo verbose targetDir "Setup.lhs"
else writeFile (targetDir `joinFileName` "Setup.hs") $ unlines [
"import Distribution.Simple",
"main = defaultMainWithHooks defaultUserHooks"]
-- the description file itself
descFile <- getCurrentDirectory >>= findPackageDesc
let targetDescFile = targetDir `joinFileName` descFile
-- We could just writePackageDescription targetDescFile pkg_descr,
-- but that would lose comments and formatting.
if snapshot then do
contents <- readFile descFile
writeFile targetDescFile $
unlines $ map (appendVersion date) $ lines $ contents
else copyFileVerbose verbose descFile targetDescFile
let tarBallFilePath = targetPref `joinFileName` tarBallName pkg_descr
system $ "(cd " ++ tmpDir
++ ";tar cf - " ++ (nameVersion pkg_descr) ++ ") | gzip -9 >"
++ tarBallFilePath
removeDirectoryRecursive tmpDir
putStrLn $ "Source tarball created: " ++ tarBallFilePath
where
updatePackage f pd = pd { package = f (package pd) }
updatePkgVersion f pkg = pkg { pkgVersion = f (pkgVersion pkg) }
updateVersionBranch f v = v { versionBranch = f (versionBranch v) }
appendVersion :: Int -> String -> String
appendVersion n line
| "version:" `isPrefixOf` map toLower line =
trimTrailingSpace line ++ "." ++ show n
| otherwise = line
trimTrailingSpace :: String -> String
trimTrailingSpace = reverse . dropWhile isSpace . reverse
-- |Move the sources into place based on buildInfo
prepareDir :: Int -- ^verbose
-> FilePath -- ^TargetPrefix
-> [PPSuffixHandler] -- ^ extra preprocessors (includes suffixes)
-> [String] -- ^Exposed modules
-> BuildInfo
-> IO ()
prepareDir verbose inPref pps mods BuildInfo{hsSourceDirs=srcDirs, otherModules=mods', cSources=cfiles}
= do let suff = ppSuffixes pps ++ ["hs", "lhs"]
smartCopySources verbose srcDirs inPref (mods++mods') suff True True
removePreprocessed (map (joinFileName inPref) srcDirs) mods suff
mapM_ (copyFileTo verbose inPref) cfiles
copyFileTo :: Int -> FilePath -> FilePath -> IO ()
copyFileTo verbose dir file = do
let targetFile = dir `joinFileName` file
createDirectoryIfMissing True (fst (splitFileName targetFile))
copyFileVerbose verbose file targetFile
------------------------------------------------------------
-- |The file name of the tarball
tarBallName :: PackageDescription -> FilePath
tarBallName p = (nameVersion p) ++ ".tar.gz"
nameVersion :: PackageDescription -> String
nameVersion = showPackageId . package
-- ------------------------------------------------------------
-- * Testing
-- ------------------------------------------------------------
#ifdef DEBUG
hunitTests :: [Test]
hunitTests = []
#endif
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/Cabal/Distribution/Simple/SrcDist.hs | haskell | ---------------------------------------------------------------------------
|
Module : Distribution.Simple.SrcDist
Stability : alpha
Portability : portable
NOTE: FIX: we don't have a great way of testing this module, since
we can't easily look inside a tarball once its created.
|Create a source distribution. FIX: Calls tar directly (won't work
on windows).
verbose & snapshot
^build prefix (temp dir)
^TargetPrefix
^ extra preprocessors (includes suffixes)
maybe move the library files into place
move the executables into place
setup isn't listed in the description file.
the description file itself
We could just writePackageDescription targetDescFile pkg_descr,
but that would lose comments and formatting.
|Move the sources into place based on buildInfo
^verbose
^TargetPrefix
^ extra preprocessors (includes suffixes)
^Exposed modules
----------------------------------------------------------
|The file name of the tarball
------------------------------------------------------------
* Testing
------------------------------------------------------------ | # OPTIONS_GHC -cpp #
Copyright : 2004
Maintainer : < >
Copyright ( c ) 2003 - 2004 ,
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are
met :
* Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above
copyright notice , this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution .
* Neither the name of nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT
OWNER OR 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 .
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
module Distribution.Simple.SrcDist (
sdist
#ifdef DEBUG
,hunitTests
#endif
) where
import Distribution.PackageDescription
(PackageDescription(..), BuildInfo(..), Executable(..), Library(..),
setupMessage, libModules)
import Distribution.Package (showPackageId, PackageIdentifier(pkgVersion))
import Distribution.Version (Version(versionBranch))
import Distribution.Simple.Utils
(smartCopySources, die, findPackageDesc, findFile, copyFileVerbose)
import Distribution.Setup (SDistFlags(..))
import Distribution.PreProcess (PPSuffixHandler, ppSuffixes, removePreprocessed)
import Control.Monad(when)
import Data.Char (isSpace, toLower)
import Data.List (isPrefixOf)
import System.Cmd (system)
import System.Time (getClockTime, toCalendarTime, CalendarTime(..))
import Distribution.Compat.Directory (doesFileExist, doesDirectoryExist,
getCurrentDirectory, createDirectoryIfMissing, removeDirectoryRecursive)
import Distribution.Compat.FilePath (joinFileName, splitFileName)
#ifdef DEBUG
import HUnit (Test)
#endif
sdist :: PackageDescription
-> IO ()
sdist pkg_descr_orig (SDistFlags snapshot verbose) tmpDir targetPref pps = do
time <- getClockTime
ct <- toCalendarTime time
let date = ctYear ct*10000 + (fromEnum (ctMonth ct) + 1)*100 + ctDay ct
let pkg_descr
| snapshot = updatePackage (updatePkgVersion
(updateVersionBranch (++ [date]))) pkg_descr_orig
| otherwise = pkg_descr_orig
setupMessage "Building source dist for" pkg_descr
ex <- doesDirectoryExist tmpDir
when ex (die $ "Source distribution already in place. please move: " ++ tmpDir)
let targetDir = tmpDir `joinFileName` (nameVersion pkg_descr)
createDirectoryIfMissing True targetDir
maybe (return ()) (\l -> prepareDir verbose targetDir pps (libModules pkg_descr) (libBuildInfo l))
(library pkg_descr)
flip mapM_ (executables pkg_descr) $ \ (Executable _ mainPath exeBi) -> do
prepareDir verbose targetDir pps [] exeBi
srcMainFile <- findFile (hsSourceDirs exeBi) mainPath
copyFileTo verbose targetDir srcMainFile
flip mapM_ (dataFiles pkg_descr) $ \ file -> do
let (dir, _) = splitFileName file
createDirectoryIfMissing True (targetDir `joinFileName` dir)
copyFileVerbose verbose file (targetDir `joinFileName` file)
when (not (null (licenseFile pkg_descr))) $
copyFileTo verbose targetDir (licenseFile pkg_descr)
flip mapM_ (extraSrcFiles pkg_descr) $ \ fpath -> do
copyFileTo verbose targetDir fpath
hsExists <- doesFileExist "Setup.hs"
lhsExists <- doesFileExist "Setup.lhs"
if hsExists then copyFileTo verbose targetDir "Setup.hs"
else if lhsExists then copyFileTo verbose targetDir "Setup.lhs"
else writeFile (targetDir `joinFileName` "Setup.hs") $ unlines [
"import Distribution.Simple",
"main = defaultMainWithHooks defaultUserHooks"]
descFile <- getCurrentDirectory >>= findPackageDesc
let targetDescFile = targetDir `joinFileName` descFile
if snapshot then do
contents <- readFile descFile
writeFile targetDescFile $
unlines $ map (appendVersion date) $ lines $ contents
else copyFileVerbose verbose descFile targetDescFile
let tarBallFilePath = targetPref `joinFileName` tarBallName pkg_descr
system $ "(cd " ++ tmpDir
++ ";tar cf - " ++ (nameVersion pkg_descr) ++ ") | gzip -9 >"
++ tarBallFilePath
removeDirectoryRecursive tmpDir
putStrLn $ "Source tarball created: " ++ tarBallFilePath
where
updatePackage f pd = pd { package = f (package pd) }
updatePkgVersion f pkg = pkg { pkgVersion = f (pkgVersion pkg) }
updateVersionBranch f v = v { versionBranch = f (versionBranch v) }
appendVersion :: Int -> String -> String
appendVersion n line
| "version:" `isPrefixOf` map toLower line =
trimTrailingSpace line ++ "." ++ show n
| otherwise = line
trimTrailingSpace :: String -> String
trimTrailingSpace = reverse . dropWhile isSpace . reverse
-> BuildInfo
-> IO ()
prepareDir verbose inPref pps mods BuildInfo{hsSourceDirs=srcDirs, otherModules=mods', cSources=cfiles}
= do let suff = ppSuffixes pps ++ ["hs", "lhs"]
smartCopySources verbose srcDirs inPref (mods++mods') suff True True
removePreprocessed (map (joinFileName inPref) srcDirs) mods suff
mapM_ (copyFileTo verbose inPref) cfiles
copyFileTo :: Int -> FilePath -> FilePath -> IO ()
copyFileTo verbose dir file = do
let targetFile = dir `joinFileName` file
createDirectoryIfMissing True (fst (splitFileName targetFile))
copyFileVerbose verbose file targetFile
tarBallName :: PackageDescription -> FilePath
tarBallName p = (nameVersion p) ++ ".tar.gz"
nameVersion :: PackageDescription -> String
nameVersion = showPackageId . package
#ifdef DEBUG
hunitTests :: [Test]
hunitTests = []
#endif
|
0d7853593af138b33607c79e1657bd56bd6131f64d7ad0b74d6617dc41738660 | agda/agda2hs | Issue14.hs | module Issue14 where
import Numeric.Natural (Natural)
constid :: a -> b -> b
constid x = \ x -> x
sectionTest₁ :: Natural -> Natural -> Natural
sectionTest₁ n = (+ n)
sectionTest₂ :: Natural -> Natural -> Natural
sectionTest₂ section = (+ section)
| null | https://raw.githubusercontent.com/agda/agda2hs/16b51f430682619e25a18cfbfb4463a4272fab4b/test/golden/Issue14.hs | haskell | module Issue14 where
import Numeric.Natural (Natural)
constid :: a -> b -> b
constid x = \ x -> x
sectionTest₁ :: Natural -> Natural -> Natural
sectionTest₁ n = (+ n)
sectionTest₂ :: Natural -> Natural -> Natural
sectionTest₂ section = (+ section)
| |
a704407bbcac2aa2e21e2f27a7e0ada51b1172b95ecc26af4828bbf8aa0f3b3b | nathanaelbayle/programming-language | CalculatorRegisterStore.hs | -- | Semantics for register based integer calculator.
-- The values of the registers are stored in a Store.
--
-- Author Magne Haveraaen
Since 2020 - 03 - 14
module CalculatorRegisterStore where
-- Use Haskell's array data structure
import Data.Array
-----------------------
| A Store for a register calculator is an array with 10 integer elements .
The access functions getregister / need to translate between register and array index .
type Store = Array Integer Integer
| Defines a store for 10 registers
registerstore :: Store
registerstore = array (0,9) [(i,0)|i<-[0..9]]
-- | Get the value stored for the given register.
getstore :: Store -> Integer -> Integer
getstore store ind =
if 0 <= ind && ind < 10
then store ! ind
else error $ "Not a register index " ++ (show ind)
-- | Set the value stored for the given register.
setstore :: Integer -> Integer -> Store -> Store
setstore ind val store =
if 0 <= ind && ind < 10
then store // [(ind,val)]
else error $ "Not a register index " ++ (show ind) ++ " for " ++ (show val)
| null | https://raw.githubusercontent.com/nathanaelbayle/programming-language/4ee0c0c2aa34ee1cb6fa6d7c37f28bc2bfee25bd/INF222%20Pamphlets/INF222%20-%20Pamphlet%202/CalculatorRegisterStore.hs | haskell | | Semantics for register based integer calculator.
The values of the registers are stored in a Store.
Author Magne Haveraaen
Use Haskell's array data structure
---------------------
| Get the value stored for the given register.
| Set the value stored for the given register. | Since 2020 - 03 - 14
module CalculatorRegisterStore where
import Data.Array
| A Store for a register calculator is an array with 10 integer elements .
The access functions getregister / need to translate between register and array index .
type Store = Array Integer Integer
| Defines a store for 10 registers
registerstore :: Store
registerstore = array (0,9) [(i,0)|i<-[0..9]]
getstore :: Store -> Integer -> Integer
getstore store ind =
if 0 <= ind && ind < 10
then store ! ind
else error $ "Not a register index " ++ (show ind)
setstore :: Integer -> Integer -> Store -> Store
setstore ind val store =
if 0 <= ind && ind < 10
then store // [(ind,val)]
else error $ "Not a register index " ++ (show ind) ++ " for " ++ (show val)
|
860c131b9f9646ecd9eee968e01c49e6483f0e538388eec805846db4eb003efb | tanakh/ICFP2011 | Yuma2.hs | # LANGUAGE CPP #
{-# OPTIONS -Wall #-}
import Control.Applicative
import qualified Control.Exception.Control as E
import Control.Monad
import Control.Monad.State
import Data.Maybe
import LTG
sittingDuck = do
I $> 0
sittingDuck
kyoukoMain :: LTG()
kyoukoMain = do
S ( K ( S ( S Attack ( K 255 ) ) ( K 8192 ) ) ) Get
clear 1
1 $< Attack
S $> 1
num 0 255
copyTo 2 0
K $> 0
apply0 1
S $> 1
0 $< Put
Dbl $> 0
K $> 0
apply0 1
0 $< Put
Dbl $> 0
Dbl $> 0
Dbl $> 0
Dbl $> 0
K $> 0
clear 3
3 $< S
3 $< Help
3 $< I
S $> 3
apply0 3
clear 16
16 $< Get
num 4 1
num 8 0
lazyApply2 16 4 8
copyTo 0 16
S $> 3
apply0 3
S $> 1
copyTo 0 3
apply0 1
K $ > 1
S $ > 1
1 $ < Get
num 0 1
num 2 1
Get $> 2
2 $< Zero
num 2 1
Get $> 2
2 $< Zero
num 2 1
Get $> 2
2 $< Zero
num 2 1
Get $> 2
2 $< Zero
num 0 2
1 $ < Zero
sittingDuck
main :: IO ()
main = runLTG $ do
kyoukoMain
| null | https://raw.githubusercontent.com/tanakh/ICFP2011/db0d670cdbe12e9cef4242d6ab202a98c254412e/ai/Yuma2.hs | haskell | # OPTIONS -Wall # | # LANGUAGE CPP #
import Control.Applicative
import qualified Control.Exception.Control as E
import Control.Monad
import Control.Monad.State
import Data.Maybe
import LTG
sittingDuck = do
I $> 0
sittingDuck
kyoukoMain :: LTG()
kyoukoMain = do
S ( K ( S ( S Attack ( K 255 ) ) ( K 8192 ) ) ) Get
clear 1
1 $< Attack
S $> 1
num 0 255
copyTo 2 0
K $> 0
apply0 1
S $> 1
0 $< Put
Dbl $> 0
K $> 0
apply0 1
0 $< Put
Dbl $> 0
Dbl $> 0
Dbl $> 0
Dbl $> 0
K $> 0
clear 3
3 $< S
3 $< Help
3 $< I
S $> 3
apply0 3
clear 16
16 $< Get
num 4 1
num 8 0
lazyApply2 16 4 8
copyTo 0 16
S $> 3
apply0 3
S $> 1
copyTo 0 3
apply0 1
K $ > 1
S $ > 1
1 $ < Get
num 0 1
num 2 1
Get $> 2
2 $< Zero
num 2 1
Get $> 2
2 $< Zero
num 2 1
Get $> 2
2 $< Zero
num 2 1
Get $> 2
2 $< Zero
num 0 2
1 $ < Zero
sittingDuck
main :: IO ()
main = runLTG $ do
kyoukoMain
|
51f5bde85066a899d9e07a079344e0a7a869adc4e2f56ab05909b60e1fe54b98 | sgbj/MaximaSharp | dlasrt.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
;;; Using Lisp CMU Common Lisp 20d (20D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :lapack)
(let* ((select 20))
(declare (type (f2cl-lib:integer4 20 20) select) (ignorable select))
(defun dlasrt (id n d info)
(declare (type (array double-float (*)) d)
(type (f2cl-lib:integer4) info n)
(type (simple-string *) id))
(f2cl-lib:with-multi-array-data
((id character id-%data% id-%offset%)
(d double-float d-%data% d-%offset%))
(prog ((stack (make-array 64 :element-type 'f2cl-lib:integer4)) (d1 0.0)
(d2 0.0) (d3 0.0) (dmnmx 0.0) (tmp 0.0) (dir 0) (endd 0) (i 0)
(j 0) (start 0) (stkpnt 0))
(declare (type (array f2cl-lib:integer4 (64)) stack)
(type (double-float) d1 d2 d3 dmnmx tmp)
(type (f2cl-lib:integer4) dir endd i j start stkpnt))
(setf info 0)
(setf dir -1)
(cond
((lsame id "D")
(setf dir 0))
((lsame id "I")
(setf dir 1)))
(cond
((= dir (f2cl-lib:int-sub 1))
(setf info -1))
((< n 0)
(setf info -2)))
(cond
((/= info 0)
(xerbla "DLASRT" (f2cl-lib:int-sub info))
(go end_label)))
(if (<= n 1) (go end_label))
(setf stkpnt 1)
(setf (f2cl-lib:fref stack (1 1) ((1 2) (1 32))) 1)
(setf (f2cl-lib:fref stack (2 1) ((1 2) (1 32))) n)
label10
(setf start (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))))
(setf endd (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))))
(setf stkpnt (f2cl-lib:int-sub stkpnt 1))
(cond
((and (<= (f2cl-lib:int-add endd (f2cl-lib:int-sub start)) select)
(> (f2cl-lib:int-add endd (f2cl-lib:int-sub start)) 0))
(cond
((= dir 0)
(f2cl-lib:fdo (i (f2cl-lib:int-add start 1)
(f2cl-lib:int-add i 1))
((> i endd) nil)
(tagbody
(f2cl-lib:fdo (j i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j (f2cl-lib:int-add start 1)) nil)
(tagbody
(cond
((> (f2cl-lib:fref d (j) ((1 *)))
(f2cl-lib:fref d
((f2cl-lib:int-add j
(f2cl-lib:int-sub
1)))
((1 *))))
(setf dmnmx
(f2cl-lib:fref d-%data%
(j)
((1 *))
d-%offset%))
(setf (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%)
(f2cl-lib:fref d-%data%
((f2cl-lib:int-sub j 1))
((1 *))
d-%offset%))
(setf (f2cl-lib:fref d-%data%
((f2cl-lib:int-sub j 1))
((1 *))
d-%offset%)
dmnmx))
(t
(go label30)))
label20))
label30)))
(t
(f2cl-lib:fdo (i (f2cl-lib:int-add start 1)
(f2cl-lib:int-add i 1))
((> i endd) nil)
(tagbody
(f2cl-lib:fdo (j i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j (f2cl-lib:int-add start 1)) nil)
(tagbody
(cond
((< (f2cl-lib:fref d (j) ((1 *)))
(f2cl-lib:fref d
((f2cl-lib:int-add j
(f2cl-lib:int-sub
1)))
((1 *))))
(setf dmnmx
(f2cl-lib:fref d-%data%
(j)
((1 *))
d-%offset%))
(setf (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%)
(f2cl-lib:fref d-%data%
((f2cl-lib:int-sub j 1))
((1 *))
d-%offset%))
(setf (f2cl-lib:fref d-%data%
((f2cl-lib:int-sub j 1))
((1 *))
d-%offset%)
dmnmx))
(t
(go label50)))
label40))
label50)))))
((> (f2cl-lib:int-add endd (f2cl-lib:int-sub start)) select)
(setf d1 (f2cl-lib:fref d-%data% (start) ((1 *)) d-%offset%))
(setf d2 (f2cl-lib:fref d-%data% (endd) ((1 *)) d-%offset%))
(setf i (the f2cl-lib:integer4 (truncate (+ start endd) 2)))
(setf d3 (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))
(cond
((< d1 d2)
(cond
((< d3 d1)
(setf dmnmx d1))
((< d3 d2)
(setf dmnmx d3))
(t
(setf dmnmx d2))))
(t
(cond
((< d3 d2)
(setf dmnmx d2))
((< d3 d1)
(setf dmnmx d3))
(t
(setf dmnmx d1)))))
(cond
((= dir 0)
(tagbody
(setf i (f2cl-lib:int-sub start 1))
(setf j (f2cl-lib:int-add endd 1))
label60
label70
(setf j (f2cl-lib:int-sub j 1))
(if (< (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%) dmnmx)
(go label70))
label80
(setf i (f2cl-lib:int-add i 1))
(if (> (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%) dmnmx)
(go label80))
(cond
((< i j)
(setf tmp (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))
(setf (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%)
(f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%))
(setf (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%) tmp)
(go label60)))
(cond
((> (f2cl-lib:int-add j (f2cl-lib:int-sub start))
(f2cl-lib:int-add endd
(f2cl-lib:int-sub j)
(f2cl-lib:int-sub 1)))
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))) start)
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) j)
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32)))
(f2cl-lib:int-add j 1))
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) endd))
(t
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32)))
(f2cl-lib:int-add j 1))
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) endd)
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))) start)
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) j)))))
(t
(tagbody
(setf i (f2cl-lib:int-sub start 1))
(setf j (f2cl-lib:int-add endd 1))
label90
label100
(setf j (f2cl-lib:int-sub j 1))
(if (> (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%) dmnmx)
(go label100))
label110
(setf i (f2cl-lib:int-add i 1))
(if (< (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%) dmnmx)
(go label110))
(cond
((< i j)
(setf tmp (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))
(setf (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%)
(f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%))
(setf (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%) tmp)
(go label90)))
(cond
((> (f2cl-lib:int-add j (f2cl-lib:int-sub start))
(f2cl-lib:int-add endd
(f2cl-lib:int-sub j)
(f2cl-lib:int-sub 1)))
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))) start)
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) j)
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32)))
(f2cl-lib:int-add j 1))
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) endd))
(t
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32)))
(f2cl-lib:int-add j 1))
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) endd)
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))) start)
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32)))
j))))))))
(if (> stkpnt 0) (go label10))
(go end_label)
end_label
(return (values nil nil nil info))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dlasrt
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-string) (fortran-to-lisp::integer4)
(array double-float (*)) (fortran-to-lisp::integer4))
:return-values '(nil nil nil fortran-to-lisp::info)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/lapack/dlasrt.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp 20d (20D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
(in-package :lapack)
(let* ((select 20))
(declare (type (f2cl-lib:integer4 20 20) select) (ignorable select))
(defun dlasrt (id n d info)
(declare (type (array double-float (*)) d)
(type (f2cl-lib:integer4) info n)
(type (simple-string *) id))
(f2cl-lib:with-multi-array-data
((id character id-%data% id-%offset%)
(d double-float d-%data% d-%offset%))
(prog ((stack (make-array 64 :element-type 'f2cl-lib:integer4)) (d1 0.0)
(d2 0.0) (d3 0.0) (dmnmx 0.0) (tmp 0.0) (dir 0) (endd 0) (i 0)
(j 0) (start 0) (stkpnt 0))
(declare (type (array f2cl-lib:integer4 (64)) stack)
(type (double-float) d1 d2 d3 dmnmx tmp)
(type (f2cl-lib:integer4) dir endd i j start stkpnt))
(setf info 0)
(setf dir -1)
(cond
((lsame id "D")
(setf dir 0))
((lsame id "I")
(setf dir 1)))
(cond
((= dir (f2cl-lib:int-sub 1))
(setf info -1))
((< n 0)
(setf info -2)))
(cond
((/= info 0)
(xerbla "DLASRT" (f2cl-lib:int-sub info))
(go end_label)))
(if (<= n 1) (go end_label))
(setf stkpnt 1)
(setf (f2cl-lib:fref stack (1 1) ((1 2) (1 32))) 1)
(setf (f2cl-lib:fref stack (2 1) ((1 2) (1 32))) n)
label10
(setf start (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))))
(setf endd (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))))
(setf stkpnt (f2cl-lib:int-sub stkpnt 1))
(cond
((and (<= (f2cl-lib:int-add endd (f2cl-lib:int-sub start)) select)
(> (f2cl-lib:int-add endd (f2cl-lib:int-sub start)) 0))
(cond
((= dir 0)
(f2cl-lib:fdo (i (f2cl-lib:int-add start 1)
(f2cl-lib:int-add i 1))
((> i endd) nil)
(tagbody
(f2cl-lib:fdo (j i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j (f2cl-lib:int-add start 1)) nil)
(tagbody
(cond
((> (f2cl-lib:fref d (j) ((1 *)))
(f2cl-lib:fref d
((f2cl-lib:int-add j
(f2cl-lib:int-sub
1)))
((1 *))))
(setf dmnmx
(f2cl-lib:fref d-%data%
(j)
((1 *))
d-%offset%))
(setf (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%)
(f2cl-lib:fref d-%data%
((f2cl-lib:int-sub j 1))
((1 *))
d-%offset%))
(setf (f2cl-lib:fref d-%data%
((f2cl-lib:int-sub j 1))
((1 *))
d-%offset%)
dmnmx))
(t
(go label30)))
label20))
label30)))
(t
(f2cl-lib:fdo (i (f2cl-lib:int-add start 1)
(f2cl-lib:int-add i 1))
((> i endd) nil)
(tagbody
(f2cl-lib:fdo (j i (f2cl-lib:int-add j (f2cl-lib:int-sub 1)))
((> j (f2cl-lib:int-add start 1)) nil)
(tagbody
(cond
((< (f2cl-lib:fref d (j) ((1 *)))
(f2cl-lib:fref d
((f2cl-lib:int-add j
(f2cl-lib:int-sub
1)))
((1 *))))
(setf dmnmx
(f2cl-lib:fref d-%data%
(j)
((1 *))
d-%offset%))
(setf (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%)
(f2cl-lib:fref d-%data%
((f2cl-lib:int-sub j 1))
((1 *))
d-%offset%))
(setf (f2cl-lib:fref d-%data%
((f2cl-lib:int-sub j 1))
((1 *))
d-%offset%)
dmnmx))
(t
(go label50)))
label40))
label50)))))
((> (f2cl-lib:int-add endd (f2cl-lib:int-sub start)) select)
(setf d1 (f2cl-lib:fref d-%data% (start) ((1 *)) d-%offset%))
(setf d2 (f2cl-lib:fref d-%data% (endd) ((1 *)) d-%offset%))
(setf i (the f2cl-lib:integer4 (truncate (+ start endd) 2)))
(setf d3 (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))
(cond
((< d1 d2)
(cond
((< d3 d1)
(setf dmnmx d1))
((< d3 d2)
(setf dmnmx d3))
(t
(setf dmnmx d2))))
(t
(cond
((< d3 d2)
(setf dmnmx d2))
((< d3 d1)
(setf dmnmx d3))
(t
(setf dmnmx d1)))))
(cond
((= dir 0)
(tagbody
(setf i (f2cl-lib:int-sub start 1))
(setf j (f2cl-lib:int-add endd 1))
label60
label70
(setf j (f2cl-lib:int-sub j 1))
(if (< (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%) dmnmx)
(go label70))
label80
(setf i (f2cl-lib:int-add i 1))
(if (> (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%) dmnmx)
(go label80))
(cond
((< i j)
(setf tmp (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))
(setf (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%)
(f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%))
(setf (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%) tmp)
(go label60)))
(cond
((> (f2cl-lib:int-add j (f2cl-lib:int-sub start))
(f2cl-lib:int-add endd
(f2cl-lib:int-sub j)
(f2cl-lib:int-sub 1)))
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))) start)
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) j)
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32)))
(f2cl-lib:int-add j 1))
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) endd))
(t
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32)))
(f2cl-lib:int-add j 1))
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) endd)
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))) start)
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) j)))))
(t
(tagbody
(setf i (f2cl-lib:int-sub start 1))
(setf j (f2cl-lib:int-add endd 1))
label90
label100
(setf j (f2cl-lib:int-sub j 1))
(if (> (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%) dmnmx)
(go label100))
label110
(setf i (f2cl-lib:int-add i 1))
(if (< (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%) dmnmx)
(go label110))
(cond
((< i j)
(setf tmp (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))
(setf (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%)
(f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%))
(setf (f2cl-lib:fref d-%data% (j) ((1 *)) d-%offset%) tmp)
(go label90)))
(cond
((> (f2cl-lib:int-add j (f2cl-lib:int-sub start))
(f2cl-lib:int-add endd
(f2cl-lib:int-sub j)
(f2cl-lib:int-sub 1)))
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))) start)
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) j)
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32)))
(f2cl-lib:int-add j 1))
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) endd))
(t
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32)))
(f2cl-lib:int-add j 1))
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32))) endd)
(setf stkpnt (f2cl-lib:int-add stkpnt 1))
(setf (f2cl-lib:fref stack (1 stkpnt) ((1 2) (1 32))) start)
(setf (f2cl-lib:fref stack (2 stkpnt) ((1 2) (1 32)))
j))))))))
(if (> stkpnt 0) (go label10))
(go end_label)
end_label
(return (values nil nil nil info))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dlasrt
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((simple-string) (fortran-to-lisp::integer4)
(array double-float (*)) (fortran-to-lisp::integer4))
:return-values '(nil nil nil fortran-to-lisp::info)
:calls '(fortran-to-lisp::xerbla fortran-to-lisp::lsame))))
|
d10a34c17f23ed8cd1fcae3bb1d6097736dfda38c751db964374ff25a8daf88c | parapluu/Concuerror | preemption.erl | -module(preemption).
-export([preemption/0]).
-export([scenarios/0]).
-concuerror_options_forced([{instant_delivery, false}, {scheduling, oldest}]).
scenarios() -> [{?MODULE, inf, dpor}].
-define(senders, 2).
-define(receivers, 2).
preemption() ->
Parent = self(),
Receivers = spawn_receivers(?senders, ?receivers),
Senders = spawn_senders(?senders, Receivers, Parent),
wait_senders(Senders),
trigger_receivers(Receivers),
receive
deadlock -> ok
end.
spawn_receivers(Senders, N) ->
[spawn(fun() -> receiver(Senders) end) || _ <- lists:seq(1,N)].
receiver(N) ->
receive
go ->
receiver(N,[])
end.
receiver(0, Acc) -> Acc;
receiver(N, Acc) ->
receive
I -> receiver(N-1, [I|Acc])
end.
spawn_senders(N, Receivers, Parent) ->
[spawn(fun() -> sender(I, Receivers, Parent) end)
|| I <- lists:seq(1,N)].
sender(I, Receivers, Parent) ->
[R ! I-1 || R <- Receivers],
Parent ! {sender, self()}.
wait_senders([]) -> ok;
wait_senders([P|R]) ->
receive
{sender, P} ->
wait_senders(R)
end.
trigger_receivers(Receivers) ->
[R ! go || R <- Receivers].
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/advanced_tests/src/preemption.erl | erlang | -module(preemption).
-export([preemption/0]).
-export([scenarios/0]).
-concuerror_options_forced([{instant_delivery, false}, {scheduling, oldest}]).
scenarios() -> [{?MODULE, inf, dpor}].
-define(senders, 2).
-define(receivers, 2).
preemption() ->
Parent = self(),
Receivers = spawn_receivers(?senders, ?receivers),
Senders = spawn_senders(?senders, Receivers, Parent),
wait_senders(Senders),
trigger_receivers(Receivers),
receive
deadlock -> ok
end.
spawn_receivers(Senders, N) ->
[spawn(fun() -> receiver(Senders) end) || _ <- lists:seq(1,N)].
receiver(N) ->
receive
go ->
receiver(N,[])
end.
receiver(0, Acc) -> Acc;
receiver(N, Acc) ->
receive
I -> receiver(N-1, [I|Acc])
end.
spawn_senders(N, Receivers, Parent) ->
[spawn(fun() -> sender(I, Receivers, Parent) end)
|| I <- lists:seq(1,N)].
sender(I, Receivers, Parent) ->
[R ! I-1 || R <- Receivers],
Parent ! {sender, self()}.
wait_senders([]) -> ok;
wait_senders([P|R]) ->
receive
{sender, P} ->
wait_senders(R)
end.
trigger_receivers(Receivers) ->
[R ! go || R <- Receivers].
| |
fad09553bf5a3ec3d2646ad7e5124f087e80d2d57a0e7fd4d16822bf38ee4f8e | lwhjp/rince | main.rkt | #lang racket/base
(require (for-syntax racket/base)
racket/provide
(prefix-in c: "../../lang/syntax.rkt")
"../../link.rkt")
(provide (filtered-out (λ (id)
(and (regexp-match? #rx"^c:" id)
(substring id 2)))
(all-from-out "../../lang/syntax.rkt"))
(rename-out [c-module-begin #%module-begin]))
(define-syntax-rule (c-module-begin object)
(#%plain-module-begin
(module* main #f
(define this-object object)
(define go (linkable->executable this-object))
(go))))
| null | https://raw.githubusercontent.com/lwhjp/rince/595db178eb7369c2e14103c3de80ae657d5a482d/c/lang/main.rkt | racket | #lang racket/base
(require (for-syntax racket/base)
racket/provide
(prefix-in c: "../../lang/syntax.rkt")
"../../link.rkt")
(provide (filtered-out (λ (id)
(and (regexp-match? #rx"^c:" id)
(substring id 2)))
(all-from-out "../../lang/syntax.rkt"))
(rename-out [c-module-begin #%module-begin]))
(define-syntax-rule (c-module-begin object)
(#%plain-module-begin
(module* main #f
(define this-object object)
(define go (linkable->executable this-object))
(go))))
| |
d94edb87c5775603f1da5facf81de521de470bc59918be0f410a6522fb3dda5b | david-broman/modelyze | utest.mli |
(** A simple unit testing framework - Utest *)
open Ustring.Op
val init : string -> unit
(** Initiate a test module, giving it a name *)
val test : string -> bool -> unit
(** Expression [test s b] runs a test with name [s].
The test is treated as successful if [b] is
true, else it is seen as unsuccessful. *)
val test_ext : string -> bool -> ustring -> ustring -> unit
val test_str : string -> string -> string -> unit
val test_int : string -> int -> int -> unit
val test_ustr : string -> ustring -> ustring -> unit
val test_ustr : string -> ustring -> ustring -> unit
val test_list : string -> 'a list -> 'a list ->
('a -> ustring) -> unit
(** Expression [test_list desc res exp ppelem] performs a unit test with
description [desc] by comparing the result of the test [res] with the
expected output [exp]. If the test fails, the function [ppelem] is used
to pretty print each element in the list. *)
val test_array : string -> 'a array -> 'a array ->
('a -> ustring) -> unit
val result : unit -> unit
(** Print out the unit test results on the screen *)
val summary : unit -> unit
(** Print out the summary of all tests *)
| null | https://raw.githubusercontent.com/david-broman/modelyze/e48c934283e683e268a9dfd0fed49d3c10277298/ext/ucamlib/src/utest.mli | ocaml | * A simple unit testing framework - Utest
* Initiate a test module, giving it a name
* Expression [test s b] runs a test with name [s].
The test is treated as successful if [b] is
true, else it is seen as unsuccessful.
* Expression [test_list desc res exp ppelem] performs a unit test with
description [desc] by comparing the result of the test [res] with the
expected output [exp]. If the test fails, the function [ppelem] is used
to pretty print each element in the list.
* Print out the unit test results on the screen
* Print out the summary of all tests |
open Ustring.Op
val init : string -> unit
val test : string -> bool -> unit
val test_ext : string -> bool -> ustring -> ustring -> unit
val test_str : string -> string -> string -> unit
val test_int : string -> int -> int -> unit
val test_ustr : string -> ustring -> ustring -> unit
val test_ustr : string -> ustring -> ustring -> unit
val test_list : string -> 'a list -> 'a list ->
('a -> ustring) -> unit
val test_array : string -> 'a array -> 'a array ->
('a -> ustring) -> unit
val result : unit -> unit
val summary : unit -> unit
|
83e57358a18dc1f820abc64227a4f1ccde990b2570404334c6f89f7b1074bf8f | futurice/haskell-mega-repo | Me.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeFamilies #
-- |
Copyright : ( c ) 2015 Futurice Oy
-- License : BSD3
Maintainer : < >
module PlanMill.Types.Me (Me(..)) where
import PlanMill.Internal.Prelude
import PlanMill.Types.Identifier (HasIdentifier (..))
import PlanMill.Types.User (User, UserId)
data Me = Me
{ meFirstName :: !Text
, meLastName :: !Text
, _meUid :: !UserId
}
deriving (Eq, Ord, Show, Read, Generic, Typeable)
makeLenses ''Me
deriveGeneric ''Me
instance HasIdentifier Me User where
identifier = meUid
instance Hashable Me
instance NFData Me
instance AnsiPretty Me
instance Binary Me
instance Structured Me
instance FromJSON Me where
parseJSON = withObject "Me" $ \obj ->
Me <$> obj .: "firstName"
<*> obj .: "lastName"
<*> obj .: "id"
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/e301c08c8dfdcca048fe82fecce6bb2d02e9558a/planmill-client/src/PlanMill/Types/Me.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE TemplateHaskell #
|
License : BSD3 | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
Copyright : ( c ) 2015 Futurice Oy
Maintainer : < >
module PlanMill.Types.Me (Me(..)) where
import PlanMill.Internal.Prelude
import PlanMill.Types.Identifier (HasIdentifier (..))
import PlanMill.Types.User (User, UserId)
data Me = Me
{ meFirstName :: !Text
, meLastName :: !Text
, _meUid :: !UserId
}
deriving (Eq, Ord, Show, Read, Generic, Typeable)
makeLenses ''Me
deriveGeneric ''Me
instance HasIdentifier Me User where
identifier = meUid
instance Hashable Me
instance NFData Me
instance AnsiPretty Me
instance Binary Me
instance Structured Me
instance FromJSON Me where
parseJSON = withObject "Me" $ \obj ->
Me <$> obj .: "firstName"
<*> obj .: "lastName"
<*> obj .: "id"
|
c26fd54c2d7f47a96609765f739ee444915beb1de56b5797d900d7f5c7c1d4c1 | nklein/clifford | def-errors-t.lisp | (in-package #:clifford-tests)
(nst:def-criterion (:basis-error (name basis reason) (:form body))
(handler-case
(progn
(eval body)
(nst:make-failure-report
:format "Expected CLIFFORD-BAD-BASIS-SPECIFICATION error"))
(clifford-bad-basis-specification (err)
(let ((nm (clifford-bad-basis-specification-algebra-name err))
(bs (clifford-bad-basis-specification-basis-spec err))
(re (clifford-bad-basis-specification-reason err)))
(if (and (eq nm name)
(equalp bs basis)
(string= re reason))
(nst:make-success-report)
(nst:make-failure-report
:format "Expected CLIFFORD-BAD-BASIS-SPECIFICATION ~S, got ~S"
:args (list (list name basis reason)
(list nm bs re))))))))
(nst:def-test-group basis-specification-error-tests ()
(nst:def-test must-specify-basis
(:basis-error bad-basis nil "Must specify at least one basis vector")
(defcliff bad-basis ()))
(nst:def-test basis-cannot-repeat
(:basis-error bad-basis (e e) "Basis cannot have repeated elements")
(defcliff bad-basis (e e)))
(nst:def-test basis-must-be-symbols
(:basis-error bad-basis (5 (a b c))
"Basis elements must be non-keyword symbols or strings")
(defcliff bad-basis (5 (a b c))))
(nst:def-test basis-must-not-be-keywords
(:basis-error bad-basis (:a :b)
"Basis elements must be non-keyword symbols or strings")
(defcliff bad-basis (:a :b)))
(nst:def-test basis-symbols-not-concat-of-others
(:basis-error bad-basis (a b ab)
"Basis elements cannot be concatenation of other elements")
(defcliff bad-basis (a b ab)))
(nst:def-test basis-cannot-contain-one
(:basis-error bad-basis (one two)
"Vector basis cannot contain element \"ONE\"")
(defcliff bad-basis (one two))))
| null | https://raw.githubusercontent.com/nklein/clifford/2ba9b9a8f68eb88c2821341dfac2f2a61c2f84ce/src/def-errors-t.lisp | lisp | (in-package #:clifford-tests)
(nst:def-criterion (:basis-error (name basis reason) (:form body))
(handler-case
(progn
(eval body)
(nst:make-failure-report
:format "Expected CLIFFORD-BAD-BASIS-SPECIFICATION error"))
(clifford-bad-basis-specification (err)
(let ((nm (clifford-bad-basis-specification-algebra-name err))
(bs (clifford-bad-basis-specification-basis-spec err))
(re (clifford-bad-basis-specification-reason err)))
(if (and (eq nm name)
(equalp bs basis)
(string= re reason))
(nst:make-success-report)
(nst:make-failure-report
:format "Expected CLIFFORD-BAD-BASIS-SPECIFICATION ~S, got ~S"
:args (list (list name basis reason)
(list nm bs re))))))))
(nst:def-test-group basis-specification-error-tests ()
(nst:def-test must-specify-basis
(:basis-error bad-basis nil "Must specify at least one basis vector")
(defcliff bad-basis ()))
(nst:def-test basis-cannot-repeat
(:basis-error bad-basis (e e) "Basis cannot have repeated elements")
(defcliff bad-basis (e e)))
(nst:def-test basis-must-be-symbols
(:basis-error bad-basis (5 (a b c))
"Basis elements must be non-keyword symbols or strings")
(defcliff bad-basis (5 (a b c))))
(nst:def-test basis-must-not-be-keywords
(:basis-error bad-basis (:a :b)
"Basis elements must be non-keyword symbols or strings")
(defcliff bad-basis (:a :b)))
(nst:def-test basis-symbols-not-concat-of-others
(:basis-error bad-basis (a b ab)
"Basis elements cannot be concatenation of other elements")
(defcliff bad-basis (a b ab)))
(nst:def-test basis-cannot-contain-one
(:basis-error bad-basis (one two)
"Vector basis cannot contain element \"ONE\"")
(defcliff bad-basis (one two))))
| |
7ab414d813d53627fdfb1288bba1789cbebdd1c11bc0302e1f1f768b2e0e14aa | nvim-treesitter/nvim-treesitter | highlights.scm | ; inherits: html
[ "---" ] @punctuation.delimiter
[ "{" "}" ] @punctuation.special
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/e3adb39586ef573fc048aeb341f3a9fb71754452/queries/astro/highlights.scm | scheme | inherits: html |
[ "---" ] @punctuation.delimiter
[ "{" "}" ] @punctuation.special
|
224234b5b86bc288825bc4382319764340b585d15f0b00189c7fbecb1e397a2f | haskell/cabal | Main.hs | module Main where
import Sublib (s)
main :: IO ()
main = putStrLn s
| null | https://raw.githubusercontent.com/haskell/cabal/da863c18c8e8c09aae57248a656ac53ca49677ea/cabal-testsuite/PackageTests/MultipleLibraries/T7270/p/Main.hs | haskell | module Main where
import Sublib (s)
main :: IO ()
main = putStrLn s
| |
7348338b83050f9d654223bd3a34c4629d6054897a6c8ecc8ad1a3ba01f31d17 | ledger/cl-ledger | textual.lisp | ;; This file contains the parser for textual ledger files
(declaim (optimize (safety 3) (debug 3) (speed 1) (space 0)))
(defpackage :ledger-textual
(:use :common-lisp :ledger :local-time :periods :cambl :cl-ppcre)
(:import-from :ledger negatef)
(:export *directive-handlers*))
(in-package :ledger-textual)
(defvar *date-regexp* "[0-9-./]+(?:\\s+[0-9:]+)?")
(defvar *spacing-regexp* (format nil "(?: |~C| ~C)\\s*" #\Tab #\Tab))
(defvar *comment-regexp* (format nil "(?:[ ~C]+;(.+))" #\Tab))
(defvar *entry-heading-scanner*
(cl-ppcre:create-scanner
(format nil (concatenate 'string
"^(?:(~A)(?:=(~A))?)\\s+(?:(\\*|!)\\s*)?"
"(?:\\((.+?)\\)\\s+)?(.+?)~A?$")
*date-regexp* *date-regexp* *comment-regexp*)))
(defvar *transaction-scanner*
(cl-ppcre:create-scanner
(format nil (concatenate 'string
"^\\s+(?:(\\*|!)\\s*)?([\\[(])?(.+?)([\\])])?"
"(?:~A(?:([^; ~C].*?)(?:(@@?)\\s*(.+?))?))?~A?$")
*spacing-regexp* #\Tab *comment-regexp*)))
(defvar *comment-line-scanner*
(cl-ppcre:create-scanner
(concatenate 'string "^" *comment-regexp*)))
(defvar *price-scanner*
(cl-ppcre:create-scanner
(format nil "^P (~A)\\s+(\\S+)\\s+(.+)$" *date-regexp*)))
(defvar *directive-handlers*
# \ * # \% # \ # )
. ,#'(lambda (in line journal)
(declare (ignore line journal))
;; comma begins a comment; gobble up the rest of
;; the line
(read-line in nil)
1))
(#\Return
. ,#'(lambda (in line journal)
(declare (ignore line journal))
DOS uses CRLF ; uses CR
(if (eq #\Newline (peek-char nil in nil))
(read-char in nil))
1))
(#\Newline
. ,#'(lambda (in line journal)
(declare (ignore line journal))
(read-char in nil)
1))
(#\F . ,#'(lambda (in line journal)
(declare (ignore line))
(read-char in)
(peek-char t in)
(setf (journal-date-format journal) (read-line in nil))
1))
(#\Y . ,#'(lambda (in line journal)
(declare (ignore line))
(read-char in)
(peek-char t in)
(setf (journal-default-year journal)
(read-preserving-whitespace in)
jww ( 2007 - 11 - 15 ): This is a total hack
(journal-date-format journal) "%m/%d")
0))
(#\A . ,#'(lambda (in line journal)
(declare (ignore line))
(read-char in)
(peek-char t in)
(setf (journal-default-account journal)
(find-account journal (read-line in)
:create-if-not-exists-p t))
1))
(#\D . ,#'(lambda (in line journal)
(declare (ignore line journal))
(read-char in)
(peek-char t in)
(cambl:read-amount in)
0))
(#\N . ,#'(lambda (in line journal)
(declare (ignore line journal))
(read-char in)
(peek-char t in)
(let ((commodity
(find-commodity (read-line in)
:create-if-not-exists-p t)))
(assert (not (annotated-commodity-p commodity)))
jww ( 2007 - 12 - 05 ): export this
(setf (commodity-no-market-price-p commodity) t)
1)))
(#\P . ,#'(lambda (in line journal)
(multiple-value-bind (date base-commodity price)
(read-price in line journal)
(exchange-commodity base-commodity
:per-unit-cost price
:moment date)
1)))
(,#'digit-char-p
. ,#'(lambda (in line journal)
(multiple-value-bind (entry lines)
(read-plain-entry in line journal)
(if entry
(add-to-contents journal entry)
(error "Failed to read entry at line ~S~%" line))
lines)))
((#\@ #\!)
. ,#'(lambda (in line journal)
(declare (ignore journal))
(let ((symbol (read-preserving-whitespace in))
(argument (read-line in)))
(if (symbolp symbol)
(progn
(setf symbol
(find-symbol (format nil "ledger-text-directive/~A"
(symbol-name symbol))))
(if (and symbol (functionp symbol))
(funcall (locally
#+sbcl(declare (sb-ext:muffle-conditions
sb-ext:code-deletion-note))
(fdefinition symbol))
argument)
(error "Unrecognized directive \"~S\" at line ~D"
argument line)))
(error "Unrecognized directive \"~S\" at line ~D"
argument line))
1)))
(#\( . ,#'(lambda (in line journal)
(declare (ignore journal))
(if *allow-embedded-lisp*
(let ((begin-pos (file-position in)) end-pos lines)
(eval (read-preserving-whitespace in))
(setf end-pos (file-position in))
(file-position in begin-pos)
(loop repeat (- end-pos begin-pos) do
(let ((ch (read-char in)) found)
(loop while (member ch '(#\Newline #\Return)) do
(setf found t ch (read-char in)))
(if found (incf lines))))
lines)
(error "Embedded Lisp not allowed at line ~D, ~
set LEDGER:*ALLOW-EMBEDDED-LISP*" line))))))
(defun read-transaction (in line entry)
(declare (type stream in))
(let* ((xact-line (string-right-trim '(#\Space #\Tab)
(read-line in nil)))
(comment (and xact-line
(nth-value 1 (cl-ppcre:scan-to-strings
*comment-line-scanner* xact-line)))))
(if comment
(aref comment 0)
(let ((groups (and xact-line
(nth-value 1 (cl-ppcre:scan-to-strings
*transaction-scanner* xact-line)))))
(when groups
(let ((status (aref groups 0))
(open-bracket (aref groups 1))
(account-name (aref groups 2))
(close-bracket (aref groups 3))
(amount-expr (aref groups 4))
(cost-specifier (aref groups 5))
(cost-expr (aref groups 6))
(note (aref groups 7))
amount cost)
(when amount-expr
(with-input-from-string (in amount-expr)
(setf amount (cambl:read-amount in))
(when (peek-char t in nil)
(file-position in 0)
(setf amount
(make-value-expr :string amount-expr
:function (read-value-expr in))))))
(when cost-expr
(with-input-from-string (in cost-expr)
(setf cost (cambl:read-amount* in))
(when (minusp (cambl:amount-quantity amount))
(negatef (cambl:amount-quantity cost)))
(when (peek-char t in nil)
(file-position in 0)
(setf cost
(make-value-expr :string cost-expr
:function (read-value-expr in))))
(unless cost
(error "Failed to read cost expression: ~S" cost-expr))))
(let ((virtualp (and open-bracket
(if (string= "(" open-bracket)
(string= ")" close-bracket)
(string= "]" close-bracket)))))
(make-transaction
:entry entry
jww ( 2007 - 12 - 09 ): NYI
;;:actual-date
;;:effective-date
:status (cond ((string= status "*") :cleared)
((string= status "!") :pending)
(t :uncleared))
:account (find-account (entry-journal entry)
(string-right-trim '(#\Space #\Tab)
account-name)
:create-if-not-exists-p t)
:amount amount
:cost (if cost
(if (string= "@" cost-specifier)
(multiply cost amount)
cost))
:note note
:position (make-item-position :begin-line line
:end-line line)
:virtualp virtualp
:must-balance-p (if virtualp
(string= open-bracket "[")
t)))))))))
(defun read-plain-entry (in line journal)
"Read in the header line for the entry, which has the syntax:
( .+ ) ) ?
:spacer: means: two spaces, a tab, or a space and a tab, followed by any
amount of whitespace.
The groups identified in this regular expression (found in the scanner
*entry-heading-scanner*) have these meanings:
1 - The actual date of the entry.
2 - The (optional) effective date of the entry.
4 - The (optional) status of the entry: *=cleared, !=pending.
6 - The (optional) \"code\" for the entry; has no meaning to Ledger.
7 - The payee or description of the entry.
9 - A comment giving further details about the entry."
(declare (type stream in))
(declare (type journal journal))
(let* ((heading-line (read-line in nil))
(groups (and heading-line
(nth-value 1 (cl-ppcre:scan-to-strings
*entry-heading-scanner* heading-line))))
(lines 1))
(when groups
(let ((actual-date (aref groups 0))
(effective-date (aref groups 1))
(status (aref groups 2))
(code (aref groups 3))
(payee (aref groups 4))
(note (aref groups 5)))
(let ((entry
(make-instance
'entry
:journal journal
:actual-date (parse-journal-date journal actual-date)
:effective-date
(and effective-date
(parse-journal-date journal effective-date))
:status (cond ((string= status "*") :cleared)
((string= status "!") :pending)
(t :uncleared))
:code code
:payee (string-right-trim '(#\Space #\Tab) payee)
:note note
:position (make-item-position :begin-line line))))
(loop for transaction = (read-transaction in (+ line lines) entry)
while transaction do
(if (stringp transaction)
(setf (entry-note entry)
(concatenate 'string
(entry-note entry)
transaction))
(add-transaction entry transaction))
(incf lines))
(incf lines)
(setf (item-position-end-line (entry-position entry))
(+ line lines))
(normalize-entry entry)
(values entry lines))))))
(defun read-price (in line journal)
(declare (type stream in)
(type journal journal)
(ignore line))
(let* ((price-line (read-line in nil))
(groups (nth-value 1 (cl-ppcre:scan-to-strings *price-scanner*
price-line)))
(date (parse-journal-date journal (aref groups 0)))
(base-commodity (amount* (concatenate 'string "1 " (aref groups 1))))
(price (amount (aref groups 2))))
(values date base-commodity price)))
(defun read-textual-journal (in binder)
(declare (type stream in))
(declare (type binder binder))
(let ((journal (make-instance 'journal :binder binder))
(line-number 1))
(loop for c = (peek-char nil in nil) while c do
(let ((handler
(cdr
(assoc-if
#'(lambda (key)
(cond
((characterp key)
(char= c key))
((listp key)
(member c key :test #'char=))
((functionp key)
(funcall key c))
(t
(error "Unexpected element in `*directive-handlers*': ~S"
key))))
*directive-handlers*))))
(if handler
(incf line-number (funcall handler in line-number journal))
(progn
(format t "Unhandled directive (line ~D): ~C~%" line-number c)
(read-line in nil)
(incf line-number)))))
journal))
(defun ledger-text-directive/include (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
(defun ledger-text-directive/account (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
(defun ledger-text-directive/end (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
(defun ledger-text-directive/alias (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
(defun ledger-text-directive/def (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
;; if (word == "include") {
;; push_var<std::string> save_path(path);
;; push_var<unsigned int> save_src_idx(src_idx);
;; push_var<unsigned long> save_beg_pos(beg_pos);
;; push_var<unsigned long> save_end_pos(end_pos);
;; push_var<unsigned int> save_linenum(linenum);
;;
;; path = p;
if ( path[0 ] ! = ' / ' & & path[0 ] ! = ' \\ ' & & path[0 ] ! = ' ~ ' ) {
std::string::size_type pos = save_path.prev.rfind('/ ' ) ;
;; if (pos == std::string::npos)
pos = ' ) ;
;; if (pos != std::string::npos)
path = std::string(save_path.prev , 0 , pos + 1 ) + path ;
;; }
;; path = resolve_path(path);
;;
;; DEBUG_PRINT("ledger-textual.include", "line " << linenum << ": " <<
;; "Including path '" << path << "'");
;;
;; include_stack.push_back(std::pair<std::string, int>
;; (journal->sources.back(), linenum - 1));
;; count += parse_journal_file(path, config, journal,
;; account_stack.front());
;; include_stack.pop_back();
;; }
;; else if (word == "account") {
;; account_t * acct;
;; acct = account_stack.front()->find_account(p);
;; account_stack.push_front(acct);
;; }
;; else if (word == "end") {
;; account_stack.pop_front();
;; }
;; else if (word == "alias") {
;; char * b = p;
;; if (char * e = std::strchr(b, '=')) {
;; char * z = e - 1;
;; while (std::isspace(*z))
;; *z-- = '\0';
;; *e++ = '\0';
;; e = skip_ws(e);
;;
;; // Once we have an alias name (b) and the target account
;; // name (e), add a reference to the account in the
;; // `account_aliases' map, which is used by the transaction
;; // parser to resolve alias references.
;; account_t * acct = account_stack.front()->find_account(e);
;; std::pair<accounts_map::iterator, bool> result
;; = account_aliases.insert(accounts_pair(b, acct));
;; assert(result.second);
;; }
;; }
;; else if (word == "def") {
;; if (! global_scope.get())
;; init_value_expr();
;; parse_value_definition(p);
;; }
(pushnew #'read-textual-journal *registered-parsers*)
(provide 'textual)
;; textual.lisp ends here
| null | https://raw.githubusercontent.com/ledger/cl-ledger/e25d5f9f721bcf3b30d6569363e723f22d19a3a0/parsers/textual/textual.lisp | lisp | This file contains the parser for textual ledger files
comma begins a comment; gobble up the rest of
the line
uses CR
:actual-date
:effective-date
has no meaning to Ledger.
if (word == "include") {
push_var<std::string> save_path(path);
push_var<unsigned int> save_src_idx(src_idx);
push_var<unsigned long> save_beg_pos(beg_pos);
push_var<unsigned long> save_end_pos(end_pos);
push_var<unsigned int> save_linenum(linenum);
path = p;
if (pos == std::string::npos)
if (pos != std::string::npos)
}
path = resolve_path(path);
DEBUG_PRINT("ledger-textual.include", "line " << linenum << ": " <<
"Including path '" << path << "'");
include_stack.push_back(std::pair<std::string, int>
(journal->sources.back(), linenum - 1));
count += parse_journal_file(path, config, journal,
account_stack.front());
include_stack.pop_back();
}
else if (word == "account") {
account_t * acct;
acct = account_stack.front()->find_account(p);
account_stack.push_front(acct);
}
else if (word == "end") {
account_stack.pop_front();
}
else if (word == "alias") {
char * b = p;
if (char * e = std::strchr(b, '=')) {
char * z = e - 1;
while (std::isspace(*z))
*z-- = '\0';
*e++ = '\0';
e = skip_ws(e);
// Once we have an alias name (b) and the target account
// name (e), add a reference to the account in the
// `account_aliases' map, which is used by the transaction
// parser to resolve alias references.
account_t * acct = account_stack.front()->find_account(e);
std::pair<accounts_map::iterator, bool> result
= account_aliases.insert(accounts_pair(b, acct));
assert(result.second);
}
}
else if (word == "def") {
if (! global_scope.get())
init_value_expr();
parse_value_definition(p);
}
textual.lisp ends here |
(declaim (optimize (safety 3) (debug 3) (speed 1) (space 0)))
(defpackage :ledger-textual
(:use :common-lisp :ledger :local-time :periods :cambl :cl-ppcre)
(:import-from :ledger negatef)
(:export *directive-handlers*))
(in-package :ledger-textual)
(defvar *date-regexp* "[0-9-./]+(?:\\s+[0-9:]+)?")
(defvar *spacing-regexp* (format nil "(?: |~C| ~C)\\s*" #\Tab #\Tab))
(defvar *comment-regexp* (format nil "(?:[ ~C]+;(.+))" #\Tab))
(defvar *entry-heading-scanner*
(cl-ppcre:create-scanner
(format nil (concatenate 'string
"^(?:(~A)(?:=(~A))?)\\s+(?:(\\*|!)\\s*)?"
"(?:\\((.+?)\\)\\s+)?(.+?)~A?$")
*date-regexp* *date-regexp* *comment-regexp*)))
(defvar *transaction-scanner*
(cl-ppcre:create-scanner
(format nil (concatenate 'string
"^\\s+(?:(\\*|!)\\s*)?([\\[(])?(.+?)([\\])])?"
"(?:~A(?:([^; ~C].*?)(?:(@@?)\\s*(.+?))?))?~A?$")
*spacing-regexp* #\Tab *comment-regexp*)))
(defvar *comment-line-scanner*
(cl-ppcre:create-scanner
(concatenate 'string "^" *comment-regexp*)))
(defvar *price-scanner*
(cl-ppcre:create-scanner
(format nil "^P (~A)\\s+(\\S+)\\s+(.+)$" *date-regexp*)))
(defvar *directive-handlers*
# \ * # \% # \ # )
. ,#'(lambda (in line journal)
(declare (ignore line journal))
(read-line in nil)
1))
(#\Return
. ,#'(lambda (in line journal)
(declare (ignore line journal))
(if (eq #\Newline (peek-char nil in nil))
(read-char in nil))
1))
(#\Newline
. ,#'(lambda (in line journal)
(declare (ignore line journal))
(read-char in nil)
1))
(#\F . ,#'(lambda (in line journal)
(declare (ignore line))
(read-char in)
(peek-char t in)
(setf (journal-date-format journal) (read-line in nil))
1))
(#\Y . ,#'(lambda (in line journal)
(declare (ignore line))
(read-char in)
(peek-char t in)
(setf (journal-default-year journal)
(read-preserving-whitespace in)
jww ( 2007 - 11 - 15 ): This is a total hack
(journal-date-format journal) "%m/%d")
0))
(#\A . ,#'(lambda (in line journal)
(declare (ignore line))
(read-char in)
(peek-char t in)
(setf (journal-default-account journal)
(find-account journal (read-line in)
:create-if-not-exists-p t))
1))
(#\D . ,#'(lambda (in line journal)
(declare (ignore line journal))
(read-char in)
(peek-char t in)
(cambl:read-amount in)
0))
(#\N . ,#'(lambda (in line journal)
(declare (ignore line journal))
(read-char in)
(peek-char t in)
(let ((commodity
(find-commodity (read-line in)
:create-if-not-exists-p t)))
(assert (not (annotated-commodity-p commodity)))
jww ( 2007 - 12 - 05 ): export this
(setf (commodity-no-market-price-p commodity) t)
1)))
(#\P . ,#'(lambda (in line journal)
(multiple-value-bind (date base-commodity price)
(read-price in line journal)
(exchange-commodity base-commodity
:per-unit-cost price
:moment date)
1)))
(,#'digit-char-p
. ,#'(lambda (in line journal)
(multiple-value-bind (entry lines)
(read-plain-entry in line journal)
(if entry
(add-to-contents journal entry)
(error "Failed to read entry at line ~S~%" line))
lines)))
((#\@ #\!)
. ,#'(lambda (in line journal)
(declare (ignore journal))
(let ((symbol (read-preserving-whitespace in))
(argument (read-line in)))
(if (symbolp symbol)
(progn
(setf symbol
(find-symbol (format nil "ledger-text-directive/~A"
(symbol-name symbol))))
(if (and symbol (functionp symbol))
(funcall (locally
#+sbcl(declare (sb-ext:muffle-conditions
sb-ext:code-deletion-note))
(fdefinition symbol))
argument)
(error "Unrecognized directive \"~S\" at line ~D"
argument line)))
(error "Unrecognized directive \"~S\" at line ~D"
argument line))
1)))
(#\( . ,#'(lambda (in line journal)
(declare (ignore journal))
(if *allow-embedded-lisp*
(let ((begin-pos (file-position in)) end-pos lines)
(eval (read-preserving-whitespace in))
(setf end-pos (file-position in))
(file-position in begin-pos)
(loop repeat (- end-pos begin-pos) do
(let ((ch (read-char in)) found)
(loop while (member ch '(#\Newline #\Return)) do
(setf found t ch (read-char in)))
(if found (incf lines))))
lines)
(error "Embedded Lisp not allowed at line ~D, ~
set LEDGER:*ALLOW-EMBEDDED-LISP*" line))))))
(defun read-transaction (in line entry)
(declare (type stream in))
(let* ((xact-line (string-right-trim '(#\Space #\Tab)
(read-line in nil)))
(comment (and xact-line
(nth-value 1 (cl-ppcre:scan-to-strings
*comment-line-scanner* xact-line)))))
(if comment
(aref comment 0)
(let ((groups (and xact-line
(nth-value 1 (cl-ppcre:scan-to-strings
*transaction-scanner* xact-line)))))
(when groups
(let ((status (aref groups 0))
(open-bracket (aref groups 1))
(account-name (aref groups 2))
(close-bracket (aref groups 3))
(amount-expr (aref groups 4))
(cost-specifier (aref groups 5))
(cost-expr (aref groups 6))
(note (aref groups 7))
amount cost)
(when amount-expr
(with-input-from-string (in amount-expr)
(setf amount (cambl:read-amount in))
(when (peek-char t in nil)
(file-position in 0)
(setf amount
(make-value-expr :string amount-expr
:function (read-value-expr in))))))
(when cost-expr
(with-input-from-string (in cost-expr)
(setf cost (cambl:read-amount* in))
(when (minusp (cambl:amount-quantity amount))
(negatef (cambl:amount-quantity cost)))
(when (peek-char t in nil)
(file-position in 0)
(setf cost
(make-value-expr :string cost-expr
:function (read-value-expr in))))
(unless cost
(error "Failed to read cost expression: ~S" cost-expr))))
(let ((virtualp (and open-bracket
(if (string= "(" open-bracket)
(string= ")" close-bracket)
(string= "]" close-bracket)))))
(make-transaction
:entry entry
jww ( 2007 - 12 - 09 ): NYI
:status (cond ((string= status "*") :cleared)
((string= status "!") :pending)
(t :uncleared))
:account (find-account (entry-journal entry)
(string-right-trim '(#\Space #\Tab)
account-name)
:create-if-not-exists-p t)
:amount amount
:cost (if cost
(if (string= "@" cost-specifier)
(multiply cost amount)
cost))
:note note
:position (make-item-position :begin-line line
:end-line line)
:virtualp virtualp
:must-balance-p (if virtualp
(string= open-bracket "[")
t)))))))))
(defun read-plain-entry (in line journal)
"Read in the header line for the entry, which has the syntax:
( .+ ) ) ?
:spacer: means: two spaces, a tab, or a space and a tab, followed by any
amount of whitespace.
The groups identified in this regular expression (found in the scanner
*entry-heading-scanner*) have these meanings:
1 - The actual date of the entry.
2 - The (optional) effective date of the entry.
4 - The (optional) status of the entry: *=cleared, !=pending.
7 - The payee or description of the entry.
9 - A comment giving further details about the entry."
(declare (type stream in))
(declare (type journal journal))
(let* ((heading-line (read-line in nil))
(groups (and heading-line
(nth-value 1 (cl-ppcre:scan-to-strings
*entry-heading-scanner* heading-line))))
(lines 1))
(when groups
(let ((actual-date (aref groups 0))
(effective-date (aref groups 1))
(status (aref groups 2))
(code (aref groups 3))
(payee (aref groups 4))
(note (aref groups 5)))
(let ((entry
(make-instance
'entry
:journal journal
:actual-date (parse-journal-date journal actual-date)
:effective-date
(and effective-date
(parse-journal-date journal effective-date))
:status (cond ((string= status "*") :cleared)
((string= status "!") :pending)
(t :uncleared))
:code code
:payee (string-right-trim '(#\Space #\Tab) payee)
:note note
:position (make-item-position :begin-line line))))
(loop for transaction = (read-transaction in (+ line lines) entry)
while transaction do
(if (stringp transaction)
(setf (entry-note entry)
(concatenate 'string
(entry-note entry)
transaction))
(add-transaction entry transaction))
(incf lines))
(incf lines)
(setf (item-position-end-line (entry-position entry))
(+ line lines))
(normalize-entry entry)
(values entry lines))))))
(defun read-price (in line journal)
(declare (type stream in)
(type journal journal)
(ignore line))
(let* ((price-line (read-line in nil))
(groups (nth-value 1 (cl-ppcre:scan-to-strings *price-scanner*
price-line)))
(date (parse-journal-date journal (aref groups 0)))
(base-commodity (amount* (concatenate 'string "1 " (aref groups 1))))
(price (amount (aref groups 2))))
(values date base-commodity price)))
(defun read-textual-journal (in binder)
(declare (type stream in))
(declare (type binder binder))
(let ((journal (make-instance 'journal :binder binder))
(line-number 1))
(loop for c = (peek-char nil in nil) while c do
(let ((handler
(cdr
(assoc-if
#'(lambda (key)
(cond
((characterp key)
(char= c key))
((listp key)
(member c key :test #'char=))
((functionp key)
(funcall key c))
(t
(error "Unexpected element in `*directive-handlers*': ~S"
key))))
*directive-handlers*))))
(if handler
(incf line-number (funcall handler in line-number journal))
(progn
(format t "Unhandled directive (line ~D): ~C~%" line-number c)
(read-line in nil)
(incf line-number)))))
journal))
(defun ledger-text-directive/include (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
(defun ledger-text-directive/account (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
(defun ledger-text-directive/end (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
(defun ledger-text-directive/alias (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
(defun ledger-text-directive/def (argument)
(declare (ignorable argument))
(format t "@include (~A)~%" argument))
if ( path[0 ] ! = ' / ' & & path[0 ] ! = ' \\ ' & & path[0 ] ! = ' ~ ' ) {
(pushnew #'read-textual-journal *registered-parsers*)
(provide 'textual)
|
203cdd7cb822b60508e07342341baeb384c871bb5947077ac05f38193a86c9c0 | ethercrow/yi-config | FuzzySnippet.hs |
module FuzzySnippet
( fuzzySnippet
) where
import Yi
import Fuzzy
import Snippet
fuzzySnippet :: [Snippet] -> YiM ()
fuzzySnippet = genericFuzzy . fmap toFuzzyItem
toFuzzyItem s@(Snippet trigger body) = FuzzyItem
{ fiToText = trigger
, fiAction = withCurrentBuffer (expandSnippet s)
} | null | https://raw.githubusercontent.com/ethercrow/yi-config/3530e6ca8e9a598d8c7ddcf7954c66254c2b760d/modules/FuzzySnippet.hs | haskell |
module FuzzySnippet
( fuzzySnippet
) where
import Yi
import Fuzzy
import Snippet
fuzzySnippet :: [Snippet] -> YiM ()
fuzzySnippet = genericFuzzy . fmap toFuzzyItem
toFuzzyItem s@(Snippet trigger body) = FuzzyItem
{ fiToText = trigger
, fiAction = withCurrentBuffer (expandSnippet s)
} | |
b4b9eb49ff928dcbab664694f93f108d3e67d88a0cadadadae76e6a87bf20903 | Perry961002/SICP | exe4.8-named-let.scm | ;对于书上的解释,对(let <var> <bindings> <body>)
;body其实就是var的过程体,参数就是bindings
;即先把var定义为以bindings中的vars为参数、以body为过程体的过程
然后以bindings里的values为实际参数调用过程var
(define (named-let? exp)
(and (taggesd-list exp 'let)
(eq? (length exp) 4)))
(define (named-let-var exp)
(cadr exp))
(define (named-let-bindings exp)
(caddr exp))
(define (named-let-bindings-vars exp)
(map car (named-let-bindings exp)))
(define (named-let-bindings-values exp)
(map cdr (named-let-bindings exp)))
(define (named-let-body exp)
(cdddr exp))
- combination,加入判断即可
(define (let-combination exp)
(cond ((named-let? exp)
(list 'define (named-let-var exp)
(make-lambda (named-let-bindings-vars exp)
(named-let-body exp)))
(cons (named-let-var exp) (named-let-bindings-values exp)))
(else
(cons (make-lambda (let-vars exp) (let-body exp))
(let-exps exp))))) | null | https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap4/exercise/exe4.8-named-let.scm | scheme | 对于书上的解释,对(let <var> <bindings> <body>)
body其实就是var的过程体,参数就是bindings
即先把var定义为以bindings中的vars为参数、以body为过程体的过程 | 然后以bindings里的values为实际参数调用过程var
(define (named-let? exp)
(and (taggesd-list exp 'let)
(eq? (length exp) 4)))
(define (named-let-var exp)
(cadr exp))
(define (named-let-bindings exp)
(caddr exp))
(define (named-let-bindings-vars exp)
(map car (named-let-bindings exp)))
(define (named-let-bindings-values exp)
(map cdr (named-let-bindings exp)))
(define (named-let-body exp)
(cdddr exp))
- combination,加入判断即可
(define (let-combination exp)
(cond ((named-let? exp)
(list 'define (named-let-var exp)
(make-lambda (named-let-bindings-vars exp)
(named-let-body exp)))
(cons (named-let-var exp) (named-let-bindings-values exp)))
(else
(cons (make-lambda (let-vars exp) (let-body exp))
(let-exps exp))))) |
a534426f3fc92010e78aab153e169712fbda533083ba002a61f344ef9fe89d79 | athensresearch/athens | orderkeeper_test.cljc | (ns athens.common-events.orderkeeper-test
(:require
[athens.common-db :as common-db]
#_[athens.common-events :as common-events]
[athens.common-events.fixture :as fixture]
#_[athens.common-events.resolver :as resolver]
[clojure.test :as t]
#_[datascript.core :as d]))
(t/use-fixtures :each (partial fixture/integration-test-fixture []))
#_(defn transact-with-orderkeeper
[tx-data]
(d/transact! @fixture/connection (common-db/orderkeeper @@fixture/connection tx-data)))
(t/deftest order-change-needed
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 1
:block/string "Lalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)]
(t/is (= (inc (count setup-tx)) (count orderkeeper-txs)))
(t/is (= {:block/uid block-uid-1
:block/order 0}
(last orderkeeper-txs)))))
(t/deftest order-change-needed-with-tie-resolution
(t/testing "missing `:block/order` 0"
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
block-uid-2 "target-block-2-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 1
:block/string "Lalala"}
{:block/uid block-uid-2
:block/order 1
:block/string "Ulalala"}]}]
diff-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-2
:block/order 1
:block/string "Ulalala"}
{:block/uid block-uid-1
:block/order 1
:block/string "Lalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)
orderkeeper-diff-txs (common-db/orderkeeper @@fixture/connection diff-tx)]
(t/are [txs] (= (inc (count setup-tx))
(count txs))
orderkeeper-txs
orderkeeper-diff-txs)
(t/are [txs] (= {:block/uid block-uid-1
:block/order 0}
(last txs))
orderkeeper-txs
orderkeeper-diff-txs)))
(t/testing "double `:block/order` 0"
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
block-uid-2 "target-block-2-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 0
:block/string "Lalala"}
{:block/uid block-uid-2
:block/order 0
:block/string "Ulalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)]
(t/is (= (inc (count setup-tx)) (count orderkeeper-txs)))
(t/is (= {:block/uid block-uid-2
:block/order 1}
(last orderkeeper-txs)))))
(t/testing "that we're not just sorting by `:block/uid`, and actually `:block/order` is our primary sort"
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
block-uid-2 "target-block-2-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-2
:block/order 2
:block/string "Lalala"}
{:block/uid block-uid-1
:block/order 3
:block/string "Ulalala"}]}]
diff-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 3
:block/string "Ulalala"}
{:block/uid block-uid-2
:block/order 2
:block/string "Lalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)
orderkeeper-diff-txs (common-db/orderkeeper @@fixture/connection diff-tx)]
(t/are [txs] (= (+ 2 (count setup-tx))
(count txs))
orderkeeper-txs
orderkeeper-diff-txs)
(t/are [txs] (= #{{:block/uid block-uid-2
:block/order 0}
{:block/uid block-uid-1
:block/order 1}}
(set
(drop (count setup-tx)
txs)))
orderkeeper-txs
orderkeeper-diff-txs))))
(t/deftest no-change-needed
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 0
:block/string "Lalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)]
(t/is (= (count setup-tx) (count orderkeeper-txs)))))
| null | https://raw.githubusercontent.com/athensresearch/athens/35a6e086b017d38e30f0023330174baa0b8b784e/test/athens/common_events/orderkeeper_test.cljc | clojure | (ns athens.common-events.orderkeeper-test
(:require
[athens.common-db :as common-db]
#_[athens.common-events :as common-events]
[athens.common-events.fixture :as fixture]
#_[athens.common-events.resolver :as resolver]
[clojure.test :as t]
#_[datascript.core :as d]))
(t/use-fixtures :each (partial fixture/integration-test-fixture []))
#_(defn transact-with-orderkeeper
[tx-data]
(d/transact! @fixture/connection (common-db/orderkeeper @@fixture/connection tx-data)))
(t/deftest order-change-needed
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 1
:block/string "Lalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)]
(t/is (= (inc (count setup-tx)) (count orderkeeper-txs)))
(t/is (= {:block/uid block-uid-1
:block/order 0}
(last orderkeeper-txs)))))
(t/deftest order-change-needed-with-tie-resolution
(t/testing "missing `:block/order` 0"
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
block-uid-2 "target-block-2-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 1
:block/string "Lalala"}
{:block/uid block-uid-2
:block/order 1
:block/string "Ulalala"}]}]
diff-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-2
:block/order 1
:block/string "Ulalala"}
{:block/uid block-uid-1
:block/order 1
:block/string "Lalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)
orderkeeper-diff-txs (common-db/orderkeeper @@fixture/connection diff-tx)]
(t/are [txs] (= (inc (count setup-tx))
(count txs))
orderkeeper-txs
orderkeeper-diff-txs)
(t/are [txs] (= {:block/uid block-uid-1
:block/order 0}
(last txs))
orderkeeper-txs
orderkeeper-diff-txs)))
(t/testing "double `:block/order` 0"
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
block-uid-2 "target-block-2-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 0
:block/string "Lalala"}
{:block/uid block-uid-2
:block/order 0
:block/string "Ulalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)]
(t/is (= (inc (count setup-tx)) (count orderkeeper-txs)))
(t/is (= {:block/uid block-uid-2
:block/order 1}
(last orderkeeper-txs)))))
(t/testing "that we're not just sorting by `:block/uid`, and actually `:block/order` is our primary sort"
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
block-uid-2 "target-block-2-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-2
:block/order 2
:block/string "Lalala"}
{:block/uid block-uid-1
:block/order 3
:block/string "Ulalala"}]}]
diff-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 3
:block/string "Ulalala"}
{:block/uid block-uid-2
:block/order 2
:block/string "Lalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)
orderkeeper-diff-txs (common-db/orderkeeper @@fixture/connection diff-tx)]
(t/are [txs] (= (+ 2 (count setup-tx))
(count txs))
orderkeeper-txs
orderkeeper-diff-txs)
(t/are [txs] (= #{{:block/uid block-uid-2
:block/order 0}
{:block/uid block-uid-1
:block/order 1}}
(set
(drop (count setup-tx)
txs)))
orderkeeper-txs
orderkeeper-diff-txs))))
(t/deftest no-change-needed
(let [target-page-title "target-page-1-title"
target-page-uid "target-page-1-uid"
block-uid-1 "target-block-1-uid"
setup-tx [{:node/title target-page-title
:block/uid target-page-uid
:block/children [{:block/uid block-uid-1
:block/order 0
:block/string "Lalala"}]}]
orderkeeper-txs (common-db/orderkeeper @@fixture/connection setup-tx)]
(t/is (= (count setup-tx) (count orderkeeper-txs)))))
| |
49f9299f7167d39ff3e073926e9aaa7fc53fe26d64881016df812773eeea134a | ska80/thinlisp | c-types.lisp | (in-package "TLI")
;;;; Module C-TYPES
Copyright ( c ) 1999 - 2001 The ThinLisp Group
Copyright ( c ) 1995 Gensym Corporation .
;;; All rights reserved.
This file is part of ThinLisp .
ThinLisp is open source ; you can redistribute it and/or modify it
under the terms of the ThinLisp License as published by the ThinLisp
Group ; either version 1 or ( at your option ) any later version .
ThinLisp 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.
For additional information see < / >
Author :
;;;; C Types
;;; This module implements operations on C types.
;;; `C types' are represented by symbols and lists of symbols. The following
;;; symbols are available:
;;; void, which is nothing,
Obj which is an sint32 whose value points to a Hdr ( aka header ) ,
is a structure holding a type tag ,
sint32 which is a signed 32 - bit integer ,
which is an unsigned 8 - bit integer ( equivalent to unsigned - char ) ,
uint16 which is an unsigned 16 - bit integer ( aka unsigned short ) ,
sint16 which is a signed 16 - bit integer ( aka signed short ) ,
unsigned - char which is C unsigned char ( equivalent to ) ,
;;; boolean which is a C int used as an arg to logical predicates,
;;; Mdouble which is a structure holding a managed-float (tag 0x4),
Ldouble which is a structure holding a double - float ( tag 0x5 ) ,
;;; Sv which is a simple-vector structure (tag 0x6),
which is a string structure ( tag 0x7 ) ,
Sa_uint8 which is a structure holding arrays ( tag 0x8 ) ,
Sa_uint16 which is a structure holding uint16 arrays ( tag 0x9 ) ,
;;; Sa_sint16 which is a structure holding sint16 arrays (tag 0x12),
;;; Sa_double which is a structure holding double arrays (tag 0xA),
which is a symbol structure ( tag 0xB ) ,
Func which is compiled - function structure ( tag 0xC ) ,
which is a package structure ( tag 0xD ) ,
jmp_buf which is a jump buffer for setjmp and , and
Thread_state which is a structure holding Lisp thread info .
C types can also be lists . In these cases the car of the list must be one
;;; of the following symbols, with the format of the remainder of the list
;;; determined by the particular symbol.
;;; (pointer <c-type>) is a pointer to the enclosed C type, and
;;; (array <c-type> [<array-length>]) is an array of the C type.
;;; (const-array <c-type> <array-length>) is described below.
;;; (c-type "<c-type-string>") allows an arbitrary type.
;;; (pointer "<c-type-string>") allows a pointer to an arbitrary type.
;;; (struct (<c-type> <name>)...) allows C struct types.
;;; (int <bit-field-width>) and (uint <b-f-w>) allows bit field widths.
;;; Const-array is a type used for emitting new type definitions to initialize
Lisp arrays of constant sizes . For example , the type Sv is a C structure
representing a Lisp simple - vector . The actual Obj array in the Sv structure
is only 1 element long , but since C explicitly performs no array bounds
;;; checking we can use this structure to access arbitrarily sized arrays in
;;; data structures we create by allocating more memory beyond the bounds of the
;;; usual Sv struct size. If however we want to have a C variable holding an
;;; initialized instance of this structure, then we need to have a C type with
;;; the correct number of elements in the Obj array embedded within the struct.
;;; That is where the const-array C type comes in. When a new type is needed
;;; for an explicitly sized embedded array within a structure, the const-array C
type will be used . The C type that is the second of the list will be the
;;; structure type whose embedded array is being specialized. The size that is
the third of the list is the length of the embedded array . If this C type
;;; is used in a c-typedef-decl, the generated type name will be the normal
;;; structure name with "_<length>" appended to it, e.g. Sv_5.
C - type is a type used for TL end - users extending the C types that TL can
;;; handle. They contain either the string naming C type, or the list (pointer
;;; "<c-name>"). These C types are exactly the same form as the Lisp type that
;;; represents them.
;;; The macro `c-type-string' takes a C type and returns a C type string
;;; suitable for use in a type casting operation. New type translations can be
;;; made using def-c-type.
(defun c-type-string (c-type)
(if (symbolp c-type)
(get c-type 'c-type-string)
(get-compound-c-type-string c-type)))
(defun get-compound-c-type-string (c-type)
(let ((car (cons-car c-type))
(second (cons-second c-type)))
(cond ((eq car 'c-type)
(cond ((stringp second)
second)
((and (consp second)
(eq (cons-car second) 'pointer)
(stringp (cons-second second)))
(format nil "~a *" (cons-second second)))
(t
(error "Can't make type string for ~s" c-type))))
((memqp car '(uint int))
;; These are integers with bit field widths. The bit widths are only
;; emitted into struct type declarations, and so can be ignored in
;; this function.
(c-type-string car))
((memqp car '(pointer array))
(cond ((symbolp second)
(get second 'c-pointer-type-string))
((stringp second)
(format nil "~a *" second))
(t
(format nil "~a *" (c-type-string second)))))
((eq car 'const-array)
(format nil "~a_~a" (c-type-string second) (third c-type)))
((eq car 'function)
(let ((return-type second)
(arg-types (cons-third c-type)))
(with-output-to-string (out)
(format out "~a (*)(" (c-type-string return-type))
(if (null arg-types)
(format out "void")
(loop for first? = t then nil
for arg-type in arg-types
do
(unless first?
(format out ", "))
(format out "~a" (c-type-string arg-type))))
(format out ")"))))
((eq car 'struct)
(c-struct-or-union-type-string "struct" c-type))
((eq car 'union)
(c-struct-or-union-type-string "union" c-type))
(t
(error "Can't make type string for ~s" c-type)))))
(defun c-struct-or-union-type-string (struct-or-union c-type)
(let* ((type-strings (loop for (elt-type) in (cons-cdr c-type)
collect (c-type-string elt-type)))
(max-length
(apply 'max (mapcar #'length type-strings))))
(format nil "~a {~%~a}"
struct-or-union
(apply 'concatenate 'string
(loop for elt in (cons-cdr c-type)
for type-string in type-strings
for (elt-type name) = elt
collect
(cond ((and (consp elt-type)
(memqp (car elt-type) '(int uint)))
(format nil " ~Va ~a : ~a;~%"
max-length type-string name
(cons-second elt-type)))
((and (consp elt-type)
(eq (car elt-type) 'array)
(third elt-type))
(format nil " ~Va ~a[~a];~%"
max-length
(c-type-string (second elt-type))
name
(third elt-type)))
(t
(format nil " ~Va ~a;~%"
max-length type-string name))))))))
The function ` c - types - equal - p ' takes two C types and returns whether or not
;;; they are equivalent. If we were being truely slick, we would implement the
C type compatibility rules found in CARM , 4th Edition , pp . 151 - 155 .
;;; Checking equality is a proper subset of what is documented inere.
(defun c-types-equal-p (type1 type2)
(equal type1 type2))
;;; The function `c-pointer-type-p' takes a C type and returns whether or not it
;;; is a pointer suitable for an indirect selection expr.
(defun c-pointer-type-p (c-type)
(and (consp c-type)
(eq (cons-car c-type) 'pointer)))
;;; The macro `expand-c-type' is used to revert C types to a cannonical form.
;;; In practice, that means that bit-fielded int types are changed to their
;;; corresponding int types, and that array types are converted into pointer
;;; types.
(defun expand-c-type (c-type)
(if (atom c-type)
c-type
(let ((car (cons-car c-type)))
(cond ((memqp car '(uint int))
car)
((eq car 'array)
(cons 'pointer (cons-cdr c-type)))
(t
c-type)))))
;;; The macro `satisfies-c-required-type-p' takes a result C type and a required
;;; C type, and then this function returns whether or not the result type is
;;; appropriate as a value to an operation needing the required-type.
(defun satisfies-c-required-type-p (result-type required-type)
(let ((result (expand-c-type result-type))
(required (expand-c-type required-type)))
(or (eq required 'void)
(c-types-equal-p result required))))
;;; The function `c-type-tag' takes a C type and returns the type tag integer
;;; for that type, if any. The function `c-type-implementing-lisp-type' takes a
;;; Lisp type and returns a C type symbol, where a pointer to that C type
;;; implements the given Lisp type. The function `lisp-type-tag' takes a Lisp
;;; type and returns an integer which is the type tag for that Lisp type. Note
;;; that c-type-tag only expects to get primitive TL types that are defined
;;; using def-c-type.
(defun c-type-tag (c-type)
(or (if (symbolp c-type)
(get c-type 'c-type-tag)
nil)
(translation-error "C type ~s has no type tag." c-type)))
(defvar c-types-implementing-lisp-type-alist nil)
(defun c-type-implementing-lisp-type (lisp-type)
(cond ((symbolp lisp-type)
(get lisp-type 'c-type-implementing-lisp-type))
((and (consp lisp-type)
(eq (cons-car lisp-type) 'c-type))
lisp-type)
(t
(loop for entry in c-types-implementing-lisp-type-alist
do
(when (tl-subtypep lisp-type (cons-car entry))
(return (cons-cdr entry)))))))
(defun lisp-type-tag (lisp-type)
(cond ((eq lisp-type 'null)
0)
((class-type-p lisp-type)
(class-type-tag lisp-type))
(t
(let ((c-type (c-type-implementing-lisp-type lisp-type)))
(if (symbolp c-type)
(get c-type 'c-type-tag)
nil)))))
;;; The function `type-tags-for-lisp-type' takes a Lisp type and returns a list
;;; of the type tags that could appear on objects of that type.
(defun type-tags-for-lisp-type (lisp-type)
(let ((tag-list nil))
(setq lisp-type (expand-type lisp-type))
(cond ((and (consp lisp-type) (eq (cons-car lisp-type) 'or))
(loop for type in (cons-cdr lisp-type) do
(loop for subtype-tag in (type-tags-for-lisp-type type) do
(pushnew subtype-tag tag-list))))
(t
(loop for (type . tag)
in '((null . 0) (fixnum . 1) (cons . 2) (character . 3))
do
(when (tl-subtypep type lisp-type)
(push tag tag-list)))
(loop for (type . c-type) in c-types-implementing-lisp-type-alist do
(when (tl-subtypep type lisp-type)
(push (c-type-tag c-type) tag-list)))
(when (class-type-p lisp-type)
(setq tag-list
(nconc tag-list (type-tags-for-class-type lisp-type))))))
(sort (the list tag-list) #'<)))
;;; The function `c-type-for-const-array' takes a C type that holds
;;; implementations of Lisp array types, and the length of a constant array.
;;; This function will return the appropriate C const-array type for that
;;; constant. Generally this involves rounding up the length to some
appropriate value . ANSI C requires that the array types be at least one
;;; element long.
(defun c-type-for-const-array (c-type length)
(when (zerop length)
(setq length 1))
(list
'const-array
c-type
(cond
((satisfies-c-required-type-p c-type 'str)
Each element is 1 byte long , so it makes sense to round up to word
sizes . We need one extra element for the NULL byte at the end of the
;; C string.
(+ (round-up length 4) 1))
((satisfies-c-required-type-p c-type 'sa-uint8)
(round-up length 4))
((satisfies-c-required-type-p c-type 'sa-uint16)
(round-up length 2))
((satisfies-c-required-type-p c-type 'sa-sint16)
(round-up length 2))
((satisfies-c-required-type-p c-type 'sa-double)
length)
((satisfies-c-required-type-p c-type 'sv)
length))))
;;; The function `c-func-type-holding-function-type' takes a C function-type and
;;; returns a variant of the C Func type which happens to hold pointers to
;;; functions of the given description. This is similar to what is done for C
constant arrays of Lisp types , but all of the currently defined C Func types
;;; are defined explicitly in tl/c/tlt.h. This function signals an error if it
;;; cannot return an appropriate type.
(defun c-func-type-holding-function-type (c-function-type)
(let* ((c-return-type (cons-second c-function-type))
(c-arg-types (cons-third c-function-type))
(arg-count (length c-arg-types)))
(declare (fixnum arg-count))
(unless (and (eq c-return-type 'obj)
(loop for type in c-arg-types
always (eq type 'obj)))
(translation-error "Cannot find appropriate function type for spec ~s"
c-function-type))
(unless (<= arg-count tl:lambda-parameters-limit)
(translation-error
"Funcalls are limited to ~a arguments, a call had ~a."
tl:lambda-parameters-limit arg-count))
;; The case statement optimizes the most common cases, but otherwise is
;; unneccesary.
(list 'pointer
(case arg-count
(0 'func-0)
(1 'func-1)
(2 'func-2)
(3 'func-3)
(4 'func-4)
(5 'func-5)
(6 'func-6)
(7 'func-7)
(8 'func-8)
(9 'func-9)
(10 'func-10)
(t
(intern (format nil "FUNC-~a" arg-count) *tli-package*))))))
;;; The macro `def-c-type' defines Lisp symbols that correspond to given C
;;; types. It takes a Lisp symbol naming a C type, a string of how that type
;;; should be printed in C files, and a string of how a pointer to that type
should be printed in C files . The last two arguments are non - NIL if a
pointer to this type represents a Lisp type . The first is the Lisp type
;;; represented by this C type and the last argument is a type-tag number if a
;;; pointer to this C type represents a Lisp type.
(defmacro def-c-type
(type-name c-type-string c-pointer-type-string lisp-type? type-tag?)
`(progn
(setf (get ',type-name 'c-type-string) ,c-type-string)
(setf (get ',type-name 'c-pointer-type-string) ,c-pointer-type-string)
,@(when lisp-type?
`(,@(when (symbolp lisp-type?)
`((setf (get ',lisp-type? 'c-type-implementing-lisp-type)
',type-name)))
(push (cons ',lisp-type? ',type-name)
c-types-implementing-lisp-type-alist)))
,@(when type-tag?
`((setf (get ',type-name 'c-type-tag) ,type-tag?)))
',type-name))
;;; The function `print-type-tags' prints out a list of all of the type tags in
use in TL , with their associated Lisp types and implementing C types .
(defun print-type-tags ()
(loop for (lisp-type . c-type) in c-types-implementing-lisp-type-alist
collect (list (lisp-type-tag lisp-type) lisp-type c-type)
into type-triplets
finally
(setq type-triplets
(sort (append '((0 null null) (1 fixnum sint32)
(2 cons cons) (3 character unsigned-char))
type-triplets)
#'<
:key #'car))
(loop for (tag l c) in type-triplets
do (format t "~2d ~30s ~30s~%" tag l c))))
| null | https://raw.githubusercontent.com/ska80/thinlisp/173573a723256d901887f1cbc26d5403025879ca/tlt/lisp/c-types.lisp | lisp | Module C-TYPES
All rights reserved.
you can redistribute it and/or modify it
either version 1 or ( at your option ) any later version .
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
C Types
This module implements operations on C types.
`C types' are represented by symbols and lists of symbols. The following
symbols are available:
void, which is nothing,
boolean which is a C int used as an arg to logical predicates,
Mdouble which is a structure holding a managed-float (tag 0x4),
Sv which is a simple-vector structure (tag 0x6),
Sa_sint16 which is a structure holding sint16 arrays (tag 0x12),
Sa_double which is a structure holding double arrays (tag 0xA),
of the following symbols, with the format of the remainder of the list
determined by the particular symbol.
(pointer <c-type>) is a pointer to the enclosed C type, and
(array <c-type> [<array-length>]) is an array of the C type.
(const-array <c-type> <array-length>) is described below.
(c-type "<c-type-string>") allows an arbitrary type.
(pointer "<c-type-string>") allows a pointer to an arbitrary type.
(struct (<c-type> <name>)...) allows C struct types.
(int <bit-field-width>) and (uint <b-f-w>) allows bit field widths.
Const-array is a type used for emitting new type definitions to initialize
checking we can use this structure to access arbitrarily sized arrays in
data structures we create by allocating more memory beyond the bounds of the
usual Sv struct size. If however we want to have a C variable holding an
initialized instance of this structure, then we need to have a C type with
the correct number of elements in the Obj array embedded within the struct.
That is where the const-array C type comes in. When a new type is needed
for an explicitly sized embedded array within a structure, the const-array C
structure type whose embedded array is being specialized. The size that is
is used in a c-typedef-decl, the generated type name will be the normal
structure name with "_<length>" appended to it, e.g. Sv_5.
handle. They contain either the string naming C type, or the list (pointer
"<c-name>"). These C types are exactly the same form as the Lisp type that
represents them.
The macro `c-type-string' takes a C type and returns a C type string
suitable for use in a type casting operation. New type translations can be
made using def-c-type.
These are integers with bit field widths. The bit widths are only
emitted into struct type declarations, and so can be ignored in
this function.
they are equivalent. If we were being truely slick, we would implement the
Checking equality is a proper subset of what is documented inere.
The function `c-pointer-type-p' takes a C type and returns whether or not it
is a pointer suitable for an indirect selection expr.
The macro `expand-c-type' is used to revert C types to a cannonical form.
In practice, that means that bit-fielded int types are changed to their
corresponding int types, and that array types are converted into pointer
types.
The macro `satisfies-c-required-type-p' takes a result C type and a required
C type, and then this function returns whether or not the result type is
appropriate as a value to an operation needing the required-type.
The function `c-type-tag' takes a C type and returns the type tag integer
for that type, if any. The function `c-type-implementing-lisp-type' takes a
Lisp type and returns a C type symbol, where a pointer to that C type
implements the given Lisp type. The function `lisp-type-tag' takes a Lisp
type and returns an integer which is the type tag for that Lisp type. Note
that c-type-tag only expects to get primitive TL types that are defined
using def-c-type.
The function `type-tags-for-lisp-type' takes a Lisp type and returns a list
of the type tags that could appear on objects of that type.
The function `c-type-for-const-array' takes a C type that holds
implementations of Lisp array types, and the length of a constant array.
This function will return the appropriate C const-array type for that
constant. Generally this involves rounding up the length to some
element long.
C string.
The function `c-func-type-holding-function-type' takes a C function-type and
returns a variant of the C Func type which happens to hold pointers to
functions of the given description. This is similar to what is done for C
are defined explicitly in tl/c/tlt.h. This function signals an error if it
cannot return an appropriate type.
The case statement optimizes the most common cases, but otherwise is
unneccesary.
The macro `def-c-type' defines Lisp symbols that correspond to given C
types. It takes a Lisp symbol naming a C type, a string of how that type
should be printed in C files, and a string of how a pointer to that type
represented by this C type and the last argument is a type-tag number if a
pointer to this C type represents a Lisp type.
The function `print-type-tags' prints out a list of all of the type tags in | (in-package "TLI")
Copyright ( c ) 1999 - 2001 The ThinLisp Group
Copyright ( c ) 1995 Gensym Corporation .
This file is part of ThinLisp .
under the terms of the ThinLisp License as published by the ThinLisp
ThinLisp is distributed in the hope that it will be useful , but
For additional information see < / >
Author :
Obj which is an sint32 whose value points to a Hdr ( aka header ) ,
is a structure holding a type tag ,
sint32 which is a signed 32 - bit integer ,
which is an unsigned 8 - bit integer ( equivalent to unsigned - char ) ,
uint16 which is an unsigned 16 - bit integer ( aka unsigned short ) ,
sint16 which is a signed 16 - bit integer ( aka signed short ) ,
unsigned - char which is C unsigned char ( equivalent to ) ,
Ldouble which is a structure holding a double - float ( tag 0x5 ) ,
which is a string structure ( tag 0x7 ) ,
Sa_uint8 which is a structure holding arrays ( tag 0x8 ) ,
Sa_uint16 which is a structure holding uint16 arrays ( tag 0x9 ) ,
which is a symbol structure ( tag 0xB ) ,
Func which is compiled - function structure ( tag 0xC ) ,
which is a package structure ( tag 0xD ) ,
jmp_buf which is a jump buffer for setjmp and , and
Thread_state which is a structure holding Lisp thread info .
C types can also be lists . In these cases the car of the list must be one
Lisp arrays of constant sizes . For example , the type Sv is a C structure
representing a Lisp simple - vector . The actual Obj array in the Sv structure
is only 1 element long , but since C explicitly performs no array bounds
type will be used . The C type that is the second of the list will be the
the third of the list is the length of the embedded array . If this C type
C - type is a type used for TL end - users extending the C types that TL can
(defun c-type-string (c-type)
(if (symbolp c-type)
(get c-type 'c-type-string)
(get-compound-c-type-string c-type)))
(defun get-compound-c-type-string (c-type)
(let ((car (cons-car c-type))
(second (cons-second c-type)))
(cond ((eq car 'c-type)
(cond ((stringp second)
second)
((and (consp second)
(eq (cons-car second) 'pointer)
(stringp (cons-second second)))
(format nil "~a *" (cons-second second)))
(t
(error "Can't make type string for ~s" c-type))))
((memqp car '(uint int))
(c-type-string car))
((memqp car '(pointer array))
(cond ((symbolp second)
(get second 'c-pointer-type-string))
((stringp second)
(format nil "~a *" second))
(t
(format nil "~a *" (c-type-string second)))))
((eq car 'const-array)
(format nil "~a_~a" (c-type-string second) (third c-type)))
((eq car 'function)
(let ((return-type second)
(arg-types (cons-third c-type)))
(with-output-to-string (out)
(format out "~a (*)(" (c-type-string return-type))
(if (null arg-types)
(format out "void")
(loop for first? = t then nil
for arg-type in arg-types
do
(unless first?
(format out ", "))
(format out "~a" (c-type-string arg-type))))
(format out ")"))))
((eq car 'struct)
(c-struct-or-union-type-string "struct" c-type))
((eq car 'union)
(c-struct-or-union-type-string "union" c-type))
(t
(error "Can't make type string for ~s" c-type)))))
(defun c-struct-or-union-type-string (struct-or-union c-type)
(let* ((type-strings (loop for (elt-type) in (cons-cdr c-type)
collect (c-type-string elt-type)))
(max-length
(apply 'max (mapcar #'length type-strings))))
(format nil "~a {~%~a}"
struct-or-union
(apply 'concatenate 'string
(loop for elt in (cons-cdr c-type)
for type-string in type-strings
for (elt-type name) = elt
collect
(cond ((and (consp elt-type)
(memqp (car elt-type) '(int uint)))
(format nil " ~Va ~a : ~a;~%"
max-length type-string name
(cons-second elt-type)))
((and (consp elt-type)
(eq (car elt-type) 'array)
(third elt-type))
(format nil " ~Va ~a[~a];~%"
max-length
(c-type-string (second elt-type))
name
(third elt-type)))
(t
(format nil " ~Va ~a;~%"
max-length type-string name))))))))
The function ` c - types - equal - p ' takes two C types and returns whether or not
C type compatibility rules found in CARM , 4th Edition , pp . 151 - 155 .
(defun c-types-equal-p (type1 type2)
(equal type1 type2))
(defun c-pointer-type-p (c-type)
(and (consp c-type)
(eq (cons-car c-type) 'pointer)))
(defun expand-c-type (c-type)
(if (atom c-type)
c-type
(let ((car (cons-car c-type)))
(cond ((memqp car '(uint int))
car)
((eq car 'array)
(cons 'pointer (cons-cdr c-type)))
(t
c-type)))))
(defun satisfies-c-required-type-p (result-type required-type)
(let ((result (expand-c-type result-type))
(required (expand-c-type required-type)))
(or (eq required 'void)
(c-types-equal-p result required))))
(defun c-type-tag (c-type)
(or (if (symbolp c-type)
(get c-type 'c-type-tag)
nil)
(translation-error "C type ~s has no type tag." c-type)))
(defvar c-types-implementing-lisp-type-alist nil)
(defun c-type-implementing-lisp-type (lisp-type)
(cond ((symbolp lisp-type)
(get lisp-type 'c-type-implementing-lisp-type))
((and (consp lisp-type)
(eq (cons-car lisp-type) 'c-type))
lisp-type)
(t
(loop for entry in c-types-implementing-lisp-type-alist
do
(when (tl-subtypep lisp-type (cons-car entry))
(return (cons-cdr entry)))))))
(defun lisp-type-tag (lisp-type)
(cond ((eq lisp-type 'null)
0)
((class-type-p lisp-type)
(class-type-tag lisp-type))
(t
(let ((c-type (c-type-implementing-lisp-type lisp-type)))
(if (symbolp c-type)
(get c-type 'c-type-tag)
nil)))))
(defun type-tags-for-lisp-type (lisp-type)
(let ((tag-list nil))
(setq lisp-type (expand-type lisp-type))
(cond ((and (consp lisp-type) (eq (cons-car lisp-type) 'or))
(loop for type in (cons-cdr lisp-type) do
(loop for subtype-tag in (type-tags-for-lisp-type type) do
(pushnew subtype-tag tag-list))))
(t
(loop for (type . tag)
in '((null . 0) (fixnum . 1) (cons . 2) (character . 3))
do
(when (tl-subtypep type lisp-type)
(push tag tag-list)))
(loop for (type . c-type) in c-types-implementing-lisp-type-alist do
(when (tl-subtypep type lisp-type)
(push (c-type-tag c-type) tag-list)))
(when (class-type-p lisp-type)
(setq tag-list
(nconc tag-list (type-tags-for-class-type lisp-type))))))
(sort (the list tag-list) #'<)))
appropriate value . ANSI C requires that the array types be at least one
(defun c-type-for-const-array (c-type length)
(when (zerop length)
(setq length 1))
(list
'const-array
c-type
(cond
((satisfies-c-required-type-p c-type 'str)
Each element is 1 byte long , so it makes sense to round up to word
sizes . We need one extra element for the NULL byte at the end of the
(+ (round-up length 4) 1))
((satisfies-c-required-type-p c-type 'sa-uint8)
(round-up length 4))
((satisfies-c-required-type-p c-type 'sa-uint16)
(round-up length 2))
((satisfies-c-required-type-p c-type 'sa-sint16)
(round-up length 2))
((satisfies-c-required-type-p c-type 'sa-double)
length)
((satisfies-c-required-type-p c-type 'sv)
length))))
constant arrays of Lisp types , but all of the currently defined C Func types
(defun c-func-type-holding-function-type (c-function-type)
(let* ((c-return-type (cons-second c-function-type))
(c-arg-types (cons-third c-function-type))
(arg-count (length c-arg-types)))
(declare (fixnum arg-count))
(unless (and (eq c-return-type 'obj)
(loop for type in c-arg-types
always (eq type 'obj)))
(translation-error "Cannot find appropriate function type for spec ~s"
c-function-type))
(unless (<= arg-count tl:lambda-parameters-limit)
(translation-error
"Funcalls are limited to ~a arguments, a call had ~a."
tl:lambda-parameters-limit arg-count))
(list 'pointer
(case arg-count
(0 'func-0)
(1 'func-1)
(2 'func-2)
(3 'func-3)
(4 'func-4)
(5 'func-5)
(6 'func-6)
(7 'func-7)
(8 'func-8)
(9 'func-9)
(10 'func-10)
(t
(intern (format nil "FUNC-~a" arg-count) *tli-package*))))))
should be printed in C files . The last two arguments are non - NIL if a
pointer to this type represents a Lisp type . The first is the Lisp type
(defmacro def-c-type
(type-name c-type-string c-pointer-type-string lisp-type? type-tag?)
`(progn
(setf (get ',type-name 'c-type-string) ,c-type-string)
(setf (get ',type-name 'c-pointer-type-string) ,c-pointer-type-string)
,@(when lisp-type?
`(,@(when (symbolp lisp-type?)
`((setf (get ',lisp-type? 'c-type-implementing-lisp-type)
',type-name)))
(push (cons ',lisp-type? ',type-name)
c-types-implementing-lisp-type-alist)))
,@(when type-tag?
`((setf (get ',type-name 'c-type-tag) ,type-tag?)))
',type-name))
use in TL , with their associated Lisp types and implementing C types .
(defun print-type-tags ()
(loop for (lisp-type . c-type) in c-types-implementing-lisp-type-alist
collect (list (lisp-type-tag lisp-type) lisp-type c-type)
into type-triplets
finally
(setq type-triplets
(sort (append '((0 null null) (1 fixnum sint32)
(2 cons cons) (3 character unsigned-char))
type-triplets)
#'<
:key #'car))
(loop for (tag l c) in type-triplets
do (format t "~2d ~30s ~30s~%" tag l c))))
|
95373cccc3ab04a79c3d511d5788981f777d3a3f3beb512d28a14f8147a36c6a | schell/gelatin | Setup.hs | import Distribution.Simple
main :: IO ()
main = defaultMain
| null | https://raw.githubusercontent.com/schell/gelatin/04c1c83d4297eac4f4cc5e8e5c805b1600b3ee98/gelatin-webgl/Setup.hs | haskell | import Distribution.Simple
main :: IO ()
main = defaultMain
| |
d84638e5974d855fbfe6c108c7be230cc4dd92cfadefb01daf892e38a302accf | SimulaVR/godot-haskell | Resource.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.Resource
(Godot.Core.Resource.sig_changed,
Godot.Core.Resource._setup_local_to_scene,
Godot.Core.Resource.duplicate, Godot.Core.Resource.get_local_scene,
Godot.Core.Resource.get_name, Godot.Core.Resource.get_path,
Godot.Core.Resource.get_rid, Godot.Core.Resource.is_local_to_scene,
Godot.Core.Resource.set_local_to_scene,
Godot.Core.Resource.set_name, Godot.Core.Resource.set_path,
Godot.Core.Resource.setup_local_to_scene,
Godot.Core.Resource.take_over_path)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Reference()
-- | Emitted whenever the resource changes.
sig_changed :: Godot.Internal.Dispatch.Signal Resource
sig_changed = Godot.Internal.Dispatch.Signal "changed"
instance NodeSignal Resource "changed" '[]
instance NodeProperty Resource "resource_local_to_scene" Bool
'False
where
nodeProperty
= (is_local_to_scene, wrapDroppingSetter set_local_to_scene,
Nothing)
instance NodeProperty Resource "resource_name" GodotString 'False
where
nodeProperty = (get_name, wrapDroppingSetter set_name, Nothing)
instance NodeProperty Resource "resource_path" GodotString 'False
where
nodeProperty = (get_path, wrapDroppingSetter set_path, Nothing)
# NOINLINE bindResource__setup_local_to_scene #
-- | Virtual function which can be overridden to customize the behavior value of @method setup_local_to_scene@.
bindResource__setup_local_to_scene :: MethodBind
bindResource__setup_local_to_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "_setup_local_to_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Virtual function which can be overridden to customize the behavior value of @method setup_local_to_scene@.
_setup_local_to_scene ::
(Resource :< cls, Object :< cls) => cls -> IO ()
_setup_local_to_scene cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource__setup_local_to_scene
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "_setup_local_to_scene" '[] (IO ())
where
nodeMethod = Godot.Core.Resource._setup_local_to_scene
# NOINLINE bindResource_duplicate #
| Duplicates the resource , returning a new resource . By default , sub - resources are shared between resource copies for efficiency . This can be changed by passing @true@ to the @subresources@ argument which will copy the subresources .
_ _ Note : _ _ If @subresources@ is @true@ , this method will only perform a shallow copy . Nested resources within subresources will not be duplicated and will still be shared .
bindResource_duplicate :: MethodBind
bindResource_duplicate
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "duplicate" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Duplicates the resource , returning a new resource . By default , sub - resources are shared between resource copies for efficiency . This can be changed by passing @true@ to the @subresources@ argument which will copy the subresources .
_ _ Note : _ _ If @subresources@ is @true@ , this method will only perform a shallow copy . Nested resources within subresources will not be duplicated and will still be shared .
duplicate ::
(Resource :< cls, Object :< cls) =>
cls -> Maybe Bool -> IO Resource
duplicate cls arg1
= withVariantArray [maybe (VariantBool False) toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_duplicate (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "duplicate" '[Maybe Bool]
(IO Resource)
where
nodeMethod = Godot.Core.Resource.duplicate
# NOINLINE bindResource_get_local_scene #
-- | If @resource_local_to_scene@ is enabled and the resource was loaded from a @PackedScene@ instantiation, returns the local scene where this resource's unique copy is in use. Otherwise, returns @null@.
bindResource_get_local_scene :: MethodBind
bindResource_get_local_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "get_local_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | If @resource_local_to_scene@ is enabled and the resource was loaded from a @PackedScene@ instantiation, returns the local scene where this resource's unique copy is in use. Otherwise, returns @null@.
get_local_scene ::
(Resource :< cls, Object :< cls) => cls -> IO Node
get_local_scene cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_get_local_scene (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "get_local_scene" '[] (IO Node) where
nodeMethod = Godot.Core.Resource.get_local_scene
# NOINLINE bindResource_get_name #
-- | The name of the resource. This is an optional identifier.
bindResource_get_name :: MethodBind
bindResource_get_name
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "get_name" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The name of the resource. This is an optional identifier.
get_name ::
(Resource :< cls, Object :< cls) => cls -> IO GodotString
get_name cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_get_name (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "get_name" '[] (IO GodotString) where
nodeMethod = Godot.Core.Resource.get_name
# NOINLINE bindResource_get_path #
-- | The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
bindResource_get_path :: MethodBind
bindResource_get_path
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "get_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
get_path ::
(Resource :< cls, Object :< cls) => cls -> IO GodotString
get_path cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_get_path (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "get_path" '[] (IO GodotString) where
nodeMethod = Godot.Core.Resource.get_path
# NOINLINE bindResource_get_rid #
| Returns the RID of the resource ( or an empty RID ) . Many resources ( such as @Texture@ , @Mesh@ , etc ) are high - level abstractions of resources stored in a server , so this function will return the original RID .
bindResource_get_rid :: MethodBind
bindResource_get_rid
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "get_rid" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the RID of the resource ( or an empty RID ) . Many resources ( such as @Texture@ , @Mesh@ , etc ) are high - level abstractions of resources stored in a server , so this function will return the original RID .
get_rid :: (Resource :< cls, Object :< cls) => cls -> IO Rid
get_rid cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_get_rid (upcast cls) arrPtr len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "get_rid" '[] (IO Rid) where
nodeMethod = Godot.Core.Resource.get_rid
# NOINLINE bindResource_is_local_to_scene #
| If @true@ , the resource will be made unique in each instance of its local scene . It can thus be modified in a scene instance without impacting other instances of that same scene .
bindResource_is_local_to_scene :: MethodBind
bindResource_is_local_to_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "is_local_to_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , the resource will be made unique in each instance of its local scene . It can thus be modified in a scene instance without impacting other instances of that same scene .
is_local_to_scene ::
(Resource :< cls, Object :< cls) => cls -> IO Bool
is_local_to_scene cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_is_local_to_scene (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "is_local_to_scene" '[] (IO Bool)
where
nodeMethod = Godot.Core.Resource.is_local_to_scene
# NOINLINE bindResource_set_local_to_scene #
| If @true@ , the resource will be made unique in each instance of its local scene . It can thus be modified in a scene instance without impacting other instances of that same scene .
bindResource_set_local_to_scene :: MethodBind
bindResource_set_local_to_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "set_local_to_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , the resource will be made unique in each instance of its local scene . It can thus be modified in a scene instance without impacting other instances of that same scene .
set_local_to_scene ::
(Resource :< cls, Object :< cls) => cls -> Bool -> IO ()
set_local_to_scene cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_set_local_to_scene (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "set_local_to_scene" '[Bool] (IO ())
where
nodeMethod = Godot.Core.Resource.set_local_to_scene
# NOINLINE bindResource_set_name #
-- | The name of the resource. This is an optional identifier.
bindResource_set_name :: MethodBind
bindResource_set_name
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "set_name" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The name of the resource. This is an optional identifier.
set_name ::
(Resource :< cls, Object :< cls) => cls -> GodotString -> IO ()
set_name cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_set_name (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "set_name" '[GodotString] (IO ())
where
nodeMethod = Godot.Core.Resource.set_name
# NOINLINE bindResource_set_path #
-- | The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
bindResource_set_path :: MethodBind
bindResource_set_path
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "set_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
set_path ::
(Resource :< cls, Object :< cls) => cls -> GodotString -> IO ()
set_path cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_set_path (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "set_path" '[GodotString] (IO ())
where
nodeMethod = Godot.Core.Resource.set_path
# NOINLINE bindResource_setup_local_to_scene #
| This method is called when a resource with @resource_local_to_scene@ enabled is loaded from a @PackedScene@ instantiation . Its behavior can be customized by overriding @method _ setup_local_to_scene@ from script .
-- For most resources, this method performs no base logic. @ViewportTexture@ performs custom logic to properly set the proxy texture and flags in the local viewport.
bindResource_setup_local_to_scene :: MethodBind
bindResource_setup_local_to_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "setup_local_to_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| This method is called when a resource with @resource_local_to_scene@ enabled is loaded from a @PackedScene@ instantiation . Its behavior can be customized by overriding @method _ setup_local_to_scene@ from script .
-- For most resources, this method performs no base logic. @ViewportTexture@ performs custom logic to properly set the proxy texture and flags in the local viewport.
setup_local_to_scene ::
(Resource :< cls, Object :< cls) => cls -> IO ()
setup_local_to_scene cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_setup_local_to_scene
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "setup_local_to_scene" '[] (IO ())
where
nodeMethod = Godot.Core.Resource.setup_local_to_scene
# NOINLINE bindResource_take_over_path #
| Sets the path of the resource , potentially overriding an existing cache entry for this path . This differs from setting @resource_path@ , as the latter would error out if another resource was already cached for the given path .
bindResource_take_over_path :: MethodBind
bindResource_take_over_path
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "take_over_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the path of the resource , potentially overriding an existing cache entry for this path . This differs from setting @resource_path@ , as the latter would error out if another resource was already cached for the given path .
take_over_path ::
(Resource :< cls, Object :< cls) => cls -> GodotString -> IO ()
take_over_path cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_take_over_path (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "take_over_path" '[GodotString]
(IO ())
where
nodeMethod = Godot.Core.Resource.take_over_path | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/Resource.hs | haskell | | Emitted whenever the resource changes.
| Virtual function which can be overridden to customize the behavior value of @method setup_local_to_scene@.
| Virtual function which can be overridden to customize the behavior value of @method setup_local_to_scene@.
| If @resource_local_to_scene@ is enabled and the resource was loaded from a @PackedScene@ instantiation, returns the local scene where this resource's unique copy is in use. Otherwise, returns @null@.
| If @resource_local_to_scene@ is enabled and the resource was loaded from a @PackedScene@ instantiation, returns the local scene where this resource's unique copy is in use. Otherwise, returns @null@.
| The name of the resource. This is an optional identifier.
| The name of the resource. This is an optional identifier.
| The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
| The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
| The name of the resource. This is an optional identifier.
| The name of the resource. This is an optional identifier.
| The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
| The path to the resource. In case it has its own file, it will return its filepath. If it's tied to the scene, it will return the scene's path, followed by the resource's index.
For most resources, this method performs no base logic. @ViewportTexture@ performs custom logic to properly set the proxy texture and flags in the local viewport.
For most resources, this method performs no base logic. @ViewportTexture@ performs custom logic to properly set the proxy texture and flags in the local viewport. | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.Resource
(Godot.Core.Resource.sig_changed,
Godot.Core.Resource._setup_local_to_scene,
Godot.Core.Resource.duplicate, Godot.Core.Resource.get_local_scene,
Godot.Core.Resource.get_name, Godot.Core.Resource.get_path,
Godot.Core.Resource.get_rid, Godot.Core.Resource.is_local_to_scene,
Godot.Core.Resource.set_local_to_scene,
Godot.Core.Resource.set_name, Godot.Core.Resource.set_path,
Godot.Core.Resource.setup_local_to_scene,
Godot.Core.Resource.take_over_path)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.Reference()
sig_changed :: Godot.Internal.Dispatch.Signal Resource
sig_changed = Godot.Internal.Dispatch.Signal "changed"
instance NodeSignal Resource "changed" '[]
instance NodeProperty Resource "resource_local_to_scene" Bool
'False
where
nodeProperty
= (is_local_to_scene, wrapDroppingSetter set_local_to_scene,
Nothing)
instance NodeProperty Resource "resource_name" GodotString 'False
where
nodeProperty = (get_name, wrapDroppingSetter set_name, Nothing)
instance NodeProperty Resource "resource_path" GodotString 'False
where
nodeProperty = (get_path, wrapDroppingSetter set_path, Nothing)
# NOINLINE bindResource__setup_local_to_scene #
bindResource__setup_local_to_scene :: MethodBind
bindResource__setup_local_to_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "_setup_local_to_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
_setup_local_to_scene ::
(Resource :< cls, Object :< cls) => cls -> IO ()
_setup_local_to_scene cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource__setup_local_to_scene
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "_setup_local_to_scene" '[] (IO ())
where
nodeMethod = Godot.Core.Resource._setup_local_to_scene
# NOINLINE bindResource_duplicate #
| Duplicates the resource , returning a new resource . By default , sub - resources are shared between resource copies for efficiency . This can be changed by passing @true@ to the @subresources@ argument which will copy the subresources .
_ _ Note : _ _ If @subresources@ is @true@ , this method will only perform a shallow copy . Nested resources within subresources will not be duplicated and will still be shared .
bindResource_duplicate :: MethodBind
bindResource_duplicate
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "duplicate" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Duplicates the resource , returning a new resource . By default , sub - resources are shared between resource copies for efficiency . This can be changed by passing @true@ to the @subresources@ argument which will copy the subresources .
_ _ Note : _ _ If @subresources@ is @true@ , this method will only perform a shallow copy . Nested resources within subresources will not be duplicated and will still be shared .
duplicate ::
(Resource :< cls, Object :< cls) =>
cls -> Maybe Bool -> IO Resource
duplicate cls arg1
= withVariantArray [maybe (VariantBool False) toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_duplicate (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "duplicate" '[Maybe Bool]
(IO Resource)
where
nodeMethod = Godot.Core.Resource.duplicate
# NOINLINE bindResource_get_local_scene #
bindResource_get_local_scene :: MethodBind
bindResource_get_local_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "get_local_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_local_scene ::
(Resource :< cls, Object :< cls) => cls -> IO Node
get_local_scene cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_get_local_scene (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "get_local_scene" '[] (IO Node) where
nodeMethod = Godot.Core.Resource.get_local_scene
# NOINLINE bindResource_get_name #
bindResource_get_name :: MethodBind
bindResource_get_name
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "get_name" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_name ::
(Resource :< cls, Object :< cls) => cls -> IO GodotString
get_name cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_get_name (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "get_name" '[] (IO GodotString) where
nodeMethod = Godot.Core.Resource.get_name
# NOINLINE bindResource_get_path #
bindResource_get_path :: MethodBind
bindResource_get_path
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "get_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_path ::
(Resource :< cls, Object :< cls) => cls -> IO GodotString
get_path cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_get_path (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "get_path" '[] (IO GodotString) where
nodeMethod = Godot.Core.Resource.get_path
# NOINLINE bindResource_get_rid #
| Returns the RID of the resource ( or an empty RID ) . Many resources ( such as @Texture@ , @Mesh@ , etc ) are high - level abstractions of resources stored in a server , so this function will return the original RID .
bindResource_get_rid :: MethodBind
bindResource_get_rid
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "get_rid" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the RID of the resource ( or an empty RID ) . Many resources ( such as @Texture@ , @Mesh@ , etc ) are high - level abstractions of resources stored in a server , so this function will return the original RID .
get_rid :: (Resource :< cls, Object :< cls) => cls -> IO Rid
get_rid cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_get_rid (upcast cls) arrPtr len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "get_rid" '[] (IO Rid) where
nodeMethod = Godot.Core.Resource.get_rid
# NOINLINE bindResource_is_local_to_scene #
| If @true@ , the resource will be made unique in each instance of its local scene . It can thus be modified in a scene instance without impacting other instances of that same scene .
bindResource_is_local_to_scene :: MethodBind
bindResource_is_local_to_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "is_local_to_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , the resource will be made unique in each instance of its local scene . It can thus be modified in a scene instance without impacting other instances of that same scene .
is_local_to_scene ::
(Resource :< cls, Object :< cls) => cls -> IO Bool
is_local_to_scene cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_is_local_to_scene (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "is_local_to_scene" '[] (IO Bool)
where
nodeMethod = Godot.Core.Resource.is_local_to_scene
# NOINLINE bindResource_set_local_to_scene #
| If @true@ , the resource will be made unique in each instance of its local scene . It can thus be modified in a scene instance without impacting other instances of that same scene .
bindResource_set_local_to_scene :: MethodBind
bindResource_set_local_to_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "set_local_to_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , the resource will be made unique in each instance of its local scene . It can thus be modified in a scene instance without impacting other instances of that same scene .
set_local_to_scene ::
(Resource :< cls, Object :< cls) => cls -> Bool -> IO ()
set_local_to_scene cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_set_local_to_scene (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "set_local_to_scene" '[Bool] (IO ())
where
nodeMethod = Godot.Core.Resource.set_local_to_scene
# NOINLINE bindResource_set_name #
bindResource_set_name :: MethodBind
bindResource_set_name
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "set_name" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_name ::
(Resource :< cls, Object :< cls) => cls -> GodotString -> IO ()
set_name cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_set_name (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "set_name" '[GodotString] (IO ())
where
nodeMethod = Godot.Core.Resource.set_name
# NOINLINE bindResource_set_path #
bindResource_set_path :: MethodBind
bindResource_set_path
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "set_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
set_path ::
(Resource :< cls, Object :< cls) => cls -> GodotString -> IO ()
set_path cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_set_path (upcast cls) arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "set_path" '[GodotString] (IO ())
where
nodeMethod = Godot.Core.Resource.set_path
# NOINLINE bindResource_setup_local_to_scene #
| This method is called when a resource with @resource_local_to_scene@ enabled is loaded from a @PackedScene@ instantiation . Its behavior can be customized by overriding @method _ setup_local_to_scene@ from script .
bindResource_setup_local_to_scene :: MethodBind
bindResource_setup_local_to_scene
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "setup_local_to_scene" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| This method is called when a resource with @resource_local_to_scene@ enabled is loaded from a @PackedScene@ instantiation . Its behavior can be customized by overriding @method _ setup_local_to_scene@ from script .
setup_local_to_scene ::
(Resource :< cls, Object :< cls) => cls -> IO ()
setup_local_to_scene cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_setup_local_to_scene
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "setup_local_to_scene" '[] (IO ())
where
nodeMethod = Godot.Core.Resource.setup_local_to_scene
# NOINLINE bindResource_take_over_path #
| Sets the path of the resource , potentially overriding an existing cache entry for this path . This differs from setting @resource_path@ , as the latter would error out if another resource was already cached for the given path .
bindResource_take_over_path :: MethodBind
bindResource_take_over_path
= unsafePerformIO $
withCString "Resource" $
\ clsNamePtr ->
withCString "take_over_path" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Sets the path of the resource , potentially overriding an existing cache entry for this path . This differs from setting @resource_path@ , as the latter would error out if another resource was already cached for the given path .
take_over_path ::
(Resource :< cls, Object :< cls) => cls -> GodotString -> IO ()
take_over_path cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindResource_take_over_path (upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod Resource "take_over_path" '[GodotString]
(IO ())
where
nodeMethod = Godot.Core.Resource.take_over_path |
9e1851113a63bd650a619bf0df88df8d30396e5578d10b94c9bdc3b74cee17a9 | ocaml-batteries-team/batteries-included | array_partition.ml | let (|>) x f = f x
let list_partition p a =
let left, right = Array.to_list a |> List.partition p in
Array.of_list left, Array.of_list right
open Array
let current_partition p xs =
let n = length xs in
(* Use a bitset to store which elements will be in which final array. *)
let bs = BatBitSet.create n in
for i = 0 to n-1 do
if p xs.(i) then BatBitSet.set bs i
done;
(* Allocate the final arrays and copy elements into them. *)
let n1 = BatBitSet.count bs in
let n2 = n - n1 in
let j = ref 0 in
let xs1 = init n1
(fun _ ->
Find the next set bit in the BitSet .
while not (BatBitSet.mem bs !j) do incr j done;
let r = xs.(!j) in
incr j;
r) in
let j = ref 0 in
let xs2 = init n2
(fun _ ->
Find the next clear bit in the BitSet .
while BatBitSet.mem bs !j do incr j done;
let r = xs.(!j) in
incr j;
r) in
xs1, xs2
let unixjunkie_partition p a =
let n = length a in
if n = 0 then ([||], [||])
else
let mask = make n false in
let ok_count = ref 0 in
iteri (fun i x ->
if p x then
(unsafe_set mask i true;
incr ok_count)
) a;
let ko_count = n - !ok_count in
let init = unsafe_get a 0 in
let ok = make !ok_count init in
let ko = make ko_count init in
let j = ref 0 in
let k = ref 0 in
iteri (fun i px ->
let x = unsafe_get a i in
if px then
(unsafe_set ok !j x;
incr j)
else
(unsafe_set ko !k x;
incr k)
) mask;
(ok, ko)
let gasche_partition p xs =
let n = length xs in
if n = 0 then ([||], [||]) else begin
let size_yes = ref 0 in
let bs = Array.init n (fun i ->
let b = p (unsafe_get xs i) in
if b then incr size_yes;
b) in
let yes = Array.make !size_yes xs.(0) in
let no = Array.make (n - !size_yes) xs.(0) in
let iyes = ref 0 in
let ino = ref 0 in
for i = 0 to n - 1 do
if (unsafe_get bs i) then begin
unsafe_set yes !iyes (unsafe_get xs i);
incr iyes;
end else begin
unsafe_set no !ino (unsafe_get xs i);
incr ino;
end
done;
yes, no
end
let input_gen n = Array.init (1000 * n) (fun x -> x)
let m4 = fun x -> x mod 4 = 0
let m5 = fun x -> x mod 5 = 0
let m10 = fun x -> x mod 10 = 0
let () =
Bench.config.Bench.samples <- 1000;
Bench.config.Bench.gc_between_tests <- true;
Bench.bench_n [
"list_partition",
(fun a -> list_partition m4 (input_gen a));
"current_partition",
(fun a -> current_partition m4 (input_gen a));
"unixjunkie_partition", (fun a -> unixjunkie_partition m4 (input_gen a));
"gasche_partition", (fun a -> gasche_partition m4 (input_gen a));
] |> Bench.summarize ~alpha:0.05
| null | https://raw.githubusercontent.com/ocaml-batteries-team/batteries-included/a1b992fd2030869421550153ac5c97f0a39780f5/benchsuite/array_partition.ml | ocaml | Use a bitset to store which elements will be in which final array.
Allocate the final arrays and copy elements into them. | let (|>) x f = f x
let list_partition p a =
let left, right = Array.to_list a |> List.partition p in
Array.of_list left, Array.of_list right
open Array
let current_partition p xs =
let n = length xs in
let bs = BatBitSet.create n in
for i = 0 to n-1 do
if p xs.(i) then BatBitSet.set bs i
done;
let n1 = BatBitSet.count bs in
let n2 = n - n1 in
let j = ref 0 in
let xs1 = init n1
(fun _ ->
Find the next set bit in the BitSet .
while not (BatBitSet.mem bs !j) do incr j done;
let r = xs.(!j) in
incr j;
r) in
let j = ref 0 in
let xs2 = init n2
(fun _ ->
Find the next clear bit in the BitSet .
while BatBitSet.mem bs !j do incr j done;
let r = xs.(!j) in
incr j;
r) in
xs1, xs2
let unixjunkie_partition p a =
let n = length a in
if n = 0 then ([||], [||])
else
let mask = make n false in
let ok_count = ref 0 in
iteri (fun i x ->
if p x then
(unsafe_set mask i true;
incr ok_count)
) a;
let ko_count = n - !ok_count in
let init = unsafe_get a 0 in
let ok = make !ok_count init in
let ko = make ko_count init in
let j = ref 0 in
let k = ref 0 in
iteri (fun i px ->
let x = unsafe_get a i in
if px then
(unsafe_set ok !j x;
incr j)
else
(unsafe_set ko !k x;
incr k)
) mask;
(ok, ko)
let gasche_partition p xs =
let n = length xs in
if n = 0 then ([||], [||]) else begin
let size_yes = ref 0 in
let bs = Array.init n (fun i ->
let b = p (unsafe_get xs i) in
if b then incr size_yes;
b) in
let yes = Array.make !size_yes xs.(0) in
let no = Array.make (n - !size_yes) xs.(0) in
let iyes = ref 0 in
let ino = ref 0 in
for i = 0 to n - 1 do
if (unsafe_get bs i) then begin
unsafe_set yes !iyes (unsafe_get xs i);
incr iyes;
end else begin
unsafe_set no !ino (unsafe_get xs i);
incr ino;
end
done;
yes, no
end
let input_gen n = Array.init (1000 * n) (fun x -> x)
let m4 = fun x -> x mod 4 = 0
let m5 = fun x -> x mod 5 = 0
let m10 = fun x -> x mod 10 = 0
let () =
Bench.config.Bench.samples <- 1000;
Bench.config.Bench.gc_between_tests <- true;
Bench.bench_n [
"list_partition",
(fun a -> list_partition m4 (input_gen a));
"current_partition",
(fun a -> current_partition m4 (input_gen a));
"unixjunkie_partition", (fun a -> unixjunkie_partition m4 (input_gen a));
"gasche_partition", (fun a -> gasche_partition m4 (input_gen a));
] |> Bench.summarize ~alpha:0.05
|
0eb9b16300a226315e7c491f6d2538d79926d90484f5a4ca92634f74647a658c | ghollisjr/cl-ana | package.lisp | cl - ana is a Common Lisp data analysis library .
Copyright 2013 , 2014
;;;;
This file is part of cl - ana .
;;;;
;;;; cl-ana 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.
;;;;
;;;; cl-ana 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 cl-ana. If not, see </>.
;;;;
You may contact ( me ! ) via email at
;;;;
(defpackage #:cl-ana.table
(:use #:cl
#:alexandria
#:cl-ana.list-utils
#:cl-ana.macro-utils
#:cl-ana.string-utils
#:cl-ana.symbol-utils
#:cl-ana.functional-utils)
(:export :table
:table-open-p
:table-field-names
:table-access-mode
:table-field-symbols
:table-load-next-row
:table-activate-fields
:table-get-field
:table-set-field
:table-push-fields
:table-commit-row
:table-close
:table-nrows
:do-table
:table-reduce
;; table-chain:
:open-table-chain
:reset-table-chain
;; plist-table:
:plist-table-plists
:open-plist-table
:create-plist-table))
| null | https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/table/package.lisp | lisp |
cl-ana is free software: you can redistribute it and/or modify it
(at your option) any later version.
cl-ana 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 cl-ana. If not, see </>.
table-chain:
plist-table: | cl - ana is a Common Lisp data analysis library .
Copyright 2013 , 2014
This file is part of cl - ana .
under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
You may contact ( me ! ) via email at
(defpackage #:cl-ana.table
(:use #:cl
#:alexandria
#:cl-ana.list-utils
#:cl-ana.macro-utils
#:cl-ana.string-utils
#:cl-ana.symbol-utils
#:cl-ana.functional-utils)
(:export :table
:table-open-p
:table-field-names
:table-access-mode
:table-field-symbols
:table-load-next-row
:table-activate-fields
:table-get-field
:table-set-field
:table-push-fields
:table-commit-row
:table-close
:table-nrows
:do-table
:table-reduce
:open-table-chain
:reset-table-chain
:plist-table-plists
:open-plist-table
:create-plist-table))
|
21eaa2329e5428486058e1208bb015b66f337bf3b611f4f2f206595eddfa5891 | janestreet/merlin-jst | magic_numbers.ml | open Std
module Cmi = struct
type error =
| Not_an_interface of string
| Wrong_version_interface of string * string
| Corrupted_interface of string
exception Error of error
let to_version_opt = function
| "Caml1999I017" -> Some "4.02"
| "Caml1999I020" -> Some "4.03"
| "Caml1999I021" -> Some "4.04 or 4.05"
| "Caml1999I022" -> Some "4.06"
| "Caml1999I023" -> Some "4.07.0"
| "Caml1999I024" -> Some "4.07.1"
| "Caml1999I025" -> Some "4.08"
| "Caml1999I026" -> Some "4.09"
| "Caml1999I027" -> Some "4.10"
| "Caml1999I028" -> Some "4.11"
| "Caml1999I029" | "Caml1999I500" -> Some "4.12"
| "Caml1999I030" -> Some "4.13"
| "Caml1999I031" | "Caml1999I501" -> Some "4.14"
| _ -> None
open Format
let report_error ppf = function
| Not_an_interface filename ->
fprintf ppf "%a@ is not a compiled interface"
Location.print_filename filename
| Wrong_version_interface (filename, compiler_magic) ->
begin match to_version_opt compiler_magic with
| None ->
fprintf ppf
"%a@ seems to be compiled with a version of OCaml (with magic number \
%s) that is not supported by Merlin.@.\
This instance of Merlin handles OCaml %s."
Location.print_filename filename
compiler_magic
(Option.get @@ to_version_opt Config.cmi_magic_number)
| Some version ->
fprintf ppf
"%a@ seems to be compiled with OCaml %s.@.\
But this instance of Merlin handles OCaml %s."
Location.print_filename filename
version
(Option.get @@ to_version_opt Config.cmi_magic_number)
end
| Corrupted_interface filename ->
fprintf ppf
"Corrupted compiled interface@ %a"
Location.print_filename filename
let () =
Location.register_error_of_exn
(function
| Error err -> Some (Location.error_of_printer_file report_error err)
| _ -> None
)
end
| null | https://raw.githubusercontent.com/janestreet/merlin-jst/9c3b60c98d80b56af18ea95c27a0902f0244659a/src/ocaml/typing/magic_numbers.ml | ocaml | open Std
module Cmi = struct
type error =
| Not_an_interface of string
| Wrong_version_interface of string * string
| Corrupted_interface of string
exception Error of error
let to_version_opt = function
| "Caml1999I017" -> Some "4.02"
| "Caml1999I020" -> Some "4.03"
| "Caml1999I021" -> Some "4.04 or 4.05"
| "Caml1999I022" -> Some "4.06"
| "Caml1999I023" -> Some "4.07.0"
| "Caml1999I024" -> Some "4.07.1"
| "Caml1999I025" -> Some "4.08"
| "Caml1999I026" -> Some "4.09"
| "Caml1999I027" -> Some "4.10"
| "Caml1999I028" -> Some "4.11"
| "Caml1999I029" | "Caml1999I500" -> Some "4.12"
| "Caml1999I030" -> Some "4.13"
| "Caml1999I031" | "Caml1999I501" -> Some "4.14"
| _ -> None
open Format
let report_error ppf = function
| Not_an_interface filename ->
fprintf ppf "%a@ is not a compiled interface"
Location.print_filename filename
| Wrong_version_interface (filename, compiler_magic) ->
begin match to_version_opt compiler_magic with
| None ->
fprintf ppf
"%a@ seems to be compiled with a version of OCaml (with magic number \
%s) that is not supported by Merlin.@.\
This instance of Merlin handles OCaml %s."
Location.print_filename filename
compiler_magic
(Option.get @@ to_version_opt Config.cmi_magic_number)
| Some version ->
fprintf ppf
"%a@ seems to be compiled with OCaml %s.@.\
But this instance of Merlin handles OCaml %s."
Location.print_filename filename
version
(Option.get @@ to_version_opt Config.cmi_magic_number)
end
| Corrupted_interface filename ->
fprintf ppf
"Corrupted compiled interface@ %a"
Location.print_filename filename
let () =
Location.register_error_of_exn
(function
| Error err -> Some (Location.error_of_printer_file report_error err)
| _ -> None
)
end
| |
610c1f49fee8d20a8bcb957a97645bed5cb95ecb07d283c337b58ad50f31acdf | kuberlog/holon | compilers.lisp |
(defun is-clonable (link)
t)
(defun get-links (git-site)
;; unimplemented, looks like I never finished this...strange
'())
(defun go-to-AwesomeCompilers-github ()
(git-get "-compilers"))
(let ((links (filter #'is-clonable (get-links (go-to-AwesomeCompilers-github)))))
(for link in links do
(into-folder "/Users/kuberlog/compilers"
(clone link))))
| null | https://raw.githubusercontent.com/kuberlog/holon/91e01d404e25353592590c3c1b8d0ed72bb7afd7/lisp/compilers.lisp | lisp | unimplemented, looks like I never finished this...strange |
(defun is-clonable (link)
t)
(defun get-links (git-site)
'())
(defun go-to-AwesomeCompilers-github ()
(git-get "-compilers"))
(let ((links (filter #'is-clonable (get-links (go-to-AwesomeCompilers-github)))))
(for link in links do
(into-folder "/Users/kuberlog/compilers"
(clone link))))
|
29e1f790eba0118d6e11ac2b5d8824eba52476ba124ae8e18d339205731097d5 | sshirokov/CLSQL | sqlite3-package.lisp | -*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Base : 10 -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
Name :
Purpose : Package definition for low - level SQLite3 interface
Programmer :
Date Started : Oct 2004
;;;;
This file , part of CLSQL , is Copyright ( c ) 2004 by
;;;;
CLSQL users are granted the rights to distribute and use this software
as governed by the terms of the Lisp Lesser GNU Public License
;;;; (), also known as the LLGPL.
;;;; *************************************************************************
(in-package #:cl-user)
(defpackage #:clsql-sqlite3
(:use #:common-lisp #:clsql-sys)
(:export #:sqlite3-database))
| null | https://raw.githubusercontent.com/sshirokov/CLSQL/c680432aea0177677ae2ee7b810a7404f7a05cab/db-sqlite3/sqlite3-package.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 -*-
*************************************************************************
FILE IDENTIFICATION
(), also known as the LLGPL.
************************************************************************* | Name :
Purpose : Package definition for low - level SQLite3 interface
Programmer :
Date Started : Oct 2004
This file , part of CLSQL , is Copyright ( c ) 2004 by
CLSQL users are granted the rights to distribute and use this software
as governed by the terms of the Lisp Lesser GNU Public License
(in-package #:cl-user)
(defpackage #:clsql-sqlite3
(:use #:common-lisp #:clsql-sys)
(:export #:sqlite3-database))
|
7eb1cd7cf158f31391c5aac3d22fcc5524900af04662a276557d0d055d1ca3ee | triffon/fp-2022-23 | 12-triangular.rkt | #lang racket
(define (starts-with-n? lst n element)
(or
(< n 1)
(and
(not (null? lst))
(equal? (car lst) element)
(starts-with-n? (cdr lst) (- n 1) element))))
(define (triangular? matrix)
(define (helper index current-matrix)
(or
(null? current-matrix)
(and
(not (null? current-matrix))
(starts-with-n? (car current-matrix) index 0)
(helper (+ index 1) (cdr current-matrix)))))
(helper 0 matrix)) | null | https://raw.githubusercontent.com/triffon/fp-2022-23/0698febf5bde7dd2b819acde64958acb7d2e97fb/exercises/inf2/07/12-triangular.rkt | racket | #lang racket
(define (starts-with-n? lst n element)
(or
(< n 1)
(and
(not (null? lst))
(equal? (car lst) element)
(starts-with-n? (cdr lst) (- n 1) element))))
(define (triangular? matrix)
(define (helper index current-matrix)
(or
(null? current-matrix)
(and
(not (null? current-matrix))
(starts-with-n? (car current-matrix) index 0)
(helper (+ index 1) (cdr current-matrix)))))
(helper 0 matrix)) | |
6501ba472ca1a7108912fab66041afadfbc147ed83ffdf9dc33aaa1cbb15ce69 | typedclojure/typedclojure | main.clj | Copyright ( c ) , contributors .
;; 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 typed.clojure.main
(:require [clojure.core.typed.errors :as err]
[clojure.edn :as edn]
[clojure.tools.namespace.repl :as-alias repl]
[nextjournal.beholder :as-alias beholder]
[babashka.process :as-alias process]
[typed.clojure :as t]
[typed.cljc.dir :as tdir]
[clojure.core.typed.current-impl :as impl]
[typed.cljc.checker.ns-deps-utils :as ns-depsu]))
(defn- dynavar [sym]
(doto (requiring-resolve sym)
(assert (str "Unresolable: " (pr-str sym)))))
Algorithm By
(defn- partition-fairly
"Partition coll into n chunks such that each chunk's
count is within one of eachother. Puts its larger chunks first.
Returns a vector of chunks (vectors)."
[n coll]
{:pre [(vector? coll)
(integer? n)]
:post [(or (empty? %)
(let [fc (count (first %))]
(every? #{fc (dec fc)} (map count %))))
(= coll (apply concat %))]}
TODO make lazier ( use partition with overlapping steps to iterate
; over `indices`)
(let [q (quot (count coll) n)
r (rem (count coll) n)
indices (mapv #(+ (* q %)
(min % r))
(range (inc n)))]
(mapv #(subvec coll
(indices %)
(indices (inc %)))
(range n))))
(defn- nses-for-this-split [[this-split num-splits] nses]
(nth (partition-fairly num-splits nses) this-split))
(defn- print-error [^Throwable e]
(if (some-> (ex-data e) err/top-level-error?)
(print (.getMessage e))
(print e))
(flush))
(defn- exec1 [{:keys [split dirs focus platform watch] :or {platform :clj split [0 1]}}]
(let [focus (cond-> focus
(symbol? focus) vector)
platforms (sort (cond-> platform
(keyword? platform) vector))
_ (assert (seq platforms) (str "Must provide at least one platform: " (pr-str platform)))
plan (mapcat (fn [platform]
(map (fn [nsym]
{:platform platform
:nsym nsym})
(nses-for-this-split
split
(or focus
(:nses
(impl/with-impl (case platform
:clj :clojure
:cljs :cljs)
(tdir/check-dir-plan dirs)))))))
platforms)]
(assert (seq plan) "No namespaces to check")
(reduce (fn [acc {:keys [platform nsym] :as info}]
{:pre [(map? info)
(keyword? platform)
(simple-symbol? nsym)
(= :ok (:result acc))]}
(let [chk #((case platform
:clj t/check-ns-clj
:cljs t/check-ns-cljs)
nsym)
res (try (chk)
(assoc info :result :ok)
(catch Throwable e
(assoc info :result :fail :ex e)))
acc (-> acc
(update :checks (fnil conj []) res)
(cond-> (not= :ok (:result res)) (into res)))]
(cond-> acc
(not= :ok (:result acc)) reduced)))
{:result :ok} plan)))
(defn- watch [{:keys [dirs refresh refresh-dirs watch-dirs] :as m}]
(let [refresh (or refresh refresh-dirs)
watch-dirs (concat watch-dirs dirs refresh-dirs)
refresh-dirs (or refresh-dirs dirs)
dirs (cond-> dirs
(string? dirs) vector)
_ (assert (seq dirs) "Must provide directories to scan")
_ (when refresh
(alter-var-root (dynavar `repl/refresh-dirs)
(fn [old]
(or (not-empty old)
refresh-dirs))))
rescan (atom (promise))
watcher (apply (dynavar `beholder/watch)
(fn [{:keys [type path]}]
(when (contains? #{:modify :create} type)
(deliver @rescan true)))
watch-dirs)]
(try (loop [last-result (exec1 m)]
(when (= :fail (:result last-result))
(println "[watch] Caught error")
(print-error (:ex last-result))
(println))
(reset! rescan (promise))
@@rescan
TODO easy special case : do n't refresh if the scan - dirs says only the currently focussed ( ie . , failing ) namespace changed
(when refresh
(let [res ((dynavar `repl/refresh-all))] ;; refresh-all to undo check-ns making namespaces stale
(when-not (= :ok res)
(println "[watch] refresh failed")
(println res))))
(recur (exec1 (cond-> m
(and (= :fail (:status last-result))
;; don't focus if deleted
(ns-depsu/should-check-ns? (:nsym last-result)))
(assoc :focus (:nsym last-result)
:platform (:platform last-result))))))
(finally ((dynavar `beholder/stop) watcher)))))
(defn exec
"Type check namespaces. Plural options may be provided as a vector.
:dirs string(s) naming directories to find namespaces to type check
:focus symbol(s) naming namespaces to type check (overrides :dirs) (default: nil)
:platform platform(s) to check: :clj{s} (default: :clj)
:refresh if true (or if :refresh-dirs option is provided) refresh with tools.namespace before rechecking (default: nil)
:refresh-dirs string(s) naming directories to refresh if repl/refresh-dirs is empty. (default: use :dirs)
:watch if true, recheck on changes to :watch-dirs.
:watch-dirs string(s) naming extra directories to watch to trigger rechecking. (default: use :dirs + :refresh-dirs)
:split a pair [this-split num-splits]. Evenly and deterministically split checkable namespaces into num-splits segments, then
check this-split segment (zero-based).
eg., [0 1] ;; check everything
check the first half of all namespaces
check the second half of all namespaces
check the 3rd split of 5 splits
(default: [0 1])
:shell-command shell command to parallelize via :parallel option (default: \"bin/typed\")
:parallel evenly parallelize :exec-command to check namespaces using GNU Parallel.
In combination with :split, assumes all splits have same parallelism."
[{:keys [parallel shell-command] :or {shell-command "bin/typed"} :as m}]
(cond
parallel (let [_ (assert (pos-int? parallel) (str ":parallel must be a positive integer, given: " (pr-str)))
[this-split num-splits] (or (:split m) [0 1])]
(require 'babashka.process.pprint)
(run! (dynavar `process/check)
((dynavar `process/pipeline)
((dynavar `process/pb)
(vec (cons "echo" (map (fn [parallel-split]
(pr-str (-> m
(dissoc :parallel)
(assoc :split [(+ this-split parallel-split)
(* num-splits parallel)]))))
(range parallel)))))
((dynavar `process/pb)
["parallel" "--halt" "now,fail=1" (str shell-command " {}")]
;; hmm this isn't working.
{:out :inherit
:err :inherit}))))
(:watch m) (watch m)
:else (let [{:keys [result ex]} (exec1 m)]
(if (= :fail result)
(throw ex)
result))))
(defn -main
"Same args as exec."
[& args]
(let [{:as m} (map edn/read-string args)]
(try (exec m)
(System/exit 0)
(catch Throwable e
(print-error e)
(System/exit 1)))))
(comment
(exec {:dirs "src"})
(-main ":dirs" "[\"typed\"]")
)
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/7e6173e16db6de40de45fd1ce8e12072281a84f0/typed/clj.checker/src/typed/clojure/main.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
over `indices`)
refresh-all to undo check-ns making namespaces stale
don't focus if deleted
check everything
hmm this isn't working. | Copyright ( c ) , contributors .
(ns typed.clojure.main
(:require [clojure.core.typed.errors :as err]
[clojure.edn :as edn]
[clojure.tools.namespace.repl :as-alias repl]
[nextjournal.beholder :as-alias beholder]
[babashka.process :as-alias process]
[typed.clojure :as t]
[typed.cljc.dir :as tdir]
[clojure.core.typed.current-impl :as impl]
[typed.cljc.checker.ns-deps-utils :as ns-depsu]))
(defn- dynavar [sym]
(doto (requiring-resolve sym)
(assert (str "Unresolable: " (pr-str sym)))))
Algorithm By
(defn- partition-fairly
"Partition coll into n chunks such that each chunk's
count is within one of eachother. Puts its larger chunks first.
Returns a vector of chunks (vectors)."
[n coll]
{:pre [(vector? coll)
(integer? n)]
:post [(or (empty? %)
(let [fc (count (first %))]
(every? #{fc (dec fc)} (map count %))))
(= coll (apply concat %))]}
TODO make lazier ( use partition with overlapping steps to iterate
(let [q (quot (count coll) n)
r (rem (count coll) n)
indices (mapv #(+ (* q %)
(min % r))
(range (inc n)))]
(mapv #(subvec coll
(indices %)
(indices (inc %)))
(range n))))
(defn- nses-for-this-split [[this-split num-splits] nses]
(nth (partition-fairly num-splits nses) this-split))
(defn- print-error [^Throwable e]
(if (some-> (ex-data e) err/top-level-error?)
(print (.getMessage e))
(print e))
(flush))
(defn- exec1 [{:keys [split dirs focus platform watch] :or {platform :clj split [0 1]}}]
(let [focus (cond-> focus
(symbol? focus) vector)
platforms (sort (cond-> platform
(keyword? platform) vector))
_ (assert (seq platforms) (str "Must provide at least one platform: " (pr-str platform)))
plan (mapcat (fn [platform]
(map (fn [nsym]
{:platform platform
:nsym nsym})
(nses-for-this-split
split
(or focus
(:nses
(impl/with-impl (case platform
:clj :clojure
:cljs :cljs)
(tdir/check-dir-plan dirs)))))))
platforms)]
(assert (seq plan) "No namespaces to check")
(reduce (fn [acc {:keys [platform nsym] :as info}]
{:pre [(map? info)
(keyword? platform)
(simple-symbol? nsym)
(= :ok (:result acc))]}
(let [chk #((case platform
:clj t/check-ns-clj
:cljs t/check-ns-cljs)
nsym)
res (try (chk)
(assoc info :result :ok)
(catch Throwable e
(assoc info :result :fail :ex e)))
acc (-> acc
(update :checks (fnil conj []) res)
(cond-> (not= :ok (:result res)) (into res)))]
(cond-> acc
(not= :ok (:result acc)) reduced)))
{:result :ok} plan)))
(defn- watch [{:keys [dirs refresh refresh-dirs watch-dirs] :as m}]
(let [refresh (or refresh refresh-dirs)
watch-dirs (concat watch-dirs dirs refresh-dirs)
refresh-dirs (or refresh-dirs dirs)
dirs (cond-> dirs
(string? dirs) vector)
_ (assert (seq dirs) "Must provide directories to scan")
_ (when refresh
(alter-var-root (dynavar `repl/refresh-dirs)
(fn [old]
(or (not-empty old)
refresh-dirs))))
rescan (atom (promise))
watcher (apply (dynavar `beholder/watch)
(fn [{:keys [type path]}]
(when (contains? #{:modify :create} type)
(deliver @rescan true)))
watch-dirs)]
(try (loop [last-result (exec1 m)]
(when (= :fail (:result last-result))
(println "[watch] Caught error")
(print-error (:ex last-result))
(println))
(reset! rescan (promise))
@@rescan
TODO easy special case : do n't refresh if the scan - dirs says only the currently focussed ( ie . , failing ) namespace changed
(when refresh
(when-not (= :ok res)
(println "[watch] refresh failed")
(println res))))
(recur (exec1 (cond-> m
(and (= :fail (:status last-result))
(ns-depsu/should-check-ns? (:nsym last-result)))
(assoc :focus (:nsym last-result)
:platform (:platform last-result))))))
(finally ((dynavar `beholder/stop) watcher)))))
(defn exec
"Type check namespaces. Plural options may be provided as a vector.
:dirs string(s) naming directories to find namespaces to type check
:focus symbol(s) naming namespaces to type check (overrides :dirs) (default: nil)
:platform platform(s) to check: :clj{s} (default: :clj)
:refresh if true (or if :refresh-dirs option is provided) refresh with tools.namespace before rechecking (default: nil)
:refresh-dirs string(s) naming directories to refresh if repl/refresh-dirs is empty. (default: use :dirs)
:watch if true, recheck on changes to :watch-dirs.
:watch-dirs string(s) naming extra directories to watch to trigger rechecking. (default: use :dirs + :refresh-dirs)
:split a pair [this-split num-splits]. Evenly and deterministically split checkable namespaces into num-splits segments, then
check this-split segment (zero-based).
check the first half of all namespaces
check the second half of all namespaces
check the 3rd split of 5 splits
(default: [0 1])
:shell-command shell command to parallelize via :parallel option (default: \"bin/typed\")
:parallel evenly parallelize :exec-command to check namespaces using GNU Parallel.
In combination with :split, assumes all splits have same parallelism."
[{:keys [parallel shell-command] :or {shell-command "bin/typed"} :as m}]
(cond
parallel (let [_ (assert (pos-int? parallel) (str ":parallel must be a positive integer, given: " (pr-str)))
[this-split num-splits] (or (:split m) [0 1])]
(require 'babashka.process.pprint)
(run! (dynavar `process/check)
((dynavar `process/pipeline)
((dynavar `process/pb)
(vec (cons "echo" (map (fn [parallel-split]
(pr-str (-> m
(dissoc :parallel)
(assoc :split [(+ this-split parallel-split)
(* num-splits parallel)]))))
(range parallel)))))
((dynavar `process/pb)
["parallel" "--halt" "now,fail=1" (str shell-command " {}")]
{:out :inherit
:err :inherit}))))
(:watch m) (watch m)
:else (let [{:keys [result ex]} (exec1 m)]
(if (= :fail result)
(throw ex)
result))))
(defn -main
"Same args as exec."
[& args]
(let [{:as m} (map edn/read-string args)]
(try (exec m)
(System/exit 0)
(catch Throwable e
(print-error e)
(System/exit 1)))))
(comment
(exec {:dirs "src"})
(-main ":dirs" "[\"typed\"]")
)
|
0746de9472b74ac4d15d72bb42485cf211bc2f6107f9020ea8c50ab67a81016c | Ptival/chick | Test.hs | module Inductive.Inductive.Test where
import Examples.Utils
import Language
import PrettyPrinting.Chick ()
import StandardLibrary
import Test.Tasty
import TestUtils
equalityChecks :: [TestTree]
equalityChecks =
[equalityCheck @'Chick ind | ind <- inductives]
inequalityChecks :: [TestTree]
inequalityChecks =
[inequalityCheck @'Chick ind1 ind2 | (ind1, ind2) <- distinctPairs inductives]
unitTests :: TestTree
unitTests =
testGroup "Inductive.Inductive" $
[]
++ equalityChecks
++ inequalityChecks
test :: IO ()
test = defaultMain unitTests
| null | https://raw.githubusercontent.com/Ptival/chick/a5ce39a842ff72348f1c9cea303997d5300163e2/backend/test/Inductive/Inductive/Test.hs | haskell | module Inductive.Inductive.Test where
import Examples.Utils
import Language
import PrettyPrinting.Chick ()
import StandardLibrary
import Test.Tasty
import TestUtils
equalityChecks :: [TestTree]
equalityChecks =
[equalityCheck @'Chick ind | ind <- inductives]
inequalityChecks :: [TestTree]
inequalityChecks =
[inequalityCheck @'Chick ind1 ind2 | (ind1, ind2) <- distinctPairs inductives]
unitTests :: TestTree
unitTests =
testGroup "Inductive.Inductive" $
[]
++ equalityChecks
++ inequalityChecks
test :: IO ()
test = defaultMain unitTests
| |
bc827081264d191b086a64a43d03a73933087d9c85d4f9c6086b66d2dca582c3 | expipiplus1/vulkan | Promoted_From_VK_KHR_vulkan_memory_model.hs | {-# language CPP #-}
No documentation found for Chapter " Promoted_From_VK_KHR_vulkan_memory_model "
module Vulkan.Core12.Promoted_From_VK_KHR_vulkan_memory_model ( PhysicalDeviceVulkanMemoryModelFeatures(..)
, StructureType(..)
) where
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Foreign.Ptr (Ptr)
import Data.Kind (Type)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES))
import Vulkan.Core10.Enums.StructureType (StructureType(..))
-- | VkPhysicalDeviceVulkanMemoryModelFeatures - Structure describing
-- features supported by the memory model
--
-- = Members
--
-- This structure describes the following features:
--
-- = Description
--
-- If the
' Vulkan . Extensions . VK_KHR_vulkan_memory_model . PhysicalDeviceVulkanMemoryModelFeaturesKHR '
-- structure is included in the @pNext@ chain of the
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 '
-- structure passed to
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2 ' ,
-- it is filled in to indicate whether each corresponding feature is
-- supported.
' Vulkan . Extensions . VK_KHR_vulkan_memory_model . PhysicalDeviceVulkanMemoryModelFeaturesKHR '
-- /can/ also be used in the @pNext@ chain of
' Vulkan . Core10.Device . DeviceCreateInfo ' to selectively enable these
-- features.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
< -extensions/html/vkspec.html#VK_VERSION_1_2 VK_VERSION_1_2 > ,
' Vulkan . Core10.FundamentalTypes . Bool32 ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data PhysicalDeviceVulkanMemoryModelFeatures = PhysicalDeviceVulkanMemoryModelFeatures
{ -- | #extension-features-vulkanMemoryModel# @vulkanMemoryModel@ indicates
whether the Vulkan Memory Model is supported , as defined in
-- <-extensions/html/vkspec.html#memory-model Vulkan Memory Model>.
This also indicates whether shader modules declare the
-- @VulkanMemoryModel@ capability.
vulkanMemoryModel :: Bool
, -- | #extension-features-vulkanMemoryModelDeviceScope#
-- @vulkanMemoryModelDeviceScope@ indicates whether the Vulkan Memory Model
can use ' Vulkan . Core10.Handles . Device ' scope synchronization . This also
indicates whether shader modules declare the
-- @VulkanMemoryModelDeviceScope@ capability.
vulkanMemoryModelDeviceScope :: Bool
, -- | #extension-features-vulkanMemoryModelAvailabilityVisibilityChains#
-- @vulkanMemoryModelAvailabilityVisibilityChains@ indicates whether the
Vulkan Memory Model can use
-- <-extensions/html/vkspec.html#memory-model-availability-visibility availability and visibility chains>
with more than one element .
vulkanMemoryModelAvailabilityVisibilityChains :: Bool
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceVulkanMemoryModelFeatures)
#endif
deriving instance Show PhysicalDeviceVulkanMemoryModelFeatures
instance ToCStruct PhysicalDeviceVulkanMemoryModelFeatures where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceVulkanMemoryModelFeatures{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (vulkanMemoryModel))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (vulkanMemoryModelDeviceScope))
poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (vulkanMemoryModelAvailabilityVisibilityChains))
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDeviceVulkanMemoryModelFeatures where
peekCStruct p = do
vulkanMemoryModel <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
vulkanMemoryModelDeviceScope <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
vulkanMemoryModelAvailabilityVisibilityChains <- peek @Bool32 ((p `plusPtr` 24 :: Ptr Bool32))
pure $ PhysicalDeviceVulkanMemoryModelFeatures
(bool32ToBool vulkanMemoryModel)
(bool32ToBool vulkanMemoryModelDeviceScope)
(bool32ToBool vulkanMemoryModelAvailabilityVisibilityChains)
instance Storable PhysicalDeviceVulkanMemoryModelFeatures where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceVulkanMemoryModelFeatures where
zero = PhysicalDeviceVulkanMemoryModelFeatures
zero
zero
zero
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/src/Vulkan/Core12/Promoted_From_VK_KHR_vulkan_memory_model.hs | haskell | # language CPP #
| VkPhysicalDeviceVulkanMemoryModelFeatures - Structure describing
features supported by the memory model
= Members
This structure describes the following features:
= Description
If the
structure is included in the @pNext@ chain of the
structure passed to
it is filled in to indicate whether each corresponding feature is
supported.
/can/ also be used in the @pNext@ chain of
features.
== Valid Usage (Implicit)
= See Also
| #extension-features-vulkanMemoryModel# @vulkanMemoryModel@ indicates
<-extensions/html/vkspec.html#memory-model Vulkan Memory Model>.
@VulkanMemoryModel@ capability.
| #extension-features-vulkanMemoryModelDeviceScope#
@vulkanMemoryModelDeviceScope@ indicates whether the Vulkan Memory Model
@VulkanMemoryModelDeviceScope@ capability.
| #extension-features-vulkanMemoryModelAvailabilityVisibilityChains#
@vulkanMemoryModelAvailabilityVisibilityChains@ indicates whether the
<-extensions/html/vkspec.html#memory-model-availability-visibility availability and visibility chains> | No documentation found for Chapter " Promoted_From_VK_KHR_vulkan_memory_model "
module Vulkan.Core12.Promoted_From_VK_KHR_vulkan_memory_model ( PhysicalDeviceVulkanMemoryModelFeatures(..)
, StructureType(..)
) where
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Foreign.Ptr (Ptr)
import Data.Kind (Type)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES))
import Vulkan.Core10.Enums.StructureType (StructureType(..))
' Vulkan . Extensions . VK_KHR_vulkan_memory_model . PhysicalDeviceVulkanMemoryModelFeaturesKHR '
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2 '
' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2 ' ,
' Vulkan . Extensions . VK_KHR_vulkan_memory_model . PhysicalDeviceVulkanMemoryModelFeaturesKHR '
' Vulkan . Core10.Device . DeviceCreateInfo ' to selectively enable these
< -extensions/html/vkspec.html#VK_VERSION_1_2 VK_VERSION_1_2 > ,
' Vulkan . Core10.FundamentalTypes . Bool32 ' ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data PhysicalDeviceVulkanMemoryModelFeatures = PhysicalDeviceVulkanMemoryModelFeatures
whether the Vulkan Memory Model is supported , as defined in
This also indicates whether shader modules declare the
vulkanMemoryModel :: Bool
can use ' Vulkan . Core10.Handles . Device ' scope synchronization . This also
indicates whether shader modules declare the
vulkanMemoryModelDeviceScope :: Bool
Vulkan Memory Model can use
with more than one element .
vulkanMemoryModelAvailabilityVisibilityChains :: Bool
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceVulkanMemoryModelFeatures)
#endif
deriving instance Show PhysicalDeviceVulkanMemoryModelFeatures
instance ToCStruct PhysicalDeviceVulkanMemoryModelFeatures where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceVulkanMemoryModelFeatures{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (vulkanMemoryModel))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (vulkanMemoryModelDeviceScope))
poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (vulkanMemoryModelAvailabilityVisibilityChains))
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDeviceVulkanMemoryModelFeatures where
peekCStruct p = do
vulkanMemoryModel <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
vulkanMemoryModelDeviceScope <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
vulkanMemoryModelAvailabilityVisibilityChains <- peek @Bool32 ((p `plusPtr` 24 :: Ptr Bool32))
pure $ PhysicalDeviceVulkanMemoryModelFeatures
(bool32ToBool vulkanMemoryModel)
(bool32ToBool vulkanMemoryModelDeviceScope)
(bool32ToBool vulkanMemoryModelAvailabilityVisibilityChains)
instance Storable PhysicalDeviceVulkanMemoryModelFeatures where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceVulkanMemoryModelFeatures where
zero = PhysicalDeviceVulkanMemoryModelFeatures
zero
zero
zero
|
167df70f5a727c0593756ca45b9eaac33c2411498ab4ba5ead65513d7e81ffbe | helpshift/mongrove | query_test.clj | (ns mongrove.query-test
(:require
[clojure.string :as cs]
[clojure.test :refer :all]
[mongrove.core :as mc]))
(def shared-connection (atom nil))
(defn- init-connection-fixture
"This will run once before tests are executed
and will initialise a connection into the shared-connection atom"
[tests]
(let [c (mc/connect :replica-set [{:host "localhost"
:port 27017}])]
(reset! shared-connection c)
(tests)))
(defn- before-each-test
[]
nil)
(defn- after-each-test
"Clean up any test data that we might create.
Note : All test data should be created under databases starting with `test-db`"
[]
(let [dbs (mc/get-database-names @shared-connection)
test-dbs (filter #(cs/starts-with? % "test-db") dbs)]
(doseq [db test-dbs]
(mc/drop-database (mc/get-db @shared-connection db)))))
(defn each-fixture
[tests]
(before-each-test)
(tests)
(after-each-test))
(use-fixtures :once (join-fixtures [init-connection-fixture each-fixture]))
(deftest fetch-one-test
(testing "Get any document"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [db-doc (mc/fetch-one db coll {})]
(is ((set docs) db-doc)))))
(testing "Get a particular document"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(mc/insert db coll {:name "harry"
:age 100
:city "knowhere"
:country "rohan"})
(let [db-doc (mc/fetch-one db coll {:age {:$gt 60}})]
(is (= {:name "harry"
:age 100
:city "knowhere"
:country "rohan"}
db-doc)))))
(testing "Get a particular document with some fields"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(mc/insert db coll {:name "harry"
:age 100
:city "knowhere"
:country "rohan"})
(let [db-doc (mc/fetch-one db coll {:age {:$gt 60}} :only [:name])
another-doc (mc/fetch-one db coll {:age {:$lt 60}} :exclude [:name])
yet-another-doc (mc/fetch-one db coll {:age {:$lt 60}}
:only [:age :city]
:exclude [:age])] ;; :only takes precedence
(is (= {:name "harry"} db-doc))
(is (= (set (keys another-doc)) #{:age :city :country}))
(is (= (set (keys yet-another-doc)) #{:age :city}))))))
(deftest query-test
(testing "Query all documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [db-docs (mc/query db coll {})]
(is (= 10 (count db-docs)))
(is (= docs db-docs)))))
(testing "Get documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
query-docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (+ 100 (rand-int 40))
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(mc/insert db coll query-docs :multi? true :write-concern :majority)
(mc/insert db coll {:name "harry"
:age 100
:city "knowhere"
:country "rohan"})
(let [db-doc (mc/query db coll {:name "harry"})
queried-docs (mc/query db coll {:age {:$gte 100}})]
(is (= {:name "harry"
:age 100
:city "knowhere"
:country "rohan"}
(first db-doc)))
(is (= query-docs queried-docs)))))
(testing "Get documents with some fields"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(mc/insert db coll {:name "harry"
:age 100
:city "knowhere"
:country "rohan"})
(let [db-doc (mc/query db coll {:age {:$gt 60}} :only [:name])
other-docs (mc/query db coll {:age {:$lt 60}} :exclude [:name])
yet-another-doc (mc/query db coll {:age {:$lt 60}}
:only [:age :city]
:exclude [:age])] ;; :only takes precedence
(is (= 1 (count db-doc)))
(is (= 10 (count other-docs)))
(is (= {:name "harry"} (first db-doc)))
(doseq [d other-docs]
(is (= (set (keys d)) #{:age :city :country})))
(is (= (set (keys (first yet-another-doc))) #{:age :city}))))))
(deftest query-sort-test
(testing "Query documents with single field sort"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
@WARN Increasing the range here because
is the age value repeats , the sort of 2 entries
;; with equal values is not predictable in MongoDB
:age (rand-int 300)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
sorted-docs (sort #(compare (:age %1) (:age %2)) docs)
r-sorted-docs (reverse sorted-docs)
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [db-docs (mc/query db coll {} :sort-by {:age 1})
r-db-docs (mc/query db coll {} :sort-by {:age -1})]
(is (= db-docs sorted-docs))
(is (= r-db-docs r-sorted-docs))))))
(deftest query-limit-test
(testing "Get only some documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 300)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
sorted-docs (sort #(compare (:age %1) (:age %2))
(filter #(< 100 (:age %)) docs))
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [queried-docs (mc/query db coll {:age {:$gt 100}} :sort-by {:age 1} :limit 2)
one-doc (mc/query db coll {:age {:$gt 100}} :sort-by {:age 1} :one? true :limit 2)
skip-docs (mc/query db coll {:age {:$gt 100}} :sort-by {:age 1} :skip 2)]
(is (= (take 2 sorted-docs) queried-docs))
(is (= 1 (count one-doc)))
(is (= (first sorted-docs) (first one-doc)))
(is (= (drop 2 sorted-docs) skip-docs))))))
(deftest count-docs-test
(testing "Count documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [count-db-docs (mc/count-docs db coll {})]
(is (= 10 count-db-docs)))))
(testing "Count only some documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 300)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
filtered-docs (filter #(< 100 (:age %)) docs)
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [queried-docs-count (mc/count-docs db coll {:age {:$gt 100}})]
(is (= (count filtered-docs) queried-docs-count))))))
| null | https://raw.githubusercontent.com/helpshift/mongrove/85f4723d7a11a17bb1fcd344250b6b371e790331/test/mongrove/query_test.clj | clojure | :only takes precedence
:only takes precedence
with equal values is not predictable in MongoDB | (ns mongrove.query-test
(:require
[clojure.string :as cs]
[clojure.test :refer :all]
[mongrove.core :as mc]))
(def shared-connection (atom nil))
(defn- init-connection-fixture
"This will run once before tests are executed
and will initialise a connection into the shared-connection atom"
[tests]
(let [c (mc/connect :replica-set [{:host "localhost"
:port 27017}])]
(reset! shared-connection c)
(tests)))
(defn- before-each-test
[]
nil)
(defn- after-each-test
"Clean up any test data that we might create.
Note : All test data should be created under databases starting with `test-db`"
[]
(let [dbs (mc/get-database-names @shared-connection)
test-dbs (filter #(cs/starts-with? % "test-db") dbs)]
(doseq [db test-dbs]
(mc/drop-database (mc/get-db @shared-connection db)))))
(defn each-fixture
[tests]
(before-each-test)
(tests)
(after-each-test))
(use-fixtures :once (join-fixtures [init-connection-fixture each-fixture]))
(deftest fetch-one-test
(testing "Get any document"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [db-doc (mc/fetch-one db coll {})]
(is ((set docs) db-doc)))))
(testing "Get a particular document"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(mc/insert db coll {:name "harry"
:age 100
:city "knowhere"
:country "rohan"})
(let [db-doc (mc/fetch-one db coll {:age {:$gt 60}})]
(is (= {:name "harry"
:age 100
:city "knowhere"
:country "rohan"}
db-doc)))))
(testing "Get a particular document with some fields"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(mc/insert db coll {:name "harry"
:age 100
:city "knowhere"
:country "rohan"})
(let [db-doc (mc/fetch-one db coll {:age {:$gt 60}} :only [:name])
another-doc (mc/fetch-one db coll {:age {:$lt 60}} :exclude [:name])
yet-another-doc (mc/fetch-one db coll {:age {:$lt 60}}
:only [:age :city]
(is (= {:name "harry"} db-doc))
(is (= (set (keys another-doc)) #{:age :city :country}))
(is (= (set (keys yet-another-doc)) #{:age :city}))))))
(deftest query-test
(testing "Query all documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [db-docs (mc/query db coll {})]
(is (= 10 (count db-docs)))
(is (= docs db-docs)))))
(testing "Get documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
query-docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (+ 100 (rand-int 40))
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(mc/insert db coll query-docs :multi? true :write-concern :majority)
(mc/insert db coll {:name "harry"
:age 100
:city "knowhere"
:country "rohan"})
(let [db-doc (mc/query db coll {:name "harry"})
queried-docs (mc/query db coll {:age {:$gte 100}})]
(is (= {:name "harry"
:age 100
:city "knowhere"
:country "rohan"}
(first db-doc)))
(is (= query-docs queried-docs)))))
(testing "Get documents with some fields"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(mc/insert db coll {:name "harry"
:age 100
:city "knowhere"
:country "rohan"})
(let [db-doc (mc/query db coll {:age {:$gt 60}} :only [:name])
other-docs (mc/query db coll {:age {:$lt 60}} :exclude [:name])
yet-another-doc (mc/query db coll {:age {:$lt 60}}
:only [:age :city]
(is (= 1 (count db-doc)))
(is (= 10 (count other-docs)))
(is (= {:name "harry"} (first db-doc)))
(doseq [d other-docs]
(is (= (set (keys d)) #{:age :city :country})))
(is (= (set (keys (first yet-another-doc))) #{:age :city}))))))
(deftest query-sort-test
(testing "Query documents with single field sort"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
@WARN Increasing the range here because
is the age value repeats , the sort of 2 entries
:age (rand-int 300)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
sorted-docs (sort #(compare (:age %1) (:age %2)) docs)
r-sorted-docs (reverse sorted-docs)
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [db-docs (mc/query db coll {} :sort-by {:age 1})
r-db-docs (mc/query db coll {} :sort-by {:age -1})]
(is (= db-docs sorted-docs))
(is (= r-db-docs r-sorted-docs))))))
(deftest query-limit-test
(testing "Get only some documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 300)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
sorted-docs (sort #(compare (:age %1) (:age %2))
(filter #(< 100 (:age %)) docs))
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [queried-docs (mc/query db coll {:age {:$gt 100}} :sort-by {:age 1} :limit 2)
one-doc (mc/query db coll {:age {:$gt 100}} :sort-by {:age 1} :one? true :limit 2)
skip-docs (mc/query db coll {:age {:$gt 100}} :sort-by {:age 1} :skip 2)]
(is (= (take 2 sorted-docs) queried-docs))
(is (= 1 (count one-doc)))
(is (= (first sorted-docs) (first one-doc)))
(is (= (drop 2 sorted-docs) skip-docs))))))
(deftest count-docs-test
(testing "Count documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 60)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [count-db-docs (mc/count-docs db coll {})]
(is (= 10 count-db-docs)))))
(testing "Count only some documents"
(let [client @shared-connection
docs (for [_ (range 10)]
{:name (.toString (java.util.UUID/randomUUID))
:age (rand-int 300)
:city (.toString (java.util.UUID/randomUUID))
:country (.toString (java.util.UUID/randomUUID))})
filtered-docs (filter #(< 100 (:age %)) docs)
db (mc/get-db client (str "test-db-" (.toString (java.util.UUID/randomUUID))))
coll (str "test-coll-" (.toString (java.util.UUID/randomUUID)))]
(mc/insert db coll docs :multi? true :write-concern :majority)
(let [queried-docs-count (mc/count-docs db coll {:age {:$gt 100}})]
(is (= (count filtered-docs) queried-docs-count))))))
|
4e87047757255d999b3bfc1675f831a26544c82080f47ac4c09fc34ce95a76a0 | naveensundarg/prover | progc.lisp | ;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark-lisp -*-
;;; File: progc.lisp
The contents of this file are subject to the Mozilla Public License
;;; Version 1.1 (the "License"); you may not use this file except in
;;; compliance with the License. You may obtain a copy of the License at
;;; /
;;;
Software distributed under the License is distributed on an " AS IS "
;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
;;; License for the specific language governing rights and limitations
;;; under the License.
;;;
The Original Code is SNARK .
The Initial Developer of the Original Code is SRI International .
Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 .
All Rights Reserved .
;;;
Contributor(s ): < > .
(in-package :snark-lisp)
(defparameter *prog->-function-second-forms*
'(funcall apply map map-into))
(defparameter *prog->-special-forms*
'(
;; (pattern . forms)
((dolist list-form &rest l ->* var)
(dolist (var list-form . l)
(unnamed-prog-> . prog->-tail)))
((dotails list-form &rest l ->* var)
(dotails (var list-form . l)
(unnamed-prog-> . prog->-tail)))
((dopairs list-form &rest l ->* var1 var2)
(dopairs (var1 var2 list-form . l)
(unnamed-prog-> . prog->-tail)))
((dotimes count-form &rest l ->* var)
(dotimes (var count-form . l)
(unnamed-prog-> . prog->-tail)))
((identity form -> var)
(let ((var form))
(unnamed-prog-> . prog->-tail)))
))
(defun prog->*-function-second-form-p (fn)
(member fn *prog->-function-second-forms*))
(defun prog->-special-form (fn)
(assoc fn *prog->-special-forms* :key #'first))
(defun prog->-special-form-pattern (fn)
(car (prog->-special-form fn)))
(defun prog->-special-form-args (fn)
(rest (prog->-special-form-pattern fn)))
(defun prog->-special-form-result (fn)
(cdr (prog->-special-form fn)))
(defun prog->-special-form-match-error (form)
(error "~S doesn't match prog-> special form ~S."
form (prog->-special-form-pattern (first form))))
(defun prog->-no-variable-error (form)
(error "No variable to assign value to in (prog-> ... ~S ...)."
form))
(defun prog->-too-many-variables-error (form)
(error "More than one variable to assign value to in (prog-> ... ~S ...)." form))
(defun prog->-too-many->s-error (form)
(error "More than one -> in (prog-> ... ~S ...)." form))
(defun prog->-unrecognized->-atom (atom form)
(error "Unrecognized operation ~S in (prog-> ... ~S ...)." atom form))
(defun prog->-atom (x)
(and (symbolp x)
(<= 2 (length (string x)))
(string= x "->" :end1 2)))
(defun prog->*-function-argument (forms args)
(cond
((and (null (rest forms))
(consp (first forms))
(eq (caar forms) 'funcall)
(equal (cddar forms) args))
(cadar forms))
((and (null (rest forms))
(consp (first forms))
(not (#-(or lucid (and mcl (not openmcl))) special-operator-p
;; #-(or allegro lucid) special-form-p
# + allegro cltl1 : special - form - p
#+(and mcl (not openmcl)) special-form-p
#+lucid lisp:special-form-p
(caar forms)))
(not (macro-function (caar forms)))
(equal (cdar forms) args))
`(function ,(caar forms)))
(t
`(function (lambda ,args ,@forms)))))
(defun process-prog-> (forms)
(cond
((null forms)
nil)
(t
(let ((form (first forms)))
(cond
((not (consp form))
(cons form (process-prog-> (rest forms))))
(t
(let* ((args (rest form))
(x (member-if #'prog->-atom args)))
(cond
((null x)
(cons (case (first form) ;forms with explicit or implicit progn also get prog-> processing
((progn)
(process-prog->-progn (rest form)))
((block when unless let let* mvlet mvlet* catch)
(list* (first form)
(second form)
(process-prog-> (cddr form))))
((multiple-value-bind progv)
(list* (first form)
(second form)
(third form)
(process-prog-> (cdddr form))))
((cond)
(cons (first form)
(mapcar (lambda (x)
(cons (first x)
(process-prog-> (rest x))))
(rest form))))
((case ecase ccase typecase etypecase ctypecase)
(list* (first form)
(second form)
(mapcar (lambda (x)
(cons (first x)
(process-prog-> (rest x))))
(cddr form))))
((if)
(cl:assert (<= 3 (length form) 4))
(list (first form)
(second form)
(process-prog->-progn (list (third form)))
(process-prog->-progn (list (fourth form)))))
(otherwise
form))
(process-prog-> (rest forms))))
((prog->-special-form (first form))
(do ((formals (prog->-special-form-args (first form)) (rest formals))
(args args (rest args))
(alist (acons 'prog->-tail (rest forms) nil)))
(nil)
(cond
((and (endp formals) (endp args))
(return (sublis alist (prog->-special-form-result (first form)))))
((endp formals)
(prog->-special-form-match-error form))
((eq (first formals) '&rest)
(setf formals (rest formals))
(cond
((or (endp args) (prog->-atom (first args)))
(setf args (cons nil args))
(setf alist (acons (first formals) nil alist)))
(t
(setf alist (acons (first formals)
(loop collect (first args)
until (or (endp (rest args)) (prog->-atom (second args)))
do (pop args))
alist)))))
((endp args)
(prog->-special-form-match-error form))
((prog->-atom (first formals))
(unless (string= (string (first formals)) (string (first args)))
(prog->-special-form-match-error form)))
(t
(setf alist (acons (first formals) (first args) alist))))))
((member-if #'prog->-atom (rest x))
(prog->-too-many->s-error form))
(t
(let ((inputs (ldiff args x))
(outputs (rest x)))
(cond
((string= (string (first x)) "->*")
(let ((funarg (prog->*-function-argument (process-prog-> (rest forms)) outputs)))
(cond
((and (consp funarg)
(eq 'function (first funarg))
(consp (second funarg))
(eq 'lambda (first (second funarg))))
(let ((g (gensym)))
(list
`(flet ((,g ,@(rest (second funarg))))
(declare (dynamic-extent (function ,g)))
,@(prog->*-call form inputs `(function ,g))))))
(t
(prog->*-call form inputs funarg)))))
((null outputs)
(prog->-no-variable-error form))
((string= (string (first x)) "->")
(cond
((null (rest outputs))
(cond
((and (consp (first outputs))
(member (first (first outputs)) '(values list list* :values :list :list*)))
(list `(mvlet ((,(first outputs) (,(first form) ,@inputs)))
,@(process-prog-> (rest forms)))))
(t
(list `(let ((,(first outputs) (,(first form) ,@inputs)))
,@(process-prog-> (rest forms)))))))
(t
(list `(multiple-value-bind ,outputs
(,(first form) ,@inputs)
,@(process-prog-> (rest forms)))))))
((string= (string (first x)) (symbol-name :->nonnil))
(cond
((null (rest outputs))
(cond
((and (consp (first outputs))
(member (first (first outputs)) '(values list list* :values :list :list*)))
(list `(mvlet ((,(first outputs) (,(first form) ,@inputs)))
(when ,(first outputs)
,@(process-prog-> (rest forms))))))
(t
(list `(let ((,(first outputs) (,(first form) ,@inputs)))
(when ,(first outputs)
,@(process-prog-> (rest forms))))))))
(t
(list `(multiple-value-bind ,outputs
(,(first form) ,@inputs)
(when ,(first outputs)
,@(process-prog-> (rest forms))))))))
((rest outputs)
(prog->-too-many-variables-error form))
((string= (string (first x)) (symbol-name :->stack))
(list `(let ((,(first outputs) (,(first form) ,@inputs)))
(declare (dynamic-extent ,(first outputs)))
,@(process-prog-> (rest forms)))))
((string= (string (first x)) (symbol-name :->progv))
(list `(let ((!prog->temp1! (list (,(first form) ,@inputs)))
(!prog->temp2! (list ,(first outputs))))
(declare (dynamic-extent !prog->temp1! !prog->temp2!))
(progv !prog->temp2! !prog->temp1! ,@(process-prog-> (rest forms))))))
(t
(prog->-unrecognized->-atom (first x) form)))))))))))))
(defun prog->*-call (form inputs funarg)
(cond
((prog->*-function-second-form-p (first form))
(list `(,(first form) ,(first inputs) ,funarg ,@(rest inputs))))
(t
(list `(,(first form) ,funarg ,@inputs)))))
(defun wrap-progn (forms &optional no-simplification)
(cond
((and (null forms)
(not no-simplification))
nil)
((and (null (rest forms))
(not no-simplification))
(first forms))
(t
(cons 'progn forms))))
(defun wrap-block (name forms &optional no-simplification)
(cond
((and (null forms)
(not no-simplification))
nil)
(t
(list* 'block name forms))))
(defun process-prog->-progn (forms)
(wrap-progn (process-prog-> forms)))
(defun process-prog->-block (forms)
(wrap-block 'prog-> (process-prog-> forms)))
(defmacro unnamed-prog-> (&body forms)
(process-prog->-progn forms))
(defmacro prog-> (&body forms)
(process-prog->-block forms))
progc.lisp EOF
| null | https://raw.githubusercontent.com/naveensundarg/prover/812baf098d8bf77e4d634cef4d12de94dcd1e113/snark-20120808r02/src/progc.lisp | lisp | -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark-lisp -*-
File: progc.lisp
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
(pattern . forms)
#-(or allegro lucid) special-form-p
forms with explicit or implicit progn also get prog-> processing | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is SNARK .
The Initial Developer of the Original Code is SRI International .
Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 .
All Rights Reserved .
Contributor(s ): < > .
(in-package :snark-lisp)
(defparameter *prog->-function-second-forms*
'(funcall apply map map-into))
(defparameter *prog->-special-forms*
'(
((dolist list-form &rest l ->* var)
(dolist (var list-form . l)
(unnamed-prog-> . prog->-tail)))
((dotails list-form &rest l ->* var)
(dotails (var list-form . l)
(unnamed-prog-> . prog->-tail)))
((dopairs list-form &rest l ->* var1 var2)
(dopairs (var1 var2 list-form . l)
(unnamed-prog-> . prog->-tail)))
((dotimes count-form &rest l ->* var)
(dotimes (var count-form . l)
(unnamed-prog-> . prog->-tail)))
((identity form -> var)
(let ((var form))
(unnamed-prog-> . prog->-tail)))
))
(defun prog->*-function-second-form-p (fn)
(member fn *prog->-function-second-forms*))
(defun prog->-special-form (fn)
(assoc fn *prog->-special-forms* :key #'first))
(defun prog->-special-form-pattern (fn)
(car (prog->-special-form fn)))
(defun prog->-special-form-args (fn)
(rest (prog->-special-form-pattern fn)))
(defun prog->-special-form-result (fn)
(cdr (prog->-special-form fn)))
(defun prog->-special-form-match-error (form)
(error "~S doesn't match prog-> special form ~S."
form (prog->-special-form-pattern (first form))))
(defun prog->-no-variable-error (form)
(error "No variable to assign value to in (prog-> ... ~S ...)."
form))
(defun prog->-too-many-variables-error (form)
(error "More than one variable to assign value to in (prog-> ... ~S ...)." form))
(defun prog->-too-many->s-error (form)
(error "More than one -> in (prog-> ... ~S ...)." form))
(defun prog->-unrecognized->-atom (atom form)
(error "Unrecognized operation ~S in (prog-> ... ~S ...)." atom form))
(defun prog->-atom (x)
(and (symbolp x)
(<= 2 (length (string x)))
(string= x "->" :end1 2)))
(defun prog->*-function-argument (forms args)
(cond
((and (null (rest forms))
(consp (first forms))
(eq (caar forms) 'funcall)
(equal (cddar forms) args))
(cadar forms))
((and (null (rest forms))
(consp (first forms))
(not (#-(or lucid (and mcl (not openmcl))) special-operator-p
# + allegro cltl1 : special - form - p
#+(and mcl (not openmcl)) special-form-p
#+lucid lisp:special-form-p
(caar forms)))
(not (macro-function (caar forms)))
(equal (cdar forms) args))
`(function ,(caar forms)))
(t
`(function (lambda ,args ,@forms)))))
(defun process-prog-> (forms)
(cond
((null forms)
nil)
(t
(let ((form (first forms)))
(cond
((not (consp form))
(cons form (process-prog-> (rest forms))))
(t
(let* ((args (rest form))
(x (member-if #'prog->-atom args)))
(cond
((null x)
((progn)
(process-prog->-progn (rest form)))
((block when unless let let* mvlet mvlet* catch)
(list* (first form)
(second form)
(process-prog-> (cddr form))))
((multiple-value-bind progv)
(list* (first form)
(second form)
(third form)
(process-prog-> (cdddr form))))
((cond)
(cons (first form)
(mapcar (lambda (x)
(cons (first x)
(process-prog-> (rest x))))
(rest form))))
((case ecase ccase typecase etypecase ctypecase)
(list* (first form)
(second form)
(mapcar (lambda (x)
(cons (first x)
(process-prog-> (rest x))))
(cddr form))))
((if)
(cl:assert (<= 3 (length form) 4))
(list (first form)
(second form)
(process-prog->-progn (list (third form)))
(process-prog->-progn (list (fourth form)))))
(otherwise
form))
(process-prog-> (rest forms))))
((prog->-special-form (first form))
(do ((formals (prog->-special-form-args (first form)) (rest formals))
(args args (rest args))
(alist (acons 'prog->-tail (rest forms) nil)))
(nil)
(cond
((and (endp formals) (endp args))
(return (sublis alist (prog->-special-form-result (first form)))))
((endp formals)
(prog->-special-form-match-error form))
((eq (first formals) '&rest)
(setf formals (rest formals))
(cond
((or (endp args) (prog->-atom (first args)))
(setf args (cons nil args))
(setf alist (acons (first formals) nil alist)))
(t
(setf alist (acons (first formals)
(loop collect (first args)
until (or (endp (rest args)) (prog->-atom (second args)))
do (pop args))
alist)))))
((endp args)
(prog->-special-form-match-error form))
((prog->-atom (first formals))
(unless (string= (string (first formals)) (string (first args)))
(prog->-special-form-match-error form)))
(t
(setf alist (acons (first formals) (first args) alist))))))
((member-if #'prog->-atom (rest x))
(prog->-too-many->s-error form))
(t
(let ((inputs (ldiff args x))
(outputs (rest x)))
(cond
((string= (string (first x)) "->*")
(let ((funarg (prog->*-function-argument (process-prog-> (rest forms)) outputs)))
(cond
((and (consp funarg)
(eq 'function (first funarg))
(consp (second funarg))
(eq 'lambda (first (second funarg))))
(let ((g (gensym)))
(list
`(flet ((,g ,@(rest (second funarg))))
(declare (dynamic-extent (function ,g)))
,@(prog->*-call form inputs `(function ,g))))))
(t
(prog->*-call form inputs funarg)))))
((null outputs)
(prog->-no-variable-error form))
((string= (string (first x)) "->")
(cond
((null (rest outputs))
(cond
((and (consp (first outputs))
(member (first (first outputs)) '(values list list* :values :list :list*)))
(list `(mvlet ((,(first outputs) (,(first form) ,@inputs)))
,@(process-prog-> (rest forms)))))
(t
(list `(let ((,(first outputs) (,(first form) ,@inputs)))
,@(process-prog-> (rest forms)))))))
(t
(list `(multiple-value-bind ,outputs
(,(first form) ,@inputs)
,@(process-prog-> (rest forms)))))))
((string= (string (first x)) (symbol-name :->nonnil))
(cond
((null (rest outputs))
(cond
((and (consp (first outputs))
(member (first (first outputs)) '(values list list* :values :list :list*)))
(list `(mvlet ((,(first outputs) (,(first form) ,@inputs)))
(when ,(first outputs)
,@(process-prog-> (rest forms))))))
(t
(list `(let ((,(first outputs) (,(first form) ,@inputs)))
(when ,(first outputs)
,@(process-prog-> (rest forms))))))))
(t
(list `(multiple-value-bind ,outputs
(,(first form) ,@inputs)
(when ,(first outputs)
,@(process-prog-> (rest forms))))))))
((rest outputs)
(prog->-too-many-variables-error form))
((string= (string (first x)) (symbol-name :->stack))
(list `(let ((,(first outputs) (,(first form) ,@inputs)))
(declare (dynamic-extent ,(first outputs)))
,@(process-prog-> (rest forms)))))
((string= (string (first x)) (symbol-name :->progv))
(list `(let ((!prog->temp1! (list (,(first form) ,@inputs)))
(!prog->temp2! (list ,(first outputs))))
(declare (dynamic-extent !prog->temp1! !prog->temp2!))
(progv !prog->temp2! !prog->temp1! ,@(process-prog-> (rest forms))))))
(t
(prog->-unrecognized->-atom (first x) form)))))))))))))
(defun prog->*-call (form inputs funarg)
(cond
((prog->*-function-second-form-p (first form))
(list `(,(first form) ,(first inputs) ,funarg ,@(rest inputs))))
(t
(list `(,(first form) ,funarg ,@inputs)))))
(defun wrap-progn (forms &optional no-simplification)
(cond
((and (null forms)
(not no-simplification))
nil)
((and (null (rest forms))
(not no-simplification))
(first forms))
(t
(cons 'progn forms))))
(defun wrap-block (name forms &optional no-simplification)
(cond
((and (null forms)
(not no-simplification))
nil)
(t
(list* 'block name forms))))
(defun process-prog->-progn (forms)
(wrap-progn (process-prog-> forms)))
(defun process-prog->-block (forms)
(wrap-block 'prog-> (process-prog-> forms)))
(defmacro unnamed-prog-> (&body forms)
(process-prog->-progn forms))
(defmacro prog-> (&body forms)
(process-prog->-block forms))
progc.lisp EOF
|
afc3ecdcb04284df1baa8d354eb23276cc0049246f05a9750125121b8d4b998e | coalton-lang/coalton | function-calls-benchmarks.lisp | (trivial-benchmark:define-benchmark-package #:coalton-benchmarks
(:use #:cl
#:coalton-impl)
(:export #:run-benchmarks))
(in-package #:coalton-benchmarks)
(defstruct function-entry
(arity 0 :type fixnum :read-only t)
(function nil :type function :read-only t)
(curried nil :type function :read-only t))
(declaim (sb-ext:freeze-type function-entry))
(defmacro define-function-macros ()
(labels ((define-function-macros-with-arity (arity)
(declare (type fixnum arity))
(let ((constructor-sym (intern (format nil "F~D" arity)))
(application-sym (intern (format nil "A~D" arity)))
(function-sym (alexandria:make-gensym "F"))
(arg-syms (alexandria:make-gensym-list arity)))
(labels ((build-curried-function (args)
(if (null (car args))
`(funcall ,function-sym ,@arg-syms)
`(lambda (,(car args)) ,(build-curried-function (cdr args)))))
(build-curried-function-type (arity)
(if (= 0 arity)
't
`(function (t) ,(build-curried-function-type (1- arity)))))
(build-curried-function-call (fun args)
(if (null (car args))
`(the ,(build-curried-function-type arity) ,fun)
`(funcall ,(build-curried-function-call fun (cdr args)) ,(car args)))))
;; NOTE: Since we are only calling these functions
;; from already typechecked coalton, we can use the
;; OPTIMIZE flags to remove type checks.
`(progn
(declaim (inline ,constructor-sym))
(defun ,constructor-sym (,function-sym)
(declare (type (function ,(loop :for i :below arity :collect 't) t) ,function-sym)
(optimize (speed 3) (safety 0))
(values function-entry))
(make-function-entry :arity ,arity
:function ,function-sym
:curried ,(build-curried-function arg-syms)))
(declaim (inline ,application-sym))
(defun ,application-sym (,function-sym ,@arg-syms)
(declare (optimize (speed 3) (safety 0))
(type (or function function-entry) ,function-sym))
(typecase ,function-sym
(function-entry
(if (= (function-entry-arity ,function-sym) ,arity)
(funcall (the (function ,(loop :for i :below arity :collect 't) t)
(function-entry-function ,function-sym))
,@arg-syms)
,(build-curried-function-call `(function-entry-curried ,function-sym) (reverse arg-syms))))
(function
,(build-curried-function-call function-sym arg-syms)))))))))
`(progn
,@(loop :for i :of-type fixnum :from 2 :below 10
:collect (define-function-macros-with-arity i)))))
(define-function-macros)
(defun add3 (a b c)
(declare (optimize (speed 3) (safety 0))
(type (signed-byte 32) a b c)
(values (signed-byte 32)))
(+ a b c))
(defvar fadd3 (f3 #'add3))
(defun unoptimized-add4 (a b c d)
(+ a b c d))
(defun add4 (a b c d)
(declare (type (signed-byte 32) a b c d)
(values (signed-byte 32)))
(+ a b c d))
(defun add4-curried (a)
(declare (type (signed-byte 32) a)
(optimize (speed 3) (safety 0)))
(lambda (b)
(declare (type (signed-byte 32) b)
(optimize (speed 3) (safety 0)))
(lambda (c)
(declare (type (signed-byte 32) c)
(optimize (speed 3) (safety 0)))
(lambda (d)
(declare (type (signed-byte 32) d)
(optimize (speed 3) (safety 0)))
(+ a b c d)))))
(defvar fadd4 (f4 #'add4))
(defvar fadd4-no-types (f4 #'unoptimized-add4))
(defun run-add4 (a b c d)
(declare (optimize (speed 3)))
(add4 a b c d))
(defun run-add4-a4 (a b c d)
(declare (optimize (speed 3)))
(a4 #'add4-curried a b c d))
(defun run-fadd4 (a b c d)
(declare (optimize (speed 3) (safety 0)))
(a4 (the (or function function-entry) fadd4) a b c d))
(trivial-benchmark:define-benchmark benchmark-add4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(add4 i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-fadd4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(a4 (the (or function-entry function) fadd4) i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-add4-a4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(a4 #'add4-curried i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-unoptimized-add4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(unoptimized-add4 i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-unoptimized-fadd4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(a4 (the function-entry fadd4-no-types) i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-fadd4-a2-a2 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(a2 (a2 (the function-entry fadd4) i _) k l)))))
(trivial-benchmark:define-benchmark benchmark-noop ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000) nil))))
| null | https://raw.githubusercontent.com/coalton-lang/coalton/b36c38226dcd2a6da3b3146125930eb179baa583/docs/design-docs/function-calls-benchmarks.lisp | lisp | NOTE: Since we are only calling these functions
from already typechecked coalton, we can use the
OPTIMIZE flags to remove type checks. | (trivial-benchmark:define-benchmark-package #:coalton-benchmarks
(:use #:cl
#:coalton-impl)
(:export #:run-benchmarks))
(in-package #:coalton-benchmarks)
(defstruct function-entry
(arity 0 :type fixnum :read-only t)
(function nil :type function :read-only t)
(curried nil :type function :read-only t))
(declaim (sb-ext:freeze-type function-entry))
(defmacro define-function-macros ()
(labels ((define-function-macros-with-arity (arity)
(declare (type fixnum arity))
(let ((constructor-sym (intern (format nil "F~D" arity)))
(application-sym (intern (format nil "A~D" arity)))
(function-sym (alexandria:make-gensym "F"))
(arg-syms (alexandria:make-gensym-list arity)))
(labels ((build-curried-function (args)
(if (null (car args))
`(funcall ,function-sym ,@arg-syms)
`(lambda (,(car args)) ,(build-curried-function (cdr args)))))
(build-curried-function-type (arity)
(if (= 0 arity)
't
`(function (t) ,(build-curried-function-type (1- arity)))))
(build-curried-function-call (fun args)
(if (null (car args))
`(the ,(build-curried-function-type arity) ,fun)
`(funcall ,(build-curried-function-call fun (cdr args)) ,(car args)))))
`(progn
(declaim (inline ,constructor-sym))
(defun ,constructor-sym (,function-sym)
(declare (type (function ,(loop :for i :below arity :collect 't) t) ,function-sym)
(optimize (speed 3) (safety 0))
(values function-entry))
(make-function-entry :arity ,arity
:function ,function-sym
:curried ,(build-curried-function arg-syms)))
(declaim (inline ,application-sym))
(defun ,application-sym (,function-sym ,@arg-syms)
(declare (optimize (speed 3) (safety 0))
(type (or function function-entry) ,function-sym))
(typecase ,function-sym
(function-entry
(if (= (function-entry-arity ,function-sym) ,arity)
(funcall (the (function ,(loop :for i :below arity :collect 't) t)
(function-entry-function ,function-sym))
,@arg-syms)
,(build-curried-function-call `(function-entry-curried ,function-sym) (reverse arg-syms))))
(function
,(build-curried-function-call function-sym arg-syms)))))))))
`(progn
,@(loop :for i :of-type fixnum :from 2 :below 10
:collect (define-function-macros-with-arity i)))))
(define-function-macros)
(defun add3 (a b c)
(declare (optimize (speed 3) (safety 0))
(type (signed-byte 32) a b c)
(values (signed-byte 32)))
(+ a b c))
(defvar fadd3 (f3 #'add3))
(defun unoptimized-add4 (a b c d)
(+ a b c d))
(defun add4 (a b c d)
(declare (type (signed-byte 32) a b c d)
(values (signed-byte 32)))
(+ a b c d))
(defun add4-curried (a)
(declare (type (signed-byte 32) a)
(optimize (speed 3) (safety 0)))
(lambda (b)
(declare (type (signed-byte 32) b)
(optimize (speed 3) (safety 0)))
(lambda (c)
(declare (type (signed-byte 32) c)
(optimize (speed 3) (safety 0)))
(lambda (d)
(declare (type (signed-byte 32) d)
(optimize (speed 3) (safety 0)))
(+ a b c d)))))
(defvar fadd4 (f4 #'add4))
(defvar fadd4-no-types (f4 #'unoptimized-add4))
(defun run-add4 (a b c d)
(declare (optimize (speed 3)))
(add4 a b c d))
(defun run-add4-a4 (a b c d)
(declare (optimize (speed 3)))
(a4 #'add4-curried a b c d))
(defun run-fadd4 (a b c d)
(declare (optimize (speed 3) (safety 0)))
(a4 (the (or function function-entry) fadd4) a b c d))
(trivial-benchmark:define-benchmark benchmark-add4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(add4 i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-fadd4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(a4 (the (or function-entry function) fadd4) i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-add4-a4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(a4 #'add4-curried i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-unoptimized-add4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(unoptimized-add4 i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-unoptimized-fadd4 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(a4 (the function-entry fadd4-no-types) i _ k l)))))
(trivial-benchmark:define-benchmark benchmark-fadd4-a2-a2 ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000)
(a2 (a2 (the function-entry fadd4) i _) k l)))))
(trivial-benchmark:define-benchmark benchmark-noop ()
(declare (optimize (speed 3) (safety 0)))
(loop :for i :below 10000
:for j :below 10000
:for k :below 10000
:for l :below 10000
:do (trivial-benchmark:with-benchmark-sampling
(dotimes (_ 10000) nil))))
|
81b7d5c64481289ded835f1457dba17e0a0e38f8709251a98ac5676290f88bed | pa-ba/compdata-param | Ditraversable.hs | # LANGUAGE TemplateHaskell #
--------------------------------------------------------------------------------
-- |
Module : Data . Comp . . Derive . Ditraversable
Copyright : ( c ) 2010 - 2011
-- License : BSD3
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC Extensions )
--
Automatically derive instances of @Ditraversable@.
--
--------------------------------------------------------------------------------
module Data.Comp.Param.Derive.Ditraversable
(
Ditraversable,
makeDitraversable
) where
import Data.Comp.Derive.Utils
import Data.Comp.Param.Derive.Utils
import Data.Comp.Param.Ditraversable
import Data.Traversable (mapM)
import Language.Haskell.TH
import Data.Maybe
import Control.Monad hiding (mapM)
import Prelude hiding (mapM)
iter 0 _ e = e
iter n f e = iter (n-1) f (f `appE` e)
iter' n f e = run n f e
where run 0 _ e = e
run m f e = let f' = iter (m-1) [|fmap|] f
in run (m-1) f (f' `appE` e)
| Derive an instance of ' ' for a type constructor of any
first - order kind taking at least one argument .
first-order kind taking at least one argument. -}
makeDitraversable :: Name -> Q [Dec]
makeDitraversable fname = do
Just (DataInfo _cxt name args constrs _deriving) <- abstractNewtypeQ $ reify fname
let fArg = VarT . tyVarBndrName $ last args
aArg = VarT . tyVarBndrName $ last (init args)
argNames = map (VarT . tyVarBndrName) (init $ init args)
complType = foldl AppT (ConT name) argNames
classType = foldl1 AppT [ConT ''Ditraversable, complType]
normConstrs <- mapM normalConExp constrs
constrs' <- mapM (mkPatAndVars . isFarg aArg fArg) normConstrs
mapMDecl <- funD 'dimapM (map mapMClause constrs')
sequenceDecl <- funD 'disequence (map sequenceClause constrs')
return [mkInstanceD [] classType [mapMDecl,sequenceDecl]]
where isFarg aArg' fArg' (constr, args, gadtTy) =
let (aArg, fArg) = getBinaryFArgs aArg' fArg' gadtTy
funTy = foldl AppT ArrowT [aArg,fArg]
in (constr, map (\t -> (t `containsType'` fArg, t `containsType'` funTy)) args)
filterVar _ _ nonFarg ([],[]) x = nonFarg x
filterVar farg _ _ ([depth],[]) x = farg depth x
filterVar _ aarg _ ([_],[depth]) x = aarg depth x
filterVar _ _ _ _ _ = error "functor variable occurring twice in argument type"
filterVars args varNs farg aarg nonFarg = zipWith (filterVar farg aarg nonFarg) args varNs
mkCPat constr varNs = ConP constr $ map mkPat varNs
mkPat = VarP
mkPatAndVars (constr, args) =
do varNs <- newNames (length args) "x"
return (conE constr, mkCPat constr varNs,
any (not . null . fst) args || any (not . null . snd) args, map varE varNs,
catMaybes $ filterVars args varNs (\x y -> Just (False,x,y)) (\x y -> Just (True, x, y)) (const Nothing))
-- Note: the monadic versions are not defined
-- applicatively, as this results in a considerable
performance penalty ( by factor 2 ) !
mapMClause (con, pat,hasFargs,allVars, fvars) =
do fn <- newName "f"
let f = varE fn
fp = if hasFargs then VarP fn else WildP
conAp = foldl appE con allVars
addDi False x = x
addDi True _ = [|dimapM $(f)|]
conBind (fun,d,x) y = [| $(iter d [|mapM|] (addDi fun f)) $(varE x) >>= $(lamE [varP x] y)|]
body <- foldr conBind [|return $conAp|] fvars
return $ Clause [fp, pat] (NormalB body) []
sequenceClause (con, pat,_hasFargs,allVars, fvars) =
do let conAp = foldl appE con allVars
varE' False _ x = varE x
varE' True d x = appE (iter d [|fmap|] [|disequence|]) (varE x)
conBind (fun,d, x) y = [| $(iter' d [|sequence|] (varE' fun d x)) >>= $(lamE [varP x] y)|]
body <- foldr conBind [|return $conAp|] fvars
return $ Clause [pat] (NormalB body) []
| null | https://raw.githubusercontent.com/pa-ba/compdata-param/5d6b0afa95a27fd3233f86e5efc6e6a6080f4236/src/Data/Comp/Param/Derive/Ditraversable.hs | haskell | ------------------------------------------------------------------------------
|
License : BSD3
Stability : experimental
------------------------------------------------------------------------------
Note: the monadic versions are not defined
applicatively, as this results in a considerable | # LANGUAGE TemplateHaskell #
Module : Data . Comp . . Derive . Ditraversable
Copyright : ( c ) 2010 - 2011
Maintainer : < >
Portability : non - portable ( GHC Extensions )
Automatically derive instances of @Ditraversable@.
module Data.Comp.Param.Derive.Ditraversable
(
Ditraversable,
makeDitraversable
) where
import Data.Comp.Derive.Utils
import Data.Comp.Param.Derive.Utils
import Data.Comp.Param.Ditraversable
import Data.Traversable (mapM)
import Language.Haskell.TH
import Data.Maybe
import Control.Monad hiding (mapM)
import Prelude hiding (mapM)
iter 0 _ e = e
iter n f e = iter (n-1) f (f `appE` e)
iter' n f e = run n f e
where run 0 _ e = e
run m f e = let f' = iter (m-1) [|fmap|] f
in run (m-1) f (f' `appE` e)
| Derive an instance of ' ' for a type constructor of any
first - order kind taking at least one argument .
first-order kind taking at least one argument. -}
makeDitraversable :: Name -> Q [Dec]
makeDitraversable fname = do
Just (DataInfo _cxt name args constrs _deriving) <- abstractNewtypeQ $ reify fname
let fArg = VarT . tyVarBndrName $ last args
aArg = VarT . tyVarBndrName $ last (init args)
argNames = map (VarT . tyVarBndrName) (init $ init args)
complType = foldl AppT (ConT name) argNames
classType = foldl1 AppT [ConT ''Ditraversable, complType]
normConstrs <- mapM normalConExp constrs
constrs' <- mapM (mkPatAndVars . isFarg aArg fArg) normConstrs
mapMDecl <- funD 'dimapM (map mapMClause constrs')
sequenceDecl <- funD 'disequence (map sequenceClause constrs')
return [mkInstanceD [] classType [mapMDecl,sequenceDecl]]
where isFarg aArg' fArg' (constr, args, gadtTy) =
let (aArg, fArg) = getBinaryFArgs aArg' fArg' gadtTy
funTy = foldl AppT ArrowT [aArg,fArg]
in (constr, map (\t -> (t `containsType'` fArg, t `containsType'` funTy)) args)
filterVar _ _ nonFarg ([],[]) x = nonFarg x
filterVar farg _ _ ([depth],[]) x = farg depth x
filterVar _ aarg _ ([_],[depth]) x = aarg depth x
filterVar _ _ _ _ _ = error "functor variable occurring twice in argument type"
filterVars args varNs farg aarg nonFarg = zipWith (filterVar farg aarg nonFarg) args varNs
mkCPat constr varNs = ConP constr $ map mkPat varNs
mkPat = VarP
mkPatAndVars (constr, args) =
do varNs <- newNames (length args) "x"
return (conE constr, mkCPat constr varNs,
any (not . null . fst) args || any (not . null . snd) args, map varE varNs,
catMaybes $ filterVars args varNs (\x y -> Just (False,x,y)) (\x y -> Just (True, x, y)) (const Nothing))
performance penalty ( by factor 2 ) !
mapMClause (con, pat,hasFargs,allVars, fvars) =
do fn <- newName "f"
let f = varE fn
fp = if hasFargs then VarP fn else WildP
conAp = foldl appE con allVars
addDi False x = x
addDi True _ = [|dimapM $(f)|]
conBind (fun,d,x) y = [| $(iter d [|mapM|] (addDi fun f)) $(varE x) >>= $(lamE [varP x] y)|]
body <- foldr conBind [|return $conAp|] fvars
return $ Clause [fp, pat] (NormalB body) []
sequenceClause (con, pat,_hasFargs,allVars, fvars) =
do let conAp = foldl appE con allVars
varE' False _ x = varE x
varE' True d x = appE (iter d [|fmap|] [|disequence|]) (varE x)
conBind (fun,d, x) y = [| $(iter' d [|sequence|] (varE' fun d x)) >>= $(lamE [varP x] y)|]
body <- foldr conBind [|return $conAp|] fvars
return $ Clause [pat] (NormalB body) []
|
84e831809a543f355db55ec486b2af6160ccb82daea4607afec8102c1674543f | samply/blaze | anomaly_test.clj | (ns blaze.anomaly-test
(:require
[blaze.anomaly :as ba :refer [if-ok when-ok]]
[blaze.anomaly-spec]
[blaze.test-util :as tu]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [deftest is testing]]
[cognitect.anomalies :as anom]
[juxt.iota :refer [given]])
(:import
[java.util.concurrent ExecutionException TimeoutException]))
(st/instrument)
(test/use-fixtures :each tu/fixture)
(deftest anomaly?-test
(testing "a map with the right category key is an anomaly"
(is (ba/anomaly? {::anom/category ::anom/fault})))
(testing "other maps are no anomalies"
(is (not (ba/anomaly? {})))
(is (not (ba/anomaly? {::foo ::bar}))))
(testing "nil is no anomaly"
(is (not (ba/anomaly? nil)))))
(deftest unsupported?-test
(testing "a unsupported anomaly has to have the right category"
(is (ba/unsupported? {::anom/category ::anom/unsupported})))
(testing "anomalies with other categories are no unsupported anomalies"
(is (not (ba/unsupported? {::anom/category ::anom/fault}))))
(testing "nil is no unsupported anomaly"
(is (not (ba/anomaly? nil)))))
(deftest not-found?-test
(testing "a not-found anomaly has to have the right category"
(is (ba/not-found? {::anom/category ::anom/not-found})))
(testing "anomalies with other categories are no not-found anomalies"
(is (not (ba/not-found? {::anom/category ::anom/fault}))))
(testing "nil is no not-found anomaly"
(is (not (ba/anomaly? nil)))))
(deftest fault?-test
(testing "a fault anomaly has to have the right category"
(is (ba/fault? {::anom/category ::anom/fault})))
(testing "anomalies with other categories are no fault anomalies"
(is (not (ba/fault? {::anom/category ::anom/not-found}))))
(testing "nil is no fault anomaly"
(is (not (ba/anomaly? nil)))))
(deftest incorrect-test
(testing "with nil message"
(is (= (ba/incorrect nil) {::anom/category ::anom/incorrect})))
(testing "with message only"
(given (ba/incorrect "msg-183005")
::anom/category := ::anom/incorrect
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/incorrect "msg-183005" ::foo ::bar)
::anom/category := ::anom/incorrect
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest forbidden-test
(testing "with nil message"
(is (= (ba/forbidden nil) {::anom/category ::anom/forbidden})))
(testing "with message only"
(given (ba/forbidden "msg-183005")
::anom/category := ::anom/forbidden
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/forbidden "msg-183005" ::foo ::bar)
::anom/category := ::anom/forbidden
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest unsupported-test
(testing "with nil message"
(is (= (ba/unsupported nil) {::anom/category ::anom/unsupported})))
(testing "with message only"
(given (ba/unsupported "msg-183005")
::anom/category := ::anom/unsupported
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/unsupported "msg-183005" ::foo ::bar)
::anom/category := ::anom/unsupported
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest not-found-test
(testing "with nil message"
(is (= (ba/not-found nil) {::anom/category ::anom/not-found})))
(testing "with message only"
(given (ba/not-found "msg-183005")
::anom/category := ::anom/not-found
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/not-found "msg-183005" ::foo ::bar)
::anom/category := ::anom/not-found
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest fault-test
(testing "without message"
(is (= (ba/fault) {::anom/category ::anom/fault})))
(testing "with nil message"
(is (= (ba/fault nil) {::anom/category ::anom/fault})))
(testing "with message only"
(given (ba/fault "msg-183005")
::anom/category := ::anom/fault
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/fault "msg-183005" ::foo ::bar)
::anom/category := ::anom/fault
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest busy-test
(testing "with nil message"
(is (= (ba/busy nil) {::anom/category ::anom/busy})))
(testing "with message only"
(given (ba/busy "msg-183005")
::anom/category := ::anom/busy
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/busy "msg-183005" ::foo ::bar)
::anom/category := ::anom/busy
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest anomaly-test
(testing "ExecutionException"
(given (ba/anomaly (ExecutionException. (Exception. "msg-184245")))
::anom/category := ::anom/fault
::anom/message := "msg-184245"))
(testing "TimeoutException"
(given (ba/anomaly (TimeoutException. "msg-122233"))
::anom/category := ::anom/busy
::anom/message := "msg-122233"))
(testing "ExceptionInfo"
(testing "without an anomaly in data"
(given (ba/anomaly (ex-info "msg-184349" {::foo ::bar}))
::anom/category := ::anom/fault
::anom/message := "msg-184349"
::foo := ::bar))
(testing "with an anomaly in data"
(given (ba/anomaly (ex-info "msg-184349" (ba/incorrect "msg-184433")))
::anom/category := ::anom/incorrect
::anom/message := "msg-184433"))
(testing "without message"
(is (= ::none ((ba/anomaly (ex-info nil {})) ::anom/message ::none))))
(testing "with cause"
(given (ba/anomaly (ex-info "msg-181247" {} (Exception. "msg-181120")))
::anom/message := "msg-181247"
[:blaze.anomaly/cause ::anom/message] := "msg-181120")
(testing "and nil message"
(given (ba/anomaly (ex-info "msg-181247" {} (Exception.)))
::anom/message := "msg-181247"
[:blaze.anomaly/cause #(% ::anom/message ::none)] := ::none))))
(testing "Exception"
(given (ba/anomaly (Exception. "msg-120840"))
::anom/category := ::anom/fault
::anom/message := "msg-120840"))
(testing "anomaly"
(given (ba/anomaly (ba/busy "msg-121702"))
::anom/category := ::anom/busy
::anom/message := "msg-121702")))
(deftest try-one-test
(testing "without message"
(is (= (ba/try-one Exception ::anom/fault (throw (Exception.)))
{::anom/category ::anom/fault})))
(testing "with message"
(given (ba/try-one Exception ::anom/fault (throw (Exception. "msg-134156")))
::anom/category := ::anom/fault
::anom/message := "msg-134156")))
(deftest try-all-test
(given (ba/try-all ::anom/fault (throw (Exception. "msg-134347")))
::anom/category := ::anom/fault
::anom/message := "msg-134347"))
(deftest try-anomaly-test
(testing "an exception leads to a fault"
(given (ba/try-anomaly (throw (Exception. "msg-134612")))
::anom/category := ::anom/fault
::anom/message := "msg-134612"))
(testing "a thrown busy anomaly will be preserved"
(given (ba/try-anomaly (throw (ba/ex-anom (ba/busy "msg-134737" ::foo ::bar))))
::anom/category := ::anom/busy
::anom/message := "msg-134737"
::foo := ::bar)))
(deftest ex-anom-test
(testing "the message will be put in the exception"
(is (= (ex-message (ba/ex-anom (ba/incorrect "msg-135018"))) "msg-135018")))
(testing "the complete anomaly goes into ex-data"
(given (ex-data (ba/ex-anom (ba/unsupported "msg-135018" ::foo ::bar)))
::anom/category := ::anom/unsupported
::anom/message := "msg-135018"
::foo := ::bar)))
(deftest throw-anom-test
(given (ba/try-anomaly (ba/throw-anom (ba/conflict "msg-174935")))
::anom/category := ::anom/conflict
::anom/message := "msg-174935"))
(deftest throw-when-test
(testing "anomalies are thrown"
(given (ba/try-anomaly (ba/throw-when (ba/unsupported "msg-135500")))
::anom/category := ::anom/unsupported
::anom/message := "msg-135500"))
(testing "other values are returned"
(is (= (ba/throw-when {::foo ::bar}) {::foo ::bar}))))
(deftest when-ok-test
(testing "no anomaly"
(testing "without a binding"
(is (= 1 (when-ok [] 1))))
(testing "with one binding"
(is (= 2 (when-ok [x 1] (inc x)))))
(testing "with two bindings"
(is (= 3 (when-ok [x 1 y 2] (+ x y))))))
(testing "anomaly on only binding"
(given (when-ok [x (ba/fault)] (inc x))
::anom/category := ::anom/fault))
(testing "anomaly on first binding"
(given (when-ok [x (ba/fault) y 2] (+ x y))
::anom/category := ::anom/fault))
(testing "anomaly on second binding"
(given (when-ok [x 1 y (ba/fault)] (+ x y))
::anom/category := ::anom/fault))
(testing "bodies can also fail"
(given (when-ok [] (ba/fault))
::anom/category := ::anom/fault)))
(deftest if-ok-test
(testing "no anomaly"
(testing "without a binding"
(is (= 1 (if-ok [] 1 identity))))
(testing "with one binding"
(is (= 2 (if-ok [x 1] (inc x) identity))))
(testing "with two bindings"
(is (= 3 (if-ok [x 1 y 2] (+ x y) identity)))))
(testing "anomaly on only binding"
(given (if-ok [x (ba/fault)] (inc x) #(assoc % ::foo ::bar))
::anom/category := ::anom/fault
::foo := ::bar))
(testing "anomaly on first binding"
(given (if-ok [x (ba/fault) y 2] (+ x y) #(assoc % ::foo ::bar))
::anom/category := ::anom/fault
::foo := ::bar))
(testing "anomaly on second binding"
(given (if-ok [x 1 y (ba/fault)] (+ x y) #(assoc % ::foo ::bar))
::anom/category := ::anom/fault
::foo := ::bar))
(testing "else doesn't see the failed body"
(given (if-ok [] (ba/fault) #(assoc % ::anom/category ::anom/busy))
::anom/category := ::anom/fault)))
(deftest map-test
(testing "no anomaly"
(is (= 2 (ba/map 1 inc))))
(testing "with anomaly"
(given (ba/map (ba/fault) inc)
::anom/category := ::anom/fault)))
(deftest exceptionally-test
(testing "no anomaly"
(is (= 1 (ba/exceptionally 1 #(assoc % ::foo ::bar)))))
(testing "with anomaly"
(given (ba/exceptionally (ba/fault) #(assoc % ::foo ::bar))
::anom/category := ::anom/fault
::foo := ::bar)))
| null | https://raw.githubusercontent.com/samply/blaze/6441a0a2f988b8784ed555c1d20f634ef2df7e4a/modules/anomaly/test/blaze/anomaly_test.clj | clojure | (ns blaze.anomaly-test
(:require
[blaze.anomaly :as ba :refer [if-ok when-ok]]
[blaze.anomaly-spec]
[blaze.test-util :as tu]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [deftest is testing]]
[cognitect.anomalies :as anom]
[juxt.iota :refer [given]])
(:import
[java.util.concurrent ExecutionException TimeoutException]))
(st/instrument)
(test/use-fixtures :each tu/fixture)
(deftest anomaly?-test
(testing "a map with the right category key is an anomaly"
(is (ba/anomaly? {::anom/category ::anom/fault})))
(testing "other maps are no anomalies"
(is (not (ba/anomaly? {})))
(is (not (ba/anomaly? {::foo ::bar}))))
(testing "nil is no anomaly"
(is (not (ba/anomaly? nil)))))
(deftest unsupported?-test
(testing "a unsupported anomaly has to have the right category"
(is (ba/unsupported? {::anom/category ::anom/unsupported})))
(testing "anomalies with other categories are no unsupported anomalies"
(is (not (ba/unsupported? {::anom/category ::anom/fault}))))
(testing "nil is no unsupported anomaly"
(is (not (ba/anomaly? nil)))))
(deftest not-found?-test
(testing "a not-found anomaly has to have the right category"
(is (ba/not-found? {::anom/category ::anom/not-found})))
(testing "anomalies with other categories are no not-found anomalies"
(is (not (ba/not-found? {::anom/category ::anom/fault}))))
(testing "nil is no not-found anomaly"
(is (not (ba/anomaly? nil)))))
(deftest fault?-test
(testing "a fault anomaly has to have the right category"
(is (ba/fault? {::anom/category ::anom/fault})))
(testing "anomalies with other categories are no fault anomalies"
(is (not (ba/fault? {::anom/category ::anom/not-found}))))
(testing "nil is no fault anomaly"
(is (not (ba/anomaly? nil)))))
(deftest incorrect-test
(testing "with nil message"
(is (= (ba/incorrect nil) {::anom/category ::anom/incorrect})))
(testing "with message only"
(given (ba/incorrect "msg-183005")
::anom/category := ::anom/incorrect
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/incorrect "msg-183005" ::foo ::bar)
::anom/category := ::anom/incorrect
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest forbidden-test
(testing "with nil message"
(is (= (ba/forbidden nil) {::anom/category ::anom/forbidden})))
(testing "with message only"
(given (ba/forbidden "msg-183005")
::anom/category := ::anom/forbidden
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/forbidden "msg-183005" ::foo ::bar)
::anom/category := ::anom/forbidden
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest unsupported-test
(testing "with nil message"
(is (= (ba/unsupported nil) {::anom/category ::anom/unsupported})))
(testing "with message only"
(given (ba/unsupported "msg-183005")
::anom/category := ::anom/unsupported
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/unsupported "msg-183005" ::foo ::bar)
::anom/category := ::anom/unsupported
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest not-found-test
(testing "with nil message"
(is (= (ba/not-found nil) {::anom/category ::anom/not-found})))
(testing "with message only"
(given (ba/not-found "msg-183005")
::anom/category := ::anom/not-found
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/not-found "msg-183005" ::foo ::bar)
::anom/category := ::anom/not-found
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest fault-test
(testing "without message"
(is (= (ba/fault) {::anom/category ::anom/fault})))
(testing "with nil message"
(is (= (ba/fault nil) {::anom/category ::anom/fault})))
(testing "with message only"
(given (ba/fault "msg-183005")
::anom/category := ::anom/fault
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/fault "msg-183005" ::foo ::bar)
::anom/category := ::anom/fault
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest busy-test
(testing "with nil message"
(is (= (ba/busy nil) {::anom/category ::anom/busy})))
(testing "with message only"
(given (ba/busy "msg-183005")
::anom/category := ::anom/busy
::anom/message := "msg-183005"))
(testing "with additional kvs"
(given (ba/busy "msg-183005" ::foo ::bar)
::anom/category := ::anom/busy
::anom/message := "msg-183005"
::foo := ::bar)))
(deftest anomaly-test
(testing "ExecutionException"
(given (ba/anomaly (ExecutionException. (Exception. "msg-184245")))
::anom/category := ::anom/fault
::anom/message := "msg-184245"))
(testing "TimeoutException"
(given (ba/anomaly (TimeoutException. "msg-122233"))
::anom/category := ::anom/busy
::anom/message := "msg-122233"))
(testing "ExceptionInfo"
(testing "without an anomaly in data"
(given (ba/anomaly (ex-info "msg-184349" {::foo ::bar}))
::anom/category := ::anom/fault
::anom/message := "msg-184349"
::foo := ::bar))
(testing "with an anomaly in data"
(given (ba/anomaly (ex-info "msg-184349" (ba/incorrect "msg-184433")))
::anom/category := ::anom/incorrect
::anom/message := "msg-184433"))
(testing "without message"
(is (= ::none ((ba/anomaly (ex-info nil {})) ::anom/message ::none))))
(testing "with cause"
(given (ba/anomaly (ex-info "msg-181247" {} (Exception. "msg-181120")))
::anom/message := "msg-181247"
[:blaze.anomaly/cause ::anom/message] := "msg-181120")
(testing "and nil message"
(given (ba/anomaly (ex-info "msg-181247" {} (Exception.)))
::anom/message := "msg-181247"
[:blaze.anomaly/cause #(% ::anom/message ::none)] := ::none))))
(testing "Exception"
(given (ba/anomaly (Exception. "msg-120840"))
::anom/category := ::anom/fault
::anom/message := "msg-120840"))
(testing "anomaly"
(given (ba/anomaly (ba/busy "msg-121702"))
::anom/category := ::anom/busy
::anom/message := "msg-121702")))
(deftest try-one-test
(testing "without message"
(is (= (ba/try-one Exception ::anom/fault (throw (Exception.)))
{::anom/category ::anom/fault})))
(testing "with message"
(given (ba/try-one Exception ::anom/fault (throw (Exception. "msg-134156")))
::anom/category := ::anom/fault
::anom/message := "msg-134156")))
(deftest try-all-test
(given (ba/try-all ::anom/fault (throw (Exception. "msg-134347")))
::anom/category := ::anom/fault
::anom/message := "msg-134347"))
(deftest try-anomaly-test
(testing "an exception leads to a fault"
(given (ba/try-anomaly (throw (Exception. "msg-134612")))
::anom/category := ::anom/fault
::anom/message := "msg-134612"))
(testing "a thrown busy anomaly will be preserved"
(given (ba/try-anomaly (throw (ba/ex-anom (ba/busy "msg-134737" ::foo ::bar))))
::anom/category := ::anom/busy
::anom/message := "msg-134737"
::foo := ::bar)))
(deftest ex-anom-test
(testing "the message will be put in the exception"
(is (= (ex-message (ba/ex-anom (ba/incorrect "msg-135018"))) "msg-135018")))
(testing "the complete anomaly goes into ex-data"
(given (ex-data (ba/ex-anom (ba/unsupported "msg-135018" ::foo ::bar)))
::anom/category := ::anom/unsupported
::anom/message := "msg-135018"
::foo := ::bar)))
(deftest throw-anom-test
(given (ba/try-anomaly (ba/throw-anom (ba/conflict "msg-174935")))
::anom/category := ::anom/conflict
::anom/message := "msg-174935"))
(deftest throw-when-test
(testing "anomalies are thrown"
(given (ba/try-anomaly (ba/throw-when (ba/unsupported "msg-135500")))
::anom/category := ::anom/unsupported
::anom/message := "msg-135500"))
(testing "other values are returned"
(is (= (ba/throw-when {::foo ::bar}) {::foo ::bar}))))
(deftest when-ok-test
(testing "no anomaly"
(testing "without a binding"
(is (= 1 (when-ok [] 1))))
(testing "with one binding"
(is (= 2 (when-ok [x 1] (inc x)))))
(testing "with two bindings"
(is (= 3 (when-ok [x 1 y 2] (+ x y))))))
(testing "anomaly on only binding"
(given (when-ok [x (ba/fault)] (inc x))
::anom/category := ::anom/fault))
(testing "anomaly on first binding"
(given (when-ok [x (ba/fault) y 2] (+ x y))
::anom/category := ::anom/fault))
(testing "anomaly on second binding"
(given (when-ok [x 1 y (ba/fault)] (+ x y))
::anom/category := ::anom/fault))
(testing "bodies can also fail"
(given (when-ok [] (ba/fault))
::anom/category := ::anom/fault)))
(deftest if-ok-test
(testing "no anomaly"
(testing "without a binding"
(is (= 1 (if-ok [] 1 identity))))
(testing "with one binding"
(is (= 2 (if-ok [x 1] (inc x) identity))))
(testing "with two bindings"
(is (= 3 (if-ok [x 1 y 2] (+ x y) identity)))))
(testing "anomaly on only binding"
(given (if-ok [x (ba/fault)] (inc x) #(assoc % ::foo ::bar))
::anom/category := ::anom/fault
::foo := ::bar))
(testing "anomaly on first binding"
(given (if-ok [x (ba/fault) y 2] (+ x y) #(assoc % ::foo ::bar))
::anom/category := ::anom/fault
::foo := ::bar))
(testing "anomaly on second binding"
(given (if-ok [x 1 y (ba/fault)] (+ x y) #(assoc % ::foo ::bar))
::anom/category := ::anom/fault
::foo := ::bar))
(testing "else doesn't see the failed body"
(given (if-ok [] (ba/fault) #(assoc % ::anom/category ::anom/busy))
::anom/category := ::anom/fault)))
(deftest map-test
(testing "no anomaly"
(is (= 2 (ba/map 1 inc))))
(testing "with anomaly"
(given (ba/map (ba/fault) inc)
::anom/category := ::anom/fault)))
(deftest exceptionally-test
(testing "no anomaly"
(is (= 1 (ba/exceptionally 1 #(assoc % ::foo ::bar)))))
(testing "with anomaly"
(given (ba/exceptionally (ba/fault) #(assoc % ::foo ::bar))
::anom/category := ::anom/fault
::foo := ::bar)))
| |
ed5d2f7b849fbe647c8ce65c2bf67d31ff72df3817c8c826b014a384d8416ba1 | clojure-interop/google-cloud-clients | CloudTasksClient$ListTasksFixedSizeCollection.clj | (ns com.google.cloud.tasks.v2beta3.CloudTasksClient$ListTasksFixedSizeCollection
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.tasks.v2beta3 CloudTasksClient$ListTasksFixedSizeCollection]))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.tasks/src/com/google/cloud/tasks/v2beta3/CloudTasksClient%24ListTasksFixedSizeCollection.clj | clojure | (ns com.google.cloud.tasks.v2beta3.CloudTasksClient$ListTasksFixedSizeCollection
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.tasks.v2beta3 CloudTasksClient$ListTasksFixedSizeCollection]))
| |
fbd1557f1f9ca00b916b80f0625745cd53406e40e1fe5163b7bcca3172228f24 | clojure-interop/google-cloud-clients | ProfileServiceClient$SearchProfilesPage.clj | (ns com.google.cloud.talent.v4beta1.ProfileServiceClient$SearchProfilesPage
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1 ProfileServiceClient$SearchProfilesPage]))
(defn create-page-async
"context - `com.google.api.gax.rpc.PageContext`
future-response - `com.google.api.core.ApiFuture`
returns: `com.google.api.core.ApiFuture<com.google.cloud.talent.v4beta1.ProfileServiceClient$SearchProfilesPage>`"
(^com.google.api.core.ApiFuture [^ProfileServiceClient$SearchProfilesPage this ^com.google.api.gax.rpc.PageContext context ^com.google.api.core.ApiFuture future-response]
(-> this (.createPageAsync context future-response))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.talent/src/com/google/cloud/talent/v4beta1/ProfileServiceClient%24SearchProfilesPage.clj | clojure | (ns com.google.cloud.talent.v4beta1.ProfileServiceClient$SearchProfilesPage
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1 ProfileServiceClient$SearchProfilesPage]))
(defn create-page-async
"context - `com.google.api.gax.rpc.PageContext`
future-response - `com.google.api.core.ApiFuture`
returns: `com.google.api.core.ApiFuture<com.google.cloud.talent.v4beta1.ProfileServiceClient$SearchProfilesPage>`"
(^com.google.api.core.ApiFuture [^ProfileServiceClient$SearchProfilesPage this ^com.google.api.gax.rpc.PageContext context ^com.google.api.core.ApiFuture future-response]
(-> this (.createPageAsync context future-response))))
| |
f69e79670a47578e66060b7fdcc55f7a2cae5d5a45920d896f4fc2fa6e661fc3 | inria-parkas/sundialsml | arkode_bbd.ml | (***********************************************************************)
(* *)
(* OCaml interface to Sundials *)
(* *)
, , and
( / ENS ) ( / ENS ) ( UPMC / ENS / Inria )
(* *)
Copyright 2015 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
(* under a New BSD License, refer to the file LICENSE. *)
(* *)
(***********************************************************************)
open Sundials
include Arkode_impl
include ArkodeBbdTypes
These types ca n't be defined in Arkode_impl because they introduce
dependence on . Some duplication is unavoidable .
dependence on Mpi. Some duplication is unavoidable. *)
type data = Nvector_parallel.data
type 'step parallel_session =
(Nvector_parallel.data, Nvector_parallel.kind, 'step) Arkode_impl.session
constraint 'step = [<Arkode.arkstep|Arkode.mristep]
type 'step parallel_preconditioner =
(Nvector_parallel.data, Nvector_parallel.kind, 'step)
Arkode_impl.SpilsTypes.preconditioner
constraint 'step = [<Arkode.arkstep|Arkode.mristep]
module Impl = ArkodeBbdParamTypes
type local_fn = data Impl.local_fn
type comm_fn = data Impl.comm_fn
type precfns =
{
local_fn : local_fn;
comm_fn : comm_fn option;
}
let bbd_precfns { local_fn; comm_fn } =
{ Impl.local_fn = local_fn; Impl.comm_fn = comm_fn }
external c_bbd_prec_init
: 'step parallel_session -> int -> bandwidths -> float -> bool -> unit
= "sunml_arkode_bbd_prec_init"
let init_preconditioner dqrely bandwidths precfns session nv =
let ba, _, _ = Nvector.unwrap nv in
let localn = RealArray.length ba in
c_bbd_prec_init session localn bandwidths dqrely (precfns.comm_fn <> None);
session.ls_precfns <- BBDPrecFns (bbd_precfns precfns)
let prec_left ?(dqrely=0.0) bandwidths ?comm local_fn =
LSI.Iterative.(PrecLeft,
init_preconditioner dqrely bandwidths { local_fn ; comm_fn = comm })
let prec_right ?(dqrely=0.0) bandwidths ?comm local_fn =
LSI.Iterative.(PrecRight,
init_preconditioner dqrely bandwidths { local_fn ; comm_fn = comm })
let prec_both ?(dqrely=0.0) bandwidths ?comm local_fn =
LSI.Iterative.(PrecBoth,
init_preconditioner dqrely bandwidths { local_fn ; comm_fn = comm })
external c_bbd_prec_reinit
: 'step parallel_session -> int -> int -> float -> unit
= "sunml_arkode_bbd_prec_reinit"
let reinit s ?(dqrely=0.0) mudq mldq =
ls_check_spils_bbd s;
match s.ls_precfns with
| BBDPrecFns _ -> c_bbd_prec_reinit s mudq mldq dqrely
| _ -> raise LinearSolver.InvalidLinearSolver
external get_work_space : 'step parallel_session -> int * int
= "sunml_arkode_bbd_get_work_space"
let get_work_space s =
ls_check_spils_bbd s;
get_work_space s
external get_num_gfn_evals : 'step parallel_session -> int
= "sunml_arkode_bbd_get_num_gfn_evals"
let get_num_gfn_evals s =
ls_check_spils_bbd s;
get_num_gfn_evals s
| null | https://raw.githubusercontent.com/inria-parkas/sundialsml/a1848318cac2e340c32ddfd42671bef07b1390db/src/arkode/arkode_bbd.ml | ocaml | *********************************************************************
OCaml interface to Sundials
under a New BSD License, refer to the file LICENSE.
********************************************************************* | , , and
( / ENS ) ( / ENS ) ( UPMC / ENS / Inria )
Copyright 2015 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
open Sundials
include Arkode_impl
include ArkodeBbdTypes
These types ca n't be defined in Arkode_impl because they introduce
dependence on . Some duplication is unavoidable .
dependence on Mpi. Some duplication is unavoidable. *)
type data = Nvector_parallel.data
type 'step parallel_session =
(Nvector_parallel.data, Nvector_parallel.kind, 'step) Arkode_impl.session
constraint 'step = [<Arkode.arkstep|Arkode.mristep]
type 'step parallel_preconditioner =
(Nvector_parallel.data, Nvector_parallel.kind, 'step)
Arkode_impl.SpilsTypes.preconditioner
constraint 'step = [<Arkode.arkstep|Arkode.mristep]
module Impl = ArkodeBbdParamTypes
type local_fn = data Impl.local_fn
type comm_fn = data Impl.comm_fn
type precfns =
{
local_fn : local_fn;
comm_fn : comm_fn option;
}
let bbd_precfns { local_fn; comm_fn } =
{ Impl.local_fn = local_fn; Impl.comm_fn = comm_fn }
external c_bbd_prec_init
: 'step parallel_session -> int -> bandwidths -> float -> bool -> unit
= "sunml_arkode_bbd_prec_init"
let init_preconditioner dqrely bandwidths precfns session nv =
let ba, _, _ = Nvector.unwrap nv in
let localn = RealArray.length ba in
c_bbd_prec_init session localn bandwidths dqrely (precfns.comm_fn <> None);
session.ls_precfns <- BBDPrecFns (bbd_precfns precfns)
let prec_left ?(dqrely=0.0) bandwidths ?comm local_fn =
LSI.Iterative.(PrecLeft,
init_preconditioner dqrely bandwidths { local_fn ; comm_fn = comm })
let prec_right ?(dqrely=0.0) bandwidths ?comm local_fn =
LSI.Iterative.(PrecRight,
init_preconditioner dqrely bandwidths { local_fn ; comm_fn = comm })
let prec_both ?(dqrely=0.0) bandwidths ?comm local_fn =
LSI.Iterative.(PrecBoth,
init_preconditioner dqrely bandwidths { local_fn ; comm_fn = comm })
external c_bbd_prec_reinit
: 'step parallel_session -> int -> int -> float -> unit
= "sunml_arkode_bbd_prec_reinit"
let reinit s ?(dqrely=0.0) mudq mldq =
ls_check_spils_bbd s;
match s.ls_precfns with
| BBDPrecFns _ -> c_bbd_prec_reinit s mudq mldq dqrely
| _ -> raise LinearSolver.InvalidLinearSolver
external get_work_space : 'step parallel_session -> int * int
= "sunml_arkode_bbd_get_work_space"
let get_work_space s =
ls_check_spils_bbd s;
get_work_space s
external get_num_gfn_evals : 'step parallel_session -> int
= "sunml_arkode_bbd_get_num_gfn_evals"
let get_num_gfn_evals s =
ls_check_spils_bbd s;
get_num_gfn_evals s
|
7983f7240e46810e289863db0016de7834dcdb2b31be87725eda4695a36e510e | heraldry/heraldicon | arms.cljs | (ns spec.heraldicon.entity.arms
(:require
[cljs.spec.alpha :as s]
[spec.heraldicon.entity]
[spec.heraldicon.entity.arms.data]))
(s/def :heraldicon.entity.arms/type #{:heraldicon.entity.type/arms})
(s/def :heraldicon.entity/arms (s/and :heraldicon/entity
(s/keys :req-un [:heraldicon.entity.arms/type
:heraldicon.entity.arms/data])))
| null | https://raw.githubusercontent.com/heraldry/heraldicon/19c9d10485bbc48e98ddee30092a246cccc986d2/src/spec/heraldicon/entity/arms.cljs | clojure | (ns spec.heraldicon.entity.arms
(:require
[cljs.spec.alpha :as s]
[spec.heraldicon.entity]
[spec.heraldicon.entity.arms.data]))
(s/def :heraldicon.entity.arms/type #{:heraldicon.entity.type/arms})
(s/def :heraldicon.entity/arms (s/and :heraldicon/entity
(s/keys :req-un [:heraldicon.entity.arms/type
:heraldicon.entity.arms/data])))
| |
54809d4a0aa5fd47d379fc1b73e46bd6a5162bc7cc4bff7b63b73e24be49be09 | MercuryTechnologies/slack-web | BlocksSpec.hs | module Web.Slack.Experimental.BlocksSpec where
import Control.Monad.Writer.Strict
import Data.StringVariants (mkNonEmptyText)
import JSONGolden (oneGoldenTestEncode)
import TestImport
import Web.Slack.Experimental.Blocks
import Web.Slack.Experimental.Blocks.Types
-- FIXME(jadel, violet): These builder things should probably be put into a
-- module to make them available, but that's later work
headerBlock :: SlackText -> WriterT [SlackBlock] Identity ()
headerBlock = tell . pure . SlackBlockHeader . SlackPlainTextOnly
sectionBlock :: SlackText -> WriterT [SlackBlock] Identity ()
sectionBlock text = tell . pure $ SlackBlockSection text Nothing
sectionBlockWithAccessory ::
SlackText ->
SlackAction ->
WriterT [SlackBlock] Identity ()
sectionBlockWithAccessory a b = tell . pure $ SlackBlockSection a (Just . SlackButtonAccessory $ b)
dividerBlock :: WriterT [SlackBlock] Identity ()
dividerBlock = tell . pure $ SlackBlockDivider
contextBlock :: [SlackContent] -> WriterT [SlackBlock] Identity ()
contextBlock = tell . pure . SlackBlockContext . SlackContext
actionsBlock ::
Maybe SlackBlockId ->
SlackActionList ->
WriterT [SlackBlock] Identity ()
actionsBlock a b = tell . pure $ SlackBlockActions a b
slackActionDoNothing :: SlackActionId
slackActionDoNothing = SlackActionId . fromJust . mkNonEmptyText $ "doNothing"
slackActionDoNothing2 :: SlackActionId
slackActionDoNothing2 = SlackActionId . fromJust . mkNonEmptyText $ "doNothing2"
slackActionDoNothing3 :: SlackActionId
slackActionDoNothing3 = SlackActionId . fromJust . mkNonEmptyText $ "doNothing3"
slackShowBlockFormat :: BlockKitBuilderMessage
slackShowBlockFormat =
BlockKitBuilderMessage $
execWriter $ do
headerBlock ("Blah: " <> list ["a", "b", "c"])
dividerBlock
sectionBlock (bold $ list ["blah", "blah2", "blah3"])
sectionBlockWithAccessory
(monospaced @Text "blah")
(button slackActionDoNothing ":mag: Look at it" buttonSettings {buttonUrl = google})
sectionBlockWithAccessory
(bold $ list ["blah", "blah2", "blah3"])
(button slackActionDoNothing ":office: Look at it but different" buttonSettings {buttonUrl = google})
sectionBlock (bold (textMessage "Letters:") <> newline (list ["a", "b", "c"]))
sectionBlock (list ["blah1", "blah2", "blah3"])
dividerBlock
sectionBlock (bold . textMessage $ "blah")
sectionBlockWithAccessory
(bold . textMessage $ "blah")
(button slackActionDoNothing ":bank: Look at it!" buttonSettings {buttonUrl = google})
contextBlock [SlackContentText ":key: Context!"]
dividerBlock
actionsBlock Nothing $
toSlackActionList
( button slackActionDoNothing ":mag: View" buttonSettings {buttonUrl = google}
, button slackActionDoNothing2 ":office: View" buttonSettings {buttonUrl = google}
, button slackActionDoNothing3 ":bank: View" buttonSettings {buttonUrl = google}
)
where
textMessage = message @Text
list x = textMessage (intercalate ", " x)
google = OptionalSetting . mkNonEmptyText @3000 $ ""
-- | This is used so that we can paste the output of these tests directly into
-- the block kit builder:
-- <-kit-builder>
newtype BlockKitBuilderMessage = BlockKitBuilderMessage {blocks :: [SlackBlock]}
instance ToJSON BlockKitBuilderMessage where
toJSON BlockKitBuilderMessage {blocks} = object [("blocks", toJSON blocks)]
spec :: Spec
spec = describe "Slack block builder" do
oneGoldenTestEncode "simple_blocks" slackShowBlockFormat
| null | https://raw.githubusercontent.com/MercuryTechnologies/slack-web/1ce60453e3ceb36b98bbb2937f70dfbfcc5f8928/tests/Web/Slack/Experimental/BlocksSpec.hs | haskell | FIXME(jadel, violet): These builder things should probably be put into a
module to make them available, but that's later work
| This is used so that we can paste the output of these tests directly into
the block kit builder:
<-kit-builder> | module Web.Slack.Experimental.BlocksSpec where
import Control.Monad.Writer.Strict
import Data.StringVariants (mkNonEmptyText)
import JSONGolden (oneGoldenTestEncode)
import TestImport
import Web.Slack.Experimental.Blocks
import Web.Slack.Experimental.Blocks.Types
headerBlock :: SlackText -> WriterT [SlackBlock] Identity ()
headerBlock = tell . pure . SlackBlockHeader . SlackPlainTextOnly
sectionBlock :: SlackText -> WriterT [SlackBlock] Identity ()
sectionBlock text = tell . pure $ SlackBlockSection text Nothing
sectionBlockWithAccessory ::
SlackText ->
SlackAction ->
WriterT [SlackBlock] Identity ()
sectionBlockWithAccessory a b = tell . pure $ SlackBlockSection a (Just . SlackButtonAccessory $ b)
dividerBlock :: WriterT [SlackBlock] Identity ()
dividerBlock = tell . pure $ SlackBlockDivider
contextBlock :: [SlackContent] -> WriterT [SlackBlock] Identity ()
contextBlock = tell . pure . SlackBlockContext . SlackContext
actionsBlock ::
Maybe SlackBlockId ->
SlackActionList ->
WriterT [SlackBlock] Identity ()
actionsBlock a b = tell . pure $ SlackBlockActions a b
slackActionDoNothing :: SlackActionId
slackActionDoNothing = SlackActionId . fromJust . mkNonEmptyText $ "doNothing"
slackActionDoNothing2 :: SlackActionId
slackActionDoNothing2 = SlackActionId . fromJust . mkNonEmptyText $ "doNothing2"
slackActionDoNothing3 :: SlackActionId
slackActionDoNothing3 = SlackActionId . fromJust . mkNonEmptyText $ "doNothing3"
slackShowBlockFormat :: BlockKitBuilderMessage
slackShowBlockFormat =
BlockKitBuilderMessage $
execWriter $ do
headerBlock ("Blah: " <> list ["a", "b", "c"])
dividerBlock
sectionBlock (bold $ list ["blah", "blah2", "blah3"])
sectionBlockWithAccessory
(monospaced @Text "blah")
(button slackActionDoNothing ":mag: Look at it" buttonSettings {buttonUrl = google})
sectionBlockWithAccessory
(bold $ list ["blah", "blah2", "blah3"])
(button slackActionDoNothing ":office: Look at it but different" buttonSettings {buttonUrl = google})
sectionBlock (bold (textMessage "Letters:") <> newline (list ["a", "b", "c"]))
sectionBlock (list ["blah1", "blah2", "blah3"])
dividerBlock
sectionBlock (bold . textMessage $ "blah")
sectionBlockWithAccessory
(bold . textMessage $ "blah")
(button slackActionDoNothing ":bank: Look at it!" buttonSettings {buttonUrl = google})
contextBlock [SlackContentText ":key: Context!"]
dividerBlock
actionsBlock Nothing $
toSlackActionList
( button slackActionDoNothing ":mag: View" buttonSettings {buttonUrl = google}
, button slackActionDoNothing2 ":office: View" buttonSettings {buttonUrl = google}
, button slackActionDoNothing3 ":bank: View" buttonSettings {buttonUrl = google}
)
where
textMessage = message @Text
list x = textMessage (intercalate ", " x)
google = OptionalSetting . mkNonEmptyText @3000 $ ""
newtype BlockKitBuilderMessage = BlockKitBuilderMessage {blocks :: [SlackBlock]}
instance ToJSON BlockKitBuilderMessage where
toJSON BlockKitBuilderMessage {blocks} = object [("blocks", toJSON blocks)]
spec :: Spec
spec = describe "Slack block builder" do
oneGoldenTestEncode "simple_blocks" slackShowBlockFormat
|
e0a71459c8f791678f71346fcef601a6a77f1d4fcb06080604fba42ebe3b5276 | Chris00/ocaml-rope | bm_ropes.ml | File : bm_ropes.ml
Copyright ( C ) 2007
< >
WWW : /
This library is free software ; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1 or
later as published by the Free Software Foundation , with the special
exception on linking described in the file LICENSE .
This library is distributed in the hope that it will be useful , but
WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
LICENSE for more details .
Copyright (C) 2007
Christophe Troestler <>
WWW: /
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1 or
later as published by the Free Software Foundation, with the special
exception on linking described in the file LICENSE.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
LICENSE for more details. *)
open Printf
let () = Random.self_init()
let nsamples = 30
let n_ops = 1000
let n_ops = 10000
let max_nconcat = 8
* how many concatenations of ropes ( in the map ) with lower length
are accepted . [ 1 ] means : pick the laegest and complete appending
chars .
are accepted. [1] means: pick the laegest and complete appending
chars. *)
let prepend_size = 128
(** if [size land prepend_size = 0] prepend chars instead of appending.
Set to [max_int]: always append (never prepend).
Set to [0]: always preprend. *)
let min_pow10 = 2
let max_pox10 = 7
let rec pow n = function 0 -> 1 | i -> n * pow n (i - 1)
let list_init n f =
let rec make acc n = if n < 0 then acc else make (f n :: acc) (n - 1) in
make [] (n-1)
let datapoints =
let basis = [1; 2; 3; 5; 17; 37; 53; 91; 201] in
let basis = List.sort compare ( list_init 15 ( fun _ - > 1 + Random.int 200 ) ) in
let d = max_pox10 - min_pow10 in
let pow10_of j = Array.init d (fun i -> j * pow 10 (i + min_pow10)) in
Array.concat (List.map pow10_of basis (*@ [ [|max_int / 2 |] } *) )
FIXME : for max_int ( 32 bits ) , TinyRope segfaults ! ! !
let datapoints2 =
Array.concat [
(Array.init 20 (fun _ -> 10000 + Random.int 10_000_000));
(Array.init 20 (fun _ -> 10_000_000 + Random.int 50_000_000));
]
(* ---------------------------------------------------------------------- *)
let datapoints_ordered =
let d = Array.copy datapoints in
Array.sort compare d;
d
(* just for laughs *)
let basic_loop_overhead =
let t1 = Unix.gettimeofday () in
for _ = 0 to 100 do
for _ = 0 to n_ops do ignore () done
done;
(Unix.gettimeofday () -. t1) /. 100.0
let random_loop_overhead =
let t1 = Unix.gettimeofday () in
for _ = 0 to 100 do
for _ = 0 to n_ops do ignore (Random.int 10000) done;
done;
(Unix.gettimeofday () -. t1) /. 100.0
let () =
printf "Random loop overhead: %12.10f\n" random_loop_overhead;
printf "Basic loop overhead: %12.10f\n" basic_loop_overhead
let time ~msg f x =
let t0 = Sys.time () in
let r = f x in
printf "%s needed %8.5fs\n%!" msg (Sys.time () -. t0);
r
let sample msg f x =
print_string msg;
let samples =
Array.init nsamples (fun i -> printf "\r%2d/%4d%!" (i + 1) nsamples; f x) in
printf "\r \r%!";
let min_sample (tmin,_) (t,d) = (min tmin t, d) in
Array.fold_left min_sample (max_float, max_int) samples
let sum_sample ( tsum , _ ) ( t , d ) = ( tsum + . t , d ) in
let t , d = ( 0.0 , 0 ) samples in
t /. , d
let t, d = Array.fold_left sum_sample (0.0, 0) samples in
t /. float_of_int nsamples, d
*)
module IMap = Map.Make(struct type t = int let compare = compare end)
module Benchmark(R :
sig
type t
val name : string
val balanced : bool
val empty : t
val append : char -> t -> t
val prepend : char -> t -> t
val concat : t -> t -> t
val length : t -> int
val height : t -> int
val balance : t -> t
val get : t -> int -> char
val sub : t -> int -> int -> t
val of_string : string -> t
val to_string : t -> string
end) =
struct
(** [make_rope size] returns a rope of length [size]. We
concatenate small ropes as it is more reprensentative than only
appending repeatedly chars. *)
let make_rope =
let rope_tbl = ref IMap.empty in
let rec add_chars r c size =
if size <= 0 then r else
let op = if size land prepend_size = 0 then R.prepend else R.append in
add_chars (op c r) c (size - 1) in
let rec build nconcat r size =
let largest =
IMap.fold (fun _ v s ->
let len = R.length v in
if len > R.length s && len <= size then v else s
) !rope_tbl R.empty in
if R.length largest = 0 || nconcat > max_nconcat then
(* no piece to add to [r] *)
add_chars r 'x' (size - R.length largest)
else
let r' =
if Random.bool() then R.concat r largest else R.concat largest r in
build (nconcat + 1) r' (size - R.length largest) in
fun size ->
let r = build 0 R.empty size in
rope_tbl := IMap.add size r !rope_tbl;
if R.balanced then R.balance r else r
;;
let append_time size =
let v = ref (make_rope size) in
let t0 = Unix.gettimeofday () in
for _ = 0 to n_ops - 1 do
v := R.append 'z' !v;
(* ignore (append_f I !v); *)
done;
let dt = (Unix.gettimeofday () -. t0) in
(dt -. basic_loop_overhead) /. (float_of_int n_ops), R.height !v
let measure_append_time size =
let msg = sprintf "Append time for %s of size %d\n%!" R.name size in
sample msg append_time size
let random_get_time size =
let r = make_rope size in
(* Gc.full_major (); *)
let t0 = Unix.gettimeofday () in
(* let sum = ref 0 in *)
for _ = 0 to n_ops - 1 do
ignore(R.get r (Random.int size));
done;
let dt = (Unix.gettimeofday () -. t0) in
(dt -. random_loop_overhead) /. float n_ops, R.height r
float ! sum /. float n_ops , r
let measure_random_get_time size =
let msg = sprintf "Random get time for %s of size %d\n%!" R.name size in
sample msg random_get_time size
let sub_time size =
let r = make_rope size in
let t0 = Unix.gettimeofday () in
let h = ref 0 in
for _ = 0 to n_ops - 1 do
h := !h + R.height(R.sub r 0 (Random.int size));
done;
let dt = (Unix.gettimeofday () -. t0) in
(dt -. random_loop_overhead) /. float n_ops,
truncate(0.5 +. float !h /. float n_ops) (* round *)
let measure_sub_time size =
let msg = sprintf "Sub time for %s of size %d\n%!" R.name size in
sample msg sub_time size
(* Test inspired by *)
let size = 512 * 1024
let size8 = 8 + size
[ text ] is make of [ nchunks ] chunks of text , each of [ size ] bytes
long . Each chunck starts with an 8 byte number . Initially the
chuncks are shuffled the this function sorts them into ascending
order .
long. Each chunck starts with an 8 byte number. Initially the
chuncks are shuffled the this function sorts them into ascending
order. *)
let rec qsort text =
if R.length text = 0 then text else begin
let pivot = int_of_string(R.to_string(R.sub text 0 8)) in
let less = ref R.empty
and more = ref R.empty in
let offset = ref size8 in
while !offset < R.length text do
let i = int_of_string(R.to_string(R.sub text !offset 8)) in
if i < pivot then
less := R.concat !less (R.sub text !offset size8)
else
more := R.concat !more (R.sub text !offset size8);
offset := !offset + 8 + size;
done;
R.concat (qsort !less) (R.concat (R.sub text 0 size8) (qsort !more))
end
let bulk_string = make_rope size
let do_qsort size =
let nchunks = size / 100_000 in
let data = ref R.empty in
for _ = 1 to nchunks do
data := R.concat !data
(R.concat (R.of_string(sprintf "%08i" (Random.int nchunks)))
bulk_string)
done;
let t0 = Unix.gettimeofday () in
let sorted = qsort !data in
let dt = (Unix.gettimeofday () -. t0) in
(dt -. random_loop_overhead) /. float n_ops, R.height sorted
let measure_qsort size =
let msg = sprintf "Qsort time for %s of size %d\n%!" R.name size in
sample msg do_qsort size
end
module TinyBM =
struct
let name = "TinyRope"
include TinyRope
let append = TinyRope.append_char
let prepend = TinyRope.prepend_char
let get r i = TinyRope.get i r
let sub r start len = TinyRope.sub start len r
end
module FullBM =
struct
let name = "Rope"
include Rope
let append c r = Rope.concat2 r (Rope.of_char c)
let prepend c r = Rope.concat2 (Rope.of_char c) r
let concat = Rope.concat2
end
module BalancedFullBM =
Benchmark(struct include FullBM let balanced = true end)
module UnbalancedFullBM =
Benchmark(struct include FullBM let balanced = false end)
module BalancedTinyBM =
Benchmark(struct include TinyBM let balanced = true end)
module UnbalancedTinyBM =
Benchmark(struct include TinyBM let balanced = false end)
let benchmark dst measl =
let gather_times f =
Array.fold_left (fun bm size -> IMap.add size (f size) bm)
IMap.empty datapoints in
let times = List.map gather_times measl in
let ch = open_out dst in
Array.iter (fun size ->
fprintf ch "%d" size;
List.iter (fun tbl ->
let t, sz = IMap.find size tbl in
fprintf ch "\t%12.10e\t%i" t sz
) times;
fprintf ch "\n"
) datapoints_ordered;
close_out ch
let () =
benchmark "append.dat" [UnbalancedTinyBM.measure_append_time;
UnbalancedFullBM.measure_append_time ];
Gc.full_major ();
benchmark "get.dat" [UnbalancedTinyBM.measure_random_get_time;
UnbalancedFullBM.measure_random_get_time ];
Gc.full_major ();
benchmark "append-balanced.dat" [BalancedTinyBM.measure_append_time;
BalancedFullBM.measure_append_time];
Gc.full_major ();
benchmark "get-balanced.dat" [BalancedTinyBM.measure_random_get_time;
BalancedFullBM.measure_random_get_time];
Gc.full_major ();
benchmark "sub.dat" [UnbalancedTinyBM.measure_sub_time;
UnbalancedFullBM.measure_sub_time;
BalancedTinyBM.measure_sub_time;
BalancedFullBM.measure_sub_time ];
Gc.full_major ();
benchmark "qsort.dat" [UnbalancedTinyBM.measure_qsort;
UnbalancedFullBM.measure_qsort;
BalancedTinyBM.measure_qsort;
BalancedFullBM.measure_qsort ];
()
| null | https://raw.githubusercontent.com/Chris00/ocaml-rope/7d457b2e69a16aede8cfbae43be29f208d007694/bench/bm_ropes.ml | ocaml | * if [size land prepend_size = 0] prepend chars instead of appending.
Set to [max_int]: always append (never prepend).
Set to [0]: always preprend.
@ [ [|max_int / 2 |] }
----------------------------------------------------------------------
just for laughs
* [make_rope size] returns a rope of length [size]. We
concatenate small ropes as it is more reprensentative than only
appending repeatedly chars.
no piece to add to [r]
ignore (append_f I !v);
Gc.full_major ();
let sum = ref 0 in
round
Test inspired by | File : bm_ropes.ml
Copyright ( C ) 2007
< >
WWW : /
This library is free software ; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1 or
later as published by the Free Software Foundation , with the special
exception on linking described in the file LICENSE .
This library is distributed in the hope that it will be useful , but
WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
LICENSE for more details .
Copyright (C) 2007
Christophe Troestler <>
WWW: /
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 2.1 or
later as published by the Free Software Foundation, with the special
exception on linking described in the file LICENSE.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
LICENSE for more details. *)
open Printf
let () = Random.self_init()
let nsamples = 30
let n_ops = 1000
let n_ops = 10000
let max_nconcat = 8
* how many concatenations of ropes ( in the map ) with lower length
are accepted . [ 1 ] means : pick the laegest and complete appending
chars .
are accepted. [1] means: pick the laegest and complete appending
chars. *)
let prepend_size = 128
let min_pow10 = 2
let max_pox10 = 7
let rec pow n = function 0 -> 1 | i -> n * pow n (i - 1)
let list_init n f =
let rec make acc n = if n < 0 then acc else make (f n :: acc) (n - 1) in
make [] (n-1)
let datapoints =
let basis = [1; 2; 3; 5; 17; 37; 53; 91; 201] in
let basis = List.sort compare ( list_init 15 ( fun _ - > 1 + Random.int 200 ) ) in
let d = max_pox10 - min_pow10 in
let pow10_of j = Array.init d (fun i -> j * pow 10 (i + min_pow10)) in
FIXME : for max_int ( 32 bits ) , TinyRope segfaults ! ! !
let datapoints2 =
Array.concat [
(Array.init 20 (fun _ -> 10000 + Random.int 10_000_000));
(Array.init 20 (fun _ -> 10_000_000 + Random.int 50_000_000));
]
let datapoints_ordered =
let d = Array.copy datapoints in
Array.sort compare d;
d
let basic_loop_overhead =
let t1 = Unix.gettimeofday () in
for _ = 0 to 100 do
for _ = 0 to n_ops do ignore () done
done;
(Unix.gettimeofday () -. t1) /. 100.0
let random_loop_overhead =
let t1 = Unix.gettimeofday () in
for _ = 0 to 100 do
for _ = 0 to n_ops do ignore (Random.int 10000) done;
done;
(Unix.gettimeofday () -. t1) /. 100.0
let () =
printf "Random loop overhead: %12.10f\n" random_loop_overhead;
printf "Basic loop overhead: %12.10f\n" basic_loop_overhead
let time ~msg f x =
let t0 = Sys.time () in
let r = f x in
printf "%s needed %8.5fs\n%!" msg (Sys.time () -. t0);
r
let sample msg f x =
print_string msg;
let samples =
Array.init nsamples (fun i -> printf "\r%2d/%4d%!" (i + 1) nsamples; f x) in
printf "\r \r%!";
let min_sample (tmin,_) (t,d) = (min tmin t, d) in
Array.fold_left min_sample (max_float, max_int) samples
let sum_sample ( tsum , _ ) ( t , d ) = ( tsum + . t , d ) in
let t , d = ( 0.0 , 0 ) samples in
t /. , d
let t, d = Array.fold_left sum_sample (0.0, 0) samples in
t /. float_of_int nsamples, d
*)
module IMap = Map.Make(struct type t = int let compare = compare end)
module Benchmark(R :
sig
type t
val name : string
val balanced : bool
val empty : t
val append : char -> t -> t
val prepend : char -> t -> t
val concat : t -> t -> t
val length : t -> int
val height : t -> int
val balance : t -> t
val get : t -> int -> char
val sub : t -> int -> int -> t
val of_string : string -> t
val to_string : t -> string
end) =
struct
let make_rope =
let rope_tbl = ref IMap.empty in
let rec add_chars r c size =
if size <= 0 then r else
let op = if size land prepend_size = 0 then R.prepend else R.append in
add_chars (op c r) c (size - 1) in
let rec build nconcat r size =
let largest =
IMap.fold (fun _ v s ->
let len = R.length v in
if len > R.length s && len <= size then v else s
) !rope_tbl R.empty in
if R.length largest = 0 || nconcat > max_nconcat then
add_chars r 'x' (size - R.length largest)
else
let r' =
if Random.bool() then R.concat r largest else R.concat largest r in
build (nconcat + 1) r' (size - R.length largest) in
fun size ->
let r = build 0 R.empty size in
rope_tbl := IMap.add size r !rope_tbl;
if R.balanced then R.balance r else r
;;
let append_time size =
let v = ref (make_rope size) in
let t0 = Unix.gettimeofday () in
for _ = 0 to n_ops - 1 do
v := R.append 'z' !v;
done;
let dt = (Unix.gettimeofday () -. t0) in
(dt -. basic_loop_overhead) /. (float_of_int n_ops), R.height !v
let measure_append_time size =
let msg = sprintf "Append time for %s of size %d\n%!" R.name size in
sample msg append_time size
let random_get_time size =
let r = make_rope size in
let t0 = Unix.gettimeofday () in
for _ = 0 to n_ops - 1 do
ignore(R.get r (Random.int size));
done;
let dt = (Unix.gettimeofday () -. t0) in
(dt -. random_loop_overhead) /. float n_ops, R.height r
float ! sum /. float n_ops , r
let measure_random_get_time size =
let msg = sprintf "Random get time for %s of size %d\n%!" R.name size in
sample msg random_get_time size
let sub_time size =
let r = make_rope size in
let t0 = Unix.gettimeofday () in
let h = ref 0 in
for _ = 0 to n_ops - 1 do
h := !h + R.height(R.sub r 0 (Random.int size));
done;
let dt = (Unix.gettimeofday () -. t0) in
(dt -. random_loop_overhead) /. float n_ops,
let measure_sub_time size =
let msg = sprintf "Sub time for %s of size %d\n%!" R.name size in
sample msg sub_time size
let size = 512 * 1024
let size8 = 8 + size
[ text ] is make of [ nchunks ] chunks of text , each of [ size ] bytes
long . Each chunck starts with an 8 byte number . Initially the
chuncks are shuffled the this function sorts them into ascending
order .
long. Each chunck starts with an 8 byte number. Initially the
chuncks are shuffled the this function sorts them into ascending
order. *)
let rec qsort text =
if R.length text = 0 then text else begin
let pivot = int_of_string(R.to_string(R.sub text 0 8)) in
let less = ref R.empty
and more = ref R.empty in
let offset = ref size8 in
while !offset < R.length text do
let i = int_of_string(R.to_string(R.sub text !offset 8)) in
if i < pivot then
less := R.concat !less (R.sub text !offset size8)
else
more := R.concat !more (R.sub text !offset size8);
offset := !offset + 8 + size;
done;
R.concat (qsort !less) (R.concat (R.sub text 0 size8) (qsort !more))
end
let bulk_string = make_rope size
let do_qsort size =
let nchunks = size / 100_000 in
let data = ref R.empty in
for _ = 1 to nchunks do
data := R.concat !data
(R.concat (R.of_string(sprintf "%08i" (Random.int nchunks)))
bulk_string)
done;
let t0 = Unix.gettimeofday () in
let sorted = qsort !data in
let dt = (Unix.gettimeofday () -. t0) in
(dt -. random_loop_overhead) /. float n_ops, R.height sorted
let measure_qsort size =
let msg = sprintf "Qsort time for %s of size %d\n%!" R.name size in
sample msg do_qsort size
end
module TinyBM =
struct
let name = "TinyRope"
include TinyRope
let append = TinyRope.append_char
let prepend = TinyRope.prepend_char
let get r i = TinyRope.get i r
let sub r start len = TinyRope.sub start len r
end
module FullBM =
struct
let name = "Rope"
include Rope
let append c r = Rope.concat2 r (Rope.of_char c)
let prepend c r = Rope.concat2 (Rope.of_char c) r
let concat = Rope.concat2
end
module BalancedFullBM =
Benchmark(struct include FullBM let balanced = true end)
module UnbalancedFullBM =
Benchmark(struct include FullBM let balanced = false end)
module BalancedTinyBM =
Benchmark(struct include TinyBM let balanced = true end)
module UnbalancedTinyBM =
Benchmark(struct include TinyBM let balanced = false end)
let benchmark dst measl =
let gather_times f =
Array.fold_left (fun bm size -> IMap.add size (f size) bm)
IMap.empty datapoints in
let times = List.map gather_times measl in
let ch = open_out dst in
Array.iter (fun size ->
fprintf ch "%d" size;
List.iter (fun tbl ->
let t, sz = IMap.find size tbl in
fprintf ch "\t%12.10e\t%i" t sz
) times;
fprintf ch "\n"
) datapoints_ordered;
close_out ch
let () =
benchmark "append.dat" [UnbalancedTinyBM.measure_append_time;
UnbalancedFullBM.measure_append_time ];
Gc.full_major ();
benchmark "get.dat" [UnbalancedTinyBM.measure_random_get_time;
UnbalancedFullBM.measure_random_get_time ];
Gc.full_major ();
benchmark "append-balanced.dat" [BalancedTinyBM.measure_append_time;
BalancedFullBM.measure_append_time];
Gc.full_major ();
benchmark "get-balanced.dat" [BalancedTinyBM.measure_random_get_time;
BalancedFullBM.measure_random_get_time];
Gc.full_major ();
benchmark "sub.dat" [UnbalancedTinyBM.measure_sub_time;
UnbalancedFullBM.measure_sub_time;
BalancedTinyBM.measure_sub_time;
BalancedFullBM.measure_sub_time ];
Gc.full_major ();
benchmark "qsort.dat" [UnbalancedTinyBM.measure_qsort;
UnbalancedFullBM.measure_qsort;
BalancedTinyBM.measure_qsort;
BalancedFullBM.measure_qsort ];
()
|
f13055a71be5ec89b507cdb3a54c43ee89a360923ec726d21615cf662b68d493 | yi-editor/yi | Eval.hs | # LANGUAGE CPP #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
#ifdef HINT
# LANGUAGE FlexibleContexts #
#endif
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
Module : . Eval
-- License : GPL-2
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Evaluator for actions ('Action', 'YiAction'). Uses a @GHCi@ session
-- under the hood.
module Yi.Eval (
-- * Main (generic) evaluation interface
execEditorAction,
getAllNamesInScope,
describeNamedAction,
Evaluator(..),
evaluator,
-- ** Standard evaluators
#ifdef HINT
ghciEvaluator,
#endif
publishedActionsEvaluator,
publishedActions,
publishAction,
-- * Eval/Interpretation
jumpToErrorE,
jumpToE,
consoleKeymap
) where
import Prelude hiding (mapM_)
import Lens.Micro.Platform ( (^.), (.=), (%=) )
import Control.Monad (when, forever, void)
import Data.Array ( elems )
import Data.Binary ( Binary )
import Data.Default ( Default, def )
import Data.Foldable ( mapM_ )
import qualified Data.HashMap.Strict as M
( HashMap, insert, lookup, empty, keys )
import Data.Monoid ((<>))
import Data.Semigroup ( Semigroup )
import Data.Typeable ( Typeable )
#ifdef HINT
import Control.Concurrent
( takeMVar, putMVar, newEmptyMVar, MVar, forkIO )
import Control.Monad.Base ( MonadBase )
import Control.Monad.Catch ( try )
import Control.Monad.Trans ( lift )
import Data.Binary ( get, put )
import Data.List ( sort )
import qualified Language.Haskell.Interpreter as LHI
( typeOf,
setImportsQ,
searchPath,
set,
runInterpreter,
ModuleElem(Data, Class, Fun),
getModuleExports,
as,
loadModules,
languageExtensions,
OptionVal((:=)),
InterpreterError,
Extension(OverloadedStrings),
setTopLevelModules,
InterpreterT,
interpret )
import System.Directory ( doesFileExist )
import Yi.Core ( errorEditor )
import Yi.Editor
( getEditorDyn,
putEditorDyn,
MonadEditor)
import qualified Yi.Paths ( getEvaluatorContextFilename )
import Yi.String ( showT )
import Yi.Utils ( io )
#endif
import Text.Read ( readMaybe )
import Yi.Buffer
( gotoLn,
moveXorEol,
BufferM,
readLnB,
pointB,
botB,
insertN,
getBookmarkB,
markPointA )
import Yi.Config.Simple.Types ( customVariable, Field, ConfigM )
import Yi.Core ( runAction )
import Yi.Types ( YiVariable, YiConfigVariable )
import Yi.Editor
( printMsg,
askCfg,
withCurrentBuffer,
withCurrentBuffer )
import Yi.File ( openingNewFile )
import Yi.Hooks ( runHook )
import Yi.Keymap
( YiM, Action, YiAction, makeAction, Keymap, write )
import Yi.Keymap.Keys ( event, Event(..), Key(KEnter) )
import Yi.Regex ( Regex, makeRegex, matchOnceText )
import qualified Yi.Rope as R
( toString, YiString, splitAt, length )
import Yi.Utils ( makeLensesWithSuffix )
infixl 1 <&>
(<&>) :: Functor f => f a -> (a -> b) -> f b
a <&> f = f <$> a
-- TODO: should we be sticking Text here?
-- | Config variable for customising the behaviour of
-- 'execEditorAction' and 'getAllNamesInScope'.
--
-- Set this variable using 'evaluator'. See 'ghciEvaluator' and
' finiteListEvaluator ' for two implementation .
data Evaluator = Evaluator
{ execEditorActionImpl :: String -> YiM ()
-- ^ implementation of 'execEditorAction'
, getAllNamesInScopeImpl :: YiM [String]
-- ^ implementation of 'getAllNamesInScope'
, describeNamedActionImpl :: String -> YiM String
-- ^ describe named action (or at least its type.), simplest implementation is at least @return@.
} deriving (Typeable)
-- * Evaluator based on GHCi
-- | Cached variable for getAllNamesInScopeImpl
newtype NamesCache = NamesCache [String] deriving (Typeable, Binary)
instance Default NamesCache where
def = NamesCache []
instance YiVariable NamesCache
| Cached dictionary for describeNameImpl
newtype HelpCache = HelpCache (M.HashMap String String) deriving (Typeable, Binary)
instance Default HelpCache where
def = HelpCache M.empty
instance YiVariable HelpCache
#ifdef HINT
data HintRequest = HintEvaluate String (MVar (Either LHI.InterpreterError Action))
| HintGetNames (MVar (Either LHI.InterpreterError [LHI.ModuleElem]))
| HintDescribe String (MVar (Either LHI.InterpreterError String))
newtype HintThreadVar = HintThreadVar (Maybe (MVar HintRequest))
deriving (Typeable, Default)
instance Binary HintThreadVar where
put _ = return ()
get = return def
instance YiVariable HintThreadVar
getHintThread :: (MonadEditor m, MonadBase IO m) => m (MVar HintRequest)
getHintThread = do
HintThreadVar x <- getEditorDyn
case x of
Just t -> return t
Nothing -> do
req <- io newEmptyMVar
contextFile <- Yi.Paths.getEvaluatorContextFilename
void . io . forkIO $ hintEvaluatorThread req contextFile
putEditorDyn . HintThreadVar $ Just req
return req
hintEvaluatorThread :: MVar HintRequest -> FilePath -> IO ()
hintEvaluatorThread request contextFile = do
haveUserContext <- doesFileExist contextFile
void $ LHI.runInterpreter $ do
LHI.set [LHI.searchPath LHI.:= []]
LHI.set [LHI.languageExtensions LHI.:= [ LHI.OverloadedStrings ]]
when haveUserContext $ do
LHI.loadModules [contextFile]
LHI.setTopLevelModules ["Env"]
Yi . : Action lives there
setImp <- try $ LHI.setImportsQ [("Yi", Nothing), ("Yi.Keymap",Just "Yi.Keymap")]
:: LHI.InterpreterT IO (Either LHI.InterpreterError ())
case setImp of
Left e -> lift $ forever $ takeMVar request >>= \case
HintEvaluate _ response -> putMVar response (Left e)
HintGetNames response -> putMVar response (Left e)
HintDescribe _ response -> putMVar response (Left e)
Right _ -> forever $ lift (takeMVar request) >>= \case
HintEvaluate s response -> do
res <- try $ LHI.interpret ("Yi.makeAction (" ++ s ++ ")") (LHI.as :: Action)
lift $ putMVar response res
HintGetNames response -> do
res <- try $ LHI.getModuleExports "Yi"
lift $ putMVar response res
HintDescribe name response -> do
res <- try $ LHI.typeOf name
lift $ putMVar response res
-- Evaluator implemented by calling GHCi. This evaluator can run
-- arbitrary expressions in the class 'YiAction'.
--
The following two imports are always present :
--
> import
> import qualified . as .
--
-- Also, if the file
--
-- > $HOME/.config/yi/local/Env.hs
--
-- exists, it is imported unqualified.
ghciEvaluator :: Evaluator
ghciEvaluator = Evaluator { execEditorActionImpl = execAction
, getAllNamesInScopeImpl = getNames
, describeNamedActionImpl = describeName -- TODO: use haddock to add docs
}
where
execAction :: String -> YiM ()
execAction s = do
request <- getHintThread
res <- io $ do
response <- newEmptyMVar
putMVar request (HintEvaluate s response)
takeMVar response
case res of
Left err -> errorEditor (showT err)
Right action -> runAction action
getNames :: YiM [String]
getNames = do
NamesCache cache <- getEditorDyn
result <- if null cache
then do
request <- getHintThread
res <- io $ do
response <- newEmptyMVar
putMVar request (HintGetNames response)
takeMVar response
return $ case res of
Left err -> [show err]
Right exports -> flattenExports exports
else return $ sort cache
putEditorDyn $ NamesCache result
return result
flattenExports :: [LHI.ModuleElem] -> [String]
flattenExports = concatMap flattenExport
flattenExport :: LHI.ModuleElem -> [String]
flattenExport (LHI.Fun x) = [x]
flattenExport (LHI.Class _ xs) = xs
flattenExport (LHI.Data _ xs) = xs
describeName :: String -> YiM String
describeName name = do
HelpCache cache <- getEditorDyn
description <- case name `M.lookup` cache of
Nothing -> do
request <- getHintThread
res <- io $ do
response <- newEmptyMVar
putMVar request (HintDescribe name response)
takeMVar response
let newDescription = either show id res
putEditorDyn $ HelpCache $ M.insert name newDescription cache
return newDescription
Just description -> return description
return $ name ++ " :: " ++ description
#endif
-- * 'PublishedActions' evaluator
newtype PublishedActions = PublishedActions {
_publishedActions :: M.HashMap String Action
} deriving(Typeable, Semigroup, Monoid)
instance Default PublishedActions where def = mempty
makeLensesWithSuffix "A" ''PublishedActions
instance YiConfigVariable PublishedActions
-- | Accessor for the published actions. Consider using
-- 'publishAction'.
publishedActions :: Field (M.HashMap String Action)
publishedActions = customVariable . _publishedActionsA
-- | Publish the given action, by the given name. This will overwrite
-- any existing actions by the same name.
publishAction :: (YiAction a x, Show x) => String -> a -> ConfigM ()
publishAction s a = publishedActions %= M.insert s (makeAction a)
-- | Evaluator based on a fixed list of published actions. Has a few
-- differences from 'ghciEvaluator':
--
-- * expressions can't be evaluated
--
-- * all suggested actions are actually valued
--
* ( related to the above ) does n't contain junk actions from Prelude
--
-- * doesn't require GHCi backend, so uses less memory
publishedActionsEvaluator :: Evaluator
publishedActionsEvaluator = Evaluator
{ getAllNamesInScopeImpl = askCfg <&> M.keys . (^. publishedActions)
, execEditorActionImpl = \s ->
askCfg <&> M.lookup s . (^. publishedActions) >>= mapM_ runAction
TODO : try to show types using TemplateHaskell !
}
-- * Miscellaneous interpreter
-- | Jumps to specified position in a given file.
jumpToE :: FilePath -- ^ Filename to make the jump in.
-> Int -- ^ Line to jump to.
-> Int -- ^ Column to jump to.
-> YiM ()
jumpToE filename line column =
openingNewFile filename $ gotoLn line >> moveXorEol column
-- | Regex parsing the error message format.
errorRegex :: Regex
errorRegex = makeRegex ("^(.+):([0-9]+):([0-9]+):.*$" :: String)
-- | Parses an error message. Fails if it can't parse out the needed
-- information, namely filename, line number and column number.
parseErrorMessage :: R.YiString -> Maybe (String, Int, Int)
parseErrorMessage ln = do
(_ ,result, _) <- matchOnceText errorRegex (R.toString ln)
case take 3 $ map fst $ elems result of
[_, fname, l, c] -> (,,) <$> return fname <*> readMaybe l <*> readMaybe c
_ -> Nothing
-- | Tries to parse an error message at current line using
-- 'parseErrorMessage'.
parseErrorMessageB :: BufferM (Maybe (String, Int, Int))
parseErrorMessageB = parseErrorMessage <$> readLnB
-- | Tries to jump to error at the current line. See
-- 'parseErrorMessageB'.
jumpToErrorE :: YiM ()
jumpToErrorE = withCurrentBuffer parseErrorMessageB >>= \case
Nothing -> printMsg "Couldn't parse out an error message."
Just (f, l, c) -> jumpToE f l c
prompt :: R.YiString
prompt = "Yi> "
-- | Tries to strip the 'prompt' from the front of the given 'String'.
-- If the prompt is not found, returns the input command as-is.
takeCommand :: R.YiString -> R.YiString
takeCommand t = case R.splitAt (R.length prompt) t of
(f, s) -> if f == prompt then s else t
consoleKeymap :: Keymap
consoleKeymap = do
_ <- event (Event KEnter [])
write $ withCurrentBuffer readLnB >>= \x -> case parseErrorMessage x of
Just (f,l,c) -> jumpToE f l c
Nothing -> do
withCurrentBuffer $ do
p <- pointB
botB
p' <- pointB
when (p /= p') $ insertN ("\n" <> prompt <> takeCommand x)
insertN "\n"
pt <- pointB
insertN prompt
bm <- getBookmarkB "errorInsert"
markPointA bm .= pt
execEditorAction . R.toString $ takeCommand x
instance Default Evaluator where
#ifdef HINT
def = ghciEvaluator
#else
def = publishedActionsEvaluator
#endif
instance YiConfigVariable Evaluator
-- | Runs the action, as written by the user.
--
-- The behaviour of this function can be customised by modifying the
-- 'Evaluator' variable.
execEditorAction :: String -> YiM ()
execEditorAction = runHook execEditorActionImpl
-- | Lists the action names in scope, for use by 'execEditorAction',
-- and 'help' index.
--
-- The behaviour of this function can be customised by modifying the
-- 'Evaluator' variable.
getAllNamesInScope :: YiM [String]
getAllNamesInScope = runHook getAllNamesInScopeImpl
-- | Describes the named action in scope, for use by 'help'.
--
-- The behaviour of this function can be customised by modifying the
-- 'Evaluator' variable.
describeNamedAction :: String -> YiM String
describeNamedAction = runHook describeNamedActionImpl
-- | The evaluator to use for 'execEditorAction' and
-- 'getAllNamesInScope'.
evaluator :: Field Evaluator
evaluator = customVariable
| null | https://raw.githubusercontent.com/yi-editor/yi/69953f00d48cc1b811310ce48c24269816e0f14b/yi-core/src/Yi/Eval.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE OverloadedStrings #
# LANGUAGE TemplateHaskell #
# OPTIONS_HADDOCK show-extensions #
|
License : GPL-2
Maintainer :
Stability : experimental
Portability : portable
Evaluator for actions ('Action', 'YiAction'). Uses a @GHCi@ session
under the hood.
* Main (generic) evaluation interface
** Standard evaluators
* Eval/Interpretation
TODO: should we be sticking Text here?
| Config variable for customising the behaviour of
'execEditorAction' and 'getAllNamesInScope'.
Set this variable using 'evaluator'. See 'ghciEvaluator' and
^ implementation of 'execEditorAction'
^ implementation of 'getAllNamesInScope'
^ describe named action (or at least its type.), simplest implementation is at least @return@.
* Evaluator based on GHCi
| Cached variable for getAllNamesInScopeImpl
Evaluator implemented by calling GHCi. This evaluator can run
arbitrary expressions in the class 'YiAction'.
Also, if the file
> $HOME/.config/yi/local/Env.hs
exists, it is imported unqualified.
TODO: use haddock to add docs
* 'PublishedActions' evaluator
| Accessor for the published actions. Consider using
'publishAction'.
| Publish the given action, by the given name. This will overwrite
any existing actions by the same name.
| Evaluator based on a fixed list of published actions. Has a few
differences from 'ghciEvaluator':
* expressions can't be evaluated
* all suggested actions are actually valued
* doesn't require GHCi backend, so uses less memory
* Miscellaneous interpreter
| Jumps to specified position in a given file.
^ Filename to make the jump in.
^ Line to jump to.
^ Column to jump to.
| Regex parsing the error message format.
| Parses an error message. Fails if it can't parse out the needed
information, namely filename, line number and column number.
| Tries to parse an error message at current line using
'parseErrorMessage'.
| Tries to jump to error at the current line. See
'parseErrorMessageB'.
| Tries to strip the 'prompt' from the front of the given 'String'.
If the prompt is not found, returns the input command as-is.
| Runs the action, as written by the user.
The behaviour of this function can be customised by modifying the
'Evaluator' variable.
| Lists the action names in scope, for use by 'execEditorAction',
and 'help' index.
The behaviour of this function can be customised by modifying the
'Evaluator' variable.
| Describes the named action in scope, for use by 'help'.
The behaviour of this function can be customised by modifying the
'Evaluator' variable.
| The evaluator to use for 'execEditorAction' and
'getAllNamesInScope'. | # LANGUAGE CPP #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
#ifdef HINT
# LANGUAGE FlexibleContexts #
#endif
Module : . Eval
module Yi.Eval (
execEditorAction,
getAllNamesInScope,
describeNamedAction,
Evaluator(..),
evaluator,
#ifdef HINT
ghciEvaluator,
#endif
publishedActionsEvaluator,
publishedActions,
publishAction,
jumpToErrorE,
jumpToE,
consoleKeymap
) where
import Prelude hiding (mapM_)
import Lens.Micro.Platform ( (^.), (.=), (%=) )
import Control.Monad (when, forever, void)
import Data.Array ( elems )
import Data.Binary ( Binary )
import Data.Default ( Default, def )
import Data.Foldable ( mapM_ )
import qualified Data.HashMap.Strict as M
( HashMap, insert, lookup, empty, keys )
import Data.Monoid ((<>))
import Data.Semigroup ( Semigroup )
import Data.Typeable ( Typeable )
#ifdef HINT
import Control.Concurrent
( takeMVar, putMVar, newEmptyMVar, MVar, forkIO )
import Control.Monad.Base ( MonadBase )
import Control.Monad.Catch ( try )
import Control.Monad.Trans ( lift )
import Data.Binary ( get, put )
import Data.List ( sort )
import qualified Language.Haskell.Interpreter as LHI
( typeOf,
setImportsQ,
searchPath,
set,
runInterpreter,
ModuleElem(Data, Class, Fun),
getModuleExports,
as,
loadModules,
languageExtensions,
OptionVal((:=)),
InterpreterError,
Extension(OverloadedStrings),
setTopLevelModules,
InterpreterT,
interpret )
import System.Directory ( doesFileExist )
import Yi.Core ( errorEditor )
import Yi.Editor
( getEditorDyn,
putEditorDyn,
MonadEditor)
import qualified Yi.Paths ( getEvaluatorContextFilename )
import Yi.String ( showT )
import Yi.Utils ( io )
#endif
import Text.Read ( readMaybe )
import Yi.Buffer
( gotoLn,
moveXorEol,
BufferM,
readLnB,
pointB,
botB,
insertN,
getBookmarkB,
markPointA )
import Yi.Config.Simple.Types ( customVariable, Field, ConfigM )
import Yi.Core ( runAction )
import Yi.Types ( YiVariable, YiConfigVariable )
import Yi.Editor
( printMsg,
askCfg,
withCurrentBuffer,
withCurrentBuffer )
import Yi.File ( openingNewFile )
import Yi.Hooks ( runHook )
import Yi.Keymap
( YiM, Action, YiAction, makeAction, Keymap, write )
import Yi.Keymap.Keys ( event, Event(..), Key(KEnter) )
import Yi.Regex ( Regex, makeRegex, matchOnceText )
import qualified Yi.Rope as R
( toString, YiString, splitAt, length )
import Yi.Utils ( makeLensesWithSuffix )
infixl 1 <&>
(<&>) :: Functor f => f a -> (a -> b) -> f b
a <&> f = f <$> a
' finiteListEvaluator ' for two implementation .
data Evaluator = Evaluator
{ execEditorActionImpl :: String -> YiM ()
, getAllNamesInScopeImpl :: YiM [String]
, describeNamedActionImpl :: String -> YiM String
} deriving (Typeable)
newtype NamesCache = NamesCache [String] deriving (Typeable, Binary)
instance Default NamesCache where
def = NamesCache []
instance YiVariable NamesCache
| Cached dictionary for describeNameImpl
newtype HelpCache = HelpCache (M.HashMap String String) deriving (Typeable, Binary)
instance Default HelpCache where
def = HelpCache M.empty
instance YiVariable HelpCache
#ifdef HINT
data HintRequest = HintEvaluate String (MVar (Either LHI.InterpreterError Action))
| HintGetNames (MVar (Either LHI.InterpreterError [LHI.ModuleElem]))
| HintDescribe String (MVar (Either LHI.InterpreterError String))
newtype HintThreadVar = HintThreadVar (Maybe (MVar HintRequest))
deriving (Typeable, Default)
instance Binary HintThreadVar where
put _ = return ()
get = return def
instance YiVariable HintThreadVar
getHintThread :: (MonadEditor m, MonadBase IO m) => m (MVar HintRequest)
getHintThread = do
HintThreadVar x <- getEditorDyn
case x of
Just t -> return t
Nothing -> do
req <- io newEmptyMVar
contextFile <- Yi.Paths.getEvaluatorContextFilename
void . io . forkIO $ hintEvaluatorThread req contextFile
putEditorDyn . HintThreadVar $ Just req
return req
hintEvaluatorThread :: MVar HintRequest -> FilePath -> IO ()
hintEvaluatorThread request contextFile = do
haveUserContext <- doesFileExist contextFile
void $ LHI.runInterpreter $ do
LHI.set [LHI.searchPath LHI.:= []]
LHI.set [LHI.languageExtensions LHI.:= [ LHI.OverloadedStrings ]]
when haveUserContext $ do
LHI.loadModules [contextFile]
LHI.setTopLevelModules ["Env"]
Yi . : Action lives there
setImp <- try $ LHI.setImportsQ [("Yi", Nothing), ("Yi.Keymap",Just "Yi.Keymap")]
:: LHI.InterpreterT IO (Either LHI.InterpreterError ())
case setImp of
Left e -> lift $ forever $ takeMVar request >>= \case
HintEvaluate _ response -> putMVar response (Left e)
HintGetNames response -> putMVar response (Left e)
HintDescribe _ response -> putMVar response (Left e)
Right _ -> forever $ lift (takeMVar request) >>= \case
HintEvaluate s response -> do
res <- try $ LHI.interpret ("Yi.makeAction (" ++ s ++ ")") (LHI.as :: Action)
lift $ putMVar response res
HintGetNames response -> do
res <- try $ LHI.getModuleExports "Yi"
lift $ putMVar response res
HintDescribe name response -> do
res <- try $ LHI.typeOf name
lift $ putMVar response res
The following two imports are always present :
> import
> import qualified . as .
ghciEvaluator :: Evaluator
ghciEvaluator = Evaluator { execEditorActionImpl = execAction
, getAllNamesInScopeImpl = getNames
}
where
execAction :: String -> YiM ()
execAction s = do
request <- getHintThread
res <- io $ do
response <- newEmptyMVar
putMVar request (HintEvaluate s response)
takeMVar response
case res of
Left err -> errorEditor (showT err)
Right action -> runAction action
getNames :: YiM [String]
getNames = do
NamesCache cache <- getEditorDyn
result <- if null cache
then do
request <- getHintThread
res <- io $ do
response <- newEmptyMVar
putMVar request (HintGetNames response)
takeMVar response
return $ case res of
Left err -> [show err]
Right exports -> flattenExports exports
else return $ sort cache
putEditorDyn $ NamesCache result
return result
flattenExports :: [LHI.ModuleElem] -> [String]
flattenExports = concatMap flattenExport
flattenExport :: LHI.ModuleElem -> [String]
flattenExport (LHI.Fun x) = [x]
flattenExport (LHI.Class _ xs) = xs
flattenExport (LHI.Data _ xs) = xs
describeName :: String -> YiM String
describeName name = do
HelpCache cache <- getEditorDyn
description <- case name `M.lookup` cache of
Nothing -> do
request <- getHintThread
res <- io $ do
response <- newEmptyMVar
putMVar request (HintDescribe name response)
takeMVar response
let newDescription = either show id res
putEditorDyn $ HelpCache $ M.insert name newDescription cache
return newDescription
Just description -> return description
return $ name ++ " :: " ++ description
#endif
newtype PublishedActions = PublishedActions {
_publishedActions :: M.HashMap String Action
} deriving(Typeable, Semigroup, Monoid)
instance Default PublishedActions where def = mempty
makeLensesWithSuffix "A" ''PublishedActions
instance YiConfigVariable PublishedActions
publishedActions :: Field (M.HashMap String Action)
publishedActions = customVariable . _publishedActionsA
publishAction :: (YiAction a x, Show x) => String -> a -> ConfigM ()
publishAction s a = publishedActions %= M.insert s (makeAction a)
* ( related to the above ) does n't contain junk actions from Prelude
publishedActionsEvaluator :: Evaluator
publishedActionsEvaluator = Evaluator
{ getAllNamesInScopeImpl = askCfg <&> M.keys . (^. publishedActions)
, execEditorActionImpl = \s ->
askCfg <&> M.lookup s . (^. publishedActions) >>= mapM_ runAction
TODO : try to show types using TemplateHaskell !
}
-> YiM ()
jumpToE filename line column =
openingNewFile filename $ gotoLn line >> moveXorEol column
errorRegex :: Regex
errorRegex = makeRegex ("^(.+):([0-9]+):([0-9]+):.*$" :: String)
parseErrorMessage :: R.YiString -> Maybe (String, Int, Int)
parseErrorMessage ln = do
(_ ,result, _) <- matchOnceText errorRegex (R.toString ln)
case take 3 $ map fst $ elems result of
[_, fname, l, c] -> (,,) <$> return fname <*> readMaybe l <*> readMaybe c
_ -> Nothing
parseErrorMessageB :: BufferM (Maybe (String, Int, Int))
parseErrorMessageB = parseErrorMessage <$> readLnB
jumpToErrorE :: YiM ()
jumpToErrorE = withCurrentBuffer parseErrorMessageB >>= \case
Nothing -> printMsg "Couldn't parse out an error message."
Just (f, l, c) -> jumpToE f l c
prompt :: R.YiString
prompt = "Yi> "
takeCommand :: R.YiString -> R.YiString
takeCommand t = case R.splitAt (R.length prompt) t of
(f, s) -> if f == prompt then s else t
consoleKeymap :: Keymap
consoleKeymap = do
_ <- event (Event KEnter [])
write $ withCurrentBuffer readLnB >>= \x -> case parseErrorMessage x of
Just (f,l,c) -> jumpToE f l c
Nothing -> do
withCurrentBuffer $ do
p <- pointB
botB
p' <- pointB
when (p /= p') $ insertN ("\n" <> prompt <> takeCommand x)
insertN "\n"
pt <- pointB
insertN prompt
bm <- getBookmarkB "errorInsert"
markPointA bm .= pt
execEditorAction . R.toString $ takeCommand x
instance Default Evaluator where
#ifdef HINT
def = ghciEvaluator
#else
def = publishedActionsEvaluator
#endif
instance YiConfigVariable Evaluator
execEditorAction :: String -> YiM ()
execEditorAction = runHook execEditorActionImpl
getAllNamesInScope :: YiM [String]
getAllNamesInScope = runHook getAllNamesInScopeImpl
describeNamedAction :: String -> YiM String
describeNamedAction = runHook describeNamedActionImpl
evaluator :: Field Evaluator
evaluator = customVariable
|
2817e70a3113b05148b38dd2dfb784324584caf49abe8aa3c256ecfc2f1704fa | ghc/packages-Cabal | legacy-autoconfigure.test.hs | import Test.Cabal.Prelude
main = cabalTest $ do
cabal' "v1-exec" ["echo", "find_me_in_output"]
>>= assertOutputContains "find_me_in_output"
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/Exec/legacy-autoconfigure.test.hs | haskell | import Test.Cabal.Prelude
main = cabalTest $ do
cabal' "v1-exec" ["echo", "find_me_in_output"]
>>= assertOutputContains "find_me_in_output"
| |
c5cafc43e6bcb435d678f8b357da1a6baed8a40932d1c711cfb50809ea02710e | blajzer/dib | Stage.hs | Copyright ( c ) 2010 - 2018
-- See LICENSE for license information.
-- | Module exposing the 'Stage' type and related type wrappers, along with a
-- convenience 'emptyStage'.
module Dib.Stage(
Stage(Stage),
InputTransformer,
DepScanner,
StageFunc,
emptyStage
) where
import Dib.Types
| A stage that does nothing and just passes the ' SrcTransform 's through .
emptyStage :: Stage
emptyStage = Stage "empty" id return [] (return.Right)
| null | https://raw.githubusercontent.com/blajzer/dib/750253c972668bb0d849239f94b96050bae74f2a/src/Dib/Stage.hs | haskell | See LICENSE for license information.
| Module exposing the 'Stage' type and related type wrappers, along with a
convenience 'emptyStage'. | Copyright ( c ) 2010 - 2018
module Dib.Stage(
Stage(Stage),
InputTransformer,
DepScanner,
StageFunc,
emptyStage
) where
import Dib.Types
| A stage that does nothing and just passes the ' SrcTransform 's through .
emptyStage :: Stage
emptyStage = Stage "empty" id return [] (return.Right)
|
e3674a9bb2de7c88a774592a3f60886e83f36d6a24b41965d85ac2e796844b42 | DATX02-17-26/DATX02-17-26 | IfElseEmpty.hs | DATX02 - 17 - 26 , automated assessment of imperative programs .
- Copyright , 2017 , see AUTHORS.md .
-
- 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 , MA 02110 - 1301 , USA .
- Copyright, 2017, see AUTHORS.md.
-
- 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, MA 02110-1301, USA.
-}
# LANGUAGE LambdaCase #
-- | Normalizers for simplifying if + else statements
-- where some branch is empty.
module Norm.IfElseEmpty (
-- * Normalizers
normIESiEmpty
, normIESeEmpty
, normIEBothEmpty
) where
import Util.Monad (traverseJ)
import Norm.NormCS
TODO allocate stages . At the moment chosen arbitrarily .
stage :: Int
stage = 1
--------------------------------------------------------------------------------
-- Exported Rules:
--------------------------------------------------------------------------------
-- | Simplifies an if else where the if branch is empty.
-- > if ( c ) ; else se => if ( !c ) se
-- and:
-- > if ( c ) ; => sideEffectsOf( c )
normIESiEmpty :: NormCUR
normIESiEmpty = makeRule' "if_else_empty.stmt.si_empty" [stage] execIESiEmpty
-- | Simplifies an if else where the else branch is empty.
-- > if ( c ) si else ; => if ( c ) si
normIESeEmpty :: NormCUR
normIESeEmpty = makeRule' "if_else_empty.stmt.se_empty" [stage] execIESeEmpty
-- | Simplifies an if else where both branches are empty.
-- > if ( c ) ; else ; => sideEffectsOf( c )
normIEBothEmpty :: NormCUR
normIEBothEmpty = makeRule' "if_else_empty.stmt.both_empty" [stage]
execIEBothEmpty
--------------------------------------------------------------------------------
-- if_else_empty.stmt.si_empty:
--------------------------------------------------------------------------------
execIESiEmpty :: NormCUA
execIESiEmpty = normEvery $ traverseJ $ \case
SIf c SEmpty -> change $ exprIntoStmts c
SIfElse c SEmpty se -> change [SIf (ENot c) se]
x -> unique [x]
--------------------------------------------------------------------------------
-- if_else_empty.stmt.se_empty:
--------------------------------------------------------------------------------
execIESeEmpty :: NormCUA
execIESeEmpty = normEvery $ \case
SIfElse c si SEmpty -> change $ SIf c si
x -> unique x
--------------------------------------------------------------------------------
-- if_else_empty.stmt.both_empty:
--------------------------------------------------------------------------------
execIEBothEmpty :: NormCUA
execIEBothEmpty = normEvery $ traverseJ $ \case
SIfElse c SEmpty SEmpty -> change $ exprIntoStmts c
x -> unique [x] | null | https://raw.githubusercontent.com/DATX02-17-26/DATX02-17-26/f5eeec0b2034d5b1adcc66071f8cb5cd1b089acb/libsrc/Norm/IfElseEmpty.hs | haskell | | Normalizers for simplifying if + else statements
where some branch is empty.
* Normalizers
------------------------------------------------------------------------------
Exported Rules:
------------------------------------------------------------------------------
| Simplifies an if else where the if branch is empty.
> if ( c ) ; else se => if ( !c ) se
and:
> if ( c ) ; => sideEffectsOf( c )
| Simplifies an if else where the else branch is empty.
> if ( c ) si else ; => if ( c ) si
| Simplifies an if else where both branches are empty.
> if ( c ) ; else ; => sideEffectsOf( c )
------------------------------------------------------------------------------
if_else_empty.stmt.si_empty:
------------------------------------------------------------------------------
------------------------------------------------------------------------------
if_else_empty.stmt.se_empty:
------------------------------------------------------------------------------
------------------------------------------------------------------------------
if_else_empty.stmt.both_empty:
------------------------------------------------------------------------------ | DATX02 - 17 - 26 , automated assessment of imperative programs .
- Copyright , 2017 , see AUTHORS.md .
-
- 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 , MA 02110 - 1301 , USA .
- Copyright, 2017, see AUTHORS.md.
-
- 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, MA 02110-1301, USA.
-}
# LANGUAGE LambdaCase #
module Norm.IfElseEmpty (
normIESiEmpty
, normIESeEmpty
, normIEBothEmpty
) where
import Util.Monad (traverseJ)
import Norm.NormCS
TODO allocate stages . At the moment chosen arbitrarily .
stage :: Int
stage = 1
normIESiEmpty :: NormCUR
normIESiEmpty = makeRule' "if_else_empty.stmt.si_empty" [stage] execIESiEmpty
normIESeEmpty :: NormCUR
normIESeEmpty = makeRule' "if_else_empty.stmt.se_empty" [stage] execIESeEmpty
normIEBothEmpty :: NormCUR
normIEBothEmpty = makeRule' "if_else_empty.stmt.both_empty" [stage]
execIEBothEmpty
execIESiEmpty :: NormCUA
execIESiEmpty = normEvery $ traverseJ $ \case
SIf c SEmpty -> change $ exprIntoStmts c
SIfElse c SEmpty se -> change [SIf (ENot c) se]
x -> unique [x]
execIESeEmpty :: NormCUA
execIESeEmpty = normEvery $ \case
SIfElse c si SEmpty -> change $ SIf c si
x -> unique x
execIEBothEmpty :: NormCUA
execIEBothEmpty = normEvery $ traverseJ $ \case
SIfElse c SEmpty SEmpty -> change $ exprIntoStmts c
x -> unique [x] |
fb54c5f312c8a887457525a933594414e889119dcbef8f929014e31a958cbe84 | zeniuseducation/poly-euler | p249.clj | (ns alfa.special.p249
(:require
[clojure.set :refer [union difference intersection subset?]]
[clojure.core.reducers :as r]
[clojure.string :refer [split-lines]]
[alfa.common :refer :all]
[clojure.string :as cs]))
(def primes (sieve 545))
(def checki
(fn [^long n]
(cond
(== n 0) 1
(< n 0) 0
(== n 1) 0
(some #(== n %) primes) 1
:else (->> (take-while #(<= % n) primes)
(drop-while #(<= % (quot n 2)))
(map #(checki (- n %)))
(reduce +')))))
(defn sol249c
[^long lim]
(let [raw (sieve (reduce + (sieve lim)))
modi (expt 10 15)]
(loop [[x & xs] raw res 0N]
(if x
(recur xs (rem (+ res (checki x)) modi))
res))))
(defn sol249d
[^long lim]
(let [primes (sieve lim)
modi (expt 10 16)
llim (reduce + (sieve lim))
lllim (int (Math/sqrt llim))
refs (boolean-array (inc llim) true)]
(do (doseq [i (range 2 (inc lllim))
:when (aget refs i)]
(doseq [j (range (* i i) (inc llim) i)]
(aset refs j false)))
(loop [[x & xs] primes npr {}]
(if x
(let [nprs (->> (map #(+ x %) (keys npr))
(map #(vector % (npr (- % x))))
(into {})
(merge-with + {x 1}))
nprss (merge-with +' npr nprs)]
(do (println x)
(recur xs nprss)))
(loop [[i & is] (keys npr) res (bigint 0)]
(if i
(if (aget refs i)
(recur is (rem (+ res (npr i)) modi))
(recur is res))
res)))))))
(defn sol249f
[^long lim]
(let [primes (sieve lim)
modi (expt 10 16)]
(loop [[x & xs] primes sum (bigint (count primes)) npr {}]
(if x
(let [nprs (->> (map #(+ x %) (keys npr))
(map #(vector % (npr (- % x))))
(into {})
(merge-with + {x 1}))
nprss (merge-with +' npr nprs)
resi (for [i (filter even? (keys nprs)) j xs
:when (odd-prime? (+ i j))] i)
reso (reduce +' (map nprs resi))]
(do (println x)
(recur xs
(rem (+' sum reso) modi)
nprss)))
sum))))
(defn sol249e
[^long lim]
(let [primes (sieve lim)
modi (expt 10 15)]
(loop [[x & xs] primes sum 0N npr []]
(if x
(let [nprs (cons x (map #(+ x %) npr))
resi (for [i (filter even? nprs) j xs
:let [s (+ i j)]
:when (odd-prime? s)] 1)
reso (reduce + resi)]
(do (println reso sum)
(recur xs (rem (+ sum reso) modi) (concat npr nprs))))
(+ (count primes) sum)))))
| null | https://raw.githubusercontent.com/zeniuseducation/poly-euler/734fdcf1ddd096a8730600b684bf7398d071d499/Alfa/src/alfa/special/p249.clj | clojure | (ns alfa.special.p249
(:require
[clojure.set :refer [union difference intersection subset?]]
[clojure.core.reducers :as r]
[clojure.string :refer [split-lines]]
[alfa.common :refer :all]
[clojure.string :as cs]))
(def primes (sieve 545))
(def checki
(fn [^long n]
(cond
(== n 0) 1
(< n 0) 0
(== n 1) 0
(some #(== n %) primes) 1
:else (->> (take-while #(<= % n) primes)
(drop-while #(<= % (quot n 2)))
(map #(checki (- n %)))
(reduce +')))))
(defn sol249c
[^long lim]
(let [raw (sieve (reduce + (sieve lim)))
modi (expt 10 15)]
(loop [[x & xs] raw res 0N]
(if x
(recur xs (rem (+ res (checki x)) modi))
res))))
(defn sol249d
[^long lim]
(let [primes (sieve lim)
modi (expt 10 16)
llim (reduce + (sieve lim))
lllim (int (Math/sqrt llim))
refs (boolean-array (inc llim) true)]
(do (doseq [i (range 2 (inc lllim))
:when (aget refs i)]
(doseq [j (range (* i i) (inc llim) i)]
(aset refs j false)))
(loop [[x & xs] primes npr {}]
(if x
(let [nprs (->> (map #(+ x %) (keys npr))
(map #(vector % (npr (- % x))))
(into {})
(merge-with + {x 1}))
nprss (merge-with +' npr nprs)]
(do (println x)
(recur xs nprss)))
(loop [[i & is] (keys npr) res (bigint 0)]
(if i
(if (aget refs i)
(recur is (rem (+ res (npr i)) modi))
(recur is res))
res)))))))
(defn sol249f
[^long lim]
(let [primes (sieve lim)
modi (expt 10 16)]
(loop [[x & xs] primes sum (bigint (count primes)) npr {}]
(if x
(let [nprs (->> (map #(+ x %) (keys npr))
(map #(vector % (npr (- % x))))
(into {})
(merge-with + {x 1}))
nprss (merge-with +' npr nprs)
resi (for [i (filter even? (keys nprs)) j xs
:when (odd-prime? (+ i j))] i)
reso (reduce +' (map nprs resi))]
(do (println x)
(recur xs
(rem (+' sum reso) modi)
nprss)))
sum))))
(defn sol249e
[^long lim]
(let [primes (sieve lim)
modi (expt 10 15)]
(loop [[x & xs] primes sum 0N npr []]
(if x
(let [nprs (cons x (map #(+ x %) npr))
resi (for [i (filter even? nprs) j xs
:let [s (+ i j)]
:when (odd-prime? s)] 1)
reso (reduce + resi)]
(do (println reso sum)
(recur xs (rem (+ sum reso) modi) (concat npr nprs))))
(+ (count primes) sum)))))
| |
e5f0047dcfb6fddb12ae68a2efa9e6f046beb142bed2dabf5a9e27fb6f628c4a | mpickering/apply-refact | Extensions16.hs | # LANGUAGE GeneralizedNewtypeDeriving , DeriveDataTypeable #
record = 1 | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Extensions16.hs | haskell | # LANGUAGE GeneralizedNewtypeDeriving , DeriveDataTypeable #
record = 1 | |
864183b4992b7523abe3371b653b3a441aa9c0a1f8dc15f6a87a4eb46cfae417 | dongcarl/guix | assembly.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2016 Jan Nieuwenhuizen < >
Copyright © 2013 , 2015 < >
Copyright © 2013 < >
Copyright © 2016 , 2020 , 2021 < >
Copyright © 2017–2021 < >
Copyright © 2019 Iteriteka < >
Copyright © 2019 < >
Copyright © 2020 < >
Copyright © 2020 < >
Copyright © 2020 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages assembly)
#:use-module (guix build-system meson)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages autotools)
#:use-module (gnu packages base)
#:use-module (gnu packages bison)
#:use-module (gnu packages compression)
#:use-module (gnu packages flex)
#:use-module (gnu packages gettext)
#:use-module (gnu packages image)
#:use-module (gnu packages linux)
#:use-module (gnu packages man)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages texinfo)
#:use-module (gnu packages python)
#:use-module (gnu packages sphinx)
#:use-module (gnu packages shells)
#:use-module (gnu packages xml)
#:use-module ((guix utils)
#:select (%current-system cc-for-target)))
(define-public nasm
(package
(name "nasm")
(version "2.14.02")
(source (origin
(method url-fetch)
(uri (string-append "/"
version "/nasm-" version ".tar.xz"))
(sha256
(base32
"1xg8dfr49py15vbwk1rzcjc3zpqydmr49ahlijm56wlgj8zdwjp2"))))
(build-system gnu-build-system)
(native-inputs `(("perl" ,perl) ;for doc and test target
("texinfo" ,texinfo)))
(arguments
`(#:test-target "test"
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'dont-build-ps-pdf-outputs
(lambda _
(substitute* "doc/Makefile.in"
(("html nasmdoc.txt nasmdoc.pdf")
"html nasmdoc.txt")
(("\\$\\(INSTALL_DATA\\) nasmdoc.pdf")
"$(INSTALL_DATA)"))
#t))
(add-after 'install 'install-info
(lambda _
(invoke "make" "install_doc"))))))
(home-page "/")
(synopsis "80x86 and x86-64 assembler")
(description
"NASM, the Netwide Assembler, is an 80x86 and x86-64 assembler designed
for portability and modularity. It supports a range of object file formats,
including Linux and *BSD a.out, ELF, COFF, Mach-O, Microsoft 16-bit OBJ,
Windows32 and Windows64. It will also output plain binary files. Its syntax
is designed to be simple and easy to understand, similar to Intel's but less
complex. It supports all currently known x86 architectural extensions, and
has strong support for macros.")
(license license:bsd-2)))
(define-public yasm
(package
(name "yasm")
(version "1.3.0")
(source (origin
(method url-fetch)
(uri (string-append
"-"
version ".tar.gz"))
(sha256
(base32
"0gv0slmm0qpq91za3v2v9glff3il594x5xsrbgab7xcmnh0ndkix"))))
(build-system gnu-build-system)
(arguments
'(#:parallel-tests? #f)) ; Some tests fail
; non-deterministically when run in
; parallel
(inputs
`(("python" ,python-wrapper)
("xmlto" ,xmlto)))
(home-page "/")
(synopsis "Rewrite of the NASM assembler")
(description
"Yasm is a complete rewrite of the NASM assembler.
Yasm currently supports the x86 and AMD64 instruction sets, accepts NASM
and GAS assembler syntaxes, outputs binary, ELF32, ELF64, 32 and 64-bit
Mach-O, RDOFF2, COFF, Win32, and Win64 object formats, and generates source
debugging information in STABS, DWARF 2, and CodeView 8 formats.")
(license (license:non-copyleft "file"
"See COPYING in the distribution."))))
(define-public lightning
(package
(name "lightning")
(version "2.1.3")
(source (origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"1jgxbq2cm51dzi3zhz38mmgwdcgs328mfl8iviw8dxn6dn36p1gd"))))
(build-system gnu-build-system)
(native-inputs `(("zlib" ,zlib)))
(synopsis "Library for generating assembly code at runtime")
(description
"GNU Lightning is a library that generates assembly language code at
run-time. Thus, it is useful in creating Just-In-Time compilers. It
abstracts over the target CPU by exposing a standardized RISC instruction set
to the clients.")
(home-page "/")
(license license:gpl3+)))
(define-public simde
(package
(name "simde")
(version "0.7.2")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-everywhere/simde")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32 "0xkf21gbkgz6zlxabkmgwvy7py6cdnfqx9aplj90gz25gzrr1mkb"))))
(build-system meson-build-system)
;; We really want this for the headers, and the tests require a bundled library.
(arguments '(#:configure-flags '("-Dtests=false")))
(synopsis "Implementations of SIMD instruction sets for foreign systems")
(description "The SIMDe header-only library provides fast, portable
implementations of SIMD intrinsics on hardware which doesn't natively support
them, such as calling SSE functions on ARM. There is no performance penalty if
the hardware supports the native implementation (e.g., SSE/AVX runs at full
speed on x86, NEON on ARM, etc.).")
(home-page "-everywhere.github.io/blog/")
(license license:expat)))
(define-public fasm
(package
(name "fasm")
(version "1.73.27")
(source
(origin
(method url-fetch)
(uri (string-append "-"
version ".tgz"))
(sha256
(base32 "1cghiks49ql77b9l4mwrnlk76kai0fm0z22j71kbdlxngwvlh0b8"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ; no tests exist
#:strip-binaries? #f ; fasm has no sections
#:phases
(modify-phases %standard-phases
(delete 'configure) ; no "configure" script
(replace 'build
(lambda _
(chdir "source/Linux/")
(if (string=? ,(%current-system) "x86_64-linux")
;; Use pre-compiled binaries in top-level directory to build
;; fasm.
(invoke "../../fasm.x64" "fasm.asm")
(invoke "../../fasm" "fasm.asm"))))
(replace 'install
(lambda _
(let ((out (assoc-ref %outputs "out")))
(install-file "fasm" (string-append out "/bin")))
#t)))))
(supported-systems '("x86_64-linux" "i686-linux"))
(synopsis "Assembler for x86 processors")
(description
"@acronym{FASM, the Flat ASseMbler} is an assembler that supports x86 and
IA-64 Intel architectures. It does multiple passes to optimize machine code.
It has macro abilities and focuses on operating system portability.")
(home-page "/")
(license license:bsd-2)))
(define-public dev86
(package
(name "dev86")
(version "0.16.21")
(source (origin
(method url-fetch)
(uri (string-append "/~lkundrak/dev86/Dev86src-"
version ".tar.gz"))
(sha256
(base32
"154dyr2ph4n0kwi8yx0n78j128kw29rk9r9f7s2gddzrdl712jr3"))))
(build-system gnu-build-system)
(arguments
`(#:parallel-build? #f ; They use submakes wrong
#:make-flags (list ,(string-append "CC=" (cc-for-target))
(string-append "PREFIX="
(assoc-ref %outputs "out")))
Standalone ld86 had problems otherwise
#:tests? #f ; No tests exist
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-before 'install 'mkdir
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(mkdir-p (string-append out "/bin"))
(mkdir-p (string-append out "/man/man1"))
#t))))))
(synopsis "Intel 8086 (primarily 16-bit) assembler, C compiler and
linker")
(description "This package provides a Intel 8086 (primarily 16-bit)
assembler, a C compiler and a linker. The assembler uses Intel syntax
(also Intel order of operands).")
(home-page "")
(supported-systems '("i686-linux" "x86_64-linux"))
(license license:gpl2+)))
(define-public libjit
(let ((commit "554c9f5c750daa6e13a6a5cd416873c81c7b8226"))
(package
(name "libjit")
(version "0.1.4")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit commit)))
(file-name (git-file-name name version))
(sha256
(base32
"0p6wklslkkp3s4aisj3w5a53bagqn5fy4m6088ppd4fcfxgqkrcd"))))
(build-system gnu-build-system)
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("bison" ,bison)
("flex" ,flex)
("help2man" ,help2man)
("gettext" ,gettext-minimal)
("libtool" ,libtool)
("makeinfo" ,texinfo)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Just-In-Time compilation library")
(description
"GNU libjit is a library that provides generic Just-In-Time compiler
functionality independent of any particular bytecode, language, or
runtime")
(license license:lgpl2.1+))))
(define-public rgbds
(package
(name "rgbds")
(version "0.4.2")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"0lygj7jzjlq4w0mkiir7ycysrd1p1akyvzrppjcchja05mi8wy9p"))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'patch-pkg-config
(lambda _
(substitute* "Makefile"
(("pkg-config")
(or (which "pkg-config")
(string-append ,(%current-target-system)
"-pkg-config"))))
#t))
(replace 'check
(lambda _
(with-directory-excursion "test/asm"
(invoke "./test.sh"))
(with-directory-excursion "test/link"
(invoke "./test.sh")))))
#:make-flags `(,(string-append "CC=" ,(cc-for-target))
,(string-append "PREFIX="
(assoc-ref %outputs "out")))))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
("pkg-config" ,pkg-config)
("util-linux" ,util-linux)))
(inputs
`(("libpng" ,libpng)))
(home-page "")
(synopsis "Rednex Game Boy Development System")
(description
"RGBDS (Rednex Game Boy Development System) is an assembler/linker
package for the Game Boy and Game Boy Color. It consists of:
@itemize @bullet
@item rgbasm (assembler)
@item rgblink (linker)
@item rgbfix (checksum/header fixer)
@item rgbgfx (PNG-to-Game Boy graphics converter)
@end itemize")
(license license:expat)))
(define-public wla-dx
(package
(name "wla-dx")
(version "9.12")
(source (origin
(method git-fetch)
(uri (git-reference
(url "-dx")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"1wlbqv2rgk9q6m9an1mi0i29250zl8lw7zipki2bbi9mczpyczli"))))
(build-system cmake-build-system)
(native-inputs
`(("sphinx" ,python-sphinx))) ; to generate man pages
(arguments
`(#:tests? #f)) ; no tests
(home-page "-dx")
(synopsis "Assemblers for various processors")
(description "WLA DX is a set of tools to assemble assembly files to
object or library files (@code{wla-ARCH}) and link them together (@code{wlalink}).
Supported architectures are:
@itemize @bullet
@item z80
@item gb (z80-gb)
@item 6502
@item 65c02
@item 6510
@item 65816
@item 6800
@item 6801
@item 6809
@item 8008
@item 8080
@item huc6280
@item spc700
@end itemize")
(license license:gpl2)))
(define-public xa
(package
(name "xa")
(version "2.3.11")
(source (origin
(method url-fetch)
(uri (string-append ""
"/dists/xa-" version ".tar.gz"))
(sha256
(base32
"0b81r7mvzqxgnbbmhixcnrf9nc72v1nqaw19k67221g3k561dwij"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ; TODO: custom test harness, not sure how it works
#:phases
(modify-phases %standard-phases
(delete 'configure)) ; no "configure" script
#:make-flags (list (string-append "DESTDIR=" (assoc-ref %outputs "out")))))
(native-inputs `(("perl" ,perl)))
(home-page "/")
(synopsis "Two-pass portable cross-assembler")
(description
"xa is a high-speed, two-pass portable cross-assembler.
It understands mnemonics and generates code for NMOS 6502s (such
as 6502A, 6504, 6507, 6510, 7501, 8500, 8501, 8502 ...),
CMOS 6502s (65C02 and Rockwell R65C02) and the 65816.")
(license license:gpl2)))
(define-public armips
(package
(name "armips")
(version "0.11.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32 "1c4dhjkvynqn9xm2vcvwzymk7yg8h25alnawkz4z1dnn1z1k3r9g"))))
(build-system cmake-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'check
(lambda* (#:key inputs #:allow-other-keys)
(invoke "./armipstests" "../source/Tests")))
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(install-file "armips" (string-append (assoc-ref outputs "out")
"/bin"))
#t)))))
(home-page "")
(synopsis "Assembler for various ARM and MIPS platforms")
(description
"armips is an assembler with full support for the MIPS R3000, MIPS R4000,
Allegrex and RSP instruction sets, partial support for the EmotionEngine
instruction set, as well as complete support for the ARM7 and ARM9 instruction
sets, both THUMB and ARM mode.")
(license license:expat)))
(define-public intel-xed
(package
(name "intel-xed")
(version "11.2.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(sha256 (base32 "1jffayski2gpd54vaska7fmiwnnia8v3cka4nfyzjgl8xsky9v2s"))
(file-name (git-file-name name version))
(patches (search-patches "intel-xed-fix-nondeterminism.patch"))))
(build-system gnu-build-system)
(native-inputs
`(("python-wrapper" ,python-wrapper)
("tcsh" ,tcsh)
As of the time of writing this comment , does not exist in the
;; Python Package Index and seems to only be used by intel-xed, so we
;; opt to include it here instead of packaging separately. Note also
;; that the git repository contains no version tags, so we directly
;; reference the "version" variable from setup.py instead.
("mbuild"
,(let ((name "mbuild")
(version "0.2496"))
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit "5304b94361fccd830c0e2417535a866b79c1c297")))
(sha256
(base32
"0r3avc3035aklqxcnc14rlmmwpj3jp09vbcbwynhvvmcp8srl7dl"))
(file-name (git-file-name name version)))))))
(outputs '("out" "lib"))
(arguments
`(#:phases
Upstream uses the custom Python build tool ` mbuild ' , so we munge
gnu - build - system to fit . The build process for this package is
;; documented at -manual/.
(let* ((build-dir "build")
(kit-dir "kit"))
(modify-phases %standard-phases
(delete 'configure)
(replace 'build
(lambda* (#:key inputs #:allow-other-keys)
(let ((mbuild (assoc-ref inputs "mbuild")))
(setenv "PYTHONPATH" (string-append
(getenv "PYTHONPATH") ":" mbuild))
(invoke "./mfile.py"
(string-append "--build-dir=" build-dir)
(string-append "--install-dir=" kit-dir)
"examples"
"doc"
"install"))))
(replace 'check
(lambda _
;; Skip broken test group `tests/tests-avx512pf'.
(invoke "tests/run-cmd.py"
(string-append "--build-dir=" kit-dir "/bin")
"--tests" "tests/tests-base"
"--tests" "tests/tests-avx512"
"--tests" "tests/tests-cet"
"--tests" "tests/tests-via"
"--tests" "tests/tests-syntax"
"--tests" "tests/tests-xop")))
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(lib (assoc-ref outputs "lib")))
(copy-recursively (string-append kit-dir "/bin")
(string-append out "/bin"))
(copy-recursively (string-append kit-dir "/include")
(string-append lib "/include"))
(copy-recursively (string-append kit-dir "/lib")
(string-append lib "/lib"))
#t)))))))
(home-page "/")
(synopsis "Encoder and decoder for x86 (IA32 and Intel64) instructions")
(description "The Intel X86 Encoder Decoder (XED) is a software library and
for encoding and decoding X86 (IA32 and Intel64) instructions. The decoder
takes sequences of 1-15 bytes along with machine mode information and produces
a data structure describing the opcode, operands, and flags. The encoder takes
a similar data structure and produces a sequence of 1 to 15 bytes. Disassembly
is essentially a printing pass on the data structure.
The library and development files are under the @code{lib} output, with a
family of command line utility wrappers in the default output. Each of the cli
tools is named like @code{xed*}. Documentation for the cli tools is sparse, so
this is a case where ``the code is the documentation.''")
(license license:asl2.0)))
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/assembly.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.
for doc and test target
Some tests fail
non-deterministically when run in
parallel
We really want this for the headers, and the tests require a bundled library.
no tests exist
fasm has no sections
no "configure" script
Use pre-compiled binaries in top-level directory to build
fasm.
They use submakes wrong
No tests exist
to generate man pages
no tests
TODO: custom test harness, not sure how it works
no "configure" script
Python Package Index and seems to only be used by intel-xed, so we
opt to include it here instead of packaging separately. Note also
that the git repository contains no version tags, so we directly
reference the "version" variable from setup.py instead.
documented at -manual/.
Skip broken test group `tests/tests-avx512pf'. | Copyright © 2016 Jan Nieuwenhuizen < >
Copyright © 2013 , 2015 < >
Copyright © 2013 < >
Copyright © 2016 , 2020 , 2021 < >
Copyright © 2017–2021 < >
Copyright © 2019 Iteriteka < >
Copyright © 2019 < >
Copyright © 2020 < >
Copyright © 2020 < >
Copyright © 2020 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages assembly)
#:use-module (guix build-system meson)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (gnu packages)
#:use-module (gnu packages admin)
#:use-module (gnu packages autotools)
#:use-module (gnu packages base)
#:use-module (gnu packages bison)
#:use-module (gnu packages compression)
#:use-module (gnu packages flex)
#:use-module (gnu packages gettext)
#:use-module (gnu packages image)
#:use-module (gnu packages linux)
#:use-module (gnu packages man)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages texinfo)
#:use-module (gnu packages python)
#:use-module (gnu packages sphinx)
#:use-module (gnu packages shells)
#:use-module (gnu packages xml)
#:use-module ((guix utils)
#:select (%current-system cc-for-target)))
(define-public nasm
(package
(name "nasm")
(version "2.14.02")
(source (origin
(method url-fetch)
(uri (string-append "/"
version "/nasm-" version ".tar.xz"))
(sha256
(base32
"1xg8dfr49py15vbwk1rzcjc3zpqydmr49ahlijm56wlgj8zdwjp2"))))
(build-system gnu-build-system)
("texinfo" ,texinfo)))
(arguments
`(#:test-target "test"
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'dont-build-ps-pdf-outputs
(lambda _
(substitute* "doc/Makefile.in"
(("html nasmdoc.txt nasmdoc.pdf")
"html nasmdoc.txt")
(("\\$\\(INSTALL_DATA\\) nasmdoc.pdf")
"$(INSTALL_DATA)"))
#t))
(add-after 'install 'install-info
(lambda _
(invoke "make" "install_doc"))))))
(home-page "/")
(synopsis "80x86 and x86-64 assembler")
(description
"NASM, the Netwide Assembler, is an 80x86 and x86-64 assembler designed
for portability and modularity. It supports a range of object file formats,
including Linux and *BSD a.out, ELF, COFF, Mach-O, Microsoft 16-bit OBJ,
Windows32 and Windows64. It will also output plain binary files. Its syntax
is designed to be simple and easy to understand, similar to Intel's but less
complex. It supports all currently known x86 architectural extensions, and
has strong support for macros.")
(license license:bsd-2)))
(define-public yasm
(package
(name "yasm")
(version "1.3.0")
(source (origin
(method url-fetch)
(uri (string-append
"-"
version ".tar.gz"))
(sha256
(base32
"0gv0slmm0qpq91za3v2v9glff3il594x5xsrbgab7xcmnh0ndkix"))))
(build-system gnu-build-system)
(arguments
(inputs
`(("python" ,python-wrapper)
("xmlto" ,xmlto)))
(home-page "/")
(synopsis "Rewrite of the NASM assembler")
(description
"Yasm is a complete rewrite of the NASM assembler.
Yasm currently supports the x86 and AMD64 instruction sets, accepts NASM
and GAS assembler syntaxes, outputs binary, ELF32, ELF64, 32 and 64-bit
Mach-O, RDOFF2, COFF, Win32, and Win64 object formats, and generates source
debugging information in STABS, DWARF 2, and CodeView 8 formats.")
(license (license:non-copyleft "file"
"See COPYING in the distribution."))))
(define-public lightning
(package
(name "lightning")
(version "2.1.3")
(source (origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32
"1jgxbq2cm51dzi3zhz38mmgwdcgs328mfl8iviw8dxn6dn36p1gd"))))
(build-system gnu-build-system)
(native-inputs `(("zlib" ,zlib)))
(synopsis "Library for generating assembly code at runtime")
(description
"GNU Lightning is a library that generates assembly language code at
run-time. Thus, it is useful in creating Just-In-Time compilers. It
abstracts over the target CPU by exposing a standardized RISC instruction set
to the clients.")
(home-page "/")
(license license:gpl3+)))
(define-public simde
(package
(name "simde")
(version "0.7.2")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "-everywhere/simde")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32 "0xkf21gbkgz6zlxabkmgwvy7py6cdnfqx9aplj90gz25gzrr1mkb"))))
(build-system meson-build-system)
(arguments '(#:configure-flags '("-Dtests=false")))
(synopsis "Implementations of SIMD instruction sets for foreign systems")
(description "The SIMDe header-only library provides fast, portable
implementations of SIMD intrinsics on hardware which doesn't natively support
them, such as calling SSE functions on ARM. There is no performance penalty if
the hardware supports the native implementation (e.g., SSE/AVX runs at full
speed on x86, NEON on ARM, etc.).")
(home-page "-everywhere.github.io/blog/")
(license license:expat)))
(define-public fasm
(package
(name "fasm")
(version "1.73.27")
(source
(origin
(method url-fetch)
(uri (string-append "-"
version ".tgz"))
(sha256
(base32 "1cghiks49ql77b9l4mwrnlk76kai0fm0z22j71kbdlxngwvlh0b8"))))
(build-system gnu-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(replace 'build
(lambda _
(chdir "source/Linux/")
(if (string=? ,(%current-system) "x86_64-linux")
(invoke "../../fasm.x64" "fasm.asm")
(invoke "../../fasm" "fasm.asm"))))
(replace 'install
(lambda _
(let ((out (assoc-ref %outputs "out")))
(install-file "fasm" (string-append out "/bin")))
#t)))))
(supported-systems '("x86_64-linux" "i686-linux"))
(synopsis "Assembler for x86 processors")
(description
"@acronym{FASM, the Flat ASseMbler} is an assembler that supports x86 and
IA-64 Intel architectures. It does multiple passes to optimize machine code.
It has macro abilities and focuses on operating system portability.")
(home-page "/")
(license license:bsd-2)))
(define-public dev86
(package
(name "dev86")
(version "0.16.21")
(source (origin
(method url-fetch)
(uri (string-append "/~lkundrak/dev86/Dev86src-"
version ".tar.gz"))
(sha256
(base32
"154dyr2ph4n0kwi8yx0n78j128kw29rk9r9f7s2gddzrdl712jr3"))))
(build-system gnu-build-system)
(arguments
#:make-flags (list ,(string-append "CC=" (cc-for-target))
(string-append "PREFIX="
(assoc-ref %outputs "out")))
Standalone ld86 had problems otherwise
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-before 'install 'mkdir
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(mkdir-p (string-append out "/bin"))
(mkdir-p (string-append out "/man/man1"))
#t))))))
(synopsis "Intel 8086 (primarily 16-bit) assembler, C compiler and
linker")
(description "This package provides a Intel 8086 (primarily 16-bit)
assembler, a C compiler and a linker. The assembler uses Intel syntax
(also Intel order of operands).")
(home-page "")
(supported-systems '("i686-linux" "x86_64-linux"))
(license license:gpl2+)))
(define-public libjit
(let ((commit "554c9f5c750daa6e13a6a5cd416873c81c7b8226"))
(package
(name "libjit")
(version "0.1.4")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit commit)))
(file-name (git-file-name name version))
(sha256
(base32
"0p6wklslkkp3s4aisj3w5a53bagqn5fy4m6088ppd4fcfxgqkrcd"))))
(build-system gnu-build-system)
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("bison" ,bison)
("flex" ,flex)
("help2man" ,help2man)
("gettext" ,gettext-minimal)
("libtool" ,libtool)
("makeinfo" ,texinfo)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Just-In-Time compilation library")
(description
"GNU libjit is a library that provides generic Just-In-Time compiler
functionality independent of any particular bytecode, language, or
runtime")
(license license:lgpl2.1+))))
(define-public rgbds
(package
(name "rgbds")
(version "0.4.2")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"0lygj7jzjlq4w0mkiir7ycysrd1p1akyvzrppjcchja05mi8wy9p"))))
(build-system gnu-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'patch-pkg-config
(lambda _
(substitute* "Makefile"
(("pkg-config")
(or (which "pkg-config")
(string-append ,(%current-target-system)
"-pkg-config"))))
#t))
(replace 'check
(lambda _
(with-directory-excursion "test/asm"
(invoke "./test.sh"))
(with-directory-excursion "test/link"
(invoke "./test.sh")))))
#:make-flags `(,(string-append "CC=" ,(cc-for-target))
,(string-append "PREFIX="
(assoc-ref %outputs "out")))))
(native-inputs
`(("bison" ,bison)
("flex" ,flex)
("pkg-config" ,pkg-config)
("util-linux" ,util-linux)))
(inputs
`(("libpng" ,libpng)))
(home-page "")
(synopsis "Rednex Game Boy Development System")
(description
"RGBDS (Rednex Game Boy Development System) is an assembler/linker
package for the Game Boy and Game Boy Color. It consists of:
@itemize @bullet
@item rgbasm (assembler)
@item rgblink (linker)
@item rgbfix (checksum/header fixer)
@item rgbgfx (PNG-to-Game Boy graphics converter)
@end itemize")
(license license:expat)))
(define-public wla-dx
(package
(name "wla-dx")
(version "9.12")
(source (origin
(method git-fetch)
(uri (git-reference
(url "-dx")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"1wlbqv2rgk9q6m9an1mi0i29250zl8lw7zipki2bbi9mczpyczli"))))
(build-system cmake-build-system)
(native-inputs
(arguments
(home-page "-dx")
(synopsis "Assemblers for various processors")
(description "WLA DX is a set of tools to assemble assembly files to
object or library files (@code{wla-ARCH}) and link them together (@code{wlalink}).
Supported architectures are:
@itemize @bullet
@item z80
@item gb (z80-gb)
@item 6502
@item 65c02
@item 6510
@item 65816
@item 6800
@item 6801
@item 6809
@item 8008
@item 8080
@item huc6280
@item spc700
@end itemize")
(license license:gpl2)))
(define-public xa
(package
(name "xa")
(version "2.3.11")
(source (origin
(method url-fetch)
(uri (string-append ""
"/dists/xa-" version ".tar.gz"))
(sha256
(base32
"0b81r7mvzqxgnbbmhixcnrf9nc72v1nqaw19k67221g3k561dwij"))))
(build-system gnu-build-system)
(arguments
#:phases
(modify-phases %standard-phases
#:make-flags (list (string-append "DESTDIR=" (assoc-ref %outputs "out")))))
(native-inputs `(("perl" ,perl)))
(home-page "/")
(synopsis "Two-pass portable cross-assembler")
(description
"xa is a high-speed, two-pass portable cross-assembler.
It understands mnemonics and generates code for NMOS 6502s (such
as 6502A, 6504, 6507, 6510, 7501, 8500, 8501, 8502 ...),
CMOS 6502s (65C02 and Rockwell R65C02) and the 65816.")
(license license:gpl2)))
(define-public armips
(package
(name "armips")
(version "0.11.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32 "1c4dhjkvynqn9xm2vcvwzymk7yg8h25alnawkz4z1dnn1z1k3r9g"))))
(build-system cmake-build-system)
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'check
(lambda* (#:key inputs #:allow-other-keys)
(invoke "./armipstests" "../source/Tests")))
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(install-file "armips" (string-append (assoc-ref outputs "out")
"/bin"))
#t)))))
(home-page "")
(synopsis "Assembler for various ARM and MIPS platforms")
(description
"armips is an assembler with full support for the MIPS R3000, MIPS R4000,
Allegrex and RSP instruction sets, partial support for the EmotionEngine
instruction set, as well as complete support for the ARM7 and ARM9 instruction
sets, both THUMB and ARM mode.")
(license license:expat)))
(define-public intel-xed
(package
(name "intel-xed")
(version "11.2.0")
(source
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit version)))
(sha256 (base32 "1jffayski2gpd54vaska7fmiwnnia8v3cka4nfyzjgl8xsky9v2s"))
(file-name (git-file-name name version))
(patches (search-patches "intel-xed-fix-nondeterminism.patch"))))
(build-system gnu-build-system)
(native-inputs
`(("python-wrapper" ,python-wrapper)
("tcsh" ,tcsh)
As of the time of writing this comment , does not exist in the
("mbuild"
,(let ((name "mbuild")
(version "0.2496"))
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit "5304b94361fccd830c0e2417535a866b79c1c297")))
(sha256
(base32
"0r3avc3035aklqxcnc14rlmmwpj3jp09vbcbwynhvvmcp8srl7dl"))
(file-name (git-file-name name version)))))))
(outputs '("out" "lib"))
(arguments
`(#:phases
Upstream uses the custom Python build tool ` mbuild ' , so we munge
gnu - build - system to fit . The build process for this package is
(let* ((build-dir "build")
(kit-dir "kit"))
(modify-phases %standard-phases
(delete 'configure)
(replace 'build
(lambda* (#:key inputs #:allow-other-keys)
(let ((mbuild (assoc-ref inputs "mbuild")))
(setenv "PYTHONPATH" (string-append
(getenv "PYTHONPATH") ":" mbuild))
(invoke "./mfile.py"
(string-append "--build-dir=" build-dir)
(string-append "--install-dir=" kit-dir)
"examples"
"doc"
"install"))))
(replace 'check
(lambda _
(invoke "tests/run-cmd.py"
(string-append "--build-dir=" kit-dir "/bin")
"--tests" "tests/tests-base"
"--tests" "tests/tests-avx512"
"--tests" "tests/tests-cet"
"--tests" "tests/tests-via"
"--tests" "tests/tests-syntax"
"--tests" "tests/tests-xop")))
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(lib (assoc-ref outputs "lib")))
(copy-recursively (string-append kit-dir "/bin")
(string-append out "/bin"))
(copy-recursively (string-append kit-dir "/include")
(string-append lib "/include"))
(copy-recursively (string-append kit-dir "/lib")
(string-append lib "/lib"))
#t)))))))
(home-page "/")
(synopsis "Encoder and decoder for x86 (IA32 and Intel64) instructions")
(description "The Intel X86 Encoder Decoder (XED) is a software library and
for encoding and decoding X86 (IA32 and Intel64) instructions. The decoder
takes sequences of 1-15 bytes along with machine mode information and produces
a data structure describing the opcode, operands, and flags. The encoder takes
a similar data structure and produces a sequence of 1 to 15 bytes. Disassembly
is essentially a printing pass on the data structure.
The library and development files are under the @code{lib} output, with a
family of command line utility wrappers in the default output. Each of the cli
tools is named like @code{xed*}. Documentation for the cli tools is sparse, so
this is a case where ``the code is the documentation.''")
(license license:asl2.0)))
|
115dd8a5c6ee85db8d9050656d6ba451ef29b6b385d5d03ae501598a379957b3 | input-output-hk/cardano-ledger | NoThunks.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
module Test.Cardano.Ledger.NoThunks (
test,
) where
import Cardano.Ledger.Core
import Cardano.Ledger.Pretty (PrettyA)
import Control.State.Transition.Extended (STS)
import Data.Default.Class (def)
import Test.Cardano.Ledger.Generic.GenState (GenSize)
import Test.Cardano.Ledger.Generic.MockChain (MOCKCHAIN, noThunksGen)
import Test.Cardano.Ledger.Generic.Proof (Evidence (Mock), Proof (..), Reflect)
import Test.Cardano.Ledger.Generic.Trace (traceProp)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
test :: TestTree
test =
testGroup
"There are no unexpected thunks in MockChainState"
[ f $ Babbage Mock
, f $ Alonzo Mock
, f $ Allegra Mock
, f $ Mary Mock
, f $ Shelley Mock
]
where
f proof = testThunks proof 100 def
testThunks ::
forall era.
( Reflect era
, STS (MOCKCHAIN era)
, PrettyA (PParamsUpdate era)
) =>
Proof era ->
Int ->
GenSize ->
TestTree
testThunks proof numTx gensize =
testProperty (show proof ++ " era. Trace length = " ++ show numTx) $
traceProp
proof
numTx
gensize
( \_ !trc -> do
nt <- noThunksGen proof trc
case nt of
Just x -> error $ "Thunks present: " <> show x
Nothing -> return ()
)
-- main :: IO ()
-- main = defaultMain test
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/551eaabfdb07ad1c1523358177578b4103ce7f52/libs/cardano-ledger-test/src/Test/Cardano/Ledger/NoThunks.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
main :: IO ()
main = defaultMain test | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
module Test.Cardano.Ledger.NoThunks (
test,
) where
import Cardano.Ledger.Core
import Cardano.Ledger.Pretty (PrettyA)
import Control.State.Transition.Extended (STS)
import Data.Default.Class (def)
import Test.Cardano.Ledger.Generic.GenState (GenSize)
import Test.Cardano.Ledger.Generic.MockChain (MOCKCHAIN, noThunksGen)
import Test.Cardano.Ledger.Generic.Proof (Evidence (Mock), Proof (..), Reflect)
import Test.Cardano.Ledger.Generic.Trace (traceProp)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
test :: TestTree
test =
testGroup
"There are no unexpected thunks in MockChainState"
[ f $ Babbage Mock
, f $ Alonzo Mock
, f $ Allegra Mock
, f $ Mary Mock
, f $ Shelley Mock
]
where
f proof = testThunks proof 100 def
testThunks ::
forall era.
( Reflect era
, STS (MOCKCHAIN era)
, PrettyA (PParamsUpdate era)
) =>
Proof era ->
Int ->
GenSize ->
TestTree
testThunks proof numTx gensize =
testProperty (show proof ++ " era. Trace length = " ++ show numTx) $
traceProp
proof
numTx
gensize
( \_ !trc -> do
nt <- noThunksGen proof trc
case nt of
Just x -> error $ "Thunks present: " <> show x
Nothing -> return ()
)
|
c8bb32c665e0c9392553cd63854b6bae0cd349843bfce38f585a14f21d8544f9 | holyjak/fulcro-intro-wshop | server.clj | (ns fulcro-todomvc.server
(:require
[clojure.core.async :as async]
[com.fulcrologic.fulcro.algorithms.do-not-use :as util]
[com.fulcrologic.fulcro.server.api-middleware :as fmw :refer [not-found-handler wrap-api]]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[immutant.web :as web]
[ring.middleware.content-type :refer [wrap-content-type]]
[ring.middleware.not-modified :refer [wrap-not-modified]]
[ring.middleware.resource :refer [wrap-resource]]
[ring.util.response :refer [content-type response file-response resource-response]]
[taoensso.timbre :as log]
[clojure.tools.namespace.repl :as tools-ns]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]))
(def item-db (atom {1 {:item/id 1
:item/label "Item 1"
:item/complete false}
2 {:item/id 2
:item/label "Item 2"
:item/complete false}
3 {:item/id 3
:item/label "Item 3"
:item/complete false}}))
(pc/defmutation todo-new-item [env {:keys [id list-id text]}]
{::pc/sym `fulcro-todomvc.api/todo-new-item
::pc/params [:list-id :id :text]
::pc/output [:item/id]}
(log/info "New item on server")
(let [new-id (tempid/uuid)]
(swap! item-db assoc new-id {:item/id new-id :item/label text :item/complete false})
{:tempids {id new-id}
:item/id new-id}))
(pc/defmutation todo-check [env {:keys [id]}]
{::pc/sym `fulcro-todomvc.api/todo-check
::pc/params [:id]
::pc/output []}
(log/info "Checked item" id)
(swap! item-db assoc-in [id :item/complete] true)
{})
(pc/defmutation todo-uncheck [env {:keys [id]}]
{::pc/sym `fulcro-todomvc.api/todo-uncheck
::pc/params [:id]
::pc/output []}
(log/info "Unchecked item" id)
(swap! item-db assoc-in [id :item/complete] false)
{})
(pc/defmutation commit-label-change [env {:keys [id text]}]
{::pc/sym `fulcro-todomvc.api/commit-label-change
::pc/params [:id :text]
::pc/output []}
(log/info "Set item label text of" id "to" text)
(swap! item-db assoc-in [id :item/label] text)
{})
(pc/defmutation todo-delete-item [env {:keys [id]}]
{::pc/sym `fulcro-todomvc.api/todo-delete-item
::pc/params [:id]
::pc/output []}
(log/info "Deleted item" id)
(swap! item-db dissoc id)
{})
(defn- to-all-todos [db f]
(into {}
(map (fn [[id todo]]
[id (f todo)]))
db))
(pc/defmutation todo-check-all [env _]
{::pc/sym `fulcro-todomvc.api/todo-check-all
::pc/params []
::pc/output []}
(log/info "Checked all items")
(swap! item-db to-all-todos #(assoc % :item/complete true))
{})
(pc/defmutation todo-uncheck-all [env _]
{::pc/sym `fulcro-todomvc.api/todo-uncheck-all
::pc/params []
::pc/output []}
(log/info "Unchecked all items")
(swap! item-db to-all-todos #(assoc % :item/complete false))
{})
(pc/defmutation todo-clear-complete [env _]
{::pc/sym `fulcro-todomvc.api/todo-clear-complete
::pc/params []
::pc/output []}
(log/info "Cleared completed items")
(swap! item-db (fn [db] (into {} (remove #(-> % val :item/complete)) db)))
{})
Support for Fulcro Inspect - Index Explorer
(pc/defresolver index-explorer
"This resolver is necessary to make it possible to use 'Load index' in Fulcro Inspect - EQL"
[env _]
{::pc/input #{:com.wsscode.pathom.viz.index-explorer/id}
::pc/output [:com.wsscode.pathom.viz.index-explorer/index]}
{:com.wsscode.pathom.viz.index-explorer/index
(-> (get env ::pc/indexes)
(update ::pc/index-resolvers #(into {} (map (fn [[k v]] [k (dissoc v ::pc/resolve)])) %))
(update ::pc/index-mutations #(into {} (map (fn [[k v]] [k (dissoc v ::pc/mutate)])) %)))})
;; How to go from :list/id to that list's details
(pc/defresolver list-resolver [env {id :list/id :as params}]
{::pc/input #{:list/id}
::pc/output [:list/title {:list/items [:item/id]}]}
;; normally you'd pull the list from the db, and satisfy the listed
;; outputs. For demo, we just always return the same list details.
(case id
1 {:list/title "The List"
:list/items (into [] (sort-by :item/id (vals @item-db)))}
2 {:list/title "Another List"
:list/items [{:item/id 99, :item/label "Hardcoded item", :item/complete true}
(assoc (get @item-db 1)
:item/label "Item 1 - re-loaded from server")]}))
;; how to go from :item/id to item details.
(pc/defresolver item-resolver [env {:keys [item/id] :as params}]
{::pc/input #{:item/id}
::pc/output [:item/complete :item/label]}
(get @item-db id))
;; define a list with our resolvers
(def my-resolvers [index-explorer
;; app resolvers:
list-resolver item-resolver
;; mutations:
todo-new-item commit-label-change todo-delete-item
todo-check todo-uncheck
todo-check-all todo-uncheck-all
todo-clear-complete])
;; setup for a given connect system
(def parser
(p/parser
{::p/env {::p/reader [p/map-reader
pc/reader2
pc/open-ident-reader]
::pc/mutation-join-globals [:tempids]}
::p/mutate pc/mutate
::p/plugins [(pc/connect-plugin {::pc/register my-resolvers})
(p/post-process-parser-plugin p/elide-not-found)
p/error-handler-plugin]}))
(defn wrap-index [handler]
(fn [req]
(if (= "/" (:uri req))
(-> (handler (assoc req :uri "/index.html", :path-info "/index.html"))
(content-type "text/html"))
(handler req))))
(def middleware (-> not-found-handler
(wrap-api {:uri "/api"
:parser (fn [query] (parser {} query))})
(fmw/wrap-transit-params)
(fmw/wrap-transit-response)
(wrap-resource "public")
wrap-index
wrap-content-type
wrap-not-modified))
(defonce server (atom nil))
(defn http-server []
(let [result (web/run middleware {:host "0.0.0.0"
:port 8181})]
(reset! server result)
(try
((requiring-resolve 'clojure.java.browse/browse-url) ":8181")
(catch UnsupportedOperationException e
(println "Browse to :8181 (opening it automatically not supported:" (ex-message e) ")")))
(fn [] (web/stop result))))
(comment
Calva setup : Execute the line below to start the server
( Alt - Enter or , on , Option - Enter ; if it does not work , make sure to
;; put your cursor after the closing parenthese)
(http-server)
;; You should see output like:
;; => #function[fulcro-todomvc.server/http-server/fn--63504]
;; if you see instead `#function[fulcro-todomvc.server/http-server]` then
;; you have not run the function, only evaluated the var
(web/stop @server)
(tools-ns/refresh-all)
(async/<!! (parser {} `[(fulcro-todomvc.api/todo-new-item {:id 2 :text "Hello"})]))
@item-db
)
| null | https://raw.githubusercontent.com/holyjak/fulcro-intro-wshop/b1cda340358ec40ec95e362d8ab3722236dea1d7/src/fulcro_todomvc/server.clj | clojure | How to go from :list/id to that list's details
normally you'd pull the list from the db, and satisfy the listed
outputs. For demo, we just always return the same list details.
how to go from :item/id to item details.
define a list with our resolvers
app resolvers:
mutations:
setup for a given connect system
if it does not work , make sure to
put your cursor after the closing parenthese)
You should see output like:
=> #function[fulcro-todomvc.server/http-server/fn--63504]
if you see instead `#function[fulcro-todomvc.server/http-server]` then
you have not run the function, only evaluated the var | (ns fulcro-todomvc.server
(:require
[clojure.core.async :as async]
[com.fulcrologic.fulcro.algorithms.do-not-use :as util]
[com.fulcrologic.fulcro.server.api-middleware :as fmw :refer [not-found-handler wrap-api]]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[immutant.web :as web]
[ring.middleware.content-type :refer [wrap-content-type]]
[ring.middleware.not-modified :refer [wrap-not-modified]]
[ring.middleware.resource :refer [wrap-resource]]
[ring.util.response :refer [content-type response file-response resource-response]]
[taoensso.timbre :as log]
[clojure.tools.namespace.repl :as tools-ns]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]))
(def item-db (atom {1 {:item/id 1
:item/label "Item 1"
:item/complete false}
2 {:item/id 2
:item/label "Item 2"
:item/complete false}
3 {:item/id 3
:item/label "Item 3"
:item/complete false}}))
(pc/defmutation todo-new-item [env {:keys [id list-id text]}]
{::pc/sym `fulcro-todomvc.api/todo-new-item
::pc/params [:list-id :id :text]
::pc/output [:item/id]}
(log/info "New item on server")
(let [new-id (tempid/uuid)]
(swap! item-db assoc new-id {:item/id new-id :item/label text :item/complete false})
{:tempids {id new-id}
:item/id new-id}))
(pc/defmutation todo-check [env {:keys [id]}]
{::pc/sym `fulcro-todomvc.api/todo-check
::pc/params [:id]
::pc/output []}
(log/info "Checked item" id)
(swap! item-db assoc-in [id :item/complete] true)
{})
(pc/defmutation todo-uncheck [env {:keys [id]}]
{::pc/sym `fulcro-todomvc.api/todo-uncheck
::pc/params [:id]
::pc/output []}
(log/info "Unchecked item" id)
(swap! item-db assoc-in [id :item/complete] false)
{})
(pc/defmutation commit-label-change [env {:keys [id text]}]
{::pc/sym `fulcro-todomvc.api/commit-label-change
::pc/params [:id :text]
::pc/output []}
(log/info "Set item label text of" id "to" text)
(swap! item-db assoc-in [id :item/label] text)
{})
(pc/defmutation todo-delete-item [env {:keys [id]}]
{::pc/sym `fulcro-todomvc.api/todo-delete-item
::pc/params [:id]
::pc/output []}
(log/info "Deleted item" id)
(swap! item-db dissoc id)
{})
(defn- to-all-todos [db f]
(into {}
(map (fn [[id todo]]
[id (f todo)]))
db))
(pc/defmutation todo-check-all [env _]
{::pc/sym `fulcro-todomvc.api/todo-check-all
::pc/params []
::pc/output []}
(log/info "Checked all items")
(swap! item-db to-all-todos #(assoc % :item/complete true))
{})
(pc/defmutation todo-uncheck-all [env _]
{::pc/sym `fulcro-todomvc.api/todo-uncheck-all
::pc/params []
::pc/output []}
(log/info "Unchecked all items")
(swap! item-db to-all-todos #(assoc % :item/complete false))
{})
(pc/defmutation todo-clear-complete [env _]
{::pc/sym `fulcro-todomvc.api/todo-clear-complete
::pc/params []
::pc/output []}
(log/info "Cleared completed items")
(swap! item-db (fn [db] (into {} (remove #(-> % val :item/complete)) db)))
{})
Support for Fulcro Inspect - Index Explorer
(pc/defresolver index-explorer
"This resolver is necessary to make it possible to use 'Load index' in Fulcro Inspect - EQL"
[env _]
{::pc/input #{:com.wsscode.pathom.viz.index-explorer/id}
::pc/output [:com.wsscode.pathom.viz.index-explorer/index]}
{:com.wsscode.pathom.viz.index-explorer/index
(-> (get env ::pc/indexes)
(update ::pc/index-resolvers #(into {} (map (fn [[k v]] [k (dissoc v ::pc/resolve)])) %))
(update ::pc/index-mutations #(into {} (map (fn [[k v]] [k (dissoc v ::pc/mutate)])) %)))})
(pc/defresolver list-resolver [env {id :list/id :as params}]
{::pc/input #{:list/id}
::pc/output [:list/title {:list/items [:item/id]}]}
(case id
1 {:list/title "The List"
:list/items (into [] (sort-by :item/id (vals @item-db)))}
2 {:list/title "Another List"
:list/items [{:item/id 99, :item/label "Hardcoded item", :item/complete true}
(assoc (get @item-db 1)
:item/label "Item 1 - re-loaded from server")]}))
(pc/defresolver item-resolver [env {:keys [item/id] :as params}]
{::pc/input #{:item/id}
::pc/output [:item/complete :item/label]}
(get @item-db id))
(def my-resolvers [index-explorer
list-resolver item-resolver
todo-new-item commit-label-change todo-delete-item
todo-check todo-uncheck
todo-check-all todo-uncheck-all
todo-clear-complete])
(def parser
(p/parser
{::p/env {::p/reader [p/map-reader
pc/reader2
pc/open-ident-reader]
::pc/mutation-join-globals [:tempids]}
::p/mutate pc/mutate
::p/plugins [(pc/connect-plugin {::pc/register my-resolvers})
(p/post-process-parser-plugin p/elide-not-found)
p/error-handler-plugin]}))
(defn wrap-index [handler]
(fn [req]
(if (= "/" (:uri req))
(-> (handler (assoc req :uri "/index.html", :path-info "/index.html"))
(content-type "text/html"))
(handler req))))
(def middleware (-> not-found-handler
(wrap-api {:uri "/api"
:parser (fn [query] (parser {} query))})
(fmw/wrap-transit-params)
(fmw/wrap-transit-response)
(wrap-resource "public")
wrap-index
wrap-content-type
wrap-not-modified))
(defonce server (atom nil))
(defn http-server []
(let [result (web/run middleware {:host "0.0.0.0"
:port 8181})]
(reset! server result)
(try
((requiring-resolve 'clojure.java.browse/browse-url) ":8181")
(catch UnsupportedOperationException e
(println "Browse to :8181 (opening it automatically not supported:" (ex-message e) ")")))
(fn [] (web/stop result))))
(comment
Calva setup : Execute the line below to start the server
(http-server)
(web/stop @server)
(tools-ns/refresh-all)
(async/<!! (parser {} `[(fulcro-todomvc.api/todo-new-item {:id 2 :text "Hello"})]))
@item-db
)
|
f561e4a3c724c4771b46e649743f9ad32efeff565a2bee42f3167a4f89c38acf | charlieg/Sparser | size-of-edge-vectors.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
copyright ( c ) 1991,1992,1993,1994 -- all rights reserved
;;;
;;; File: "size of edge vectors"
Module : " tools;measurements : "
Version : 1.0 December 1991
;; initiated 12/13/91
(in-package :sparser)
;;;------------
;;; data array
;;;-----------
(defparameter *maximum-permitted-count-in-an-edge-vector* 10
"If we find an edge vector with more than this number of edges
we'll blow out the measurement vector.")
(defparameter *size-of-starting-vectors*
(make-array *maximum-permitted-count-in-an-edge-vector*
:element-type 'integer))
(defparameter *size-of-ending-vectors*
(make-array *maximum-permitted-count-in-an-edge-vector*
:element-type 'integer))
;;;--------
;;; driver
;;;--------
(defun size-of-edge-vectors ()
;; called from toplevel after a parse has finished.
;; Scans the chart from beginning to end, counting the number
;; of edges that start/end at each position by accumulating
the information into two arrays .
(initialize-ev-count-arrays)
(dotimes (i (or (and *position-array-is-wrapped*
*number-of-positions-in-the-chart*)
*next-array-position-to-fill*))
(count-start-vector (chart-array-cell i))
(count-end-vector (chart-array-cell i)))
(display-edge-vector-sizes))
(defun initialize-ev-count-arrays ()
(dotimes (i *maximum-permitted-count-in-an-edge-vector*)
(setf (aref *size-of-starting-vectors* i) 0)
(setf (aref *size-of-ending-vectors* i) 0)))
(defun display-edge-vector-sizes (&optional
(stream *standard-output*))
(terpri stream)
(dotimes (i *maximum-permitted-count-in-an-edge-vector*)
(format stream "length ~A:~11,2tstarts: ~A~23,2tends: ~A~%"
i (aref *size-of-starting-vectors* i)
(aref *size-of-ending-vectors* i))))
(defun count-start-vector (position)
(let ((n (ev-number-of-edges (pos-starts-here position))))
(when (null n)
(setq n 0))
(if (>= n *maximum-permitted-count-in-an-edge-vector*)
(format t "~%~%-----------------------------------------~
~% number of edges exceeded limit: ~A~
~%-----------------------------------------~%"
n)
(incf (aref *size-of-starting-vectors* n)))))
(defun count-end-vector (position)
(let ((n (ev-number-of-edges (pos-ends-here position))))
(when (null n)
(setq n 0))
(if (>= n *maximum-permitted-count-in-an-edge-vector*)
(format t "~%~%-----------------------------------------~
~% number of edges exceeded limit: ~A~
~%-----------------------------------------~%"
n)
(incf (aref *size-of-ending-vectors* n)))))
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/tools/timing/size-of-edge-vectors.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
File: "size of edge vectors"
initiated 12/13/91
------------
data array
-----------
--------
driver
--------
called from toplevel after a parse has finished.
Scans the chart from beginning to end, counting the number
of edges that start/end at each position by accumulating | copyright ( c ) 1991,1992,1993,1994 -- all rights reserved
Module : " tools;measurements : "
Version : 1.0 December 1991
(in-package :sparser)
(defparameter *maximum-permitted-count-in-an-edge-vector* 10
"If we find an edge vector with more than this number of edges
we'll blow out the measurement vector.")
(defparameter *size-of-starting-vectors*
(make-array *maximum-permitted-count-in-an-edge-vector*
:element-type 'integer))
(defparameter *size-of-ending-vectors*
(make-array *maximum-permitted-count-in-an-edge-vector*
:element-type 'integer))
(defun size-of-edge-vectors ()
the information into two arrays .
(initialize-ev-count-arrays)
(dotimes (i (or (and *position-array-is-wrapped*
*number-of-positions-in-the-chart*)
*next-array-position-to-fill*))
(count-start-vector (chart-array-cell i))
(count-end-vector (chart-array-cell i)))
(display-edge-vector-sizes))
(defun initialize-ev-count-arrays ()
(dotimes (i *maximum-permitted-count-in-an-edge-vector*)
(setf (aref *size-of-starting-vectors* i) 0)
(setf (aref *size-of-ending-vectors* i) 0)))
(defun display-edge-vector-sizes (&optional
(stream *standard-output*))
(terpri stream)
(dotimes (i *maximum-permitted-count-in-an-edge-vector*)
(format stream "length ~A:~11,2tstarts: ~A~23,2tends: ~A~%"
i (aref *size-of-starting-vectors* i)
(aref *size-of-ending-vectors* i))))
(defun count-start-vector (position)
(let ((n (ev-number-of-edges (pos-starts-here position))))
(when (null n)
(setq n 0))
(if (>= n *maximum-permitted-count-in-an-edge-vector*)
(format t "~%~%-----------------------------------------~
~% number of edges exceeded limit: ~A~
~%-----------------------------------------~%"
n)
(incf (aref *size-of-starting-vectors* n)))))
(defun count-end-vector (position)
(let ((n (ev-number-of-edges (pos-ends-here position))))
(when (null n)
(setq n 0))
(if (>= n *maximum-permitted-count-in-an-edge-vector*)
(format t "~%~%-----------------------------------------~
~% number of edges exceeded limit: ~A~
~%-----------------------------------------~%"
n)
(incf (aref *size-of-ending-vectors* n)))))
|
4802718c49560883f54e6aad938383ed404eb218579b70b9c55c7c856d8499e1 | romstad/clj-chess | ecn.clj | (ns clj-chess.ecn
"Functions for reading chess games in ECN (extensible chess notation)
format."
(:require [clojure.edn :as edn]
[clojure.java.io :as io])
(:import (java.io PushbackReader)))
(defn reader
"Convenience function for creating a java PushbackReader for the given
file name. Why isn't this included in Clojure?"
[filename]
(PushbackReader. (io/reader filename)))
(defn edn-seq
"A lazy sequence of EDN objects in from the provided reader."
[rdr]
(when-let [game (edn/read {:eof nil} rdr)]
(cons game (lazy-seq (edn-seq rdr)))))
(defn game-headers
"Returns a lazy sequence of the game headers of an ECN file."
[rdr]
(map (comp rest second) (edn-seq rdr)))
(defn games-in-file [ecn-file]
(edn-seq (reader ecn-file))) | null | https://raw.githubusercontent.com/romstad/clj-chess/1f7d4d0217c7299d49386a1e5dca404a37441728/src/clojure/clj_chess/ecn.clj | clojure | (ns clj-chess.ecn
"Functions for reading chess games in ECN (extensible chess notation)
format."
(:require [clojure.edn :as edn]
[clojure.java.io :as io])
(:import (java.io PushbackReader)))
(defn reader
"Convenience function for creating a java PushbackReader for the given
file name. Why isn't this included in Clojure?"
[filename]
(PushbackReader. (io/reader filename)))
(defn edn-seq
"A lazy sequence of EDN objects in from the provided reader."
[rdr]
(when-let [game (edn/read {:eof nil} rdr)]
(cons game (lazy-seq (edn-seq rdr)))))
(defn game-headers
"Returns a lazy sequence of the game headers of an ECN file."
[rdr]
(map (comp rest second) (edn-seq rdr)))
(defn games-in-file [ecn-file]
(edn-seq (reader ecn-file))) | |
bb7fa78605969b056774607db7134813895921af3ac9ec9ec1fc840bd342b048 | footprintanalytics/footprint-web | revision.clj | (ns metabase.api.revision
(:require [compojure.core :refer [GET POST]]
[metabase.api.card :as api.card]
[metabase.api.common :as api]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.revision :as revision :refer [Revision]]
[schema.core :as s]
[toucan.db :as db]))
(def ^:private ^:const valid-entity-names
#{"card" "dashboard"})
(def ^:private Entity
"Schema for a valid revisionable entity name."
(apply s/enum valid-entity-names))
(defn- model-and-instance [entity-name id]
(case entity-name
"card" [Card (db/select-one Card :id id)]
"dashboard" [Dashboard (db/select-one Dashboard :id id)]))
(api/defendpoint GET "/"
"Get revisions of an object."
[entity id]
{entity Entity, id s/Int}
(let [[model instance] (model-and-instance entity id)]
(when (api/read-check instance)
(revision/revisions+details model id))))
(api/defendpoint POST "/revert"
"Revert an object to a prior revision."
[:as {{:keys [entity id revision_id]} :body}]
{entity Entity, id s/Int, revision_id s/Int}
(let [[model instance] (model-and-instance entity id)
_ (api/write-check instance)
revision (api/check-404 (db/select-one Revision :model (:name model), :model_id id, :id revision_id))]
if reverting a Card , make sure we have * data * permissions to run the query we 're reverting to
(when (= model Card)
(api.card/check-data-permissions-for-query (get-in revision [:object :dataset_query])))
ok , we 're
(revision/revert!
:entity model
:id id
:user-id api/*current-user-id*
:revision-id revision_id)))
(api/define-routes)
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/api/revision.clj | clojure | (ns metabase.api.revision
(:require [compojure.core :refer [GET POST]]
[metabase.api.card :as api.card]
[metabase.api.common :as api]
[metabase.models.card :refer [Card]]
[metabase.models.dashboard :refer [Dashboard]]
[metabase.models.revision :as revision :refer [Revision]]
[schema.core :as s]
[toucan.db :as db]))
(def ^:private ^:const valid-entity-names
#{"card" "dashboard"})
(def ^:private Entity
"Schema for a valid revisionable entity name."
(apply s/enum valid-entity-names))
(defn- model-and-instance [entity-name id]
(case entity-name
"card" [Card (db/select-one Card :id id)]
"dashboard" [Dashboard (db/select-one Dashboard :id id)]))
(api/defendpoint GET "/"
"Get revisions of an object."
[entity id]
{entity Entity, id s/Int}
(let [[model instance] (model-and-instance entity id)]
(when (api/read-check instance)
(revision/revisions+details model id))))
(api/defendpoint POST "/revert"
"Revert an object to a prior revision."
[:as {{:keys [entity id revision_id]} :body}]
{entity Entity, id s/Int, revision_id s/Int}
(let [[model instance] (model-and-instance entity id)
_ (api/write-check instance)
revision (api/check-404 (db/select-one Revision :model (:name model), :model_id id, :id revision_id))]
if reverting a Card , make sure we have * data * permissions to run the query we 're reverting to
(when (= model Card)
(api.card/check-data-permissions-for-query (get-in revision [:object :dataset_query])))
ok , we 're
(revision/revert!
:entity model
:id id
:user-id api/*current-user-id*
:revision-id revision_id)))
(api/define-routes)
| |
2ba9adb07242cd5f2c7028dfa4eac1f46007a29a457b57b906b512c05e1c056c | geneweb/geneweb | plugin_xhtml.ml | open Geneweb
open Config
let ns = "xhtml"
let () =
Gwd_lib.GwdPlugin.register_se ~ns @@ fun _assets conf _base ->
if Util.p_getenv conf.env "xhtml" = Some "on" then
let buffer_status = ref None in
let buffer_headers = ref [] in
let buffer_body = Buffer.create 1023 in
let previous_status = conf.output_conf.status in
let previous_header = conf.output_conf.header in
let previous_body = conf.output_conf.body in
let previous_flush = conf.output_conf.flush in
let status s = buffer_status := Some s in
let header s = buffer_headers := s :: !buffer_headers in
let body s = Buffer.add_string buffer_body s in
let flush () =
conf.output_conf <-
{
status = previous_status;
header = previous_header;
body = previous_body;
flush = previous_flush;
};
(match !buffer_status with Some s -> Output.status conf s | None -> ());
List.iter
(fun s ->
Output.header conf "%s"
@@
try
Scanf.sscanf s "Content-type: %_s; charset=%s" (fun c ->
"Content-type: application/xhtml+xml; charset=" ^ c)
with _ -> (
try
Scanf.sscanf s "Content-type: %_s"
"Content-type: application/xhtml+xml"
with _ -> s))
(List.rev !buffer_headers);
let open Markup in
buffer buffer_body |> parse_html |> signals |> write_xml |> to_string
|> Output.print_sstring conf;
Output.flush conf;
Buffer.reset buffer_body
in
conf.output_conf <- { status; header; body; flush }
| null | https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/plugins/xhtml/plugin_xhtml.ml | ocaml | open Geneweb
open Config
let ns = "xhtml"
let () =
Gwd_lib.GwdPlugin.register_se ~ns @@ fun _assets conf _base ->
if Util.p_getenv conf.env "xhtml" = Some "on" then
let buffer_status = ref None in
let buffer_headers = ref [] in
let buffer_body = Buffer.create 1023 in
let previous_status = conf.output_conf.status in
let previous_header = conf.output_conf.header in
let previous_body = conf.output_conf.body in
let previous_flush = conf.output_conf.flush in
let status s = buffer_status := Some s in
let header s = buffer_headers := s :: !buffer_headers in
let body s = Buffer.add_string buffer_body s in
let flush () =
conf.output_conf <-
{
status = previous_status;
header = previous_header;
body = previous_body;
flush = previous_flush;
};
(match !buffer_status with Some s -> Output.status conf s | None -> ());
List.iter
(fun s ->
Output.header conf "%s"
@@
try
Scanf.sscanf s "Content-type: %_s; charset=%s" (fun c ->
"Content-type: application/xhtml+xml; charset=" ^ c)
with _ -> (
try
Scanf.sscanf s "Content-type: %_s"
"Content-type: application/xhtml+xml"
with _ -> s))
(List.rev !buffer_headers);
let open Markup in
buffer buffer_body |> parse_html |> signals |> write_xml |> to_string
|> Output.print_sstring conf;
Output.flush conf;
Buffer.reset buffer_body
in
conf.output_conf <- { status; header; body; flush }
| |
44bd23284ee901b25bec6cddf327f910994a357794be88d2e93746f519694737 | samoht/camloo | instruct.scm | ;; Le module
(module
__caml_instruct
(library camloo-runtime)
(import __caml_const __caml_globals __caml_prim)
(export Nolabel_4@instruct))
L'initialisation du module
(init_camloo!)
;; Les variables globales
;; Les expressions globales
(define Nolabel_4@instruct -1)
| null | https://raw.githubusercontent.com/samoht/camloo/29a578a152fa23a3125a2a5b23e325b6d45d3abd/src/camloo/Llib.bootstrap/instruct.scm | scheme | Le module
Les variables globales
Les expressions globales | (module
__caml_instruct
(library camloo-runtime)
(import __caml_const __caml_globals __caml_prim)
(export Nolabel_4@instruct))
L'initialisation du module
(init_camloo!)
(define Nolabel_4@instruct -1)
|
26b7ce2572000a2c69a0b4a5a8fa41c620d112d23237adc28aa0ec56450c4617 | Shirakumo/kandria | prompt.lisp | (in-package #:org.shirakumo.fraf.kandria)
(defclass prompt-label (alloy:label*)
())
(presentations:define-realization (ui prompt-label)
((:label simple:text)
(alloy:margins)
alloy:text
:valign :middle
:halign :middle
:font "PromptFont"
:size (alloy:un 30)
:pattern colors:white))
(presentations:define-update (ui prompt-label)
(:label :pattern colors:white))
(defclass prompt-description (alloy:label*)
())
(presentations:define-realization (ui prompt-description)
((:label simple:text)
(alloy:margins)
alloy:text
:valign :middle
:halign :middle
:font (setting :display :font)
:size (alloy:un 15)
:pattern colors:white))
(presentations:define-update (ui prompt-description)
(:label :pattern colors:white))
(defclass prompt (alloy:horizontal-linear-layout alloy:renderable)
((alloy:cell-margins :initform (alloy:margins))
(alloy:min-size :initform (alloy:size 16 16))
(label :accessor label)
(description :accessor description)))
(defmethod initialize-instance :after ((prompt prompt) &key button description input)
(let ((label (setf (label prompt) (make-instance 'prompt-label :value (if button (coerce-button-string button input) ""))))
(descr (setf (description prompt) (make-instance 'prompt-description :value (or description "")))))
(alloy:enter label prompt)
(alloy:enter descr prompt)))
(presentations:define-realization (ui prompt)
((:tail-shadow simple:polygon)
(list (alloy:point -2 0) (alloy:point 22 0) (alloy:point 10 -12))
:pattern colors:white)
((:background-shadow simple:rectangle)
(alloy:margins -5 -2 -5 -4)
:pattern colors:white)
((:tail simple:polygon)
(list (alloy:point 0 0) (alloy:point 20 0) (alloy:point 10 -10))
:pattern (colored:color 0.15 0.15 0.15))
((:background simple:rectangle)
(alloy:margins -5 -2 -5 -2)
:pattern colors:black))
(presentations:define-update (ui prompt)
(:tail-shadow
:points (list (alloy:point -2 0) (alloy:point 22 0) (alloy:point 10 -12)))
(:tail
:points (list (alloy:point 0 0) (alloy:point 20 0) (alloy:point 10 -10)))
(:label :pattern colors:white))
(defun coerce-button-string (button &optional input)
(etypecase button
(string button)
(symbol (prompt-string button :bank input :default (@ unbound-action-label)))
(list (format NIL "~{~a~^ ~}" (mapcar (lambda (c) (prompt-string c :bank input :default "")) button)))))
(defmethod show ((prompt prompt) &key button input location (description NIL description-p))
(when button
(setf (alloy:value (label prompt)) (coerce-button-string button input)))
(when description-p
(setf (alloy:value (description prompt)) (or description "")))
(unless (alloy:layout-tree prompt)
(alloy:enter prompt (alloy:layout-element (find-panel 'hud))))
(alloy:mark-for-render prompt)
(alloy:with-unit-parent prompt
(let* ((screen-location (world-screen-pos location))
(size (alloy:suggest-size (alloy:px-size 16 16) prompt)))
(setf (alloy:bounds prompt) (alloy:px-extent (min (- (vx screen-location) (alloy:to-px (alloy:un 10)))
(- (alloy:to-px (alloy:vw 1)) (alloy:pxw size)))
(min (+ (vy screen-location) (alloy:pxh size))
(- (alloy:to-px (alloy:vh 1)) (alloy:pxh size)))
(max 1 (alloy:pxw size))
(max 1 (alloy:pxh size)))))))
(defmethod hide ((prompt prompt))
(when (alloy:layout-tree prompt)
(alloy:leave prompt T)))
(defmethod alloy:render :around ((ui ui) (prompt prompt))
(unless (find-panel 'fullscreen-panel)
(call-next-method)))
(defclass big-prompt (alloy:label*)
())
(presentations:define-realization (ui big-prompt)
((:label simple:text)
(alloy:margins -10) alloy:text
:font "PromptFont"
:size (alloy:un 90)
:valign :middle
:halign :middle))
(animation:define-animation (pulse :loop T)
0.0 ((setf presentations:scale) (alloy:px-size 1.0))
0.3 ((setf presentations:scale) (alloy:px-size 1.2) :easing animation::quint-in)
0.6 ((setf presentations:scale) (alloy:px-size 1.0) :easing animation::quint-out))
(defmethod presentations:realize-renderable :after ((ui ui) (prompt big-prompt))
(let ((text (presentations:find-shape :label prompt)))
: no idea why this pivot is like this , but whatever ...
(setf (presentations:pivot text) (alloy:point 180 45))
(animation:apply-animation 'pulse text)))
(defclass big-prompt-title (alloy:label*)
())
(presentations:define-realization (ui big-prompt-title)
((:top-border simple:rectangle)
(alloy:extent 0 0 (alloy:pw 1) 2)
:pattern colors:white)
((:label simple:text)
(alloy:margins) alloy:text
:font (setting :display :font)
:size (alloy:un 20)
:valign :top
:halign :left
:wrap T))
(defclass big-prompt-description (alloy:label*)
())
(presentations:define-realization (ui big-prompt-description)
((:top-border simple:rectangle)
(alloy:extent 0 (alloy:ph 1) (alloy:pw 1) 2)
:pattern colors:white)
((:label simple:text)
(alloy:margins) alloy:text
:font (setting :display :font)
:size (alloy:un 30)
:valign :top
:halign :middle
:wrap T))
(defclass big-prompt-layout (eating-constraint-layout alloy:renderable)
())
(presentations:define-realization (ui big-prompt-layout)
((:bg simple:rectangle)
(alloy:margins)
:pattern (colored:color 0 0 0 0.5)))
(defclass fullscreen-prompt (action-set-change-panel pausing-panel)
((button :initarg :button :accessor button)))
(defmethod initialize-instance :after ((prompt fullscreen-prompt) &key button input title description)
(let ((layout (make-instance 'big-prompt-layout))
(button (make-instance 'big-prompt :value (coerce-button-string button input)))
(title (make-instance 'big-prompt-title :value (ensure-language-string title)))
(description (make-instance 'big-prompt-description :value (ensure-language-string description)))
(confirm (make-instance 'label :value (@ press-prompted-button) :style `((:label :size ,(alloy:un 14)) :halign :middle))))
(alloy:enter button layout :constraints `(:center (:size 500 120)))
(alloy:enter description layout :constraints `((:center :w) (:below ,button 20) (:size 1000 150)))
(alloy:enter title layout :constraints `((:center :w) (:above ,button 20) (:align :left ,description -30) (:size 300 30)))
(alloy:enter confirm layout :constraints `((:center :w) (:below ,description 20) (:size 1000 30)))
(alloy:finish-structure prompt layout NIL)))
(defmethod show :after ((prompt fullscreen-prompt) &key)
(harmony:play (// 'sound 'ui-tutorial-popup)))
(defmethod handle ((ev event) (prompt fullscreen-prompt))
(when (etypecase (button prompt)
(list (loop for type in (button prompt)
thereis (typep ev type)))
(symbol (typep ev (button prompt))))
(hide prompt)))
(defmethod (setf active-p) :after (value (panel fullscreen-prompt))
(when value
(setf (active-p (action-set 'in-game)) T)))
(defun fullscreen-prompt (action &key (title action) input (description (trial::mksym #.*package* title '/description)))
(show (make-instance 'fullscreen-prompt :button action :input input :title title :description description)))
(defclass quest-indicator (alloy:popup alloy:renderable popup)
((angle :initform 0f0 :accessor angle)
(target :initarg :target :accessor target)
(clock :initarg :clock :initform 5f0 :accessor clock)))
(defmethod initialize-instance :after ((prompt quest-indicator) &key target)
(let* ((target (typecase target
(entity target)
(symbol (unit target +world+))
(T target))))
(setf (target prompt) (closest-visible-target target))))
(defmethod animation:update :after ((prompt quest-indicator) dt)
(when (alloy:layout-tree prompt)
(let* ((target (target prompt))
(tloc (ensure-location target))
(bounds (in-view-tester (camera +world+))))
(cond ((in-bounds-p tloc bounds)
(let* ((yoff (typecase target
(layer 0.0)
(sized-entity (vy (bsize target)))
(T 0.0)))
(screen-location (world-screen-pos (tvec (vx tloc) (+ (vy tloc) yoff)))))
(setf (angle prompt) (* 1.5 PI))
(setf (alloy:bounds prompt) (alloy:px-extent (vx screen-location) (alloy:u+ (alloy:un 60) (vy screen-location))
1 1))))
(T
(labels ((div (x)
(if (= 0.0 x) 100000.0 (/ x)))
(ray-rect (bounds origin direction)
;; Project ray from inside bounds to border and compute intersection.
(let* ((scale-x (div (vx direction)))
(scale-y (div (vy direction)))
(tx1 (* scale-x (- (vx bounds) (vx origin))))
(tx2 (* scale-x (- (vz bounds) (vx origin))))
(ty1 (* scale-y (- (vy bounds) (vy origin))))
(ty2 (* scale-y (- (vw bounds) (vy origin))))
(tt (min (max tx1 tx2) (max ty1 ty2))))
(nv+ (v* direction tt) origin))))
(let* ((middle (tvec (* (+ (vx bounds) (vz bounds)) 0.5)
(* (+ (vy bounds) (vw bounds)) 0.5)))
(direction (v- tloc middle))
(position (ray-rect (tvec (+ (vx bounds) 30) (+ (vy bounds) 30)
(- (vz bounds) 30) (- (vw bounds) 30))
middle direction))
(screen-location (world-screen-pos position)))
(setf (alloy:bounds prompt) (alloy:px-extent (vx screen-location) (vy screen-location) 1 1))
(setf (angle prompt) (point-angle direction))))))
(if (<= (decf (clock prompt) dt) 0f0)
(hide prompt)
(alloy:mark-for-render prompt)))))
(presentations:define-realization (ui quest-indicator)
((:indicator simple:polygon)
(list (alloy:point 0 -20)
(alloy:point 50 0)
(alloy:point 0 20))
:pattern colors:white)
((:bg simple:ellipse)
(alloy:extent -28 -28 56 56)
:pattern colors:white)
((:indicator-fill simple:polygon)
(list (alloy:point 0 -15)
(alloy:point 45 0)
(alloy:point 0 15))
:pattern (colored:color 0.2 0.2 0.2))
((:fg simple:ellipse)
(alloy:extent -25 -25 50 50)
:pattern (colored:color 0.2 0.2 0.2))
((:text simple:text)
(alloy:extent -32 -28 60 60)
"⌖"
:font "PromptFont"
:pattern colors:white
:size (alloy:un 35)
:halign :middle
:valign :middle))
(presentations:define-update (ui quest-indicator)
(:indicator
:rotation (angle alloy:renderable))
(:indicator-fill
:rotation (angle alloy:renderable)))
(defmethod show ((prompt quest-indicator) &key target)
(unless (alloy:layout-tree prompt)
(alloy:enter prompt (unit 'ui-pass T) :w 1 :h 1))
(when target
(setf (target prompt) target))
(alloy:mark-for-render prompt))
(defmethod hide ((prompt quest-indicator))
(when (alloy:layout-tree prompt)
(alloy:leave prompt T)))
| null | https://raw.githubusercontent.com/Shirakumo/kandria/94fd727bd93e302c6a28fae33815043d486d794b/ui/prompt.lisp | lisp | Project ray from inside bounds to border and compute intersection. | (in-package #:org.shirakumo.fraf.kandria)
(defclass prompt-label (alloy:label*)
())
(presentations:define-realization (ui prompt-label)
((:label simple:text)
(alloy:margins)
alloy:text
:valign :middle
:halign :middle
:font "PromptFont"
:size (alloy:un 30)
:pattern colors:white))
(presentations:define-update (ui prompt-label)
(:label :pattern colors:white))
(defclass prompt-description (alloy:label*)
())
(presentations:define-realization (ui prompt-description)
((:label simple:text)
(alloy:margins)
alloy:text
:valign :middle
:halign :middle
:font (setting :display :font)
:size (alloy:un 15)
:pattern colors:white))
(presentations:define-update (ui prompt-description)
(:label :pattern colors:white))
(defclass prompt (alloy:horizontal-linear-layout alloy:renderable)
((alloy:cell-margins :initform (alloy:margins))
(alloy:min-size :initform (alloy:size 16 16))
(label :accessor label)
(description :accessor description)))
(defmethod initialize-instance :after ((prompt prompt) &key button description input)
(let ((label (setf (label prompt) (make-instance 'prompt-label :value (if button (coerce-button-string button input) ""))))
(descr (setf (description prompt) (make-instance 'prompt-description :value (or description "")))))
(alloy:enter label prompt)
(alloy:enter descr prompt)))
(presentations:define-realization (ui prompt)
((:tail-shadow simple:polygon)
(list (alloy:point -2 0) (alloy:point 22 0) (alloy:point 10 -12))
:pattern colors:white)
((:background-shadow simple:rectangle)
(alloy:margins -5 -2 -5 -4)
:pattern colors:white)
((:tail simple:polygon)
(list (alloy:point 0 0) (alloy:point 20 0) (alloy:point 10 -10))
:pattern (colored:color 0.15 0.15 0.15))
((:background simple:rectangle)
(alloy:margins -5 -2 -5 -2)
:pattern colors:black))
(presentations:define-update (ui prompt)
(:tail-shadow
:points (list (alloy:point -2 0) (alloy:point 22 0) (alloy:point 10 -12)))
(:tail
:points (list (alloy:point 0 0) (alloy:point 20 0) (alloy:point 10 -10)))
(:label :pattern colors:white))
(defun coerce-button-string (button &optional input)
(etypecase button
(string button)
(symbol (prompt-string button :bank input :default (@ unbound-action-label)))
(list (format NIL "~{~a~^ ~}" (mapcar (lambda (c) (prompt-string c :bank input :default "")) button)))))
(defmethod show ((prompt prompt) &key button input location (description NIL description-p))
(when button
(setf (alloy:value (label prompt)) (coerce-button-string button input)))
(when description-p
(setf (alloy:value (description prompt)) (or description "")))
(unless (alloy:layout-tree prompt)
(alloy:enter prompt (alloy:layout-element (find-panel 'hud))))
(alloy:mark-for-render prompt)
(alloy:with-unit-parent prompt
(let* ((screen-location (world-screen-pos location))
(size (alloy:suggest-size (alloy:px-size 16 16) prompt)))
(setf (alloy:bounds prompt) (alloy:px-extent (min (- (vx screen-location) (alloy:to-px (alloy:un 10)))
(- (alloy:to-px (alloy:vw 1)) (alloy:pxw size)))
(min (+ (vy screen-location) (alloy:pxh size))
(- (alloy:to-px (alloy:vh 1)) (alloy:pxh size)))
(max 1 (alloy:pxw size))
(max 1 (alloy:pxh size)))))))
(defmethod hide ((prompt prompt))
(when (alloy:layout-tree prompt)
(alloy:leave prompt T)))
(defmethod alloy:render :around ((ui ui) (prompt prompt))
(unless (find-panel 'fullscreen-panel)
(call-next-method)))
(defclass big-prompt (alloy:label*)
())
(presentations:define-realization (ui big-prompt)
((:label simple:text)
(alloy:margins -10) alloy:text
:font "PromptFont"
:size (alloy:un 90)
:valign :middle
:halign :middle))
(animation:define-animation (pulse :loop T)
0.0 ((setf presentations:scale) (alloy:px-size 1.0))
0.3 ((setf presentations:scale) (alloy:px-size 1.2) :easing animation::quint-in)
0.6 ((setf presentations:scale) (alloy:px-size 1.0) :easing animation::quint-out))
(defmethod presentations:realize-renderable :after ((ui ui) (prompt big-prompt))
(let ((text (presentations:find-shape :label prompt)))
: no idea why this pivot is like this , but whatever ...
(setf (presentations:pivot text) (alloy:point 180 45))
(animation:apply-animation 'pulse text)))
(defclass big-prompt-title (alloy:label*)
())
(presentations:define-realization (ui big-prompt-title)
((:top-border simple:rectangle)
(alloy:extent 0 0 (alloy:pw 1) 2)
:pattern colors:white)
((:label simple:text)
(alloy:margins) alloy:text
:font (setting :display :font)
:size (alloy:un 20)
:valign :top
:halign :left
:wrap T))
(defclass big-prompt-description (alloy:label*)
())
(presentations:define-realization (ui big-prompt-description)
((:top-border simple:rectangle)
(alloy:extent 0 (alloy:ph 1) (alloy:pw 1) 2)
:pattern colors:white)
((:label simple:text)
(alloy:margins) alloy:text
:font (setting :display :font)
:size (alloy:un 30)
:valign :top
:halign :middle
:wrap T))
(defclass big-prompt-layout (eating-constraint-layout alloy:renderable)
())
(presentations:define-realization (ui big-prompt-layout)
((:bg simple:rectangle)
(alloy:margins)
:pattern (colored:color 0 0 0 0.5)))
(defclass fullscreen-prompt (action-set-change-panel pausing-panel)
((button :initarg :button :accessor button)))
(defmethod initialize-instance :after ((prompt fullscreen-prompt) &key button input title description)
(let ((layout (make-instance 'big-prompt-layout))
(button (make-instance 'big-prompt :value (coerce-button-string button input)))
(title (make-instance 'big-prompt-title :value (ensure-language-string title)))
(description (make-instance 'big-prompt-description :value (ensure-language-string description)))
(confirm (make-instance 'label :value (@ press-prompted-button) :style `((:label :size ,(alloy:un 14)) :halign :middle))))
(alloy:enter button layout :constraints `(:center (:size 500 120)))
(alloy:enter description layout :constraints `((:center :w) (:below ,button 20) (:size 1000 150)))
(alloy:enter title layout :constraints `((:center :w) (:above ,button 20) (:align :left ,description -30) (:size 300 30)))
(alloy:enter confirm layout :constraints `((:center :w) (:below ,description 20) (:size 1000 30)))
(alloy:finish-structure prompt layout NIL)))
(defmethod show :after ((prompt fullscreen-prompt) &key)
(harmony:play (// 'sound 'ui-tutorial-popup)))
(defmethod handle ((ev event) (prompt fullscreen-prompt))
(when (etypecase (button prompt)
(list (loop for type in (button prompt)
thereis (typep ev type)))
(symbol (typep ev (button prompt))))
(hide prompt)))
(defmethod (setf active-p) :after (value (panel fullscreen-prompt))
(when value
(setf (active-p (action-set 'in-game)) T)))
(defun fullscreen-prompt (action &key (title action) input (description (trial::mksym #.*package* title '/description)))
(show (make-instance 'fullscreen-prompt :button action :input input :title title :description description)))
(defclass quest-indicator (alloy:popup alloy:renderable popup)
((angle :initform 0f0 :accessor angle)
(target :initarg :target :accessor target)
(clock :initarg :clock :initform 5f0 :accessor clock)))
(defmethod initialize-instance :after ((prompt quest-indicator) &key target)
(let* ((target (typecase target
(entity target)
(symbol (unit target +world+))
(T target))))
(setf (target prompt) (closest-visible-target target))))
(defmethod animation:update :after ((prompt quest-indicator) dt)
(when (alloy:layout-tree prompt)
(let* ((target (target prompt))
(tloc (ensure-location target))
(bounds (in-view-tester (camera +world+))))
(cond ((in-bounds-p tloc bounds)
(let* ((yoff (typecase target
(layer 0.0)
(sized-entity (vy (bsize target)))
(T 0.0)))
(screen-location (world-screen-pos (tvec (vx tloc) (+ (vy tloc) yoff)))))
(setf (angle prompt) (* 1.5 PI))
(setf (alloy:bounds prompt) (alloy:px-extent (vx screen-location) (alloy:u+ (alloy:un 60) (vy screen-location))
1 1))))
(T
(labels ((div (x)
(if (= 0.0 x) 100000.0 (/ x)))
(ray-rect (bounds origin direction)
(let* ((scale-x (div (vx direction)))
(scale-y (div (vy direction)))
(tx1 (* scale-x (- (vx bounds) (vx origin))))
(tx2 (* scale-x (- (vz bounds) (vx origin))))
(ty1 (* scale-y (- (vy bounds) (vy origin))))
(ty2 (* scale-y (- (vw bounds) (vy origin))))
(tt (min (max tx1 tx2) (max ty1 ty2))))
(nv+ (v* direction tt) origin))))
(let* ((middle (tvec (* (+ (vx bounds) (vz bounds)) 0.5)
(* (+ (vy bounds) (vw bounds)) 0.5)))
(direction (v- tloc middle))
(position (ray-rect (tvec (+ (vx bounds) 30) (+ (vy bounds) 30)
(- (vz bounds) 30) (- (vw bounds) 30))
middle direction))
(screen-location (world-screen-pos position)))
(setf (alloy:bounds prompt) (alloy:px-extent (vx screen-location) (vy screen-location) 1 1))
(setf (angle prompt) (point-angle direction))))))
(if (<= (decf (clock prompt) dt) 0f0)
(hide prompt)
(alloy:mark-for-render prompt)))))
(presentations:define-realization (ui quest-indicator)
((:indicator simple:polygon)
(list (alloy:point 0 -20)
(alloy:point 50 0)
(alloy:point 0 20))
:pattern colors:white)
((:bg simple:ellipse)
(alloy:extent -28 -28 56 56)
:pattern colors:white)
((:indicator-fill simple:polygon)
(list (alloy:point 0 -15)
(alloy:point 45 0)
(alloy:point 0 15))
:pattern (colored:color 0.2 0.2 0.2))
((:fg simple:ellipse)
(alloy:extent -25 -25 50 50)
:pattern (colored:color 0.2 0.2 0.2))
((:text simple:text)
(alloy:extent -32 -28 60 60)
"⌖"
:font "PromptFont"
:pattern colors:white
:size (alloy:un 35)
:halign :middle
:valign :middle))
(presentations:define-update (ui quest-indicator)
(:indicator
:rotation (angle alloy:renderable))
(:indicator-fill
:rotation (angle alloy:renderable)))
(defmethod show ((prompt quest-indicator) &key target)
(unless (alloy:layout-tree prompt)
(alloy:enter prompt (unit 'ui-pass T) :w 1 :h 1))
(when target
(setf (target prompt) target))
(alloy:mark-for-render prompt))
(defmethod hide ((prompt quest-indicator))
(when (alloy:layout-tree prompt)
(alloy:leave prompt T)))
|
85d83af84cd5b8f4d379616afd33bd0107c37eb02014e603867645bbf64639e0 | viesti/table-spec | fixture.clj | (ns table-spec.fixture
(:require [clojure.test :refer :all]
[clojure.string :as str]
[clojure.java.shell :refer [sh]]
[clojure.java.jdbc :as jdbc]))
(defn sh! [& args]
(let [{:keys [exit out]} (apply sh args)]
(when-not (zero? exit)
(throw (Exception. (str "'" (str/join " " args) "' returned " exit))))
(.trim out)))
(defn db-available? [uri]
(try
(jdbc/with-db-connection [db {:connection-uri uri}])
true
(catch Throwable t
false)))
(defn wait-for-db [uri]
(loop [count 0
available? false]
(if (and (not available?)
(< count 10))
(if-not (db-available? uri)
(do
(Thread/sleep 1000)
(recur (inc count) false))
(recur (inc count) true))
(when (>= count 10)
(throw (Exception. "Database not available"))))))
(defn with-db [uri f]
(let [id (sh! "docker" "run"
"--name" "table-spec"
"-e" "POSTGRES_PASSWORD=secret"
"-d"
"-p" "5433:5432"
"postgres:9.6.2-alpine")]
(wait-for-db uri)
(f)
(sh! "docker" "stop" id)
(sh "docker" "rm" "table-spec")))
| null | https://raw.githubusercontent.com/viesti/table-spec/723d86e96950c84f2970052ee3a35e2c5ef58530/test/table_spec/fixture.clj | clojure | (ns table-spec.fixture
(:require [clojure.test :refer :all]
[clojure.string :as str]
[clojure.java.shell :refer [sh]]
[clojure.java.jdbc :as jdbc]))
(defn sh! [& args]
(let [{:keys [exit out]} (apply sh args)]
(when-not (zero? exit)
(throw (Exception. (str "'" (str/join " " args) "' returned " exit))))
(.trim out)))
(defn db-available? [uri]
(try
(jdbc/with-db-connection [db {:connection-uri uri}])
true
(catch Throwable t
false)))
(defn wait-for-db [uri]
(loop [count 0
available? false]
(if (and (not available?)
(< count 10))
(if-not (db-available? uri)
(do
(Thread/sleep 1000)
(recur (inc count) false))
(recur (inc count) true))
(when (>= count 10)
(throw (Exception. "Database not available"))))))
(defn with-db [uri f]
(let [id (sh! "docker" "run"
"--name" "table-spec"
"-e" "POSTGRES_PASSWORD=secret"
"-d"
"-p" "5433:5432"
"postgres:9.6.2-alpine")]
(wait-for-db uri)
(f)
(sh! "docker" "stop" id)
(sh "docker" "rm" "table-spec")))
| |
d57645da7bb3fa2198149d5750b510f1deff00e0cf778a89b7d025a341c4c969 | openweb-nl/open-bank-mark | load.clj | (ns nl.openweb.test.load
(:require [nrepl.core :as repl])
(:import (java.io IOException)))
(def conn (atom nil))
(def client (atom nil))
(defn close-conn
[]
(if-let [c @conn]
(try
(.close c)
(catch IOException e
(println e "Failed to close " @conn)))))
(defn reconnect
[]
(close-conn)
(reset! conn (repl/connect :port 17888))
(reset! client (repl/client @conn 1000))
(Double/NaN))
(defn safe-read
[input]
(if (nil? input) (reconnect) (read-string input)))
(defn set-batch-size
[batch-size]
(let [code (str "(do (ns nl.openweb.heartbeat.core) (reset! batch-size " batch-size "))")
set-batch-size (-> (repl/message @client {:op :eval :code code})
first
:value
safe-read)]
(if (Double/isNaN set-batch-size)
(recur batch-size)
set-batch-size)))
(defn set-sleep-time
[sleep-time]
(let [code (str "(do (ns nl.openweb.heartbeat.core) (reset! sleep-time " sleep-time "))")
set-sleep-time (-> (repl/message @client {:op :eval :code code})
first
:value
safe-read)]
(if (Double/isNaN set-sleep-time)
(recur sleep-time)
set-batch-size)))
(defn init
[]
(reconnect)
(set-sleep-time 100)
(set-batch-size 0))
(defn get-counter
[]
(let [code (str "(do (ns nl.openweb.heartbeat.core) @counter)")]
(-> (repl/message @client {:op :eval :code code})
first
:value
safe-read)))
(defn close
[]
(set-batch-size 0)
(close-conn)
(reset! conn nil)
(reset! client nil))
| null | https://raw.githubusercontent.com/openweb-nl/open-bank-mark/786c940dafb39c36fdbcae736fe893af9c00ef17/test/src/nl/openweb/test/load.clj | clojure | (ns nl.openweb.test.load
(:require [nrepl.core :as repl])
(:import (java.io IOException)))
(def conn (atom nil))
(def client (atom nil))
(defn close-conn
[]
(if-let [c @conn]
(try
(.close c)
(catch IOException e
(println e "Failed to close " @conn)))))
(defn reconnect
[]
(close-conn)
(reset! conn (repl/connect :port 17888))
(reset! client (repl/client @conn 1000))
(Double/NaN))
(defn safe-read
[input]
(if (nil? input) (reconnect) (read-string input)))
(defn set-batch-size
[batch-size]
(let [code (str "(do (ns nl.openweb.heartbeat.core) (reset! batch-size " batch-size "))")
set-batch-size (-> (repl/message @client {:op :eval :code code})
first
:value
safe-read)]
(if (Double/isNaN set-batch-size)
(recur batch-size)
set-batch-size)))
(defn set-sleep-time
[sleep-time]
(let [code (str "(do (ns nl.openweb.heartbeat.core) (reset! sleep-time " sleep-time "))")
set-sleep-time (-> (repl/message @client {:op :eval :code code})
first
:value
safe-read)]
(if (Double/isNaN set-sleep-time)
(recur sleep-time)
set-batch-size)))
(defn init
[]
(reconnect)
(set-sleep-time 100)
(set-batch-size 0))
(defn get-counter
[]
(let [code (str "(do (ns nl.openweb.heartbeat.core) @counter)")]
(-> (repl/message @client {:op :eval :code code})
first
:value
safe-read)))
(defn close
[]
(set-batch-size 0)
(close-conn)
(reset! conn nil)
(reset! client nil))
| |
9b92c5d2289a2bbf863fe1a96cbd4e3a66449b8d6078042ec72da765e6705ed7 | tezos/tezos-mirror | eth_cli.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2023 Nomadic Labs < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
let path = "eth"
let spawn_command command decode =
let process = Process.spawn path command in
let* output = Process.check_and_read_stdout process in
return (JSON.parse ~origin:"eth_spawn_command" output |> decode)
let balance ~account ~endpoint =
spawn_command ["address:balance"; account; "--network"; endpoint] JSON.as_int
let transaction_send ~source_private_key ~to_public_key ~value ~endpoint =
spawn_command
[
"transaction:send";
"--pk";
source_private_key;
"--to";
to_public_key;
"--value";
Z.to_string value;
"--network";
endpoint;
]
JSON.as_string
let get_block ~block_id ~endpoint =
spawn_command ["block:get"; block_id; "--network"; endpoint] Eth.Block.of_json
let block_number ~endpoint =
spawn_command ["block:number"; "--network"; endpoint] JSON.as_int
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/aaa7c826ef23269d5d158939605a689453a4b357/tezt/lib_tezos/eth_cli.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*************************************************************************** | Copyright ( c ) 2023 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
let path = "eth"
let spawn_command command decode =
let process = Process.spawn path command in
let* output = Process.check_and_read_stdout process in
return (JSON.parse ~origin:"eth_spawn_command" output |> decode)
let balance ~account ~endpoint =
spawn_command ["address:balance"; account; "--network"; endpoint] JSON.as_int
let transaction_send ~source_private_key ~to_public_key ~value ~endpoint =
spawn_command
[
"transaction:send";
"--pk";
source_private_key;
"--to";
to_public_key;
"--value";
Z.to_string value;
"--network";
endpoint;
]
JSON.as_string
let get_block ~block_id ~endpoint =
spawn_command ["block:get"; block_id; "--network"; endpoint] Eth.Block.of_json
let block_number ~endpoint =
spawn_command ["block:number"; "--network"; endpoint] JSON.as_int
|
43fe836cdbdebd466506a7d4709e55deceeba16ccc3bb01b5962161389a975cb | faylang/fay | Typecheck.hs | | Type - check using GHC .
module Fay.Compiler.Typecheck where
import Fay.Compiler.Prelude
import Fay.Compiler.Defaults
import Fay.Compiler.Misc
import Fay.Config
import Fay.Types
import qualified GHC.Paths as GHCPaths
import System.Directory
import System.Environment
| Call out to GHC to type - check the file .
typecheck :: Config -> FilePath -> IO (Either CompileError String)
typecheck cfg fp = do
faydir <- faySourceDir
let includes = configDirectoryIncludes cfg
Remove the fay source from includeDirs to prevent errors on FFI instance declarations .
let includeDirs = map snd . filter ((/= faydir) . snd) . filter (isNothing . fst) $ includes
let packages = nub . map (fromJust . fst) . filter (isJust . fst) $ includes
ghcPackageDbArgs <-
case configPackageConf cfg of
Nothing -> return []
Just pk -> do
flag <- getGhcPackageDbFlag
return [flag ++ '=' : pk]
let flags =
[ "-fno-code"
, "-hide-all-packages"
, "-cpp", "-pgmPcpphs", "-optP--cpp"
, "-optP-C" -- Don't let hse-cpp remove //-style comments.
, "-DFAY=1"
, "-main-is"
, "Language.Fay.DummyMain"
, "-i" ++ intercalate ":" includeDirs
, fp ] ++ ghcPackageDbArgs ++ wallF ++ map ("-package " ++) packages
exists <- doesFileExist GHCPaths.ghc
stackInNixShell <- fmap isJust (lookupEnv "STACK_IN_NIX_SHELL")
let ghcPath = if exists
then if (isInfixOf ".stack" GHCPaths.ghc || stackInNixShell)
then "stack"
else GHCPaths.ghc
else "ghc"
extraFlags = case ghcPath of
"stack" -> ["exec","--","ghc"]
_ -> []
when (configShowGhcCalls cfg) $
putStrLn . unwords $ ghcPath : (extraFlags ++ flags)
when stackInNixShell (unsetEnv "STACK_IN_NIX_SHELL")
res <- readAllFromProcess ghcPath (extraFlags ++ flags) ""
when stackInNixShell (setEnv "STACK_IN_NIX_SHELL" "1")
either (return . Left . GHCError . fst) (return . Right . fst) res
where
wallF | configWall cfg = ["-Wall"]
| otherwise = []
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/src/Fay/Compiler/Typecheck.hs | haskell | Don't let hse-cpp remove //-style comments. | | Type - check using GHC .
module Fay.Compiler.Typecheck where
import Fay.Compiler.Prelude
import Fay.Compiler.Defaults
import Fay.Compiler.Misc
import Fay.Config
import Fay.Types
import qualified GHC.Paths as GHCPaths
import System.Directory
import System.Environment
| Call out to GHC to type - check the file .
typecheck :: Config -> FilePath -> IO (Either CompileError String)
typecheck cfg fp = do
faydir <- faySourceDir
let includes = configDirectoryIncludes cfg
Remove the fay source from includeDirs to prevent errors on FFI instance declarations .
let includeDirs = map snd . filter ((/= faydir) . snd) . filter (isNothing . fst) $ includes
let packages = nub . map (fromJust . fst) . filter (isJust . fst) $ includes
ghcPackageDbArgs <-
case configPackageConf cfg of
Nothing -> return []
Just pk -> do
flag <- getGhcPackageDbFlag
return [flag ++ '=' : pk]
let flags =
[ "-fno-code"
, "-hide-all-packages"
, "-cpp", "-pgmPcpphs", "-optP--cpp"
, "-DFAY=1"
, "-main-is"
, "Language.Fay.DummyMain"
, "-i" ++ intercalate ":" includeDirs
, fp ] ++ ghcPackageDbArgs ++ wallF ++ map ("-package " ++) packages
exists <- doesFileExist GHCPaths.ghc
stackInNixShell <- fmap isJust (lookupEnv "STACK_IN_NIX_SHELL")
let ghcPath = if exists
then if (isInfixOf ".stack" GHCPaths.ghc || stackInNixShell)
then "stack"
else GHCPaths.ghc
else "ghc"
extraFlags = case ghcPath of
"stack" -> ["exec","--","ghc"]
_ -> []
when (configShowGhcCalls cfg) $
putStrLn . unwords $ ghcPath : (extraFlags ++ flags)
when stackInNixShell (unsetEnv "STACK_IN_NIX_SHELL")
res <- readAllFromProcess ghcPath (extraFlags ++ flags) ""
when stackInNixShell (setEnv "STACK_IN_NIX_SHELL" "1")
either (return . Left . GHCError . fst) (return . Right . fst) res
where
wallF | configWall cfg = ["-Wall"]
| otherwise = []
|
15292e5353c7758e39087286838d407023d7c911518863d279b4768648af9f97 | lspitzner/brittany | Test331.hs | go l [] = Right l
go l ((IRType, _a) : eqr) = go l eqr
go l ((_, IRType) : eqr) = go l eqr
go _ ((IRTypeError ps t1 t2, _) : _) = Left $ makeError ps t1 t2
go _ ((_, IRTypeError ps t1 t2) : _) = Left $ makeError ps t1 t2
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test331.hs | haskell | go l [] = Right l
go l ((IRType, _a) : eqr) = go l eqr
go l ((_, IRType) : eqr) = go l eqr
go _ ((IRTypeError ps t1 t2, _) : _) = Left $ makeError ps t1 t2
go _ ((_, IRTypeError ps t1 t2) : _) = Left $ makeError ps t1 t2
| |
ca7738a6d3e9765c0fb820e95d53c98751c52f67f015d49b1e5c7d43f313dd0b | Clojure2D/clojure2d-examples | noisewalk_I_6.clj | (ns examples.NOC.introduction.noisewalk-I-6
(:require [clojure2d.core :refer :all]
[fastmath.core :as m]
[fastmath.random :as r]
[fastmath.vector :as v])
(:import [fastmath.vector Vec2]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(def step (v/vec2 0.005 0.005))
(defn draw
""
[canvas _ _ state]
(let [^Vec2 noff (or state (v/vec2 (r/drand 1000) (r/drand 1000)))
x (m/norm (r/noise (.x noff)) 0.0 1.0 0.0 (width canvas))
y (m/norm (r/noise (.y noff)) 0.0 1.0 0.0 (height canvas))]
(-> canvas
(set-background :white)
(set-color 127 127 127)
(ellipse x y 48 48)
(set-color :black)
(ellipse x y 48 48 true))
(v/add noff step)))
(show-window (canvas 800 200) "Noise Walk I_6" 30 draw)
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/9de82f5ac0737b7e78e07a17cf03ac577d973817/src/NOC/introduction/noisewalk_I_6.clj | clojure | (ns examples.NOC.introduction.noisewalk-I-6
(:require [clojure2d.core :refer :all]
[fastmath.core :as m]
[fastmath.random :as r]
[fastmath.vector :as v])
(:import [fastmath.vector Vec2]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(def step (v/vec2 0.005 0.005))
(defn draw
""
[canvas _ _ state]
(let [^Vec2 noff (or state (v/vec2 (r/drand 1000) (r/drand 1000)))
x (m/norm (r/noise (.x noff)) 0.0 1.0 0.0 (width canvas))
y (m/norm (r/noise (.y noff)) 0.0 1.0 0.0 (height canvas))]
(-> canvas
(set-background :white)
(set-color 127 127 127)
(ellipse x y 48 48)
(set-color :black)
(ellipse x y 48 48 true))
(v/add noff step)))
(show-window (canvas 800 200) "Noise Walk I_6" 30 draw)
| |
7d988806089a9146a362fd65a97c99f6994e3c6f17db7dc2ef2b4c02cfa38de9 | ollef/sixty | Clauses.hs | # LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedRecordDot #
# LANGUAGE ViewPatterns #
module Elaboration.Clauses where
import Core.Binding (Binding)
import qualified Core.Binding as Binding
import Core.Bindings (Bindings)
import qualified Core.Bindings as Bindings
import qualified Core.Domain as Domain
import qualified Core.Evaluation as Evaluation
import qualified Core.Syntax as Syntax
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap
import Data.Tsil (Tsil)
import qualified Data.Tsil as Tsil
import {-# SOURCE #-} qualified Elaboration
import Elaboration.Context (Context)
import qualified Elaboration.Context as Context
import qualified Elaboration.Matching as Matching
import qualified Elaboration.Matching.SuggestedName as SuggestedName
import qualified Elaboration.Unification as Unification
import qualified Error
import Monad
import Name (Name)
import Plicity
import Protolude hiding (check, force)
import qualified Surface.Syntax as Surface
check
:: Context v
-> [Clause]
-> Domain.Type
-> M (Syntax.Term v)
check context (fmap removeEmptyImplicits -> clauses) expectedType
| all isEmpty clauses = do
let matchingClauses =
[ Matching.Clause {span, matches = toList matches, rhs}
| Clause (Surface.Clause span _ rhs) matches <- clauses
]
Matching.checkClauses context matchingClauses expectedType
| otherwise = do
expectedType' <- Context.forceHead context expectedType
case expectedType' of
Domain.Pi _piBinding domain Explicit targetClosure
| HashMap.null implicits -> do
bindings <- nextExplicitBindings context clauses
(context', var) <- Context.extend context (Bindings.toName bindings) domain
target <-
Evaluation.evaluateClosure
targetClosure
(Domain.var var)
explicitFunCase context' bindings var domain target
Domain.Fun domain Explicit target
| HashMap.null implicits -> do
bindings <- nextExplicitBindings context clauses
(context', var) <- Context.extend context (Bindings.toName bindings) domain
explicitFunCase context' bindings var domain target
Domain.Pi piBinding domain Implicit targetClosure -> do
bindings <- nextImplicitBindings context piBinding clauses
(context', var) <- Context.extend context (Bindings.toName bindings) domain
let value =
Domain.var var
target <- Evaluation.evaluateClosure targetClosure value
domain'' <- Elaboration.readback context domain
body <- check context' (shiftImplicit piBinding value domain <$> clauses) target
pure $ Syntax.Lam bindings domain'' Implicit body
_ -> do
(term', type_) <- infer context clauses
f <- Unification.tryUnify context type_ expectedType
pure $ f term'
where
implicits =
foldMap clauseImplicits clauses
explicitFunCase context' bindings var domain target = do
domain'' <- Elaboration.readback context domain
clauses' <- mapM (shiftExplicit context (Domain.var var) domain) clauses
body <- check context' clauses' target
pure $ Syntax.Lam bindings domain'' Explicit body
infer
:: Context v
-> [Clause]
-> M (Syntax.Term v, Domain.Type)
infer context (fmap removeEmptyImplicits -> clauses)
| all isEmpty clauses = do
let matchingClauses =
[ Matching.Clause {span, matches = toList matches, rhs}
| Clause (Surface.Clause span _ rhs) matches <- clauses
]
expectedType <- Context.newMetaType context
result <- Matching.checkClauses context matchingClauses expectedType
pure (result, expectedType)
| otherwise =
case HashMap.toList implicits of
[] -> do
domain <- Context.newMetaType context
domain' <- Elaboration.readback context domain
bindings <- nextExplicitBindings context clauses
let name =
Bindings.toName bindings
(context', var) <- Context.extend context name domain
clauses' <- mapM (shiftExplicit context (Domain.var var) domain) clauses
(body, target) <- infer context' clauses'
target' <- Elaboration.readback context' target
pure
( Syntax.Lam bindings domain' Explicit body
, Domain.Pi (Binding.Unspanned name) domain Explicit $
Domain.Closure (Context.toEnvironment context) target'
)
[(piName, _)] -> do
let piBinding =
Binding.Unspanned piName
bindings <- nextImplicitBindings context piBinding clauses
domain <- Context.newMetaType context
domain' <- Elaboration.readback context domain
(context', var) <- Context.extend context piName domain
let value =
Domain.var var
(body, target) <- infer context' (shiftImplicit (Binding.Unspanned piName) value domain <$> clauses)
target' <- Elaboration.readback context' target
pure
( Syntax.Lam bindings domain' Implicit body
, Domain.Pi piBinding domain Implicit $
Domain.Closure (Context.toEnvironment context) target'
)
_ -> do
Context.report context Error.UnableToInferImplicitLambda
Elaboration.inferenceFailed context
where
implicits =
foldMap clauseImplicits clauses
-------------------------------------------------------------------------------
data Clause = Clause !Surface.Clause (Tsil Matching.Match)
clausePatterns :: Clause -> [Surface.PlicitPattern]
clausePatterns (Clause (Surface.Clause _ patterns _) _) =
patterns
isEmpty :: Clause -> Bool
isEmpty clause =
case clausePatterns clause of
[] ->
True
_ : _ ->
False
removeEmptyImplicits :: Clause -> Clause
removeEmptyImplicits clause@(Clause (Surface.Clause span patterns term) matches) =
case patterns of
Surface.ImplicitPattern _ namedPats : patterns'
| HashMap.null namedPats ->
removeEmptyImplicits $ Clause (Surface.Clause span patterns' term) matches
_ ->
clause
clauseImplicits :: Clause -> HashMap Name Surface.Pattern
clauseImplicits clause =
case clausePatterns clause of
Surface.ImplicitPattern _ namedPats : _ -> (.pattern_) <$> namedPats
_ -> mempty
shiftImplicit :: Binding -> Domain.Value -> Domain.Type -> Clause -> Clause
shiftImplicit binding value type_ (Clause (Surface.Clause span patterns term) matches) =
case patterns of
Surface.ImplicitPattern patSpan namedPats : patterns'
| let name = Binding.toName binding
, Just patBinding <- HashMap.lookup name namedPats ->
Clause
( Surface.Clause
span
(Surface.ImplicitPattern patSpan (HashMap.delete name namedPats) : patterns')
term
)
(matches Tsil.:> Matching.Match value value Implicit (Matching.unresolvedPattern patBinding.pattern_) type_)
_ ->
Clause
(Surface.Clause span patterns term)
(matches Tsil.:> Matching.Match value value Implicit (Matching.unresolvedPattern $ Surface.Pattern span Surface.WildcardPattern) type_)
shiftExplicit :: Context v -> Domain.Value -> Domain.Type -> Clause -> M Clause
shiftExplicit context value type_ clause@(Clause (Surface.Clause span patterns term) matches) =
case patterns of
Surface.ExplicitPattern pat : patterns' ->
pure $
Clause
(Surface.Clause span patterns' term)
(matches Tsil.:> Matching.Match value value Explicit (Matching.unresolvedPattern pat) type_)
Surface.ImplicitPattern patSpan _ : patterns' -> do
Context.report
(Context.spanned patSpan context)
(Error.PlicityMismatch Error.Argument $ Error.Mismatch Explicit Implicit)
shiftExplicit
context
value
type_
( Clause
(Surface.Clause span patterns' term)
matches
)
[] -> do
Context.report
(Context.spanned span context)
(Error.PlicityMismatch Error.Argument $ Error.Missing Explicit)
pure clause
nextExplicitBindings :: Context v -> [Clause] -> M Bindings
nextExplicitBindings context clauses = do
(bindings, _) <- SuggestedName.nextExplicit context $ clausePatterns <$> clauses
pure bindings
nextImplicitBindings :: Context v -> Binding -> [Clause] -> M Bindings
nextImplicitBindings context piBinding clauses = do
(bindings, _) <- SuggestedName.nextImplicit context (Binding.toName piBinding) $ clausePatterns <$> clauses
pure bindings
| null | https://raw.githubusercontent.com/ollef/sixty/ad1b9dea082841e09e9fb7e8754819c43511824e/src/Elaboration/Clauses.hs | haskell | # SOURCE #
----------------------------------------------------------------------------- | # LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedRecordDot #
# LANGUAGE ViewPatterns #
module Elaboration.Clauses where
import Core.Binding (Binding)
import qualified Core.Binding as Binding
import Core.Bindings (Bindings)
import qualified Core.Bindings as Bindings
import qualified Core.Domain as Domain
import qualified Core.Evaluation as Evaluation
import qualified Core.Syntax as Syntax
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap
import Data.Tsil (Tsil)
import qualified Data.Tsil as Tsil
import Elaboration.Context (Context)
import qualified Elaboration.Context as Context
import qualified Elaboration.Matching as Matching
import qualified Elaboration.Matching.SuggestedName as SuggestedName
import qualified Elaboration.Unification as Unification
import qualified Error
import Monad
import Name (Name)
import Plicity
import Protolude hiding (check, force)
import qualified Surface.Syntax as Surface
check
:: Context v
-> [Clause]
-> Domain.Type
-> M (Syntax.Term v)
check context (fmap removeEmptyImplicits -> clauses) expectedType
| all isEmpty clauses = do
let matchingClauses =
[ Matching.Clause {span, matches = toList matches, rhs}
| Clause (Surface.Clause span _ rhs) matches <- clauses
]
Matching.checkClauses context matchingClauses expectedType
| otherwise = do
expectedType' <- Context.forceHead context expectedType
case expectedType' of
Domain.Pi _piBinding domain Explicit targetClosure
| HashMap.null implicits -> do
bindings <- nextExplicitBindings context clauses
(context', var) <- Context.extend context (Bindings.toName bindings) domain
target <-
Evaluation.evaluateClosure
targetClosure
(Domain.var var)
explicitFunCase context' bindings var domain target
Domain.Fun domain Explicit target
| HashMap.null implicits -> do
bindings <- nextExplicitBindings context clauses
(context', var) <- Context.extend context (Bindings.toName bindings) domain
explicitFunCase context' bindings var domain target
Domain.Pi piBinding domain Implicit targetClosure -> do
bindings <- nextImplicitBindings context piBinding clauses
(context', var) <- Context.extend context (Bindings.toName bindings) domain
let value =
Domain.var var
target <- Evaluation.evaluateClosure targetClosure value
domain'' <- Elaboration.readback context domain
body <- check context' (shiftImplicit piBinding value domain <$> clauses) target
pure $ Syntax.Lam bindings domain'' Implicit body
_ -> do
(term', type_) <- infer context clauses
f <- Unification.tryUnify context type_ expectedType
pure $ f term'
where
implicits =
foldMap clauseImplicits clauses
explicitFunCase context' bindings var domain target = do
domain'' <- Elaboration.readback context domain
clauses' <- mapM (shiftExplicit context (Domain.var var) domain) clauses
body <- check context' clauses' target
pure $ Syntax.Lam bindings domain'' Explicit body
infer
:: Context v
-> [Clause]
-> M (Syntax.Term v, Domain.Type)
infer context (fmap removeEmptyImplicits -> clauses)
| all isEmpty clauses = do
let matchingClauses =
[ Matching.Clause {span, matches = toList matches, rhs}
| Clause (Surface.Clause span _ rhs) matches <- clauses
]
expectedType <- Context.newMetaType context
result <- Matching.checkClauses context matchingClauses expectedType
pure (result, expectedType)
| otherwise =
case HashMap.toList implicits of
[] -> do
domain <- Context.newMetaType context
domain' <- Elaboration.readback context domain
bindings <- nextExplicitBindings context clauses
let name =
Bindings.toName bindings
(context', var) <- Context.extend context name domain
clauses' <- mapM (shiftExplicit context (Domain.var var) domain) clauses
(body, target) <- infer context' clauses'
target' <- Elaboration.readback context' target
pure
( Syntax.Lam bindings domain' Explicit body
, Domain.Pi (Binding.Unspanned name) domain Explicit $
Domain.Closure (Context.toEnvironment context) target'
)
[(piName, _)] -> do
let piBinding =
Binding.Unspanned piName
bindings <- nextImplicitBindings context piBinding clauses
domain <- Context.newMetaType context
domain' <- Elaboration.readback context domain
(context', var) <- Context.extend context piName domain
let value =
Domain.var var
(body, target) <- infer context' (shiftImplicit (Binding.Unspanned piName) value domain <$> clauses)
target' <- Elaboration.readback context' target
pure
( Syntax.Lam bindings domain' Implicit body
, Domain.Pi piBinding domain Implicit $
Domain.Closure (Context.toEnvironment context) target'
)
_ -> do
Context.report context Error.UnableToInferImplicitLambda
Elaboration.inferenceFailed context
where
implicits =
foldMap clauseImplicits clauses
data Clause = Clause !Surface.Clause (Tsil Matching.Match)
clausePatterns :: Clause -> [Surface.PlicitPattern]
clausePatterns (Clause (Surface.Clause _ patterns _) _) =
patterns
isEmpty :: Clause -> Bool
isEmpty clause =
case clausePatterns clause of
[] ->
True
_ : _ ->
False
removeEmptyImplicits :: Clause -> Clause
removeEmptyImplicits clause@(Clause (Surface.Clause span patterns term) matches) =
case patterns of
Surface.ImplicitPattern _ namedPats : patterns'
| HashMap.null namedPats ->
removeEmptyImplicits $ Clause (Surface.Clause span patterns' term) matches
_ ->
clause
clauseImplicits :: Clause -> HashMap Name Surface.Pattern
clauseImplicits clause =
case clausePatterns clause of
Surface.ImplicitPattern _ namedPats : _ -> (.pattern_) <$> namedPats
_ -> mempty
shiftImplicit :: Binding -> Domain.Value -> Domain.Type -> Clause -> Clause
shiftImplicit binding value type_ (Clause (Surface.Clause span patterns term) matches) =
case patterns of
Surface.ImplicitPattern patSpan namedPats : patterns'
| let name = Binding.toName binding
, Just patBinding <- HashMap.lookup name namedPats ->
Clause
( Surface.Clause
span
(Surface.ImplicitPattern patSpan (HashMap.delete name namedPats) : patterns')
term
)
(matches Tsil.:> Matching.Match value value Implicit (Matching.unresolvedPattern patBinding.pattern_) type_)
_ ->
Clause
(Surface.Clause span patterns term)
(matches Tsil.:> Matching.Match value value Implicit (Matching.unresolvedPattern $ Surface.Pattern span Surface.WildcardPattern) type_)
shiftExplicit :: Context v -> Domain.Value -> Domain.Type -> Clause -> M Clause
shiftExplicit context value type_ clause@(Clause (Surface.Clause span patterns term) matches) =
case patterns of
Surface.ExplicitPattern pat : patterns' ->
pure $
Clause
(Surface.Clause span patterns' term)
(matches Tsil.:> Matching.Match value value Explicit (Matching.unresolvedPattern pat) type_)
Surface.ImplicitPattern patSpan _ : patterns' -> do
Context.report
(Context.spanned patSpan context)
(Error.PlicityMismatch Error.Argument $ Error.Mismatch Explicit Implicit)
shiftExplicit
context
value
type_
( Clause
(Surface.Clause span patterns' term)
matches
)
[] -> do
Context.report
(Context.spanned span context)
(Error.PlicityMismatch Error.Argument $ Error.Missing Explicit)
pure clause
nextExplicitBindings :: Context v -> [Clause] -> M Bindings
nextExplicitBindings context clauses = do
(bindings, _) <- SuggestedName.nextExplicit context $ clausePatterns <$> clauses
pure bindings
nextImplicitBindings :: Context v -> Binding -> [Clause] -> M Bindings
nextImplicitBindings context piBinding clauses = do
(bindings, _) <- SuggestedName.nextImplicit context (Binding.toName piBinding) $ clausePatterns <$> clauses
pure bindings
|
eae28c1ba7127b497641003901d15ca52944c60355b0999176935a9843aa64e1 | bytekid/mkbtt | oldacrpo.ml | Copyright 2008 , Christian Sternagel ,
* GNU Lesser General Public License
*
* This file is part of TTT2 .
*
* TTT2 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 .
*
* TTT2 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 TTT2 . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of TTT2.
*
* TTT2 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.
*
* TTT2 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 TTT2. If not, see </>.
*)
(*** OPENS ********************************************************************)
open Util;;
open Rewritingx;;
open Logic.Operators;;
(*** MODULES ******************************************************************)
module L = Logic;;
module AF = Filtering;;
module C = Coefficient;;
module Co = Complexity;;
module F = Format;;
module Fun = Function;;
module H = Hashtbl;;
module M = Rewritingx.Monad;;
module Number = L.Number;;
module P = Problem;;
module Pos = Position;;
module Prec = Precedence;;
module Sig = Signature;;
module Var = Variable;;
module R = Rule;;
module Status = struct
(*** INCLUDES ****************************************************************)
include Index.Make (Fun) (Bool);;
(*** FUNCTIONS ***************************************************************)
let (>>=) = M.(>>=);;
let is_lex s f = not (find f s);;
let is_mul s f = find f s;;
let fprintf fmt p =
let rec fprintf fmt = function
| [] -> ()
| (f,b) :: p ->
if b then F.fprintf fmt "%a:mul@ @ %a" Fun.fprintf f fprintf p
else F.fprintf fmt "%a:lex@ @ %a" Fun.fprintf f fprintf p
in
F.fprintf fmt "@[%a@]" fprintf (to_list p)
;;
let fprintfm fmt p =
let rec fprintfm = function
| [] -> M.return ()
| (f,b) :: p ->
M.fprintf_fun fmt f >>= fun _ ->
if b then F.fprintf fmt ":lex @ " else F.fprintf fmt ":mul @ ";
fprintfm p
in
M.filter (fun (f,_) -> M.is_theory Label.AC f >>= (M.return <.> not)) (to_list p) >>=
M.filter (fun (f,_) -> M.find_ari f >>= fun a -> M.return (a > 1)) >>=
(F.fprintf fmt "@["; fprintfm) >>= fun _ ->
M.return (F.fprintf fmt "@]")
;;
let fprintfx fmt p s =
let p = Prec.to_list p in
F.fprintf fmt "@{<statusPrecedence>";
M.iter (fun(f,b) ->
F.fprintf fmt "@{<statusPrecedenceEntry>";
M.fprintfx_fun fmt f >>= fun _ ->
M.find_ari f >>= fun a ->
F.fprintf fmt "@{<arity>%i@}" a;
F.fprintf fmt "@{<precedence>%i@}" (List.assoc f p);
F.fprintf fmt "@{<%s>@}" (if b then "mul" else "lex");
M.return(F.fprintf fmt "@}")
) (to_list s) >>= fun _ ->
M.return(F.fprintf fmt "@}")
;;
end;;
(*** TYPES ********************************************************************)
type context = {
solver : L.solver;
prec_num : int;
state : Signature.t;
precs : (Fun.t, L.a) H.t;
gt_encodings : (R.t, L.p) H.t;
(* encoding statuses of function symbols; true is multiset *)
stats : (Fun.t, L.p) H.t;
multiset cover : if ( s->t , j ) has value i then both s , t are rooted by f and
in multiset comparison of args(s ) , args(t ) term t_j is covered by s_i
in multiset comparison of args(s), args(t) term t_j is covered by s_i *)
mcov_a_encodings : (Term.t list * Term.t list * int, L.a) H.t;
(* multiset comparison formula caching *)
mcov_encodings : (Term.t list*Term.t list, L.p*L.a list) H.t;
(* for argument filterings *)
af_l : (Fun.t, L.p) H.t;
af_p : (Fun.t * int, L.p) H.t;
emb_gt_encodings : (Rule.t, Logic.p) H.t;
emb_eq_encodings : (Rule.t, Logic.p) H.t;
eq_af_encodings : (Fun.t*Fun.t*Term.t list*Term.t list, L.p) H.t;
rpo_af_same_encodings : (Fun.t*Term.t list*Term.t list,L.p) H.t;
rpo_af_diff_encodings : (Fun.t*Fun.t*Term.t list*Term.t list,L.p) H.t;
};;
type flags = {
dp : bool ref;
direct : bool ref;
help : bool ref;
quasi : ;
sat : bool ref;
};;
type t = {
af : AF.t option;
input : P.t;
output : P.t;
precedence : Prec.t;
status : Status.t;
};;
(*** GLOBALS ******************************************************************)
let code = "acrpo";;
let name = "AC-RPO Processor";;
let comment = "Applies AC-Recursive Path Order."
let keywords =
["AC";"recursive path order";"simplification order";"termination"]
;;
let flags = {
dp = ref false;
direct = ref false;
help = ref false;
(* quasi = ref false;*)
sat = ref false;
};;
let spec =
let spec = [
("-af",Arg.Set flags.dp,
"Allows non-monotone interpretations (argument filterings).");
("-direct",Arg.Set flags.direct,
"Try to finish termination proof.");
("--help",Arg.Set flags.help,"Prints information about flags.");
("-help",Arg.Set flags.help,"Prints information about flags.");
("-h",Arg.Set flags.help,"Prints information about flags.");
(* ("-quasi",Arg.Set flags.quasi,"Allows quasi-precedences (currently not \
supported together with -dp flag).");*)
("-sat",Arg.Set flags.sat,"Uses SAT backend.");
("-smt",Arg.Clear flags.sat,"Uses SMT backend (default).")]
in
Arg.alignx 80 spec
;;
let help = (comment,keywords,List.map Triple.drop_snd spec);;
* * ( part 2 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
module Statex = struct type t = context end;;
module Made = Util.Monad.Transformer.State (Statex) (L.Monad);;
open Made;;
(*** FUNCTIONS ****************************************************************)
let init _ =
flags.dp := false;
flags.direct := false;
flags.help := false;
(* flags.quasi := false;*)
flags.sat := false;
;;
Constructors and Destructors
let make af input output precedence st = {
af = af;
input = input;
output = output;
precedence = precedence;
status = st;
};;
let get_ip p = p.input;;
let get_op p = p.output;;
(* Complexity Bounds *)
let complexity c _ = Co.mul c Co.other;;
(* Compare Functions *)
let equal p q =
P.equal p.input q.input && P.equal p.output q.output
;;
(* Printers *)
let (>>=) = M.(>>=);;
let fprintf_af fmt = function
| None -> Monad.return ()
| Some af ->
F.fprintf fmt "@\n@[<1>argument filtering:@\n";
AF.fprintfm fmt af >>= fun _ -> Monad.return (F.fprintf fmt "@]")
;;
let fprintf fs fmt p =
F.fprintf fmt "@[<1>%s:" name;
fprintf_af fmt p.af >>= fun _ ->
F.fprintf fmt "@]@\n@[<1>precedence:@\n";
Prec.fprintfm fmt p.precedence >>= fun _ ->
F.fprintf fmt "@]@\n@[<1>status:@\n";
Status.fprintfm fmt p.status >>= fun _ ->
F.fprintf fmt "@]@\n@[<1>problem:@\n";
P.fprintfm fmt p.output >>= fun _ ->
F.fprintf fmt "@]@\n"; List.hd fs fmt >>= fun _ ->
Monad.return (F.fprintf fmt "@]")
;;
let fprintfx_af fmt = function
| None -> Monad.return()
| Some af -> AF.fprintfx fmt af
;;
let fprintfx_redpair fmt p =
F.fprintf fmt "@{<redPair>@{<pathOrder>";
Status.fprintfx fmt p.precedence p.status >>= fun _ ->
fprintfx_af fmt p.af >>= fun _ ->
M.return(F.fprintf fmt "@}@}")
;;
let fprintfx fs fmt p =
if (Problem.is_dp p.input) || (Problem.is_edp p.input) then (
let tag = "redPairProc" in
F.fprintf fmt "@{<%s>" tag;
fprintfx_redpair fmt p >>= fun _ ->
Problem.fprintfx fmt p.output >>= fun _ ->
List.hd fs fmt >>= fun _ ->
Monad.return(F.fprintf fmt "@}");
) else if (Problem.is_sp p.input) || (Problem.is_ep p.input) then (
failwith "AC-RPO full termination not supported!"
) else (
failwith "for this problem AC-RPO is not supported!"
)
;;
(* general functions *)
let (>>=) = Made.(>>=);;
(* functions lifted from L into Made *)
let fresh_arith_spec spec = liftm (L.fresh_arith spec);;
let fresh_bool = get >>= fun s -> liftm L.fresh_bool;;
let eval_a a ass = a >>= fun a -> liftm (L.eval_a a ass);;
let eval_p p ass = p >>= fun p -> liftm (L.eval_p p ass);;
let ($>=$) a b = lift2 (<>=>) a b;;
let ($=$) a b = lift2 (<=>) a b;;
let ($>$) a b = lift2 (<>>) a b;;
let ($->$) a b = lift2 (<->>) a b;;
let ($|$) a b = lift2 (<|>) a b;;
let ($&$) a b = lift2 (<&>) a b;;
let ($*$) a b = lift2 (<*>) a b;;
let ($+$) a b = lift2 (<+>) a b;;
let ($-$) a b = lift2 (<->) a b;;
let mnot a = lift (~!) a;;
let zero = L.zero;;
let one = L.one;;
let constant = L.constant <.> Number.of_int;;
let sum f = List.foldl (fun s x -> f x <+> s) L.zero;;
let big_xor ps = sum (fun p -> p <?> one <:> zero) ps <=> one;;
let map_op op f ls = sequence (List.map f ls) >>= (return <.> op);;
let mapi_op op f ls = sequence (List.mapi f ls) >>= (return <.> op);;
let gen_op op f n = sequence (List.gen f n) >>= (return <.> op);;
let map_and f = map_op L.big_and f;;
let mapi_and f = mapi_op L.big_and f;;
let map_or f = map_op L.big_or f;;
let mapi_or f = mapi_op Logic.big_or f;;
let gen_or f = gen_op Logic.big_or f;;
let gen_and f = gen_op Logic.big_and f;;
(* actual content starts here *)
let context state fs =
let solver = if !(flags.sat) then L.MiniSat else L.Yices in
{
solver = solver;
prec_num = max 0 (List.length fs - 1);
precs = H.create 512;
state = state;
gt_encodings = H.create 512;
stats = H.create 512;
mcov_a_encodings = H.create 512;
mcov_encodings = H.create 512;
af_l = H.create 512;
af_p = H.create 512;
emb_gt_encodings = H.create 512;
emb_eq_encodings = H.create 512;
eq_af_encodings = H.create 512;
rpo_af_same_encodings = H.create 512;
rpo_af_diff_encodings = H.create 512;
}
;;
(* administrative functions *)
let cache_m tbl f k =
if H.mem tbl k then return (H.find tbl k)
else (f k >>= fun v -> (H.add tbl k v; return v))
;;
(* encoding starts here *)
(* caching variables *)
let prec f = get >>= fun c ->
let arith = L.nat c.prec_num in
cache_m c.precs (const (fresh_arith_spec arith)) f
;;
let prec_gt f g = prec f $>$ prec g;;
let prec_eq f g = return (if f = g then L.top else L.bot);; (* not quasi *)
let is_mul f = get >>= fun c -> cache_m c.stats (const fresh_bool) f;;
let is_lex = mnot <.> is_mul;;
let is_ac f = get >>= fun c -> return (Sig.is_theory Label.AC f c.state);;
let is_c f = get >>= fun c -> return (Sig.is_theory Label.C f c.state);;
let set_ac f =
get >>= fun c -> let (f, s) = Sig.set_theory f Label.AC c.state in
Made.set {c with state = s} >>
return f
;;
let arity f = get >>= fun c -> return (Sig.find_ari f c.state);;
let af_l f = get >>= fun c -> cache_m c.af_l (const fresh_bool) f;;
let af_n f = af_l f >>= (return <.> L.neg);;
let af_p f i = get >>= fun c -> cache_m c.af_p (const fresh_bool) (f,i);;
let af_all f = (af_l f) $&$ (af_p f 0) $&$ (af_p f 1)
let af_none f = (af_l f) $&$ (mnot ((af_p f 0) $|$ (af_p f 1)))
(* *** *)
let find_term_with f =
let rooted_f = function Term.Fun (g,_) when f=g -> true | _ -> false in
let rec find ys = function
| [] -> None
| x::xs when rooted_f x -> Some(x, ys@xs)
| x::xs -> find (x::ys) xs
in find []
;;
(* sorts list of terms such that constants come before compound
terms where the root has positive arity come before variables *)
let rec lex = function
| [],[] -> 0
| [],_ -> -1
|_, [] -> 1
| x::xs,y::ys -> let c = my_compare x y in if c=0 then lex (xs,ys) else c
and my_compare t t' =
match t, t' with
| Term.Var x, Term.Var y -> Var.compare x y
| Term.Fun _, Term.Var _ -> -1
| Term.Var _, Term.Fun _ -> 1
| Term.Fun(_,[]), Term.Fun(_,_::_) -> -1
| Term.Fun(_,_::_), Term.Fun(_,[]) -> 1
| Term.Fun(f,fs), Term.Fun(g,gs) when f=g -> lex (fs,gs)
| Term.Fun(f,_), Term.Fun(g,_) -> Fun.compare f g
;;
(* recursively flatten term with respect to all ac symbols *)
let rec flatten = function
| Term.Fun(f, ts) ->
is_ac f >>= fun f_is_ac -> (
if f_is_ac then
Made.map flatten ts >>= fun ts' ->
match find_term_with f ts' with
| None -> Made.return (Term.Fun(f, List.sort my_compare ts'))
| Some (ti,ts'') -> flatten (Term.Fun(f, (ts''@(Term.args ti))))
else
Made.map flatten ts >>= fun us -> Made.return (Term.Fun(f,us)))
| v -> Made.return v
;;
let rec term_is_embedded s t = match (s,t) with
| Term.Var x, Term.Var y -> x = y
| Term.Fun (f,ss), Term.Fun (g,ts) ->
(f = g
&& List.length ss = List.length ts
&& List.for_all2 term_is_embedded ss ts) || List.exists (term_is_embedded s) ts
| _, Term.Fun (f,ts) -> List.exists (term_is_embedded s) ts
| _, _ -> false
;;
let is_embedded = Util.uncurry (flip term_is_embedded) <.> R.to_terms;;
let is_proper_embedded r =
List.exists (term_is_embedded (R.rhs r)) (Term.subterms (R.lhs r))
;;
(* *** *)
(* multiset cover arith variable caching, where key=(ss,tt,j) *)
let mcov_a_var key =
let m = List.length (Triple.fst key) -1 in
get >>= fun c -> let arith = L.nat m in
(*cache_m c.mcov_a_encodings*) (const (fresh_arith_spec arith)) key
;;
(* encoding *)
let rec lex gt eq ts ss = match ts,ss with
| _::_,[] -> return L.top
| [], _ -> return L.bot
| ti::ts,si::ss ->
gt (R.of_terms ti si) $|$ (eq (R.of_terms ti si) $&$ lex gt eq ts ss)
;;
(* multiset cover *)
let mul_cover ss ts =
let aux (ss,ts) =
Made.mapi (fun j _ -> mcov_a_var (ss,ts,j)) ts >>= fun cs ->
let m = List.length ss in
let sm = L.big_and (List.map (fun ci -> ci <<> (constant m)) cs) in
return (sm,cs)
in (*get >>= fun c -> cache_m c.mcov_encodings*) aux (ss,ts)
;;
let mul gt eq ss ts =
mul_cover ss ts >>= fun (cover,cs) ->
let tcs = List.zip ts cs in
mapi_and (fun i si -> mapi_and (fun j (tj,cj) ->
(return (cj <=> (constant i))) $->$ (gt (R.of_terms si tj))
) tcs) ss >>= fun phi ->
return (cover <&> phi)
;;
let diff ?(cmp=compare) xs ys =
let rec rem x = function
| [] -> []
| y::ys when cmp x y = 0 -> ys
| y::ys -> y::(rem x ys)
in List.foldl (flip rem) xs ys
;;
let mul_ge gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if List.is_empty ss && List.is_empty ts then
return L.top
else
mul gt eq ss ts
;;
let mul_gt gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if ss = [] then return L.bot else mul gt eq ss ts
;;
let mul_eq gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if List.is_empty ss && List.is_empty ts then
return L.top
else
return L.bot
;;
to compute no_small_head and multiset comparisons
let mul_g' cs p gt eq ss ts =
let tcs = List.zip ts cs in
let gt si tj = gt (R.of_terms si tj) in
let has_val cj i = return (cj <=> (constant i)) in
mapi_and (fun j (tj,cj) ->
(p tj) $->$
(mapi_and (fun i si -> has_val cj i $->$ (gt si tj $&$ (p si))) ss))
tcs
;;
let mul_ge' p gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
mul_cover ss ts >>= fun (cover,cs) ->
mul_g' cs p gt eq ss ts >>= fun phi ->
return (cover <&> phi)
;;
let mul_gt' p gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
mul_cover ss ts >>= fun (cover,cs) ->
mul_g' cs p gt eq ss ts >>= fun phi ->
map_or p ss >>= fun non_empty ->
return (cover <&> phi <&> non_empty)
;;
(* emb_small candidates *)
let emb_sm f ts =
let tf t = if Term.root t = Some f then Term.args t else [t] in
let rec emb hd = function
| [] -> []
| ((Term.Var _) as t)::ts -> emb (hd@[t]) ts
| (Term.Fun(h,hs) as t)::ts when f=h -> emb (hd@[t]) ts
| (Term.Fun(h,hs) as t)::ts ->
(List.map (fun hi -> (hd@(tf hi)@ts,h)) hs)@(emb (hd@[t]) ts)
in List.map (Pair.apply (Term.make_fun f) id) (emb [] ts )
;;
(* #s > #t *)
let size_gt ss ts =
let (vs,fs),(vt,ft) = Pair.map (List.partition Term.is_var) (ss,ts) in
let vs,vt = diff vs vt,diff vt vs in
(List.is_empty vt) && (List.length (vs@fs) > (List.length ft))
;;
(* #s = #t *)
let size_ge ss ts =
let (vs,fs),(vt,ft) = Pair.map (List.partition Term.is_var) (ss,ts) in
let vs,vt = diff vs vt,diff vt vs in
(List.is_empty vt) && (List.length (vs@fs) >= (List.length ft))
;;
(* until quasi prec *)
let rpo_eq r =
let s,t = R.to_terms r in
return (if Term.compare s t = 0 then L.top else L.bot)
;;
let flat_rule r =
Made.project flatten (R.to_terms r) >>= fun (l,r) ->
return (R.of_terms l r)
;;
let rec rpo_gt rule =
flat_rule rule >>= fun rule ->
Format.printf " check : % s > % s\n% ! " ( Term.to_string s ) ( Term.to_string t ) ;
let helper rule =
if is_embedded (R.invert rule) || not (R.is_rewrite_rule rule) then
return L.bot
else if is_proper_embedded rule then
return L.top
else
let s,t = R.to_terms rule in
match s,t with
| Term.Var _, _ -> return L.bot
| Term.Fun _, Term.Var x ->
return (if List.mem x (Term.vars s) then L.top else L.bot)
| Term.Fun (f,ss), Term.Fun (g,ts) when f <> g ->
( 1 )
( 2 )
| Term.Fun (f,ss), Term.Fun (_,ts) ->
is_ac f >>= fun f_is_ac -> is_c f >>= fun f_is_c ->
if not (f_is_ac || f_is_c) then
( 1 )
( 3 )
( 4 )
else if f_is_c then
mul_gt rpo_gt rpo_eq ss ts (* multiset extension *)
else (
let gt s t = rpo_gt (R.of_terms s t) in
let ge s t = rpo_ge (R.of_terms s t) in
let cover h s' = prec_gt f h $&$ (ge s' t) in
( 5 )
(map_and (fun (t',h) -> prec_gt f h $->$ (gt s t')) (emb_sm f ts) $&$
( 6 )
( 6b )
( 6a )
else ((big_head f ss ts) $|$
( 6c )
)
in
get >>= fun c -> cache_m c.gt_encodings helper rule
and no_small_head f ss ts =
let p u = match Term.root u with
None -> return L.top | Some h -> mnot (prec_gt f h) in
mul_ge' p rpo_gt rpo_eq ss ts
and big_head f ss ts =
if List.is_empty ss then return L.bot
else
let p u = match Term.root u with
None -> return L.bot | Some h -> prec_gt h f in
mul_gt' p rpo_gt rpo_eq ss ts
and rpo_ge rule = rpo_gt rule $|$ (rpo_eq rule)
;;
(* encode with argument filtering *)
(* useful shorthands. *)
let exists f p ts = mapi_or (fun i ti -> (af_p f i) $&$ (p ti)) ts;;
let existsi f p ts = mapi_or (fun i ti -> (af_p f i) $&$ (p i ti)) ts;;
let for_all f p ts = mapi_and (fun i ti -> (af_p f i) $->$ (p ti)) ts;;
let exists2 f p ss ts = exists f p (List.map2 R.of_terms ss ts);;
let for_all2 f p ss ts = for_all f p (List.map2 R.of_terms ss ts);;
let rot f s t = f (R.of_terms s t);;
let rot2 f s t = f (R.of_terms t s);;
let af_collapsing f a i =
let make j = if i = j then af_p f i else (lift L.neg (af_p f j)) in
gen_and make a
;;
let lex_af f eq gt ss ts =
let rec lex' eq gt ss ts i =
match ss, ts with
| [],[] -> return L.bot
| [], _ | _, [] -> failwith "lists of different length"
| sn::sss,tn::tss ->
(af_p f i $&$ gt (R.of_terms sn tn))
$|$
((af_p f i $->$ eq (R.of_terms sn tn)) $&$ lex' eq gt sss tss (i+1))
in
lex' eq gt ss ts 0
;;
(* equality, embedding *)
let eq_af_diff eq f g ss ts =
let helper eq (f,g,ss,ts) =
let s = Term.Fun (f, ss) and t = Term.Fun (g, ts) in
(af_n f $&$ exists f (fun si -> eq (R.of_terms si t)) ss) $|$
(af_n g $&$ exists g (fun tj -> eq (R.of_terms s tj)) ts)
in get >>= fun c -> cache_m c.eq_af_encodings (helper eq) (f,g,ss,ts)
;;
let rec eq_af rule =
let helper r =
let (s,t) = R.to_terms rule in match (s,t) with
| _, _ when s = t -> return L.top
| Term.Var x, Term.Var y (* then, x <> y holds *) -> return L.bot
| Term.Var _, Term.Fun (g, ts) ->
af_n g $&$ exists g (fun tj -> eq_af (R.of_terms s tj)) ts
| Term.Fun (f, ss), Term.Var _ ->
af_n f $&$ exists f (fun si -> eq_af (R.of_terms si t)) ss
| Term.Fun (f, ss), Term.Fun (g, ts) when f = g ->
if List.length ss <> List.length ts then return L.bot
else for_all2 f eq_af ss ts (*equality holds when AF(f) is added*)
| Term.Fun (f, ss), Term.Fun (g, ts) ->
eq_af_diff eq_af f g ss ts
in get >>= fun c -> cache_m c.emb_eq_encodings helper rule
;;
let mul_af f gt eq ss ts =
mul_cover ss ts >>= fun (cover,cs) ->
let tcs = List.zip ts cs in
let is cj i = return (cj <=> (constant i)) in
mapi_and (fun i si -> mapi_and (fun j (tj,cj) ->
af_p f j $->$
((is cj i) $->$ (gt (R.of_terms si tj) $&$ (af_p f i)))
) tcs) ss >>= fun phi ->
return (cover <&> phi)
;;
let mul_ge_af f gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if List.is_empty ss && List.is_empty ts then return L.top
else
let rl = R.of_terms (Term.Fun (f, ss)) (Term.Fun (f, ts)) in
(mul_af f gt eq ss ts) $|$ (eq_af rl)
;;
let mul_gt_af f gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if ss = [] then return L.bot
else
mul_cover ss ts >>= fun (cover,cs) ->
let tcs = List.zip ts cs in
let is cj i = return (cj <=> (constant i)) in
let phi = mapi_and (fun i si -> mapi_and (fun j (tj,cj) ->
(af_p f j $&$ af_l f) $->$
((is cj i) $->$ (gt (R.of_terms si tj) $&$ (af_p f i)))
) tcs) ss
in
let is_strict i si j tj = is (List.nth cs j) i $&$ gt (R.of_terms si tj) in
let strict = existsi f (fun i si -> existsi f (is_strict i si) ts) ss in
let s_nonempty = exists f (fun _ -> return L.top) ss in
let t_empty = mnot (exists f (fun _ -> return L.top) ts) in
phi $&$ (strict $|$ (s_nonempty $&$ t_empty))
;;
(*
(* comparing conditional multisets *)
let cond_mul gt eq ss ts =
mul_cover ss ts >>= fun (cover_aux,cs) ->
let tcs = List.zip ts cs in
let gt si tj = gt (R.of_terms si tj) in
let is cj i = return (cj <=> (constant i)) in
let cov_i_j_imp (tj,cj) i (si,psi) = is cj i $->$ (gt si tj $&$ return psi) in
let cov_j_and tcj = mapi_and (cov_i_j_imp tcj) ss in
let covered = mapi_and (fun j ((tj,ptj),cj) -> return ptj $->$ cov_j_and (tj,cj)) tcs in
let cov_i_j_and (tj,cj) i (si,psi) = is cj i $&$ gt si tj $&$ return psi in
let cov_j_or tcj = mapi_or (cov_i_j_and tcj) ss in
let strict = mapi_or (fun j ((tj,ptj),cj) -> return ptj $&$ cov_j_or (tj,cj)) tcs in
let s_nonempty = return (L.big_or (List.map snd ss)) in
let t_empty = return (~! (L.big_and (List.map snd ts))) in
strict $|$ (s_nonempty $&$ t_empty) >>= fun is_strict ->
return cover_aux $&$ covered >>= fun is_covered ->
return (is_covered, is_strict)
;;
let cond_mul_gt gt eq ss ts = cond_mul gt eq ss ts >>= fun (c,s) -> return (c <&> s)
let cond_mul_ge gt eq ss = lift fst <.> (cond_mul gt eq ss)
*)
to compute no_small_head and multiset comparisons
let mul_g_af' cs (ps,pt) gt eq ss ts =
let tcs = List.zip ts cs in
let gt si tj = gt (R.of_terms si tj) in
let has_val cj i = return (cj <=> (constant i)) in
mapi_and (fun j (tj,cj) ->
(pt tj) $->$
(mapi_and (fun i si -> has_val cj i $->$ (gt si tj $&$ (ps si))) ss))
tcs
;;
let mul_ge_af' p gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
mul_cover ss ts >>= fun (cover,cs) ->
mul_g_af' cs p gt eq ss ts >>= fun phi ->
return (cover <&> phi)
;;
let mul_gt_af' (ps,pt) gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
mul_cover ss ts >>= fun (cover,cs) ->
let tcs = List.zip ts cs in
let gt si tj = gt (R.of_terms si tj) in
let has_val cj i = return (cj <=> (constant i)) in
let phi =
mapi_and (fun j (tj,cj) ->
(pt tj) $->$
(mapi_and (fun i si -> has_val cj i $->$ (gt si tj $&$ (ps si))) ss))
tcs
in
let strict =
mapi_or (fun j (tj,cj) ->
(pt tj) $&$ (mapi_or (fun i si -> has_val cj i $&$ (gt si tj $&$ (ps si))) ss))
tcs
in
let s_nonempty = map_or ps ss in
let t_empty = mnot (map_or pt ts) in
phi $&$ (strict $|$ (s_nonempty $&$ t_empty))
;;
(* emb_small candidates for af*)
let emb_sm_af f ts =
let tf t = if Term.root t = Some f then Term.args t else [ t ] in
let rec emb hd = function
| [ ] - > [ ]
| ( ( Term . Var _ ) as t)::ts - > emb ( hd@[t ] ) ts
| ( Term . Fun(h , hs ) as t)::ts when f = h - > emb ( hd@[t ] ) ts
| ( Term . Fun(h , hs ) as t)::ts - >
( List.mapi ( fun i hi - > ( hd@(tf hi)@ts,(h , i ) ) ) hs)@(emb ( hd@[t ] ) ts )
in List.map ( Pair.apply ( Term.make_fun f ) i d ) ( emb [ ] ts )
; ;
let emb_sm_af f ts =
let tf t = if Term.root t = Some f then Term.args t else [t] in
let rec emb hd = function
| [] -> []
| ((Term.Var _) as t)::ts -> emb (hd@[t]) ts
| (Term.Fun(h,hs) as t)::ts when f=h -> emb (hd@[t]) ts
| (Term.Fun(h,hs) as t)::ts ->
(List.mapi (fun i hi -> (hd@(tf hi)@ts,(h,i))) hs)@(emb (hd@[t]) ts)
in List.map (Pair.apply (Term.make_fun f) id) (emb [] ts )
;;*)
let emb_sm_af f ts =
let add ci hd tl' = function
| Term.Var _ -> []
| (Term.Fun(h,hs) as si) -> [Term.Fun(f, hd @ (si::tl')), fh <&> ci]
in
let rec emb (hd,tl) acc =
match tl with
| [] -> return acc
| (Term.Fun(h,hs)) :: tl' ->
cond_sub hs >>= map (fun (si,ci) -> add ci hd tl') >>= fun ss ->
emb (hd @ [t],tl') (acc @ ss)
| t :: tl' -> emb (hd @ [t],tl') (acc @ ss)
in emb ([],ts) []
;;
let rec emb_af_ge rule = emb_af_gt rule $|$ eq_af rule
and emb_af_gt rule =
let helper rule =
let s, t = Rule.to_terms rule in match s, t with
| Term.Var _, _ -> return Logic.bot
| Term.Fun (f, ss), Term.Var _ ->
exists f (fun si -> emb_af_gt (Rule.of_terms si t)) ss $|$
(af_l f $&$ exists f (fun si -> eq_af (Rule.of_terms si t)) ss)
| Term.Fun (f, ss), Term.Fun (g, ts) when f = g ->
(af_l f $&$ exists f (fun si -> emb_af_ge (Rule.of_terms si t)) ss) $|$
(((af_l f $&$ for_all2 f emb_af_ge ss ts) $|$ af_n f)
$&$ exists2 f emb_af_gt ss ts)
| Term.Fun (f, ss), Term.Fun (g, ts) ->
(af_l f $&$
((af_l g $&$ exists f (fun si -> eq_af (Rule.of_terms si t)) ss) $|$
(af_n g $&$ exists g (fun tj -> emb_af_gt (Rule.of_terms s tj)) ts)))
$|$
((af_n f $|$ af_l g) $&$
exists f (fun si -> emb_af_gt (Rule.of_terms si t)) ss)
in get >>= fun c -> cache_m c.emb_gt_encodings helper rule
;;
let rpo_af_same eq gt f ts0 ts1 =
let s = Term.Fun (f,ts0) in
let t = Term.Fun (f,ts1) in
let geq rule = eq rule $|$ gt rule in
let nc = is_c f >>= fun c -> return (if c then L.top else L.bot) in
let helper (eq,gt) (f0,ts0,ts1) =
let rec_gt = for_all f (rot gt s) ts1 in
(af_l f $&$ is_lex f $&$ lex_af f eq gt ts0 ts1 $&$ rec_gt $&$ nc) $|$
(af_l f $&$ is_mul f $&$ mul_gt_af f gt eq ts0 ts1 $&$ rec_gt) $|$
(af_l f $&$ exists f (rot2 geq t) ts0) $|$
(af_n f $&$ exists2 f gt ts0 ts1)
in get >>= fun c -> cache_m c.rpo_af_same_encodings (helper (eq,gt))
(f,ts0,ts1)
;;
let rpo_af_diff eq gt f0 f1 ts0 ts1 =
let helper gt (f0,f1,ts0,ts1) =
let s = Term.Fun (f0, ts0) and t = Term.Fun (f1, ts1) in
(af_l f0 $&$ af_l f1 $&$ exists f0 (rot2 eq t) ts0) $|$
((af_n f0 $|$ af_l f1) $&$ exists f0 (rot2 gt t) ts0) $|$
(((af_l f0 $&$ af_l f1 $&$ prec_gt f0 f1) $|$ af_n f1) $&$
for_all f1 (rot gt s) ts1)
in get >>= fun c -> cache_m c.rpo_af_diff_encodings (helper gt) (f0,f1,ts0,ts1)
;;
let p_term v f = function Term.Var _ -> v | Term.Fun(h,_) -> f h;;
let rec rpo_gt_af rule =
flat_rule rule >>= fun rule ->
let helper rl =
if is_embedded ( R.invert rl ) || not ( R.is_rewrite_rule rl ) then return L.bot
else if is_proper_embedded rl then return L.top
else
else if is_proper_embedded rl then return L.top
else*)
let s,t = R.to_terms rl in
match s,t with
| Term.Var _, _ -> return L.bot
| Term.Fun _, Term.Var x -> emb_af_gt rl
| Term.Fun (f,ss), Term.Fun (g,ts) when f <> g ->
rpo_af_diff eq_af rpo_gt_af f g ss ts
| Term.Fun (f,ss), Term.Fun (_,ts) ->
is_ac f >>= fun f_is_ac ->
if not f_is_ac then
rpo_af_same eq_af rpo_gt_af f ss ts
else
" \nR : % s\n% ! " ( R.to_string ( Rule.of_terms s t ) ) ;
(af_all f) $&$ ((exists f (rot2 rpo_ge_af t) ss) $|$ (
let gt s t = rpo_gt (R.of_terms s t) in
let ge s t = rpo_ge (R.of_terms s t) in
(* FIXME: the af_p h i restriction is sound but actually not necessary *)
let cover (h,i) s' = af_l h $&$ af_p h i $&$ prec_gt f h $&$ (ge s' t) in
( 5 )
(map_and (fun (t',h) -> prec_gt f h $->$ (gt s t')) (emb_sm f ts) $&$
( 6 )
( 6b )
( 6a )
else ( (big_head f ss ts) $|$
( 6c )
))
in
get >>= fun c -> cache_m c.gt_encodings helper rule
and no_small_head f ss ts =
let ps = p_term (return L.top) (fun h -> mnot (prec_gt f h) $&$ af_l h) in
let pt = p_term (return L.top) (fun h -> mnot (prec_gt f h)) in
mul_ge_af' (ps,pt) rpo_gt_af eq_af ss ts
and big_head f ss ts =
if List.is_empty ss then return L.bot
else
let ps = p_term (return L.bot) (fun h -> prec_gt h f $&$ af_l h) in
let pt = p_term (return L.bot) (fun h -> prec_gt h f) in
mul_gt_af' (ps,pt) rpo_gt_af eq_af ss ts
and rpo_ge_af rule = rpo_gt_af rule $|$ (eq_af rule)
;;
(* encoding *)
let rpo_gt r = get >>= fun c -> if !(flags.dp) then rpo_gt_af r else rpo_gt r
let rpo_ge r = get >>= fun c -> if !(flags.dp) then rpo_ge_af r else rpo_ge r
let total_prec fs =
let comparable (f,g) = prec_gt f g $|$ prec_gt g f in
map_and comparable (List.filter (fun (a,b) -> compare a b < 0) (List.square fs))
;;
let flat s w =
let s, w = Pair.map Trs.to_list (s, w) in
Made.project ((lift Trs.of_list) <.> (Made.map flat_rule)) (s,w)
;;
let encode_gt s =
(if !(flags.direct) then map_and else map_or) rpo_gt s
let encode_ge s w = map_and rpo_ge (s@w)
let af_f f =
arity f >>= fun a ->
is_ac f >>= fun ac ->
if ac then ((af_all f) $|$ (af_none f)) $&$
(mnot (af_collapsing f a 0)) $&$ (mnot (af_collapsing f a 1))
else af_l f $|$ gen_or (af_collapsing f a) a
;;
let af fs = map_and af_f fs;;
let af fs = get >>= fun c -> if !(flags.dp) then af fs else return Logic.top;;
let encode s w = get >>= fun c ->
flat s w >>= fun (s,w) ->
let fs = Trs.funs (Trs.union s w) in
let s, w = Pair.map Trs.to_list (s, w) in
encode_gt s $&$ encode_ge s w $&$ total_prec fs $&$ af fs
;;
(* decode from assignment *)
let decode_rule ass rule =
get >>= fun c ->
flat_rule rule >>= fun rule ->
( Format.printf " \nR : % s\n% ! " ( R.to_string rule ) ;
match Rule.to_terms rule with
Term . Fun(f , ss ) as s , ( Term . Fun(g , ts ) as t ) - >
is_ac f > > = fun fac - > is_ac g > > = fun gac - >
if fac & & gac then
let gt s t = rpo_gt ( R.of_terms s t ) in
let ge s t = rpo_ge ( R.of_terms s t ) in
let cover ( h , i ) s ' = af_l h $ & $ af_p h i $ & $ prec_gt f h $ & $ ( ge s ' t ) in
eval_p ( map_or ( fun ( s',hi ) - > flatten s ' > > = cover hi ) ( emb_sm_af f ss ) ) ass > > = fun b - >
Format.printf " ( 5 ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( map_and ( fun ( t',h ) - > prec_gt f h $ ->$ ( gt s t ' ) ) ( emb_sm f ts )
$ & $ ( no_small_head f ss ts ) ) ass > > = fun b - >
Format.printf " ( 6- ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( ( big_head f ss ts ) ) ass > > = fun b - >
Format.printf " ( ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( ( mul_gt_af f rpo_gt rpo_eq ss ts ) ) ass > > = fun b - >
Format.printf " ( mul_gt ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
return ( )
else return ( ) ) > >
match Rule.to_terms rule with
Term.Fun(f,ss) as s, (Term.Fun(g,ts) as t) ->
is_ac f >>= fun fac -> is_ac g >>= fun gac ->
if fac && gac then
let gt s t = rpo_gt (R.of_terms s t) in
let ge s t = rpo_ge (R.of_terms s t) in
let cover (h,i) s' = af_l h $&$ af_p h i $&$ prec_gt f h $&$ (ge s' t) in
eval_p (map_or (fun (s',hi) -> flatten s' >>= cover hi) (emb_sm_af f ss)) ass >>= fun b ->
Format.printf "(5) applies: %i \n%!" (if b then 1 else 0);
eval_p (map_and (fun (t',h) -> prec_gt f h $->$ (gt s t')) (emb_sm f ts)
$&$ (no_small_head f ss ts)) ass >>= fun b ->
Format.printf "(6-) applies: %i \n%!" (if b then 1 else 0);
eval_p ( (big_head f ss ts)) ass >>= fun b ->
Format.printf "(bighead) applies: %i \n%!" (if b then 1 else 0);
eval_p ((mul_gt_af f rpo_gt rpo_eq ss ts)) ass >>= fun b ->
Format.printf "(mul_gt) applies: %i \n%!" (if b then 1 else 0);
return ()
else return ()) >>*)
Format.printf " \nR : % s\n% ! " ( R.to_string rule ) ;
eval_p ( case_five rule ) ass > > = fun b - >
Format.printf " ( 5 ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( case_sixa rule ) ass > > = fun b - >
Format.printf " ( 6a ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( no_small_head rule ) ass > > = fun b - >
Format.printf " no small head applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( rule ) ass > > = fun b - >
Format.printf " big head applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( case_sixb rule ) ass > > = fun b - >
Format.printf " ( 6b ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( case_sixc rule ) ass > > = fun b - >
Format.printf " ( 6c ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p (case_five rule) ass >>= fun b ->
Format.printf "(5) applies: %i \n%!" (if b then 1 else 0);
eval_p (case_sixa rule) ass >>= fun b ->
Format.printf "(6a) applies: %i \n%!" (if b then 1 else 0);
eval_p (no_small_head rule) ass >>= fun b ->
Format.printf "no small head applies: %i \n%!" (if b then 1 else 0);
eval_p (big_head rule) ass >>= fun b ->
Format.printf "big head applies: %i \n%!" (if b then 1 else 0);
eval_p (case_sixb rule) ass >>= fun b ->
Format.printf "(6b) applies: %i \n%!" (if b then 1 else 0);
eval_p (case_sixc rule) ass >>= fun b ->
Format.printf "(6c) applies: %i \n%!" (if b then 1 else 0);*)
(* L.fprintf_assignment Format.std_formatter ass;*)
lift not (eval_p (rpo_gt rule) ass)
;;
let decode_trs ass trs =
Made.filter (decode_rule ass) (Trs.to_list trs) >>= (return <.> Trs.of_list)
;;
let decode ass s w = get >>= fun c ->
decode_trs ass
;;
let decode_status_f ass f = eval_p (is_mul f) ass >>= fun b -> return (f,b)
let decode_status ass s w =
let fs = Trs.funs (Trs.union s w) in
Made.sequence (List.map (decode_status_f ass) fs) >>= fun ps ->
return (Status.of_list ps)
;;
let decode_prec_f ass f =
eval_a (prec f) ass >>= fun p ->
return (f,int_of_string (Number.to_string p))
;;
let decode_prec ass s w =
let fs = Trs.funs (Trs.union s w) in
Made.sequence (List.map (decode_prec_f ass) fs) >>= fun ps ->
return (Prec.of_list ps)
;;
let decode_af_f ass f =
arity f >>= fun a ->
sequence (List.gen (fun i -> eval_p (af_p f i) ass) a) >>= fun ps ->
let psi = List.mapi Pair.make ps in
let ps = List.filter snd psi in
let ps = List.map fst ps in
eval_p (af_l f) ass >>= fun l ->
if l then return (f,AF.List ps)
assert ( ps = 1 ) ;
;;
let decode_af ass s w = get >>= fun c ->
if !(flags.dp) then (
let fs = Trs.funs (Trs.union s w) in
Made.sequence (List.map (decode_af_f ass) fs) >>= fun af ->
return (Some (AF.of_list af))
) else return None
;;
let solve signature fs p =
let configurate s = F.printf "%s@\n%!" s; flags.help := true in
(try init (); Arg.parsex code spec fs with Arg.Bad s -> configurate s);
if !(flags.help) then (Arg.usage spec ("Options for "^code^":"); exit 0);
let (s,w) = P.get_sw p in
let c = context signature (Trs.funs (Trs.union s w)) in
L.run (
Made.run c (encode s w >>= fun phi ->
Made.liftm (L.solve ~solver:c.solver phi) >>= function
| None -> return None
| Some ass ->
decode ass s w >>= fun (s',w') ->
decode_af ass s w >>= fun af ->
decode_prec ass s w >>= fun prec ->
decode_status ass s w >>= fun status ->
return (Some (make af p (P.set_sw s' w' p) prec status))))
;;
(* wrap into state monad *)
let (>>=) = M.(>>=);;
let solve fs p = M.get >>= fun s -> M.return (solve s fs p);;
| null | https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/processors/src/termination/orderings/oldacrpo.ml | ocaml | ** OPENS *******************************************************************
** MODULES *****************************************************************
** INCLUDES ***************************************************************
** FUNCTIONS **************************************************************
** TYPES *******************************************************************
encoding statuses of function symbols; true is multiset
multiset comparison formula caching
for argument filterings
** GLOBALS *****************************************************************
quasi = ref false;
("-quasi",Arg.Set flags.quasi,"Allows quasi-precedences (currently not \
supported together with -dp flag).");
** FUNCTIONS ***************************************************************
flags.quasi := false;
Complexity Bounds
Compare Functions
Printers
general functions
functions lifted from L into Made
actual content starts here
administrative functions
encoding starts here
caching variables
not quasi
***
sorts list of terms such that constants come before compound
terms where the root has positive arity come before variables
recursively flatten term with respect to all ac symbols
***
multiset cover arith variable caching, where key=(ss,tt,j)
cache_m c.mcov_a_encodings
encoding
multiset cover
get >>= fun c -> cache_m c.mcov_encodings
emb_small candidates
#s > #t
#s = #t
until quasi prec
multiset extension
encode with argument filtering
useful shorthands.
equality, embedding
then, x <> y holds
equality holds when AF(f) is added
(* comparing conditional multisets
emb_small candidates for af
FIXME: the af_p h i restriction is sound but actually not necessary
encoding
decode from assignment
L.fprintf_assignment Format.std_formatter ass;
wrap into state monad | Copyright 2008 , Christian Sternagel ,
* GNU Lesser General Public License
*
* This file is part of TTT2 .
*
* TTT2 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 .
*
* TTT2 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 TTT2 . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of TTT2.
*
* TTT2 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.
*
* TTT2 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 TTT2. If not, see </>.
*)
open Util;;
open Rewritingx;;
open Logic.Operators;;
module L = Logic;;
module AF = Filtering;;
module C = Coefficient;;
module Co = Complexity;;
module F = Format;;
module Fun = Function;;
module H = Hashtbl;;
module M = Rewritingx.Monad;;
module Number = L.Number;;
module P = Problem;;
module Pos = Position;;
module Prec = Precedence;;
module Sig = Signature;;
module Var = Variable;;
module R = Rule;;
module Status = struct
include Index.Make (Fun) (Bool);;
let (>>=) = M.(>>=);;
let is_lex s f = not (find f s);;
let is_mul s f = find f s;;
let fprintf fmt p =
let rec fprintf fmt = function
| [] -> ()
| (f,b) :: p ->
if b then F.fprintf fmt "%a:mul@ @ %a" Fun.fprintf f fprintf p
else F.fprintf fmt "%a:lex@ @ %a" Fun.fprintf f fprintf p
in
F.fprintf fmt "@[%a@]" fprintf (to_list p)
;;
let fprintfm fmt p =
let rec fprintfm = function
| [] -> M.return ()
| (f,b) :: p ->
M.fprintf_fun fmt f >>= fun _ ->
if b then F.fprintf fmt ":lex @ " else F.fprintf fmt ":mul @ ";
fprintfm p
in
M.filter (fun (f,_) -> M.is_theory Label.AC f >>= (M.return <.> not)) (to_list p) >>=
M.filter (fun (f,_) -> M.find_ari f >>= fun a -> M.return (a > 1)) >>=
(F.fprintf fmt "@["; fprintfm) >>= fun _ ->
M.return (F.fprintf fmt "@]")
;;
let fprintfx fmt p s =
let p = Prec.to_list p in
F.fprintf fmt "@{<statusPrecedence>";
M.iter (fun(f,b) ->
F.fprintf fmt "@{<statusPrecedenceEntry>";
M.fprintfx_fun fmt f >>= fun _ ->
M.find_ari f >>= fun a ->
F.fprintf fmt "@{<arity>%i@}" a;
F.fprintf fmt "@{<precedence>%i@}" (List.assoc f p);
F.fprintf fmt "@{<%s>@}" (if b then "mul" else "lex");
M.return(F.fprintf fmt "@}")
) (to_list s) >>= fun _ ->
M.return(F.fprintf fmt "@}")
;;
end;;
type context = {
solver : L.solver;
prec_num : int;
state : Signature.t;
precs : (Fun.t, L.a) H.t;
gt_encodings : (R.t, L.p) H.t;
stats : (Fun.t, L.p) H.t;
multiset cover : if ( s->t , j ) has value i then both s , t are rooted by f and
in multiset comparison of args(s ) , args(t ) term t_j is covered by s_i
in multiset comparison of args(s), args(t) term t_j is covered by s_i *)
mcov_a_encodings : (Term.t list * Term.t list * int, L.a) H.t;
mcov_encodings : (Term.t list*Term.t list, L.p*L.a list) H.t;
af_l : (Fun.t, L.p) H.t;
af_p : (Fun.t * int, L.p) H.t;
emb_gt_encodings : (Rule.t, Logic.p) H.t;
emb_eq_encodings : (Rule.t, Logic.p) H.t;
eq_af_encodings : (Fun.t*Fun.t*Term.t list*Term.t list, L.p) H.t;
rpo_af_same_encodings : (Fun.t*Term.t list*Term.t list,L.p) H.t;
rpo_af_diff_encodings : (Fun.t*Fun.t*Term.t list*Term.t list,L.p) H.t;
};;
type flags = {
dp : bool ref;
direct : bool ref;
help : bool ref;
quasi : ;
sat : bool ref;
};;
type t = {
af : AF.t option;
input : P.t;
output : P.t;
precedence : Prec.t;
status : Status.t;
};;
let code = "acrpo";;
let name = "AC-RPO Processor";;
let comment = "Applies AC-Recursive Path Order."
let keywords =
["AC";"recursive path order";"simplification order";"termination"]
;;
let flags = {
dp = ref false;
direct = ref false;
help = ref false;
sat = ref false;
};;
let spec =
let spec = [
("-af",Arg.Set flags.dp,
"Allows non-monotone interpretations (argument filterings).");
("-direct",Arg.Set flags.direct,
"Try to finish termination proof.");
("--help",Arg.Set flags.help,"Prints information about flags.");
("-help",Arg.Set flags.help,"Prints information about flags.");
("-h",Arg.Set flags.help,"Prints information about flags.");
("-sat",Arg.Set flags.sat,"Uses SAT backend.");
("-smt",Arg.Clear flags.sat,"Uses SMT backend (default).")]
in
Arg.alignx 80 spec
;;
let help = (comment,keywords,List.map Triple.drop_snd spec);;
* * ( part 2 ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
module Statex = struct type t = context end;;
module Made = Util.Monad.Transformer.State (Statex) (L.Monad);;
open Made;;
let init _ =
flags.dp := false;
flags.direct := false;
flags.help := false;
flags.sat := false;
;;
Constructors and Destructors
let make af input output precedence st = {
af = af;
input = input;
output = output;
precedence = precedence;
status = st;
};;
let get_ip p = p.input;;
let get_op p = p.output;;
let complexity c _ = Co.mul c Co.other;;
let equal p q =
P.equal p.input q.input && P.equal p.output q.output
;;
let (>>=) = M.(>>=);;
let fprintf_af fmt = function
| None -> Monad.return ()
| Some af ->
F.fprintf fmt "@\n@[<1>argument filtering:@\n";
AF.fprintfm fmt af >>= fun _ -> Monad.return (F.fprintf fmt "@]")
;;
let fprintf fs fmt p =
F.fprintf fmt "@[<1>%s:" name;
fprintf_af fmt p.af >>= fun _ ->
F.fprintf fmt "@]@\n@[<1>precedence:@\n";
Prec.fprintfm fmt p.precedence >>= fun _ ->
F.fprintf fmt "@]@\n@[<1>status:@\n";
Status.fprintfm fmt p.status >>= fun _ ->
F.fprintf fmt "@]@\n@[<1>problem:@\n";
P.fprintfm fmt p.output >>= fun _ ->
F.fprintf fmt "@]@\n"; List.hd fs fmt >>= fun _ ->
Monad.return (F.fprintf fmt "@]")
;;
let fprintfx_af fmt = function
| None -> Monad.return()
| Some af -> AF.fprintfx fmt af
;;
let fprintfx_redpair fmt p =
F.fprintf fmt "@{<redPair>@{<pathOrder>";
Status.fprintfx fmt p.precedence p.status >>= fun _ ->
fprintfx_af fmt p.af >>= fun _ ->
M.return(F.fprintf fmt "@}@}")
;;
let fprintfx fs fmt p =
if (Problem.is_dp p.input) || (Problem.is_edp p.input) then (
let tag = "redPairProc" in
F.fprintf fmt "@{<%s>" tag;
fprintfx_redpair fmt p >>= fun _ ->
Problem.fprintfx fmt p.output >>= fun _ ->
List.hd fs fmt >>= fun _ ->
Monad.return(F.fprintf fmt "@}");
) else if (Problem.is_sp p.input) || (Problem.is_ep p.input) then (
failwith "AC-RPO full termination not supported!"
) else (
failwith "for this problem AC-RPO is not supported!"
)
;;
let (>>=) = Made.(>>=);;
let fresh_arith_spec spec = liftm (L.fresh_arith spec);;
let fresh_bool = get >>= fun s -> liftm L.fresh_bool;;
let eval_a a ass = a >>= fun a -> liftm (L.eval_a a ass);;
let eval_p p ass = p >>= fun p -> liftm (L.eval_p p ass);;
let ($>=$) a b = lift2 (<>=>) a b;;
let ($=$) a b = lift2 (<=>) a b;;
let ($>$) a b = lift2 (<>>) a b;;
let ($->$) a b = lift2 (<->>) a b;;
let ($|$) a b = lift2 (<|>) a b;;
let ($&$) a b = lift2 (<&>) a b;;
let ($*$) a b = lift2 (<*>) a b;;
let ($+$) a b = lift2 (<+>) a b;;
let ($-$) a b = lift2 (<->) a b;;
let mnot a = lift (~!) a;;
let zero = L.zero;;
let one = L.one;;
let constant = L.constant <.> Number.of_int;;
let sum f = List.foldl (fun s x -> f x <+> s) L.zero;;
let big_xor ps = sum (fun p -> p <?> one <:> zero) ps <=> one;;
let map_op op f ls = sequence (List.map f ls) >>= (return <.> op);;
let mapi_op op f ls = sequence (List.mapi f ls) >>= (return <.> op);;
let gen_op op f n = sequence (List.gen f n) >>= (return <.> op);;
let map_and f = map_op L.big_and f;;
let mapi_and f = mapi_op L.big_and f;;
let map_or f = map_op L.big_or f;;
let mapi_or f = mapi_op Logic.big_or f;;
let gen_or f = gen_op Logic.big_or f;;
let gen_and f = gen_op Logic.big_and f;;
let context state fs =
let solver = if !(flags.sat) then L.MiniSat else L.Yices in
{
solver = solver;
prec_num = max 0 (List.length fs - 1);
precs = H.create 512;
state = state;
gt_encodings = H.create 512;
stats = H.create 512;
mcov_a_encodings = H.create 512;
mcov_encodings = H.create 512;
af_l = H.create 512;
af_p = H.create 512;
emb_gt_encodings = H.create 512;
emb_eq_encodings = H.create 512;
eq_af_encodings = H.create 512;
rpo_af_same_encodings = H.create 512;
rpo_af_diff_encodings = H.create 512;
}
;;
let cache_m tbl f k =
if H.mem tbl k then return (H.find tbl k)
else (f k >>= fun v -> (H.add tbl k v; return v))
;;
let prec f = get >>= fun c ->
let arith = L.nat c.prec_num in
cache_m c.precs (const (fresh_arith_spec arith)) f
;;
let prec_gt f g = prec f $>$ prec g;;
let is_mul f = get >>= fun c -> cache_m c.stats (const fresh_bool) f;;
let is_lex = mnot <.> is_mul;;
let is_ac f = get >>= fun c -> return (Sig.is_theory Label.AC f c.state);;
let is_c f = get >>= fun c -> return (Sig.is_theory Label.C f c.state);;
let set_ac f =
get >>= fun c -> let (f, s) = Sig.set_theory f Label.AC c.state in
Made.set {c with state = s} >>
return f
;;
let arity f = get >>= fun c -> return (Sig.find_ari f c.state);;
let af_l f = get >>= fun c -> cache_m c.af_l (const fresh_bool) f;;
let af_n f = af_l f >>= (return <.> L.neg);;
let af_p f i = get >>= fun c -> cache_m c.af_p (const fresh_bool) (f,i);;
let af_all f = (af_l f) $&$ (af_p f 0) $&$ (af_p f 1)
let af_none f = (af_l f) $&$ (mnot ((af_p f 0) $|$ (af_p f 1)))
let find_term_with f =
let rooted_f = function Term.Fun (g,_) when f=g -> true | _ -> false in
let rec find ys = function
| [] -> None
| x::xs when rooted_f x -> Some(x, ys@xs)
| x::xs -> find (x::ys) xs
in find []
;;
let rec lex = function
| [],[] -> 0
| [],_ -> -1
|_, [] -> 1
| x::xs,y::ys -> let c = my_compare x y in if c=0 then lex (xs,ys) else c
and my_compare t t' =
match t, t' with
| Term.Var x, Term.Var y -> Var.compare x y
| Term.Fun _, Term.Var _ -> -1
| Term.Var _, Term.Fun _ -> 1
| Term.Fun(_,[]), Term.Fun(_,_::_) -> -1
| Term.Fun(_,_::_), Term.Fun(_,[]) -> 1
| Term.Fun(f,fs), Term.Fun(g,gs) when f=g -> lex (fs,gs)
| Term.Fun(f,_), Term.Fun(g,_) -> Fun.compare f g
;;
let rec flatten = function
| Term.Fun(f, ts) ->
is_ac f >>= fun f_is_ac -> (
if f_is_ac then
Made.map flatten ts >>= fun ts' ->
match find_term_with f ts' with
| None -> Made.return (Term.Fun(f, List.sort my_compare ts'))
| Some (ti,ts'') -> flatten (Term.Fun(f, (ts''@(Term.args ti))))
else
Made.map flatten ts >>= fun us -> Made.return (Term.Fun(f,us)))
| v -> Made.return v
;;
let rec term_is_embedded s t = match (s,t) with
| Term.Var x, Term.Var y -> x = y
| Term.Fun (f,ss), Term.Fun (g,ts) ->
(f = g
&& List.length ss = List.length ts
&& List.for_all2 term_is_embedded ss ts) || List.exists (term_is_embedded s) ts
| _, Term.Fun (f,ts) -> List.exists (term_is_embedded s) ts
| _, _ -> false
;;
let is_embedded = Util.uncurry (flip term_is_embedded) <.> R.to_terms;;
let is_proper_embedded r =
List.exists (term_is_embedded (R.rhs r)) (Term.subterms (R.lhs r))
;;
let mcov_a_var key =
let m = List.length (Triple.fst key) -1 in
get >>= fun c -> let arith = L.nat m in
;;
let rec lex gt eq ts ss = match ts,ss with
| _::_,[] -> return L.top
| [], _ -> return L.bot
| ti::ts,si::ss ->
gt (R.of_terms ti si) $|$ (eq (R.of_terms ti si) $&$ lex gt eq ts ss)
;;
let mul_cover ss ts =
let aux (ss,ts) =
Made.mapi (fun j _ -> mcov_a_var (ss,ts,j)) ts >>= fun cs ->
let m = List.length ss in
let sm = L.big_and (List.map (fun ci -> ci <<> (constant m)) cs) in
return (sm,cs)
;;
let mul gt eq ss ts =
mul_cover ss ts >>= fun (cover,cs) ->
let tcs = List.zip ts cs in
mapi_and (fun i si -> mapi_and (fun j (tj,cj) ->
(return (cj <=> (constant i))) $->$ (gt (R.of_terms si tj))
) tcs) ss >>= fun phi ->
return (cover <&> phi)
;;
let diff ?(cmp=compare) xs ys =
let rec rem x = function
| [] -> []
| y::ys when cmp x y = 0 -> ys
| y::ys -> y::(rem x ys)
in List.foldl (flip rem) xs ys
;;
let mul_ge gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if List.is_empty ss && List.is_empty ts then
return L.top
else
mul gt eq ss ts
;;
let mul_gt gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if ss = [] then return L.bot else mul gt eq ss ts
;;
let mul_eq gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if List.is_empty ss && List.is_empty ts then
return L.top
else
return L.bot
;;
to compute no_small_head and multiset comparisons
let mul_g' cs p gt eq ss ts =
let tcs = List.zip ts cs in
let gt si tj = gt (R.of_terms si tj) in
let has_val cj i = return (cj <=> (constant i)) in
mapi_and (fun j (tj,cj) ->
(p tj) $->$
(mapi_and (fun i si -> has_val cj i $->$ (gt si tj $&$ (p si))) ss))
tcs
;;
let mul_ge' p gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
mul_cover ss ts >>= fun (cover,cs) ->
mul_g' cs p gt eq ss ts >>= fun phi ->
return (cover <&> phi)
;;
let mul_gt' p gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
mul_cover ss ts >>= fun (cover,cs) ->
mul_g' cs p gt eq ss ts >>= fun phi ->
map_or p ss >>= fun non_empty ->
return (cover <&> phi <&> non_empty)
;;
let emb_sm f ts =
let tf t = if Term.root t = Some f then Term.args t else [t] in
let rec emb hd = function
| [] -> []
| ((Term.Var _) as t)::ts -> emb (hd@[t]) ts
| (Term.Fun(h,hs) as t)::ts when f=h -> emb (hd@[t]) ts
| (Term.Fun(h,hs) as t)::ts ->
(List.map (fun hi -> (hd@(tf hi)@ts,h)) hs)@(emb (hd@[t]) ts)
in List.map (Pair.apply (Term.make_fun f) id) (emb [] ts )
;;
let size_gt ss ts =
let (vs,fs),(vt,ft) = Pair.map (List.partition Term.is_var) (ss,ts) in
let vs,vt = diff vs vt,diff vt vs in
(List.is_empty vt) && (List.length (vs@fs) > (List.length ft))
;;
let size_ge ss ts =
let (vs,fs),(vt,ft) = Pair.map (List.partition Term.is_var) (ss,ts) in
let vs,vt = diff vs vt,diff vt vs in
(List.is_empty vt) && (List.length (vs@fs) >= (List.length ft))
;;
let rpo_eq r =
let s,t = R.to_terms r in
return (if Term.compare s t = 0 then L.top else L.bot)
;;
let flat_rule r =
Made.project flatten (R.to_terms r) >>= fun (l,r) ->
return (R.of_terms l r)
;;
let rec rpo_gt rule =
flat_rule rule >>= fun rule ->
Format.printf " check : % s > % s\n% ! " ( Term.to_string s ) ( Term.to_string t ) ;
let helper rule =
if is_embedded (R.invert rule) || not (R.is_rewrite_rule rule) then
return L.bot
else if is_proper_embedded rule then
return L.top
else
let s,t = R.to_terms rule in
match s,t with
| Term.Var _, _ -> return L.bot
| Term.Fun _, Term.Var x ->
return (if List.mem x (Term.vars s) then L.top else L.bot)
| Term.Fun (f,ss), Term.Fun (g,ts) when f <> g ->
( 1 )
( 2 )
| Term.Fun (f,ss), Term.Fun (_,ts) ->
is_ac f >>= fun f_is_ac -> is_c f >>= fun f_is_c ->
if not (f_is_ac || f_is_c) then
( 1 )
( 3 )
( 4 )
else if f_is_c then
else (
let gt s t = rpo_gt (R.of_terms s t) in
let ge s t = rpo_ge (R.of_terms s t) in
let cover h s' = prec_gt f h $&$ (ge s' t) in
( 5 )
(map_and (fun (t',h) -> prec_gt f h $->$ (gt s t')) (emb_sm f ts) $&$
( 6 )
( 6b )
( 6a )
else ((big_head f ss ts) $|$
( 6c )
)
in
get >>= fun c -> cache_m c.gt_encodings helper rule
and no_small_head f ss ts =
let p u = match Term.root u with
None -> return L.top | Some h -> mnot (prec_gt f h) in
mul_ge' p rpo_gt rpo_eq ss ts
and big_head f ss ts =
if List.is_empty ss then return L.bot
else
let p u = match Term.root u with
None -> return L.bot | Some h -> prec_gt h f in
mul_gt' p rpo_gt rpo_eq ss ts
and rpo_ge rule = rpo_gt rule $|$ (rpo_eq rule)
;;
let exists f p ts = mapi_or (fun i ti -> (af_p f i) $&$ (p ti)) ts;;
let existsi f p ts = mapi_or (fun i ti -> (af_p f i) $&$ (p i ti)) ts;;
let for_all f p ts = mapi_and (fun i ti -> (af_p f i) $->$ (p ti)) ts;;
let exists2 f p ss ts = exists f p (List.map2 R.of_terms ss ts);;
let for_all2 f p ss ts = for_all f p (List.map2 R.of_terms ss ts);;
let rot f s t = f (R.of_terms s t);;
let rot2 f s t = f (R.of_terms t s);;
let af_collapsing f a i =
let make j = if i = j then af_p f i else (lift L.neg (af_p f j)) in
gen_and make a
;;
let lex_af f eq gt ss ts =
let rec lex' eq gt ss ts i =
match ss, ts with
| [],[] -> return L.bot
| [], _ | _, [] -> failwith "lists of different length"
| sn::sss,tn::tss ->
(af_p f i $&$ gt (R.of_terms sn tn))
$|$
((af_p f i $->$ eq (R.of_terms sn tn)) $&$ lex' eq gt sss tss (i+1))
in
lex' eq gt ss ts 0
;;
let eq_af_diff eq f g ss ts =
let helper eq (f,g,ss,ts) =
let s = Term.Fun (f, ss) and t = Term.Fun (g, ts) in
(af_n f $&$ exists f (fun si -> eq (R.of_terms si t)) ss) $|$
(af_n g $&$ exists g (fun tj -> eq (R.of_terms s tj)) ts)
in get >>= fun c -> cache_m c.eq_af_encodings (helper eq) (f,g,ss,ts)
;;
let rec eq_af rule =
let helper r =
let (s,t) = R.to_terms rule in match (s,t) with
| _, _ when s = t -> return L.top
| Term.Var _, Term.Fun (g, ts) ->
af_n g $&$ exists g (fun tj -> eq_af (R.of_terms s tj)) ts
| Term.Fun (f, ss), Term.Var _ ->
af_n f $&$ exists f (fun si -> eq_af (R.of_terms si t)) ss
| Term.Fun (f, ss), Term.Fun (g, ts) when f = g ->
if List.length ss <> List.length ts then return L.bot
| Term.Fun (f, ss), Term.Fun (g, ts) ->
eq_af_diff eq_af f g ss ts
in get >>= fun c -> cache_m c.emb_eq_encodings helper rule
;;
let mul_af f gt eq ss ts =
mul_cover ss ts >>= fun (cover,cs) ->
let tcs = List.zip ts cs in
let is cj i = return (cj <=> (constant i)) in
mapi_and (fun i si -> mapi_and (fun j (tj,cj) ->
af_p f j $->$
((is cj i) $->$ (gt (R.of_terms si tj) $&$ (af_p f i)))
) tcs) ss >>= fun phi ->
return (cover <&> phi)
;;
let mul_ge_af f gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if List.is_empty ss && List.is_empty ts then return L.top
else
let rl = R.of_terms (Term.Fun (f, ss)) (Term.Fun (f, ts)) in
(mul_af f gt eq ss ts) $|$ (eq_af rl)
;;
let mul_gt_af f gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
if ss = [] then return L.bot
else
mul_cover ss ts >>= fun (cover,cs) ->
let tcs = List.zip ts cs in
let is cj i = return (cj <=> (constant i)) in
let phi = mapi_and (fun i si -> mapi_and (fun j (tj,cj) ->
(af_p f j $&$ af_l f) $->$
((is cj i) $->$ (gt (R.of_terms si tj) $&$ (af_p f i)))
) tcs) ss
in
let is_strict i si j tj = is (List.nth cs j) i $&$ gt (R.of_terms si tj) in
let strict = existsi f (fun i si -> existsi f (is_strict i si) ts) ss in
let s_nonempty = exists f (fun _ -> return L.top) ss in
let t_empty = mnot (exists f (fun _ -> return L.top) ts) in
phi $&$ (strict $|$ (s_nonempty $&$ t_empty))
;;
let cond_mul gt eq ss ts =
mul_cover ss ts >>= fun (cover_aux,cs) ->
let tcs = List.zip ts cs in
let gt si tj = gt (R.of_terms si tj) in
let is cj i = return (cj <=> (constant i)) in
let cov_i_j_imp (tj,cj) i (si,psi) = is cj i $->$ (gt si tj $&$ return psi) in
let cov_j_and tcj = mapi_and (cov_i_j_imp tcj) ss in
let covered = mapi_and (fun j ((tj,ptj),cj) -> return ptj $->$ cov_j_and (tj,cj)) tcs in
let cov_i_j_and (tj,cj) i (si,psi) = is cj i $&$ gt si tj $&$ return psi in
let cov_j_or tcj = mapi_or (cov_i_j_and tcj) ss in
let strict = mapi_or (fun j ((tj,ptj),cj) -> return ptj $&$ cov_j_or (tj,cj)) tcs in
let s_nonempty = return (L.big_or (List.map snd ss)) in
let t_empty = return (~! (L.big_and (List.map snd ts))) in
strict $|$ (s_nonempty $&$ t_empty) >>= fun is_strict ->
return cover_aux $&$ covered >>= fun is_covered ->
return (is_covered, is_strict)
;;
let cond_mul_gt gt eq ss ts = cond_mul gt eq ss ts >>= fun (c,s) -> return (c <&> s)
let cond_mul_ge gt eq ss = lift fst <.> (cond_mul gt eq ss)
*)
to compute no_small_head and multiset comparisons
let mul_g_af' cs (ps,pt) gt eq ss ts =
let tcs = List.zip ts cs in
let gt si tj = gt (R.of_terms si tj) in
let has_val cj i = return (cj <=> (constant i)) in
mapi_and (fun j (tj,cj) ->
(pt tj) $->$
(mapi_and (fun i si -> has_val cj i $->$ (gt si tj $&$ (ps si))) ss))
tcs
;;
let mul_ge_af' p gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
mul_cover ss ts >>= fun (cover,cs) ->
mul_g_af' cs p gt eq ss ts >>= fun phi ->
return (cover <&> phi)
;;
let mul_gt_af' (ps,pt) gt eq ss ts =
let ss,ts = diff ~cmp:compare ss ts, diff ~cmp:compare ts ss in
mul_cover ss ts >>= fun (cover,cs) ->
let tcs = List.zip ts cs in
let gt si tj = gt (R.of_terms si tj) in
let has_val cj i = return (cj <=> (constant i)) in
let phi =
mapi_and (fun j (tj,cj) ->
(pt tj) $->$
(mapi_and (fun i si -> has_val cj i $->$ (gt si tj $&$ (ps si))) ss))
tcs
in
let strict =
mapi_or (fun j (tj,cj) ->
(pt tj) $&$ (mapi_or (fun i si -> has_val cj i $&$ (gt si tj $&$ (ps si))) ss))
tcs
in
let s_nonempty = map_or ps ss in
let t_empty = mnot (map_or pt ts) in
phi $&$ (strict $|$ (s_nonempty $&$ t_empty))
;;
let emb_sm_af f ts =
let tf t = if Term.root t = Some f then Term.args t else [ t ] in
let rec emb hd = function
| [ ] - > [ ]
| ( ( Term . Var _ ) as t)::ts - > emb ( hd@[t ] ) ts
| ( Term . Fun(h , hs ) as t)::ts when f = h - > emb ( hd@[t ] ) ts
| ( Term . Fun(h , hs ) as t)::ts - >
( List.mapi ( fun i hi - > ( hd@(tf hi)@ts,(h , i ) ) ) hs)@(emb ( hd@[t ] ) ts )
in List.map ( Pair.apply ( Term.make_fun f ) i d ) ( emb [ ] ts )
; ;
let emb_sm_af f ts =
let tf t = if Term.root t = Some f then Term.args t else [t] in
let rec emb hd = function
| [] -> []
| ((Term.Var _) as t)::ts -> emb (hd@[t]) ts
| (Term.Fun(h,hs) as t)::ts when f=h -> emb (hd@[t]) ts
| (Term.Fun(h,hs) as t)::ts ->
(List.mapi (fun i hi -> (hd@(tf hi)@ts,(h,i))) hs)@(emb (hd@[t]) ts)
in List.map (Pair.apply (Term.make_fun f) id) (emb [] ts )
;;*)
let emb_sm_af f ts =
let add ci hd tl' = function
| Term.Var _ -> []
| (Term.Fun(h,hs) as si) -> [Term.Fun(f, hd @ (si::tl')), fh <&> ci]
in
let rec emb (hd,tl) acc =
match tl with
| [] -> return acc
| (Term.Fun(h,hs)) :: tl' ->
cond_sub hs >>= map (fun (si,ci) -> add ci hd tl') >>= fun ss ->
emb (hd @ [t],tl') (acc @ ss)
| t :: tl' -> emb (hd @ [t],tl') (acc @ ss)
in emb ([],ts) []
;;
let rec emb_af_ge rule = emb_af_gt rule $|$ eq_af rule
and emb_af_gt rule =
let helper rule =
let s, t = Rule.to_terms rule in match s, t with
| Term.Var _, _ -> return Logic.bot
| Term.Fun (f, ss), Term.Var _ ->
exists f (fun si -> emb_af_gt (Rule.of_terms si t)) ss $|$
(af_l f $&$ exists f (fun si -> eq_af (Rule.of_terms si t)) ss)
| Term.Fun (f, ss), Term.Fun (g, ts) when f = g ->
(af_l f $&$ exists f (fun si -> emb_af_ge (Rule.of_terms si t)) ss) $|$
(((af_l f $&$ for_all2 f emb_af_ge ss ts) $|$ af_n f)
$&$ exists2 f emb_af_gt ss ts)
| Term.Fun (f, ss), Term.Fun (g, ts) ->
(af_l f $&$
((af_l g $&$ exists f (fun si -> eq_af (Rule.of_terms si t)) ss) $|$
(af_n g $&$ exists g (fun tj -> emb_af_gt (Rule.of_terms s tj)) ts)))
$|$
((af_n f $|$ af_l g) $&$
exists f (fun si -> emb_af_gt (Rule.of_terms si t)) ss)
in get >>= fun c -> cache_m c.emb_gt_encodings helper rule
;;
let rpo_af_same eq gt f ts0 ts1 =
let s = Term.Fun (f,ts0) in
let t = Term.Fun (f,ts1) in
let geq rule = eq rule $|$ gt rule in
let nc = is_c f >>= fun c -> return (if c then L.top else L.bot) in
let helper (eq,gt) (f0,ts0,ts1) =
let rec_gt = for_all f (rot gt s) ts1 in
(af_l f $&$ is_lex f $&$ lex_af f eq gt ts0 ts1 $&$ rec_gt $&$ nc) $|$
(af_l f $&$ is_mul f $&$ mul_gt_af f gt eq ts0 ts1 $&$ rec_gt) $|$
(af_l f $&$ exists f (rot2 geq t) ts0) $|$
(af_n f $&$ exists2 f gt ts0 ts1)
in get >>= fun c -> cache_m c.rpo_af_same_encodings (helper (eq,gt))
(f,ts0,ts1)
;;
let rpo_af_diff eq gt f0 f1 ts0 ts1 =
let helper gt (f0,f1,ts0,ts1) =
let s = Term.Fun (f0, ts0) and t = Term.Fun (f1, ts1) in
(af_l f0 $&$ af_l f1 $&$ exists f0 (rot2 eq t) ts0) $|$
((af_n f0 $|$ af_l f1) $&$ exists f0 (rot2 gt t) ts0) $|$
(((af_l f0 $&$ af_l f1 $&$ prec_gt f0 f1) $|$ af_n f1) $&$
for_all f1 (rot gt s) ts1)
in get >>= fun c -> cache_m c.rpo_af_diff_encodings (helper gt) (f0,f1,ts0,ts1)
;;
let p_term v f = function Term.Var _ -> v | Term.Fun(h,_) -> f h;;
let rec rpo_gt_af rule =
flat_rule rule >>= fun rule ->
let helper rl =
if is_embedded ( R.invert rl ) || not ( R.is_rewrite_rule rl ) then return L.bot
else if is_proper_embedded rl then return L.top
else
else if is_proper_embedded rl then return L.top
else*)
let s,t = R.to_terms rl in
match s,t with
| Term.Var _, _ -> return L.bot
| Term.Fun _, Term.Var x -> emb_af_gt rl
| Term.Fun (f,ss), Term.Fun (g,ts) when f <> g ->
rpo_af_diff eq_af rpo_gt_af f g ss ts
| Term.Fun (f,ss), Term.Fun (_,ts) ->
is_ac f >>= fun f_is_ac ->
if not f_is_ac then
rpo_af_same eq_af rpo_gt_af f ss ts
else
" \nR : % s\n% ! " ( R.to_string ( Rule.of_terms s t ) ) ;
(af_all f) $&$ ((exists f (rot2 rpo_ge_af t) ss) $|$ (
let gt s t = rpo_gt (R.of_terms s t) in
let ge s t = rpo_ge (R.of_terms s t) in
let cover (h,i) s' = af_l h $&$ af_p h i $&$ prec_gt f h $&$ (ge s' t) in
( 5 )
(map_and (fun (t',h) -> prec_gt f h $->$ (gt s t')) (emb_sm f ts) $&$
( 6 )
( 6b )
( 6a )
else ( (big_head f ss ts) $|$
( 6c )
))
in
get >>= fun c -> cache_m c.gt_encodings helper rule
and no_small_head f ss ts =
let ps = p_term (return L.top) (fun h -> mnot (prec_gt f h) $&$ af_l h) in
let pt = p_term (return L.top) (fun h -> mnot (prec_gt f h)) in
mul_ge_af' (ps,pt) rpo_gt_af eq_af ss ts
and big_head f ss ts =
if List.is_empty ss then return L.bot
else
let ps = p_term (return L.bot) (fun h -> prec_gt h f $&$ af_l h) in
let pt = p_term (return L.bot) (fun h -> prec_gt h f) in
mul_gt_af' (ps,pt) rpo_gt_af eq_af ss ts
and rpo_ge_af rule = rpo_gt_af rule $|$ (eq_af rule)
;;
let rpo_gt r = get >>= fun c -> if !(flags.dp) then rpo_gt_af r else rpo_gt r
let rpo_ge r = get >>= fun c -> if !(flags.dp) then rpo_ge_af r else rpo_ge r
let total_prec fs =
let comparable (f,g) = prec_gt f g $|$ prec_gt g f in
map_and comparable (List.filter (fun (a,b) -> compare a b < 0) (List.square fs))
;;
let flat s w =
let s, w = Pair.map Trs.to_list (s, w) in
Made.project ((lift Trs.of_list) <.> (Made.map flat_rule)) (s,w)
;;
let encode_gt s =
(if !(flags.direct) then map_and else map_or) rpo_gt s
let encode_ge s w = map_and rpo_ge (s@w)
let af_f f =
arity f >>= fun a ->
is_ac f >>= fun ac ->
if ac then ((af_all f) $|$ (af_none f)) $&$
(mnot (af_collapsing f a 0)) $&$ (mnot (af_collapsing f a 1))
else af_l f $|$ gen_or (af_collapsing f a) a
;;
let af fs = map_and af_f fs;;
let af fs = get >>= fun c -> if !(flags.dp) then af fs else return Logic.top;;
let encode s w = get >>= fun c ->
flat s w >>= fun (s,w) ->
let fs = Trs.funs (Trs.union s w) in
let s, w = Pair.map Trs.to_list (s, w) in
encode_gt s $&$ encode_ge s w $&$ total_prec fs $&$ af fs
;;
let decode_rule ass rule =
get >>= fun c ->
flat_rule rule >>= fun rule ->
( Format.printf " \nR : % s\n% ! " ( R.to_string rule ) ;
match Rule.to_terms rule with
Term . Fun(f , ss ) as s , ( Term . Fun(g , ts ) as t ) - >
is_ac f > > = fun fac - > is_ac g > > = fun gac - >
if fac & & gac then
let gt s t = rpo_gt ( R.of_terms s t ) in
let ge s t = rpo_ge ( R.of_terms s t ) in
let cover ( h , i ) s ' = af_l h $ & $ af_p h i $ & $ prec_gt f h $ & $ ( ge s ' t ) in
eval_p ( map_or ( fun ( s',hi ) - > flatten s ' > > = cover hi ) ( emb_sm_af f ss ) ) ass > > = fun b - >
Format.printf " ( 5 ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( map_and ( fun ( t',h ) - > prec_gt f h $ ->$ ( gt s t ' ) ) ( emb_sm f ts )
$ & $ ( no_small_head f ss ts ) ) ass > > = fun b - >
Format.printf " ( 6- ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( ( big_head f ss ts ) ) ass > > = fun b - >
Format.printf " ( ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( ( mul_gt_af f rpo_gt rpo_eq ss ts ) ) ass > > = fun b - >
Format.printf " ( mul_gt ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
return ( )
else return ( ) ) > >
match Rule.to_terms rule with
Term.Fun(f,ss) as s, (Term.Fun(g,ts) as t) ->
is_ac f >>= fun fac -> is_ac g >>= fun gac ->
if fac && gac then
let gt s t = rpo_gt (R.of_terms s t) in
let ge s t = rpo_ge (R.of_terms s t) in
let cover (h,i) s' = af_l h $&$ af_p h i $&$ prec_gt f h $&$ (ge s' t) in
eval_p (map_or (fun (s',hi) -> flatten s' >>= cover hi) (emb_sm_af f ss)) ass >>= fun b ->
Format.printf "(5) applies: %i \n%!" (if b then 1 else 0);
eval_p (map_and (fun (t',h) -> prec_gt f h $->$ (gt s t')) (emb_sm f ts)
$&$ (no_small_head f ss ts)) ass >>= fun b ->
Format.printf "(6-) applies: %i \n%!" (if b then 1 else 0);
eval_p ( (big_head f ss ts)) ass >>= fun b ->
Format.printf "(bighead) applies: %i \n%!" (if b then 1 else 0);
eval_p ((mul_gt_af f rpo_gt rpo_eq ss ts)) ass >>= fun b ->
Format.printf "(mul_gt) applies: %i \n%!" (if b then 1 else 0);
return ()
else return ()) >>*)
Format.printf " \nR : % s\n% ! " ( R.to_string rule ) ;
eval_p ( case_five rule ) ass > > = fun b - >
Format.printf " ( 5 ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( case_sixa rule ) ass > > = fun b - >
Format.printf " ( 6a ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( no_small_head rule ) ass > > = fun b - >
Format.printf " no small head applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( rule ) ass > > = fun b - >
Format.printf " big head applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( case_sixb rule ) ass > > = fun b - >
Format.printf " ( 6b ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p ( case_sixc rule ) ass > > = fun b - >
Format.printf " ( 6c ) applies : % i \n% ! " ( if b then 1 else 0 ) ;
eval_p (case_five rule) ass >>= fun b ->
Format.printf "(5) applies: %i \n%!" (if b then 1 else 0);
eval_p (case_sixa rule) ass >>= fun b ->
Format.printf "(6a) applies: %i \n%!" (if b then 1 else 0);
eval_p (no_small_head rule) ass >>= fun b ->
Format.printf "no small head applies: %i \n%!" (if b then 1 else 0);
eval_p (big_head rule) ass >>= fun b ->
Format.printf "big head applies: %i \n%!" (if b then 1 else 0);
eval_p (case_sixb rule) ass >>= fun b ->
Format.printf "(6b) applies: %i \n%!" (if b then 1 else 0);
eval_p (case_sixc rule) ass >>= fun b ->
Format.printf "(6c) applies: %i \n%!" (if b then 1 else 0);*)
lift not (eval_p (rpo_gt rule) ass)
;;
let decode_trs ass trs =
Made.filter (decode_rule ass) (Trs.to_list trs) >>= (return <.> Trs.of_list)
;;
let decode ass s w = get >>= fun c ->
decode_trs ass
;;
let decode_status_f ass f = eval_p (is_mul f) ass >>= fun b -> return (f,b)
let decode_status ass s w =
let fs = Trs.funs (Trs.union s w) in
Made.sequence (List.map (decode_status_f ass) fs) >>= fun ps ->
return (Status.of_list ps)
;;
let decode_prec_f ass f =
eval_a (prec f) ass >>= fun p ->
return (f,int_of_string (Number.to_string p))
;;
let decode_prec ass s w =
let fs = Trs.funs (Trs.union s w) in
Made.sequence (List.map (decode_prec_f ass) fs) >>= fun ps ->
return (Prec.of_list ps)
;;
let decode_af_f ass f =
arity f >>= fun a ->
sequence (List.gen (fun i -> eval_p (af_p f i) ass) a) >>= fun ps ->
let psi = List.mapi Pair.make ps in
let ps = List.filter snd psi in
let ps = List.map fst ps in
eval_p (af_l f) ass >>= fun l ->
if l then return (f,AF.List ps)
assert ( ps = 1 ) ;
;;
let decode_af ass s w = get >>= fun c ->
if !(flags.dp) then (
let fs = Trs.funs (Trs.union s w) in
Made.sequence (List.map (decode_af_f ass) fs) >>= fun af ->
return (Some (AF.of_list af))
) else return None
;;
let solve signature fs p =
let configurate s = F.printf "%s@\n%!" s; flags.help := true in
(try init (); Arg.parsex code spec fs with Arg.Bad s -> configurate s);
if !(flags.help) then (Arg.usage spec ("Options for "^code^":"); exit 0);
let (s,w) = P.get_sw p in
let c = context signature (Trs.funs (Trs.union s w)) in
L.run (
Made.run c (encode s w >>= fun phi ->
Made.liftm (L.solve ~solver:c.solver phi) >>= function
| None -> return None
| Some ass ->
decode ass s w >>= fun (s',w') ->
decode_af ass s w >>= fun af ->
decode_prec ass s w >>= fun prec ->
decode_status ass s w >>= fun status ->
return (Some (make af p (P.set_sw s' w' p) prec status))))
;;
let (>>=) = M.(>>=);;
let solve fs p = M.get >>= fun s -> M.return (solve s fs p);;
|
88f7662ac0f849eff0acc01c801a25fa7f6ab32063f8605072b5ee457589b720 | chenyukang/eopl | cps-in-lang.scm | (module cps-in-lang (lib "eopl.ss" "eopl")
input language for the CPS converter .
(require "drscheme-init.scm")
(provide (all-defined))
;;;;;;;;;;;;;;;; grammatical specification ;;;;;;;;;;;;;;;;
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (number) const-exp)
(expression
("-" "(" expression "," expression ")")
diff-exp)
(expression
("+" "(" (separated-list expression ",") ")")
sum-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression
("letrec"
(arbno identifier "(" (arbno identifier) ")"
"=" expression)
"in"
expression)
letrec-exp)
(expression (identifier) var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
(expression
("proc" "(" (arbno identifier) ")" expression)
proc-exp)
(expression
("(" expression (arbno expression) ")")
call-exp)
))
;;;;;;;;;;;;;;;; sllgen boilerplate ;;;;;;;;;;;;;;;;
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
)
| null | https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/base/chapter6/cps-lang/cps-in-lang.scm | scheme | grammatical specification ;;;;;;;;;;;;;;;;
sllgen boilerplate ;;;;;;;;;;;;;;;;
| (module cps-in-lang (lib "eopl.ss" "eopl")
input language for the CPS converter .
(require "drscheme-init.scm")
(provide (all-defined))
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (number) const-exp)
(expression
("-" "(" expression "," expression ")")
diff-exp)
(expression
("+" "(" (separated-list expression ",") ")")
sum-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression
("letrec"
(arbno identifier "(" (arbno identifier) ")"
"=" expression)
"in"
expression)
letrec-exp)
(expression (identifier) var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
(expression
("proc" "(" (arbno identifier) ")" expression)
proc-exp)
(expression
("(" expression (arbno expression) ")")
call-exp)
))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
)
|
4f485dea1defa2666a3e0e0c9f9953928b91f4768b0a31c38c27ae62797f836c | ocaml-multicore/ocaml-tsan | topeval.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* The interactive toplevel loop *)
open Format
open Misc
open Parsetree
open Types
open Typedtree
open Outcometree
open Topcommon
module String = Misc.Stdlib.String
(* The table of toplevel value bindings and its accessors *)
let toplevel_value_bindings : Obj.t String.Map.t ref = ref String.Map.empty
let getvalue name =
try
String.Map.find name !toplevel_value_bindings
with Not_found ->
fatal_error (name ^ " unbound at toplevel")
let setvalue name v =
toplevel_value_bindings := String.Map.add name v !toplevel_value_bindings
let implementation_label = ""
(* To print values *)
module EvalBase = struct
let eval_ident id =
if Ident.persistent id || Ident.global id then begin
try
Symtable.get_global_value id
with Symtable.Error (Undefined_global name) ->
raise (Undefined_global name)
end else begin
let name = Translmod.toplevel_name id in
try
String.Map.find name !toplevel_value_bindings
with Not_found ->
raise (Undefined_global name)
end
end
include Topcommon.MakeEvalPrinter(EvalBase)
(* Load in-core and execute a lambda term *)
let may_trace = ref false (* Global lock on tracing *)
let load_lambda ppf lam =
if !Clflags.dump_rawlambda then fprintf ppf "%a@." Printlambda.lambda lam;
let slam = Simplif.simplify_lambda lam in
if !Clflags.dump_lambda then fprintf ppf "%a@." Printlambda.lambda slam;
let (init_code, fun_code) = Bytegen.compile_phrase slam in
if !Clflags.dump_instr then
fprintf ppf "%a%a@."
Printinstr.instrlist init_code
Printinstr.instrlist fun_code;
let (code, reloc, events) =
Emitcode.to_memory init_code fun_code
in
let can_free = (fun_code = []) in
let initial_symtable = Symtable.current_state() in
Symtable.patch_object code reloc;
Symtable.check_global_initialized reloc;
Symtable.update_global_table();
let initial_bindings = !toplevel_value_bindings in
let bytecode, closure = Meta.reify_bytecode code [| events |] None in
match
may_trace := true;
closure ()
with
| retval ->
may_trace := false;
if can_free then Meta.release_bytecode bytecode;
Result retval
| exception x ->
may_trace := false;
record_backtrace ();
if can_free then Meta.release_bytecode bytecode;
toplevel_value_bindings := initial_bindings; (* PR#6211 *)
Symtable.restore_state initial_symtable;
Exception x
(* Print the outcome of an evaluation *)
let pr_item =
Printtyp.print_items
(fun env -> function
| Sig_value(id, {val_kind = Val_reg; val_type}, _) ->
Some (outval_of_value env (getvalue (Translmod.toplevel_name id))
val_type)
| _ -> None
)
(* Execute a toplevel phrase *)
let execute_phrase print_outcome ppf phr =
match phr with
| Ptop_def sstr ->
let oldenv = !toplevel_env in
Typecore.reset_delayed_checks ();
let (str, sg, sn, shape, newenv) =
Typemod.type_toplevel_phrase oldenv sstr
in
if !Clflags.dump_typedtree then Printtyped.implementation ppf str;
let sg' = Typemod.Signature_names.simplify newenv sn sg in
ignore (Includemod.signatures ~mark:Mark_positive oldenv sg sg');
Typecore.force_delayed_checks ();
let shape = Shape.local_reduce shape in
if !Clflags.dump_shape then Shape.print ppf shape;
let lam = Translmod.transl_toplevel_definition str in
Warnings.check_fatal ();
begin try
toplevel_env := newenv;
let res = load_lambda ppf lam in
let out_phr =
match res with
| Result v ->
if print_outcome then
Printtyp.wrap_printing_env ~error:false oldenv (fun () ->
match str.str_items with
| [] -> Ophr_signature []
| _ ->
match find_eval_phrase str with
| Some (exp, _, _) ->
let outv = outval_of_value newenv v exp.exp_type in
let ty = Printtyp.tree_of_type_scheme exp.exp_type in
Ophr_eval (outv, ty)
| None -> Ophr_signature (pr_item oldenv sg'))
else Ophr_signature []
| Exception exn ->
toplevel_env := oldenv;
if exn = Out_of_memory then Gc.full_major();
let outv =
outval_of_value !toplevel_env (Obj.repr exn) Predef.type_exn
in
Ophr_exception (exn, outv)
in
!print_out_phrase ppf out_phr;
if Printexc.backtrace_status ()
then begin
match !backtrace with
| None -> ()
| Some b ->
pp_print_string ppf b;
pp_print_flush ppf ();
backtrace := None;
end;
begin match out_phr with
| Ophr_eval (_, _) | Ophr_signature _ -> true
| Ophr_exception _ -> false
end
with x ->
toplevel_env := oldenv; raise x
end
| Ptop_dir {pdir_name = {Location.txt = dir_name}; pdir_arg } ->
try_run_directive ppf dir_name pdir_arg
let execute_phrase print_outcome ppf phr =
try execute_phrase print_outcome ppf phr
with exn ->
Warnings.reset_fatal ();
raise exn
(* Additional directives for the bytecode toplevel only *)
open Cmo_format
(* Loading files *)
exception Load_failed
let check_consistency ppf filename cu =
try Env.import_crcs ~source:filename cu.cu_imports
with Persistent_env.Consistbl.Inconsistency {
unit_name = name;
inconsistent_source = user;
original_source = auth;
} ->
fprintf ppf "@[<hv 0>The files %s@ and %s@ \
disagree over interface %s@]@."
user auth name;
raise Load_failed
(* This is basically Dynlink.Bytecode.run with no digest *)
let load_compunit ic filename ppf compunit =
check_consistency ppf filename compunit;
seek_in ic compunit.cu_pos;
let code_size = compunit.cu_codesize + 8 in
let code = LongString.create code_size in
LongString.input_bytes_into code ic compunit.cu_codesize;
LongString.set code compunit.cu_codesize (Char.chr Opcodes.opRETURN);
LongString.blit_string "\000\000\000\001\000\000\000" 0
code (compunit.cu_codesize + 1) 7;
let initial_symtable = Symtable.current_state() in
Symtable.patch_object code compunit.cu_reloc;
Symtable.update_global_table();
let events =
if compunit.cu_debug = 0 then [| |]
else begin
seek_in ic compunit.cu_debug;
[| input_value ic |]
end in
begin try
may_trace := true;
let _bytecode, closure = Meta.reify_bytecode code events None in
ignore (closure ());
may_trace := false;
with exn ->
record_backtrace ();
may_trace := false;
Symtable.restore_state initial_symtable;
print_exception_outcome ppf exn;
raise Load_failed
end
let rec load_file recursive ppf name =
let filename =
try Some (Load_path.find name) with Not_found -> None
in
match filename with
| None -> fprintf ppf "Cannot find file %s.@." name; false
| Some filename ->
let ic = open_in_bin filename in
Misc.try_finally
~always:(fun () -> close_in ic)
(fun () -> really_load_file recursive ppf name filename ic)
and really_load_file recursive ppf name filename ic =
let buffer = really_input_string ic (String.length Config.cmo_magic_number) in
try
if buffer = Config.cmo_magic_number then begin
let compunit_pos = input_binary_int ic in (* Go to descriptor *)
seek_in ic compunit_pos;
let cu : compilation_unit = input_value ic in
if recursive then
List.iter
(function
| (Reloc_getglobal id, _)
when not (Symtable.is_global_defined id) ->
let file = Ident.name id ^ ".cmo" in
begin match Load_path.find_uncap file with
| exception Not_found -> ()
| file ->
if not (load_file recursive ppf file) then raise Load_failed
end
| _ -> ()
)
cu.cu_reloc;
load_compunit ic filename ppf cu;
true
end else
if buffer = Config.cma_magic_number then begin
let toc_pos = input_binary_int ic in (* Go to table of contents *)
seek_in ic toc_pos;
let lib = (input_value ic : library) in
List.iter
(fun dllib ->
let name = Dll.extract_dll_name dllib in
try Dll.open_dlls Dll.For_execution [name]
with Failure reason ->
fprintf ppf
"Cannot load required shared library %s.@.Reason: %s.@."
name reason;
raise Load_failed)
lib.lib_dllibs;
List.iter (load_compunit ic filename ppf) lib.lib_units;
true
end else begin
fprintf ppf "File %s is not a bytecode object file.@." name;
false
end
with Load_failed -> false
let init () =
let crc_intfs = Symtable.init_toplevel() in
Compmisc.init_path ();
Env.import_crcs ~source:Sys.executable_name crc_intfs;
()
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/f54002470cc6ab780963cc81b11a85a820a40819/toplevel/byte/topeval.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
The interactive toplevel loop
The table of toplevel value bindings and its accessors
To print values
Load in-core and execute a lambda term
Global lock on tracing
PR#6211
Print the outcome of an evaluation
Execute a toplevel phrase
Additional directives for the bytecode toplevel only
Loading files
This is basically Dynlink.Bytecode.run with no digest
Go to descriptor
Go to table of contents | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Format
open Misc
open Parsetree
open Types
open Typedtree
open Outcometree
open Topcommon
module String = Misc.Stdlib.String
let toplevel_value_bindings : Obj.t String.Map.t ref = ref String.Map.empty
let getvalue name =
try
String.Map.find name !toplevel_value_bindings
with Not_found ->
fatal_error (name ^ " unbound at toplevel")
let setvalue name v =
toplevel_value_bindings := String.Map.add name v !toplevel_value_bindings
let implementation_label = ""
module EvalBase = struct
let eval_ident id =
if Ident.persistent id || Ident.global id then begin
try
Symtable.get_global_value id
with Symtable.Error (Undefined_global name) ->
raise (Undefined_global name)
end else begin
let name = Translmod.toplevel_name id in
try
String.Map.find name !toplevel_value_bindings
with Not_found ->
raise (Undefined_global name)
end
end
include Topcommon.MakeEvalPrinter(EvalBase)
let load_lambda ppf lam =
if !Clflags.dump_rawlambda then fprintf ppf "%a@." Printlambda.lambda lam;
let slam = Simplif.simplify_lambda lam in
if !Clflags.dump_lambda then fprintf ppf "%a@." Printlambda.lambda slam;
let (init_code, fun_code) = Bytegen.compile_phrase slam in
if !Clflags.dump_instr then
fprintf ppf "%a%a@."
Printinstr.instrlist init_code
Printinstr.instrlist fun_code;
let (code, reloc, events) =
Emitcode.to_memory init_code fun_code
in
let can_free = (fun_code = []) in
let initial_symtable = Symtable.current_state() in
Symtable.patch_object code reloc;
Symtable.check_global_initialized reloc;
Symtable.update_global_table();
let initial_bindings = !toplevel_value_bindings in
let bytecode, closure = Meta.reify_bytecode code [| events |] None in
match
may_trace := true;
closure ()
with
| retval ->
may_trace := false;
if can_free then Meta.release_bytecode bytecode;
Result retval
| exception x ->
may_trace := false;
record_backtrace ();
if can_free then Meta.release_bytecode bytecode;
Symtable.restore_state initial_symtable;
Exception x
let pr_item =
Printtyp.print_items
(fun env -> function
| Sig_value(id, {val_kind = Val_reg; val_type}, _) ->
Some (outval_of_value env (getvalue (Translmod.toplevel_name id))
val_type)
| _ -> None
)
let execute_phrase print_outcome ppf phr =
match phr with
| Ptop_def sstr ->
let oldenv = !toplevel_env in
Typecore.reset_delayed_checks ();
let (str, sg, sn, shape, newenv) =
Typemod.type_toplevel_phrase oldenv sstr
in
if !Clflags.dump_typedtree then Printtyped.implementation ppf str;
let sg' = Typemod.Signature_names.simplify newenv sn sg in
ignore (Includemod.signatures ~mark:Mark_positive oldenv sg sg');
Typecore.force_delayed_checks ();
let shape = Shape.local_reduce shape in
if !Clflags.dump_shape then Shape.print ppf shape;
let lam = Translmod.transl_toplevel_definition str in
Warnings.check_fatal ();
begin try
toplevel_env := newenv;
let res = load_lambda ppf lam in
let out_phr =
match res with
| Result v ->
if print_outcome then
Printtyp.wrap_printing_env ~error:false oldenv (fun () ->
match str.str_items with
| [] -> Ophr_signature []
| _ ->
match find_eval_phrase str with
| Some (exp, _, _) ->
let outv = outval_of_value newenv v exp.exp_type in
let ty = Printtyp.tree_of_type_scheme exp.exp_type in
Ophr_eval (outv, ty)
| None -> Ophr_signature (pr_item oldenv sg'))
else Ophr_signature []
| Exception exn ->
toplevel_env := oldenv;
if exn = Out_of_memory then Gc.full_major();
let outv =
outval_of_value !toplevel_env (Obj.repr exn) Predef.type_exn
in
Ophr_exception (exn, outv)
in
!print_out_phrase ppf out_phr;
if Printexc.backtrace_status ()
then begin
match !backtrace with
| None -> ()
| Some b ->
pp_print_string ppf b;
pp_print_flush ppf ();
backtrace := None;
end;
begin match out_phr with
| Ophr_eval (_, _) | Ophr_signature _ -> true
| Ophr_exception _ -> false
end
with x ->
toplevel_env := oldenv; raise x
end
| Ptop_dir {pdir_name = {Location.txt = dir_name}; pdir_arg } ->
try_run_directive ppf dir_name pdir_arg
let execute_phrase print_outcome ppf phr =
try execute_phrase print_outcome ppf phr
with exn ->
Warnings.reset_fatal ();
raise exn
open Cmo_format
exception Load_failed
let check_consistency ppf filename cu =
try Env.import_crcs ~source:filename cu.cu_imports
with Persistent_env.Consistbl.Inconsistency {
unit_name = name;
inconsistent_source = user;
original_source = auth;
} ->
fprintf ppf "@[<hv 0>The files %s@ and %s@ \
disagree over interface %s@]@."
user auth name;
raise Load_failed
let load_compunit ic filename ppf compunit =
check_consistency ppf filename compunit;
seek_in ic compunit.cu_pos;
let code_size = compunit.cu_codesize + 8 in
let code = LongString.create code_size in
LongString.input_bytes_into code ic compunit.cu_codesize;
LongString.set code compunit.cu_codesize (Char.chr Opcodes.opRETURN);
LongString.blit_string "\000\000\000\001\000\000\000" 0
code (compunit.cu_codesize + 1) 7;
let initial_symtable = Symtable.current_state() in
Symtable.patch_object code compunit.cu_reloc;
Symtable.update_global_table();
let events =
if compunit.cu_debug = 0 then [| |]
else begin
seek_in ic compunit.cu_debug;
[| input_value ic |]
end in
begin try
may_trace := true;
let _bytecode, closure = Meta.reify_bytecode code events None in
ignore (closure ());
may_trace := false;
with exn ->
record_backtrace ();
may_trace := false;
Symtable.restore_state initial_symtable;
print_exception_outcome ppf exn;
raise Load_failed
end
let rec load_file recursive ppf name =
let filename =
try Some (Load_path.find name) with Not_found -> None
in
match filename with
| None -> fprintf ppf "Cannot find file %s.@." name; false
| Some filename ->
let ic = open_in_bin filename in
Misc.try_finally
~always:(fun () -> close_in ic)
(fun () -> really_load_file recursive ppf name filename ic)
and really_load_file recursive ppf name filename ic =
let buffer = really_input_string ic (String.length Config.cmo_magic_number) in
try
if buffer = Config.cmo_magic_number then begin
seek_in ic compunit_pos;
let cu : compilation_unit = input_value ic in
if recursive then
List.iter
(function
| (Reloc_getglobal id, _)
when not (Symtable.is_global_defined id) ->
let file = Ident.name id ^ ".cmo" in
begin match Load_path.find_uncap file with
| exception Not_found -> ()
| file ->
if not (load_file recursive ppf file) then raise Load_failed
end
| _ -> ()
)
cu.cu_reloc;
load_compunit ic filename ppf cu;
true
end else
if buffer = Config.cma_magic_number then begin
seek_in ic toc_pos;
let lib = (input_value ic : library) in
List.iter
(fun dllib ->
let name = Dll.extract_dll_name dllib in
try Dll.open_dlls Dll.For_execution [name]
with Failure reason ->
fprintf ppf
"Cannot load required shared library %s.@.Reason: %s.@."
name reason;
raise Load_failed)
lib.lib_dllibs;
List.iter (load_compunit ic filename ppf) lib.lib_units;
true
end else begin
fprintf ppf "File %s is not a bytecode object file.@." name;
false
end
with Load_failed -> false
let init () =
let crc_intfs = Symtable.init_toplevel() in
Compmisc.init_path ();
Env.import_crcs ~source:Sys.executable_name crc_intfs;
()
|
7e92c1077aa5861f5859def389b0b80ca90257b5bfe7cb74905b32b0f6d29818 | erlang/otp | erl_syntax_lib.erl | %% =====================================================================
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may
%% not use this file except in compliance with the License. You may obtain
%% a copy of the License at <-2.0>
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% Alternatively, you may use this file under the terms of the GNU Lesser
General Public License ( the " LGPL " ) as published by the Free Software
Foundation ; either version 2.1 , or ( at your option ) any later version .
%% If you wish to allow use of your version of this file only under the
%% terms of the LGPL, you should delete the provisions above and replace
%% them with the notice and other provisions required by the LGPL; see
%% </>. If you do not delete the provisions
%% above, a recipient may use your version of this file under the terms of
either the Apache License or the LGPL .
%%
1997 - 2006
@author < >
%% @end
%% =====================================================================
@doc Support library for abstract Erlang syntax trees .
%%
%% This module contains utility functions for working with the
%% abstract data type defined in the module {@link erl_syntax}.
%%
%% @type syntaxTree() = erl_syntax:syntaxTree(). An abstract syntax
%% tree. See the {@link erl_syntax} module for details.
-module(erl_syntax_lib).
-export([analyze_application/1, analyze_attribute/1,
analyze_export_attribute/1, analyze_file_attribute/1,
analyze_form/1, analyze_forms/1, analyze_function/1,
analyze_function_name/1, analyze_implicit_fun/1,
analyze_import_attribute/1, analyze_module_attribute/1,
analyze_record_attribute/1, analyze_record_expr/1,
analyze_record_field/1, analyze_wild_attribute/1, annotate_bindings/1,
analyze_type_application/1, analyze_type_name/1,
annotate_bindings/2, fold/3, fold_subtrees/3, foldl_listlist/3,
function_name_expansions/1, is_fail_expr/1, limit/2, limit/3,
map/2, map_subtrees/2, mapfold/3, mapfold_subtrees/3,
mapfoldl_listlist/3, new_variable_name/1, new_variable_name/2,
new_variable_names/2, new_variable_names/3, strip_comments/1,
to_comment/1, to_comment/2, to_comment/3, variables/1]).
-export_type([info_pair/0]).
%% =====================================================================
%% @spec map(Function, Tree::syntaxTree()) -> syntaxTree()
%%
%% Function = (syntaxTree()) -> syntaxTree()
%%
%% @doc Applies a function to each node of a syntax tree. The result of
%% each application replaces the corresponding original node. The order
%% of traversal is bottom-up.
%%
%% @see map_subtrees/2
-spec map(fun((erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree()),
erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
map(F, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
F(Tree);
Gs ->
Tree1 = erl_syntax:make_tree(erl_syntax:type(Tree),
[[map(F, T) || T <- G]
|| G <- Gs]),
F(erl_syntax:copy_attrs(Tree, Tree1))
end.
%% =====================================================================
, syntaxTree ( ) ) - > syntaxTree ( )
%%
%% Function = (Tree) -> Tree1
%%
%% @doc Applies a function to each immediate subtree of a syntax tree.
%% The result of each application replaces the corresponding original
%% node.
%%
@see map/2
-spec map_subtrees(fun((erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree()),
erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
map_subtrees(F, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
Tree;
Gs ->
Tree1 = erl_syntax:make_tree(erl_syntax:type(Tree),
[[F(T) || T <- G] || G <- Gs]),
erl_syntax:copy_attrs(Tree, Tree1)
end.
%% =====================================================================
%% @spec fold(Function, Start::term(), Tree::syntaxTree()) -> term()
%%
%% Function = (syntaxTree(), term()) -> term()
%%
%% @doc Folds a function over all nodes of a syntax tree. The result is
the value of ` Function(X1 , Function(X2 , ... , Start )
... ) ) ' , where ` [ X1 , X2 , ... , Xn ] ' are the nodes of
%% `Tree' in a post-order traversal.
%%
%% @see fold_subtrees/3
@see foldl_listlist/3
-spec fold(fun((erl_syntax:syntaxTree(), term()) -> term()),
term(), erl_syntax:syntaxTree()) -> term().
fold(F, S, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
F(Tree, S);
Gs ->
F(Tree, fold_1(F, S, Gs))
end.
fold_1(F, S, [L | Ls]) ->
fold_1(F, fold_2(F, S, L), Ls);
fold_1(_, S, []) ->
S.
fold_2(F, S, [T | Ts]) ->
fold_2(F, fold(F, S, T), Ts);
fold_2(_, S, []) ->
S.
%% =====================================================================
%% @spec fold_subtrees(Function, Start::term(), Tree::syntaxTree()) ->
%% term()
%%
%% Function = (syntaxTree(), term()) -> term()
%%
%% @doc Folds a function over the immediate subtrees of a syntax tree.
%% This is similar to `fold/3', but only on the immediate
%% subtrees of `Tree', in left-to-right order; it does not
%% include the root node of `Tree'.
%%
%% @see fold/3
-spec fold_subtrees(fun((erl_syntax:syntaxTree(), term()) -> term()),
term(), erl_syntax:syntaxTree()) -> term().
fold_subtrees(F, S, Tree) ->
foldl_listlist(F, S, erl_syntax:subtrees(Tree)).
%% =====================================================================
, Start::term ( ) , [ [ term ( ) ] ] ) - > term ( )
%%
%% Function = (term(), term()) -> term()
%%
%% @doc Like `lists:foldl/3', but over a list of lists.
%%
%% @see fold/3
%% @see //stdlib/lists:foldl/3
-spec foldl_listlist(fun((term(), term()) -> term()),
term(), [[term()]]) -> term().
foldl_listlist(F, S, [L | Ls]) ->
foldl_listlist(F, foldl(F, S, L), Ls);
foldl_listlist(_, S, []) ->
S.
foldl(F, S, [T | Ts]) ->
foldl(F, F(T, S), Ts);
foldl(_, S, []) ->
S.
%% =====================================================================
%% @spec mapfold(Function, Start::term(), Tree::syntaxTree()) ->
%% {syntaxTree(), term()}
%%
%% Function = (syntaxTree(), term()) -> {syntaxTree(), term()}
%%
%% @doc Combines map and fold in a single operation. This is similar to
%% `map/2', but also propagates an extra value from each
application of the ` Function ' to the next , while doing a
%% post-order traversal of the tree like `fold/3'. The value
` Start ' is passed to the first function application , and
%% the final result is the result of the last application.
%%
@see map/2
%% @see fold/3
-spec mapfold(fun((erl_syntax:syntaxTree(), term()) -> {erl_syntax:syntaxTree(), term()}),
term(), erl_syntax:syntaxTree()) -> {erl_syntax:syntaxTree(), term()}.
mapfold(F, S, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
F(Tree, S);
Gs ->
{Gs1, S1} = mapfold_1(F, S, Gs),
Tree1 = erl_syntax:make_tree(erl_syntax:type(Tree), Gs1),
F(erl_syntax:copy_attrs(Tree, Tree1), S1)
end.
mapfold_1(F, S, [L | Ls]) ->
{L1, S1} = mapfold_2(F, S, L),
{Ls1, S2} = mapfold_1(F, S1, Ls),
{[L1 | Ls1], S2};
mapfold_1(_, S, []) ->
{[], S}.
mapfold_2(F, S, [T | Ts]) ->
{T1, S1} = mapfold(F, S, T),
{Ts1, S2} = mapfold_2(F, S1, Ts),
{[T1 | Ts1], S2};
mapfold_2(_, S, []) ->
{[], S}.
%% =====================================================================
%% @spec mapfold_subtrees(Function, Start::term(),
%% Tree::syntaxTree()) -> {syntaxTree(), term()}
%%
%% Function = (syntaxTree(), term()) -> {syntaxTree(), term()}
%%
%% @doc Does a mapfold operation over the immediate subtrees of a syntax
%% tree. This is similar to `mapfold/3', but only on the
%% immediate subtrees of `Tree', in left-to-right order; it
%% does not include the root node of `Tree'.
%%
%% @see mapfold/3
-spec mapfold_subtrees(fun((erl_syntax:syntaxTree(), term()) ->
{erl_syntax:syntaxTree(), term()}),
term(), erl_syntax:syntaxTree()) ->
{erl_syntax:syntaxTree(), term()}.
mapfold_subtrees(F, S, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
{Tree, S};
Gs ->
{Gs1, S1} = mapfoldl_listlist(F, S, Gs),
Tree1 = erl_syntax:make_tree(erl_syntax:type(Tree), Gs1),
{erl_syntax:copy_attrs(Tree, Tree1), S1}
end.
%% =====================================================================
, State , [ [ term ( ) ] ] ) - >
%% {[[term()]], term()}
%%
%% Function = (term(), term()) -> {term(), term()}
%%
%% @doc Like `lists:mapfoldl/3', but over a list of lists.
%% The list of lists in the result has the same structure as the given
%% list of lists.
-spec mapfoldl_listlist(fun((term(), term()) -> {term(), term()}),
term(), [[term()]]) -> {[[term()]], term()}.
mapfoldl_listlist(F, S, [L | Ls]) ->
{L1, S1} = mapfoldl(F, S, L),
{Ls1, S2} = mapfoldl_listlist(F, S1, Ls),
{[L1 | Ls1], S2};
mapfoldl_listlist(_, S, []) ->
{[], S}.
mapfoldl(F, S, [L | Ls]) ->
{L1, S1} = F(L, S),
{Ls1, S2} = mapfoldl(F, S1, Ls),
{[L1 | Ls1], S2};
mapfoldl(_, S, []) ->
{[], S}.
%% =====================================================================
( ) ) - > set(atom ( ) )
%%
%% @type set(T) = //stdlib/sets:set(T)
%%
%% @doc Returns the names of variables occurring in a syntax tree, The
result is a set of variable names represented by atoms . Macro names
%% are not included.
%%
%% @see //stdlib/sets
-spec variables(erl_syntax:syntaxTree()) -> sets:set(atom()).
variables(Tree) ->
variables(Tree, sets:new()).
variables(T, S) ->
case erl_syntax:type(T) of
variable ->
sets:add_element(erl_syntax:variable_name(T), S);
macro ->
%% macro names are ignored, even if represented by variables
case erl_syntax:macro_arguments(T) of
none -> S;
As ->
variables_2(As, S)
end;
_ ->
case erl_syntax:subtrees(T) of
[] ->
S;
Gs ->
variables_1(Gs, S)
end
end.
variables_1([L | Ls], S) ->
variables_1(Ls, variables_2(L, S));
variables_1([], S) ->
S.
variables_2([T | Ts], S) ->
variables_2(Ts, variables(T, S));
variables_2([], S) ->
S.
-define(MINIMUM_RANGE, 100).
-define(START_RANGE_FACTOR, 100).
-define(MAX_RETRIES, 3). % retries before enlarging range
-define(ENLARGE_ENUM, 8). % range enlargement enumerator
-define(ENLARGE_DENOM, 1). % range enlargement denominator
default_variable_name(N) ->
list_to_atom("V" ++ integer_to_list(N)).
%% =====================================================================
%% @spec new_variable_name(Used::set(atom())) -> atom()
%%
%% @doc Returns an atom which is not already in the set `Used'. This is
%% equivalent to `new_variable_name(Function, Used)', where `Function'
%% maps a given integer `N' to the atom whose name consists of "`V'"
%% followed by the numeral for `N'.
%%
%% @see new_variable_name/2
-spec new_variable_name(sets:set(atom())) -> atom().
new_variable_name(S) ->
new_variable_name(fun default_variable_name/1, S).
%% =====================================================================
@spec new_variable_name(Function , Used::set(atom ( ) ) ) - > atom ( )
%%
%% Function = (integer()) -> atom()
%%
%% @doc Returns a user-named atom which is not already in the set
%% `Used'. The atom is generated by applying the given
%% `Function' to a generated integer. Integers are generated
%% using an algorithm which tries to keep the names randomly distributed
%% within a reasonably small range relative to the number of elements in
%% the set.
%%
%% This function uses the module `rand' to generate new
%% keys. The seed it uses may be initialized by calling
` rand : seed/1 ' or ` rand : seed/2 ' before this
function is first called .
%%
@see
%% @see //stdlib/sets
%% @see //stdlib/random
-spec new_variable_name(fun((integer()) -> atom()), sets:set(atom())) -> atom().
new_variable_name(F, S) ->
R = start_range(S),
new_variable_name(R, F, S).
new_variable_name(R, F, S) ->
new_variable_name(generate(R, R), R, 0, F, S).
new_variable_name(N, R, T, F, S) when T < ?MAX_RETRIES ->
A = F(N),
case sets:is_element(A, S) of
true ->
new_variable_name(generate(N, R), R, T + 1, F, S);
false ->
A
end;
new_variable_name(N, R, _T, F, S) ->
%% Too many retries - enlarge the range and start over.
R1 = (R * ?ENLARGE_ENUM) div ?ENLARGE_DENOM,
new_variable_name(generate(N, R1), R1, 0, F, S).
%% Note that we assume that it is very cheap to take the size of
%% the given set. This should be valid for the stdlib
%% implementation of `sets'.
start_range(S) ->
erlang:max(sets:size(S) * ?START_RANGE_FACTOR, ?MINIMUM_RANGE).
%% The previous number might or might not be used to compute the
%% next number to be tried. It is currently not used.
%%
%% It is important that this function does not generate values in
%% order, but (pseudo-)randomly distributed over the range.
generate(_Key, Range) ->
_ = case rand:export_seed() of
undefined ->
rand:seed(exsplus, {753,8,73});
_ ->
ok
end,
rand:uniform(Range). % works well
%% =====================================================================
( ) , Used::set(atom ( ) ) ) - > [ atom ( ) ]
%%
@doc Like ` ' , but generates a list of
%% `N' new names.
%%
@see
-spec new_variable_names(integer(), sets:set(atom())) -> [atom()].
new_variable_names(N, S) ->
new_variable_names(N, fun default_variable_name/1, S).
%% =====================================================================
( ) , Function ,
%% Used::set(atom())) -> [atom()]
%%
%% Function = (integer()) -> atom()
%%
%% @doc Like `new_variable_name/2', but generates a list of
%% `N' new names.
%%
%% @see new_variable_name/2
-spec new_variable_names(integer(), fun((integer()) -> atom()), sets:set(atom())) ->
[atom()].
new_variable_names(N, F, S) when is_integer(N) ->
R = start_range(S),
new_variable_names(N, [], R, F, S).
new_variable_names(N, Names, R, F, S) when N > 0 ->
Name = new_variable_name(R, F, S),
S1 = sets:add_element(Name, S),
new_variable_names(N - 1, [Name | Names], R, F, S1);
new_variable_names(0, Names, _, _, _) ->
Names.
%% =====================================================================
%% @spec annotate_bindings(Tree::syntaxTree(),
%% Bindings::ordset(atom())) -> syntaxTree()
%%
%% @type ordset(T) = //stdlib/ordsets:ordset(T)
%%
%% @doc Adds or updates annotations on nodes in a syntax tree.
%% `Bindings' specifies the set of bound variables in the
%% environment of the top level node. The following annotations are
%% affected:
%% <ul>
< li>`{env , Vars } ' , representing the input environment
%% of the subtree.</li>
%%
< li>`{bound , Vars } ' , representing the variables that
%% are bound in the subtree.</li>
%%
< li>`{free , Vars } ' , representing the free variables in
the subtree.</li >
%% </ul>
` Bindings ' and ` Vars ' are ordered - set lists
%% (cf. module `ordsets') of atoms representing variable
%% names.
%%
%% @see annotate_bindings/1
%% @see //stdlib/ordsets
-spec annotate_bindings(erl_syntax:syntaxTree(), ordsets:ordset(atom())) ->
erl_syntax:syntaxTree().
annotate_bindings(Tree, Env) ->
{Tree1, _, _} = vann(Tree, Env),
Tree1.
%% =====================================================================
%% @spec annotate_bindings(Tree::syntaxTree()) -> syntaxTree()
%%
%% @doc Adds or updates annotations on nodes in a syntax tree.
%% Equivalent to `annotate_bindings(Tree, Bindings)' where
%% the top-level environment `Bindings' is taken from the
%% annotation `{env, Bindings}' on the root node of
%% `Tree'. An exception is thrown if no such annotation
%% should exist.
%%
%% @see annotate_bindings/2
-spec annotate_bindings(erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
annotate_bindings(Tree) ->
As = erl_syntax:get_ann(Tree),
case lists:keyfind(env, 1, As) of
{env, InVars} ->
annotate_bindings(Tree, InVars);
_ ->
erlang:error(badarg)
end.
vann(Tree, Env) ->
case erl_syntax:type(Tree) of
variable ->
%% Variable use
Bound = [],
Free = [erl_syntax:variable_name(Tree)],
{ann_bindings(Tree, Env, Bound, Free), Bound, Free};
match_expr ->
vann_match_expr(Tree, Env);
case_expr ->
vann_case_expr(Tree, Env);
if_expr ->
vann_if_expr(Tree, Env);
receive_expr ->
vann_receive_expr(Tree, Env);
catch_expr ->
vann_catch_expr(Tree, Env);
try_expr ->
vann_try_expr(Tree, Env);
function ->
vann_function(Tree, Env);
fun_expr ->
vann_fun_expr(Tree, Env);
named_fun_expr ->
vann_named_fun_expr(Tree, Env);
list_comp ->
vann_list_comp(Tree, Env);
binary_comp ->
vann_binary_comp(Tree, Env);
generator ->
vann_generator(Tree, Env);
binary_generator ->
vann_binary_generator(Tree, Env);
block_expr ->
vann_block_expr(Tree, Env);
macro ->
vann_macro(Tree, Env);
_Type ->
F = vann_list_join(Env),
{Tree1, {Bound, Free}} = mapfold_subtrees(F, {[], []},
Tree),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}
end.
vann_list_join(Env) ->
fun (T, {Bound, Free}) ->
{T1, Bound1, Free1} = vann(T, Env),
{T1, {ordsets:union(Bound, Bound1),
ordsets:union(Free, Free1)}}
end.
vann_list(Ts, Env) ->
lists:mapfoldl(vann_list_join(Env), {[], []}, Ts).
vann_function(Tree, Env) ->
Cs = erl_syntax:function_clauses(Tree),
{Cs1, {_, Free}} = vann_clauses(Cs, Env),
N = erl_syntax:function_name(Tree),
{N1, _, _} = vann(N, Env),
Tree1 = rewrite(Tree, erl_syntax:function(N1, Cs1)),
Bound = [],
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_fun_expr(Tree, Env) ->
Cs = erl_syntax:fun_expr_clauses(Tree),
{Cs1, {_, Free}} = vann_clauses(Cs, Env),
Tree1 = rewrite(Tree, erl_syntax:fun_expr(Cs1)),
Bound = [],
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_named_fun_expr(Tree, Env) ->
N = erl_syntax:named_fun_expr_name(Tree),
NBound = [erl_syntax:variable_name(N)],
NFree = [],
N1 = ann_bindings(N, Env, NBound, NFree),
Env1 = ordsets:union(Env, NBound),
Cs = erl_syntax:named_fun_expr_clauses(Tree),
{Cs1, {_, Free}} = vann_clauses(Cs, Env1),
Tree1 = rewrite(Tree, erl_syntax:named_fun_expr(N1,Cs1)),
Bound = [],
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_match_expr(Tree, Env) ->
E = erl_syntax:match_expr_body(Tree),
{E1, Bound1, Free1} = vann(E, Env),
Env1 = ordsets:union(Env, Bound1),
P = erl_syntax:match_expr_pattern(Tree),
{P1, Bound2, Free2} = vann_pattern(P, Env1),
Bound = ordsets:union(Bound1, Bound2),
Free = ordsets:union(Free1, Free2),
Tree1 = rewrite(Tree, erl_syntax:match_expr(P1, E1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_case_expr(Tree, Env) ->
E = erl_syntax:case_expr_argument(Tree),
{E1, Bound1, Free1} = vann(E, Env),
Env1 = ordsets:union(Env, Bound1),
Cs = erl_syntax:case_expr_clauses(Tree),
{Cs1, {Bound2, Free2}} = vann_clauses(Cs, Env1),
Bound = ordsets:union(Bound1, Bound2),
Free = ordsets:union(Free1, Free2),
Tree1 = rewrite(Tree, erl_syntax:case_expr(E1, Cs1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_if_expr(Tree, Env) ->
Cs = erl_syntax:if_expr_clauses(Tree),
{Cs1, {Bound, Free}} = vann_clauses(Cs, Env),
Tree1 = rewrite(Tree, erl_syntax:if_expr(Cs1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_catch_expr(Tree, Env) ->
E = erl_syntax:catch_expr_body(Tree),
{E1, _, Free} = vann(E, Env),
Tree1 = rewrite(Tree, erl_syntax:catch_expr(E1)),
Bound = [],
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_try_expr(Tree, Env) ->
Es = erl_syntax:try_expr_body(Tree),
{Es1, {Bound1, Free1}} = vann_body(Es, Env),
Cs = erl_syntax:try_expr_clauses(Tree),
%% bindings in the body should be available in the success case,
{Cs1, {_, Free2}} = vann_clauses(Cs, ordsets:union(Env, Bound1)),
Hs = erl_syntax:try_expr_handlers(Tree),
{Hs1, {_, Free3}} = vann_clauses(Hs, Env),
%% the after part does not export anything, yet; this might change
As = erl_syntax:try_expr_after(Tree),
{As1, {_, Free4}} = vann_body(As, Env),
Tree1 = rewrite(Tree, erl_syntax:try_expr(Es1, Cs1, Hs1, As1)),
Bound = [],
Free = ordsets:union(Free1, ordsets:union(Free2, ordsets:union(Free3, Free4))),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_receive_expr(Tree, Env) ->
%% The timeout action is treated as an extra clause.
%% Bindings in the expiry expression are local only.
Cs = erl_syntax:receive_expr_clauses(Tree),
Es = erl_syntax:receive_expr_action(Tree),
C = erl_syntax:clause([], Es),
{[C1 | Cs1], {Bound, Free1}} = vann_clauses([C | Cs], Env),
Es1 = erl_syntax:clause_body(C1),
{T1, _, Free2} = case erl_syntax:receive_expr_timeout(Tree) of
none ->
{none, [], []};
T ->
vann(T, Env)
end,
Free = ordsets:union(Free1, Free2),
Tree1 = rewrite(Tree, erl_syntax:receive_expr(Cs1, T1, Es1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_list_comp(Tree, Env) ->
Es = erl_syntax:list_comp_body(Tree),
{Es1, {Bound1, Free1}} = vann_list_comp_body(Es, Env),
Env1 = ordsets:union(Env, Bound1),
T = erl_syntax:list_comp_template(Tree),
{T1, _, Free2} = vann(T, Env1),
Free = ordsets:union(Free1, ordsets:subtract(Free2, Bound1)),
Bound = [],
Tree1 = rewrite(Tree, erl_syntax:list_comp(T1, Es1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_list_comp_body_join() ->
fun (T, {Env, Bound, Free}) ->
{T1, Bound1, Free1} = case erl_syntax:type(T) of
binary_generator ->
vann_binary_generator(T,Env);
generator ->
vann_generator(T, Env);
_ ->
%% Bindings in filters are not
%% exported to the rest of the
%% body.
{T2, _, Free2} = vann(T, Env),
{T2, [], Free2}
end,
Env1 = ordsets:union(Env, Bound1),
{T1, {Env1, ordsets:union(Bound, Bound1),
ordsets:union(Free,
ordsets:subtract(Free1, Bound))}}
end.
vann_list_comp_body(Ts, Env) ->
F = vann_list_comp_body_join(),
{Ts1, {_, Bound, Free}} = lists:mapfoldl(F, {Env, [], []}, Ts),
{Ts1, {Bound, Free}}.
vann_binary_comp(Tree, Env) ->
Es = erl_syntax:binary_comp_body(Tree),
{Es1, {Bound1, Free1}} = vann_binary_comp_body(Es, Env),
Env1 = ordsets:union(Env, Bound1),
T = erl_syntax:binary_comp_template(Tree),
{T1, _, Free2} = vann(T, Env1),
Free = ordsets:union(Free1, ordsets:subtract(Free2, Bound1)),
Bound = [],
Tree1 = rewrite(Tree, erl_syntax:binary_comp(T1, Es1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_binary_comp_body_join() ->
fun (T, {Env, Bound, Free}) ->
{T1, Bound1, Free1} = case erl_syntax:type(T) of
binary_generator ->
vann_binary_generator(T, Env);
generator ->
vann_generator(T, Env);
_ ->
%% Bindings in filters are not
%% exported to the rest of the
%% body.
{T2, _, Free2} = vann(T, Env),
{T2, [], Free2}
end,
Env1 = ordsets:union(Env, Bound1),
{T1, {Env1, ordsets:union(Bound, Bound1),
ordsets:union(Free,
ordsets:subtract(Free1, Bound))}}
end.
vann_binary_comp_body(Ts, Env) ->
F = vann_binary_comp_body_join(),
{Ts1, {_, Bound, Free}} = lists:mapfoldl(F, {Env, [], []}, Ts),
{Ts1, {Bound, Free}}.
%% In list comprehension generators, the pattern variables are always
%% viewed as new occurrences, shadowing whatever is in the input
%% environment (thus, the pattern contains no variable uses, only
%% bindings). Bindings in the generator body are not exported.
vann_generator(Tree, Env) ->
P = erl_syntax:generator_pattern(Tree),
{P1, Bound, _} = vann_pattern(P, []),
E = erl_syntax:generator_body(Tree),
{E1, _, Free} = vann(E, Env),
Tree1 = rewrite(Tree, erl_syntax:generator(P1, E1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_binary_generator(Tree, Env) ->
P = erl_syntax:binary_generator_pattern(Tree),
{P1, Bound, _} = vann_pattern(P, Env),
E = erl_syntax:binary_generator_body(Tree),
{E1, _, Free} = vann(E, Env),
Tree1 = rewrite(Tree, erl_syntax:binary_generator(P1, E1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_block_expr(Tree, Env) ->
Es = erl_syntax:block_expr_body(Tree),
{Es1, {Bound, Free}} = vann_body(Es, Env),
Tree1 = rewrite(Tree, erl_syntax:block_expr(Es1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_body_join() ->
fun (T, {Env, Bound, Free}) ->
{T1, Bound1, Free1} = vann(T, Env),
Env1 = ordsets:union(Env, Bound1),
{T1, {Env1, ordsets:union(Bound, Bound1),
ordsets:union(Free,
ordsets:subtract(Free1, Bound))}}
end.
vann_body(Ts, Env) ->
{Ts1, {_, Bound, Free}} = lists:mapfoldl(vann_body_join(),
{Env, [], []}, Ts),
{Ts1, {Bound, Free}}.
Macro names must be ignored even if they happen to be variables ,
%% lexically speaking.
vann_macro(Tree, Env) ->
{As, {Bound, Free}} = case erl_syntax:macro_arguments(Tree) of
none ->
{none, {[], []}};
As1 ->
vann_list(As1, Env)
end,
N = erl_syntax:macro_name(Tree),
Tree1 = rewrite(Tree, erl_syntax:macro(N, As)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_pattern(Tree, Env) ->
case erl_syntax:type(Tree) of
variable ->
V = erl_syntax:variable_name(Tree),
case ordsets:is_element(V, Env) of
true ->
%% Variable use
Bound = [],
Free = [V],
{ann_bindings(Tree, Env, Bound, Free), Bound, Free};
false ->
%% Variable binding
Bound = [V],
Free = [],
{ann_bindings(Tree, Env, Bound, Free), Bound, Free}
end;
match_expr ->
pattern
P = erl_syntax:match_expr_pattern(Tree),
{P1, Bound1, Free1} = vann_pattern(P, Env),
E = erl_syntax:match_expr_body(Tree),
{E1, Bound2, Free2} = vann_pattern(E, Env),
Bound = ordsets:union(Bound1, Bound2),
Free = ordsets:union(Free1, Free2),
Tree1 = rewrite(Tree, erl_syntax:match_expr(P1, E1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free};
macro ->
%% The macro name must be ignored. The arguments are treated
%% as patterns.
{As, {Bound, Free}} =
case erl_syntax:macro_arguments(Tree) of
none ->
{none, {[], []}};
As1 ->
vann_patterns(As1, Env)
end,
N = erl_syntax:macro_name(Tree),
Tree1 = rewrite(Tree, erl_syntax:macro(N, As)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free};
_Type ->
F = vann_patterns_join(Env),
{Tree1, {Bound, Free}} = mapfold_subtrees(F, {[], []},
Tree),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}
end.
vann_patterns_join(Env) ->
fun (T, {Bound, Free}) ->
{T1, Bound1, Free1} = vann_pattern(T, Env),
{T1, {ordsets:union(Bound, Bound1),
ordsets:union(Free, Free1)}}
end.
vann_patterns(Ps, Env) ->
lists:mapfoldl(vann_patterns_join(Env), {[], []}, Ps).
vann_clause(C, Env) ->
{Ps, {Bound1, Free1}} = vann_patterns(erl_syntax:clause_patterns(C),
Env),
Env1 = ordsets:union(Env, Bound1),
%% Guards cannot add bindings
{G1, _, Free2} = case erl_syntax:clause_guard(C) of
none ->
{none, [], []};
G ->
vann(G, Env1)
end,
{Es, {Bound2, Free3}} = vann_body(erl_syntax:clause_body(C), Env1),
Bound = ordsets:union(Bound1, Bound2),
Free = ordsets:union(Free1,
ordsets:subtract(ordsets:union(Free2, Free3),
Bound1)),
Tree1 = rewrite(C, erl_syntax:clause(Ps, G1, Es)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_clauses_join(Env) ->
fun (C, {Bound, Free}) ->
{C1, Bound1, Free1} = vann_clause(C, Env),
{C1, {ordsets:intersection(Bound, Bound1),
ordsets:union(Free, Free1)}}
end.
vann_clauses([C | Cs], Env) ->
{C1, Bound, Free} = vann_clause(C, Env),
{Cs1, BF} = lists:mapfoldl(vann_clauses_join(Env), {Bound, Free}, Cs),
{[C1 | Cs1], BF};
vann_clauses([], _Env) ->
{[], {[], []}}.
ann_bindings(Tree, Env, Bound, Free) ->
As0 = erl_syntax:get_ann(Tree),
As1 = [{env, Env},
{bound, Bound},
{free, Free}
| delete_binding_anns(As0)],
erl_syntax:set_ann(Tree, As1).
delete_binding_anns([{env, _} | As]) ->
delete_binding_anns(As);
delete_binding_anns([{bound, _} | As]) ->
delete_binding_anns(As);
delete_binding_anns([{free, _} | As]) ->
delete_binding_anns(As);
delete_binding_anns([A | As]) ->
[A | delete_binding_anns(As)];
delete_binding_anns([]) ->
[].
%% =====================================================================
( ) ) - > boolean ( )
%%
%% @doc Returns `true' if `Tree' represents an
%% expression which never terminates normally. Note that the reverse
%% does not apply. Currently, the detected cases are calls to
` exit/1 ' , ` throw/1 ' ,
` erlang : error/1 ' and ` erlang : error/2 ' .
%%
@see //erts / erlang : exit/1
%% @see //erts/erlang:throw/1
%% @see //erts/erlang:error/1
@see //erts / erlang : error/2
-spec is_fail_expr(erl_syntax:syntaxTree()) -> boolean().
is_fail_expr(E) ->
case erl_syntax:type(E) of
application ->
N = length(erl_syntax:application_arguments(E)),
F = erl_syntax:application_operator(E),
case catch {ok, analyze_function_name(F)} of
syntax_error ->
false;
{ok, exit} when N =:= 1 ->
true;
{ok, throw} when N =:= 1 ->
true;
{ok, {erlang, exit}} when N =:= 1 ->
true;
{ok, {erlang, throw}} when N =:= 1 ->
true;
{ok, {erlang, error}} when N =:= 1 ->
true;
{ok, {erlang, error}} when N =:= 2 ->
true;
{ok, {erlang, fault}} when N =:= 1 ->
true;
{ok, {erlang, fault}} when N =:= 2 ->
true;
_ ->
false
end;
_ ->
false
end.
%% =====================================================================
%% @spec analyze_forms(Forms) -> [{Key, term()}]
%%
%% Forms = syntaxTree() | [syntaxTree()]
%% Key = attributes | errors | exports | functions | imports
%% | module | records | warnings
%%
%% @doc Analyzes a sequence of "program forms". The given
%% `Forms' may be a single syntax tree of type
%% `form_list', or a list of "program form" syntax trees. The
%% returned value is a list of pairs `{Key, Info}', where
%% each value of `Key' occurs at most once in the list; the
%% absence of a particular key indicates that there is no well-defined
%% value for that key.
%%
%% Each entry in the resulting list contains the following
%% corresponding information about the program forms:
%% <dl>
%% <dt>`{attributes, Attributes}'</dt>
%% <dd><ul>
%% <li>`Attributes = [{atom(), term()}]'</li>
%% </ul>
%% `Attributes' is a list of pairs representing the
%% names and corresponding values of all so-called "wild"
%% attributes (as e.g. "`-compile(...)'") occurring in
%% `Forms' (cf. `analyze_wild_attribute/1').
%% We do not guarantee that each name occurs at most once in the
list . The order of listing is not defined.</dd >
%%
%% <dt>`{errors, Errors}'</dt>
%% <dd><ul>
%% <li>`Errors = [term()]'</li>
%% </ul>
%% `Errors' is the list of error descriptors of all
%% `error_marker' nodes that occur in
` Forms ' . The order of listing is not defined.</dd >
%%
%% <dt>`{exports, Exports}'</dt>
%% <dd><ul>
%% <li>`Exports = [FunctionName]'</li>
%% <li>`FunctionName = atom()
%% | {atom(), integer()}
| { ModuleName , FunctionName}'</li >
%% <li>`ModuleName = atom()'</li>
%% </ul>
%% `Exports' is a list of representations of those
%% function names that are listed by export declaration attributes
%% in `Forms' (cf.
%% `analyze_export_attribute/1'). We do not guarantee
%% that each name occurs at most once in the list. The order of
listing is not defined.</dd >
%%
%% <dt>`{functions, Functions}'</dt>
%% <dd><ul>
< li>`Functions = [ { atom ( ) , integer()}]'</li >
%% </ul>
%% `Functions' is a list of the names of the functions
%% that are defined in `Forms' (cf.
%% `analyze_function/1'). We do not guarantee that each
%% name occurs at most once in the list. The order of listing is
not defined.</dd >
%%
%% <dt>`{imports, Imports}'</dt>
%% <dd><ul>
%% <li>`Imports = [{Module, Names}]'</li>
= atom()'</li >
%% <li>`Names = [FunctionName]'</li>
%% <li>`FunctionName = atom()
%% | {atom(), integer()}
| { ModuleName , FunctionName}'</li >
%% <li>`ModuleName = atom()'</li>
%% </ul>
%% `Imports' is a list of pairs representing those
%% module names and corresponding function names that are listed
%% by import declaration attributes in `Forms' (cf.
%% `analyze_import_attribute/1'), where each
%% `Module' occurs at most once in
%% `Imports'. We do not guarantee that each name occurs
%% at most once in the lists of function names. The order of
listing is not defined.</dd >
%%
%% <dt>`{module, ModuleName}'</dt>
%% <dd><ul>
%% <li>`ModuleName = atom()'</li>
%% </ul>
` ModuleName ' is the name declared by a module
%% attribute in `Forms'. If no module name is defined
%% in `Forms', the result will contain no entry for the
%% `module' key. If multiple module name declarations
should occur , all but the first will be ignored.</dd >
%%
%% <dt>`{records, Records}'</dt>
%% <dd><ul>
%% <li>`Records = [{atom(), Fields}]'</li>
%% <li>`Fields = [{atom(), {Default, Type}}]'</li>
%% <li>`Default = none | syntaxTree()'</li>
%% <li>`Type = none | syntaxTree()'</li>
%% </ul>
%% `Records' is a list of pairs representing the names
%% and corresponding field declarations of all record declaration
%% attributes occurring in `Forms'. For fields declared
%% without a default value, the corresponding value for
%% `Default' is the atom `none'. Similarly, for fields declared
%% without a type, the corresponding value for `Type' is the
%% atom `none' (cf.
%% `analyze_record_attribute/1'). We do not guarantee
%% that each record name occurs at most once in the list. The
order of listing is not defined.</dd >
%%
%% <dt>`{warnings, Warnings}'</dt>
%% <dd><ul>
%% <li>`Warnings = [term()]'</li>
%% </ul>
%% `Warnings' is the list of error descriptors of all
%% `warning_marker' nodes that occur in
` Forms ' . The order of listing is not defined.</dd >
%% </dl>
%%
%% The evaluation throws `syntax_error' if an ill-formed
Erlang construct is encountered .
%%
%% @see analyze_wild_attribute/1
%% @see analyze_export_attribute/1
@see analyze_function/1
%% @see analyze_import_attribute/1
%% @see analyze_record_attribute/1
@see erl_syntax : error_marker_info/1
%% @see erl_syntax:warning_marker_info/1
-type key() :: 'attributes' | 'errors' | 'exports' | 'functions' | 'imports'
| 'module' | 'records' | 'warnings'.
-type info_pair() :: {key(), term()}.
-spec analyze_forms(erl_syntax:forms()) -> [info_pair()].
analyze_forms(Forms) when is_list(Forms) ->
finfo_to_list(lists:foldl(fun collect_form/2, new_finfo(), Forms));
analyze_forms(Forms) ->
analyze_forms(
erl_syntax:form_list_elements(
erl_syntax:flatten_form_list(Forms))).
collect_form(Node, Info) ->
case analyze_form(Node) of
{attribute, {Name, Data}} ->
collect_attribute(Name, Data, Info);
{attribute, preprocessor} ->
Info;
{function, Name} ->
finfo_add_function(Name, Info);
{error_marker, Data} ->
finfo_add_error(Data, Info);
{warning_marker, Data} ->
finfo_add_warning(Data, Info);
_ ->
Info
end.
collect_attribute(module, M, Info) ->
finfo_set_module(M, Info);
collect_attribute(export, L, Info) ->
finfo_add_exports(L, Info);
collect_attribute(import, {M, L}, Info) ->
finfo_add_imports(M, L, Info);
collect_attribute(import, M, Info) ->
finfo_add_module_import(M, Info);
collect_attribute(file, _, Info) ->
Info;
collect_attribute(record, {R, L}, Info) ->
finfo_add_record(R, L, Info);
collect_attribute(N, V, Info) ->
finfo_add_attribute(N, V, Info).
%% Abstract datatype for collecting module information.
-record(forms, {module = none :: 'none' | {'value', atom()},
exports = [] :: [{atom(), arity()}],
module_imports = [] :: [atom()],
imports = [] :: [{atom(), [{atom(), arity()}]}],
attributes = [] :: [{atom(), term()}],
records = [] :: [{atom(), [{atom(),
field_default(),
field_type()}]}],
errors = [] :: [term()],
warnings = [] :: [term()],
functions = [] :: [{atom(), arity()}]}).
-type field_default() :: 'none' | erl_syntax:syntaxTree().
-type field_type() :: 'none' | erl_syntax:syntaxTree().
new_finfo() ->
#forms{}.
finfo_set_module(Name, Info) ->
case Info#forms.module of
none ->
Info#forms{module = {value, Name}};
{value, _} ->
Info
end.
finfo_add_exports(L, Info) ->
Info#forms{exports = L ++ Info#forms.exports}.
finfo_add_module_import(M, Info) ->
Info#forms{module_imports = [M | Info#forms.module_imports]}.
finfo_add_imports(M, L, Info) ->
Es = Info#forms.imports,
case lists:keyfind(M, 1, Es) of
{_, L1} ->
Es1 = lists:keyreplace(M, 1, Es, {M, L ++ L1}),
Info#forms{imports = Es1};
false ->
Info#forms{imports = [{M, L} | Es]}
end.
finfo_add_attribute(Name, Val, Info) ->
Info#forms{attributes = [{Name, Val} | Info#forms.attributes]}.
finfo_add_record(R, L, Info) ->
Info#forms{records = [{R, L} | Info#forms.records]}.
finfo_add_error(R, Info) ->
Info#forms{errors = [R | Info#forms.errors]}.
finfo_add_warning(R, Info) ->
Info#forms{warnings = [R | Info#forms.warnings]}.
finfo_add_function(F, Info) ->
Info#forms{functions = [F | Info#forms.functions]}.
finfo_to_list(Info) ->
[{Key, Value}
|| {Key, {value, Value}} <-
[{module, Info#forms.module},
{exports, list_value(Info#forms.exports)},
{imports, list_value(Info#forms.imports)},
{module_imports, list_value(Info#forms.module_imports)},
{attributes, list_value(Info#forms.attributes)},
{records, list_value(Info#forms.records)},
{errors, list_value(Info#forms.errors)},
{warnings, list_value(Info#forms.warnings)},
{functions, list_value(Info#forms.functions)}
]].
list_value([]) ->
none;
list_value(List) ->
{value, List}.
%% =====================================================================
%% @spec analyze_form(Node::syntaxTree()) -> {atom(), term()} | atom()
%%
@doc Analyzes a " source code form " node . If ` Node ' is a
%% "form" type (cf. `erl_syntax:is_form/1'), the returned
%% value is a tuple `{Type, Info}' where `Type' is
%% the node type and `Info' depends on `Type', as
%% follows:
%% <dl>
%% <dt>`{attribute, Info}'</dt>
%%
%% <dd>where `Info = analyze_attribute(Node)'.</dd>
%%
%% <dt>`{error_marker, Info}'</dt>
%%
%% <dd>where `Info =
%% erl_syntax:error_marker_info(Node)'.</dd>
%%
%% <dt>`{function, Info}'</dt>
%%
%% <dd>where `Info = analyze_function(Node)'.</dd>
%%
%% <dt>`{warning_marker, Info}'</dt>
%%
%% <dd>where `Info =
%% erl_syntax:warning_marker_info(Node)'.</dd>
%% </dl>
%% For other types of forms, only the node type is returned.
%%
%% The evaluation throws `syntax_error' if
` Node ' is not well - formed .
%%
%% @see analyze_attribute/1
@see analyze_function/1
%% @see erl_syntax:is_form/1
@see erl_syntax : error_marker_info/1
%% @see erl_syntax:warning_marker_info/1
-spec analyze_form(erl_syntax:syntaxTree()) -> {atom(), term()} | atom().
analyze_form(Node) ->
case erl_syntax:type(Node) of
attribute ->
{attribute, analyze_attribute(Node)};
function ->
{function, analyze_function(Node)};
error_marker ->
{error_marker, erl_syntax:error_marker_info(Node)};
warning_marker ->
{warning_marker, erl_syntax:warning_marker_info(Node)};
_ ->
case erl_syntax:is_form(Node) of
true ->
erl_syntax:type(Node);
false ->
throw(syntax_error)
end
end.
%% =====================================================================
%% @spec analyze_attribute(Node::syntaxTree()) ->
%% preprocessor | {atom(), atom()}
%%
%% @doc Analyzes an attribute node. If `Node' represents a
%% preprocessor directive, the atom `preprocessor' is
%% returned. Otherwise, if `Node' represents a module
%% attribute "`-Name...'", a tuple `{Name,
%% Info}' is returned, where `Info' depends on
%% `Name', as follows:
%% <dl>
%% <dt>`{module, Info}'</dt>
%%
%% <dd>where `Info =
%% analyze_module_attribute(Node)'.</dd>
%%
< dt>`{export , Info}'</dt >
%%
%% <dd>where `Info =
%% analyze_export_attribute(Node)'.</dd>
%%
< dt>`{import , Info}'</dt >
%%
%% <dd>where `Info =
%% analyze_import_attribute(Node)'.</dd>
%%
%% <dt>`{file, Info}'</dt>
%%
%% <dd>where `Info =
%% analyze_file_attribute(Node)'.</dd>
%%
%% <dt>`{record, Info}'</dt>
%%
%% <dd>where `Info =
%% analyze_record_attribute(Node)'.</dd>
%%
%% <dt>`{Name, Info}'</dt>
%%
%% <dd>where `{Name, Info} =
%% analyze_wild_attribute(Node)'.</dd>
%% </dl>
%% The evaluation throws `syntax_error' if `Node'
%% does not represent a well-formed module attribute.
%%
@see analyze_module_attribute/1
%% @see analyze_export_attribute/1
%% @see analyze_import_attribute/1
%% @see analyze_file_attribute/1
%% @see analyze_record_attribute/1
%% @see analyze_wild_attribute/1
-spec analyze_attribute(erl_syntax:syntaxTree()) ->
'preprocessor' | {atom(), term()}. % XXX: underspecified
analyze_attribute(Node) ->
Name = erl_syntax:attribute_name(Node),
case erl_syntax:type(Name) of
atom ->
case erl_syntax:atom_value(Name) of
define -> preprocessor;
undef -> preprocessor;
include -> preprocessor;
include_lib -> preprocessor;
ifdef -> preprocessor;
ifndef -> preprocessor;
'if' -> preprocessor;
elif -> preprocessor;
'else' -> preprocessor;
endif -> preprocessor;
A ->
{A, analyze_attribute(A, Node)}
end;
_ ->
throw(syntax_error)
end.
analyze_attribute(module, Node) ->
analyze_module_attribute(Node);
analyze_attribute(export, Node) ->
analyze_export_attribute(Node);
analyze_attribute(import, Node) ->
analyze_import_attribute(Node);
analyze_attribute(file, Node) ->
analyze_file_attribute(Node);
analyze_attribute(record, Node) ->
analyze_record_attribute(Node);
analyze_attribute(_, Node) ->
%% A "wild" attribute (such as e.g. a `compile' directive).
{_, Info} = analyze_wild_attribute(Node),
Info.
%% =====================================================================
( ) ) - >
%% Name::atom() | {Name::atom(), Variables::[atom()]}
%%
%% @doc Returns the module name and possible parameters declared by a
%% module attribute. If the attribute is a plain module declaration such
%% as `-module(name)', the result is the module name. If the attribute
%% is a parameterized module declaration, the result is a tuple
%% containing the module name and a list of the parameter variable
%% names.
%%
%% The evaluation throws `syntax_error' if `Node' does not represent a
%% well-formed module attribute.
%%
%% @see analyze_attribute/1
-spec analyze_module_attribute(erl_syntax:syntaxTree()) ->
atom() | {atom(), [atom()]}.
analyze_module_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[M] ->
module_name_to_atom(M);
[M, L] ->
M1 = module_name_to_atom(M),
L1 = analyze_variable_list(L),
{M1, L1};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
analyze_variable_list(Node) ->
case erl_syntax:is_proper_list(Node) of
true ->
[erl_syntax:variable_name(V)
|| V <- erl_syntax:list_elements(Node)];
false ->
throw(syntax_error)
end.
%% =====================================================================
( ) ) - > [ FunctionName ]
%%
%% FunctionName = atom() | {atom(), integer()}
| { ModuleName , FunctionName }
ModuleName = atom ( )
%%
%% @doc Returns the list of function names declared by an export
%% attribute. We do not guarantee that each name occurs at most once in
%% the list. The order of listing is not defined.
%%
%% The evaluation throws `syntax_error' if `Node' does not represent a
%% well-formed export attribute.
%%
%% @see analyze_attribute/1
-type functionN() :: atom() | {atom(), arity()}.
-type functionName() :: functionN() | {atom(), functionN()}.
-spec analyze_export_attribute(erl_syntax:syntaxTree()) -> [functionName()].
analyze_export_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[L] ->
analyze_function_name_list(L);
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
analyze_function_name_list(Node) ->
case erl_syntax:is_proper_list(Node) of
true ->
[analyze_function_name(F)
|| F <- erl_syntax:list_elements(Node)];
false ->
throw(syntax_error)
end.
%% =====================================================================
%% @spec analyze_function_name(Node::syntaxTree()) -> FunctionName
%%
%% FunctionName = atom() | {atom(), integer()}
| { ModuleName , FunctionName }
ModuleName = atom ( )
%%
%% @doc Returns the function name represented by a syntax tree. If
` Node ' represents a function name , such as
%% "`foo/1'" or "`bloggs:fred/2'", a uniform
%% representation of that name is returned. Different nestings of arity
%% and module name qualifiers in the syntax tree does not affect the
%% result.
%%
%% The evaluation throws `syntax_error' if
` Node ' does not represent a well - formed function name .
-spec analyze_function_name(erl_syntax:syntaxTree()) -> functionName().
analyze_function_name(Node) ->
case erl_syntax:type(Node) of
atom ->
erl_syntax:atom_value(Node);
arity_qualifier ->
A = erl_syntax:arity_qualifier_argument(Node),
case erl_syntax:type(A) of
integer ->
F = erl_syntax:arity_qualifier_body(Node),
F1 = analyze_function_name(F),
append_arity(erl_syntax:integer_value(A), F1);
_ ->
throw(syntax_error)
end;
module_qualifier ->
M = erl_syntax:module_qualifier_argument(Node),
case erl_syntax:type(M) of
atom ->
F = erl_syntax:module_qualifier_body(Node),
F1 = analyze_function_name(F),
{erl_syntax:atom_value(M), F1};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
append_arity(A, {Module, Name}) ->
{Module, append_arity(A, Name)};
append_arity(A, Name) when is_atom(Name) ->
{Name, A};
append_arity(A, A) ->
A;
append_arity(_A, Name) ->
Name. % quietly drop extra arity in case of conflict
%% =====================================================================
%% @spec analyze_import_attribute(Node::syntaxTree()) ->
%% {atom(), [FunctionName]} | atom()
%%
%% FunctionName = atom() | {atom(), integer()}
| { ModuleName , FunctionName }
ModuleName = atom ( )
%%
%% @doc Returns the module name and (if present) list of function names
%% declared by an import attribute. The returned value is an atom
%% `Module' or a pair `{Module, Names}', where
%% `Names' is a list of function names declared as imported
%% from the module named by `Module'. We do not guarantee
%% that each name occurs at most once in `Names'. The order
%% of listing is not defined.
%%
%% The evaluation throws `syntax_error' if `Node' does not represent a
%% well-formed import attribute.
%%
%% @see analyze_attribute/1
-spec analyze_import_attribute(erl_syntax:syntaxTree()) ->
{atom(), [functionName()]} | atom().
analyze_import_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[M] ->
module_name_to_atom(M);
[M, L] ->
M1 = module_name_to_atom(M),
L1 = analyze_function_name_list(L),
{M1, L1};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
%% =====================================================================
@spec analyze_type_name(Node::syntaxTree ( ) ) - > TypeName
%%
%% TypeName = atom()
%% | {atom(), integer()}
| { ModuleName , { atom ( ) , integer ( ) } }
ModuleName = atom ( )
%%
%% @doc Returns the type name represented by a syntax tree. If
` Node ' represents a type name , such as
%% "`foo/1'" or "`bloggs:fred/2'", a uniform
%% representation of that name is returned.
%%
%% The evaluation throws `syntax_error' if
` Node ' does not represent a well - formed type name .
-spec analyze_type_name(erl_syntax:syntaxTree()) -> typeName().
analyze_type_name(Node) ->
case erl_syntax:type(Node) of
atom ->
erl_syntax:atom_value(Node);
arity_qualifier ->
A = erl_syntax:arity_qualifier_argument(Node),
N = erl_syntax:arity_qualifier_body(Node),
case ((erl_syntax:type(A) =:= integer)
and (erl_syntax:type(N) =:= atom))
of
true ->
append_arity(erl_syntax:integer_value(A),
erl_syntax:atom_value(N));
_ ->
throw(syntax_error)
end;
module_qualifier ->
M = erl_syntax:module_qualifier_argument(Node),
case erl_syntax:type(M) of
atom ->
N = erl_syntax:module_qualifier_body(Node),
N1 = analyze_type_name(N),
{erl_syntax:atom_value(M), N1};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
%% =====================================================================
( ) ) - > { atom ( ) , term ( ) }
%%
%% @doc Returns the name and value of a "wild" attribute. The result is
%% the pair `{Name, Value}', if `Node' represents "`-Name(Value)'".
%%
%% Note that no checking is done whether `Name' is a
%% reserved attribute name such as `module' or
%% `export': it is assumed that the attribute is "wild".
%%
%% The evaluation throws `syntax_error' if `Node' does not represent a
%% well-formed wild attribute.
%%
%% @see analyze_attribute/1
-spec analyze_wild_attribute(erl_syntax:syntaxTree()) -> {atom(), term()}.
analyze_wild_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
N = erl_syntax:attribute_name(Node),
case erl_syntax:type(N) of
atom ->
case erl_syntax:attribute_arguments(Node) of
[V] ->
%% Note: does not work well with macros.
case catch {ok, erl_syntax:concrete(V)} of
{ok, Val} ->
{erl_syntax:atom_value(N), Val};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
%% =====================================================================
%% @spec analyze_record_attribute(Node::syntaxTree()) ->
%% {atom(), Fields}
%%
%% Fields = [{atom(), {Default, Type}}]
%% Default = none | syntaxTree()
%% Type = none | syntaxTree()
%%
%% @doc Returns the name and the list of fields of a record declaration
%% attribute. The result is a pair `{Name, Fields}', if
%% `Node' represents "`-record(Name, {...}).'",
%% where `Fields' is a list of pairs `{Label,
%% {Default, Type}}' for each field "`Label'", "`Label =
%% Default'", "`Label :: Type'", or
" ` Label = Default : : Type ' " in the declaration ,
%% listed in left-to-right
%% order. If the field has no default-value declaration, the value for
%% `Default' will be the atom `none'. If the field has no type declaration,
%% the value for `Type' will be the atom `none'. We do not
%% guarantee that each label occurs at most once in the list.
%%
%% The evaluation throws `syntax_error' if
` Node ' does not represent a well - formed record declaration
%% attribute.
%%
%% @see analyze_attribute/1
@see analyze_record_field/1
-type field() :: {atom(), {field_default(), field_type()}}.
-type fields() :: [field()].
-spec analyze_record_attribute(erl_syntax:syntaxTree()) -> {atom(), fields()}.
analyze_record_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[R, T] ->
case erl_syntax:type(R) of
atom ->
Es = analyze_record_attribute_tuple(T),
{erl_syntax:atom_value(R), Es};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
analyze_record_attribute_tuple(Node) ->
case erl_syntax:type(Node) of
tuple ->
[analyze_record_field(F)
|| F <- erl_syntax:tuple_elements(Node)];
_ ->
throw(syntax_error)
end.
%% =====================================================================
%% @spec analyze_record_expr(Node::syntaxTree()) ->
%% {atom(), Info} | atom()
%%
%% Info = {atom(), [{atom(), Value}]} | {atom(), atom()} | atom()
%% Value = syntaxTree()
%%
%% @doc Returns the record name and field name/names of a record
%% expression. If `Node' has type `record_expr',
%% `record_index_expr' or `record_access', a pair
%% `{Type, Info}' is returned, otherwise an atom
%% `Type' is returned. `Type' is the node type of
%% `Node', and `Info' depends on
%% `Type', as follows:
%% <dl>
%% <dt>`record_expr':</dt>
< dd>`{atom ( ) , [ { atom ( ) , Value}]}'</dd >
%% <dt>`record_access':</dt>
%% <dd>`{atom(), atom()}'</dd>
%% <dt>`record_index_expr':</dt>
%% <dd>`{atom(), atom()}'</dd>
%% </dl>
%%
%% For a `record_expr' node, `Info' represents
%% the record name and the list of descriptors for the involved fields,
%% listed in the order they appear. A field descriptor is a pair
` { Label , Value } ' , if ` Node ' represents " ` Label = Value ' " .
%% For a `record_access' node,
%% `Info' represents the record name and the field name. For a
%% `record_index_expr' node, `Info' represents the
%% record name and the name field name.
%%
%% The evaluation throws `syntax_error' if
` Node ' represents a record expression that is not
%% well-formed.
%%
%% @see analyze_record_attribute/1
@see analyze_record_field/1
-type info() :: {atom(), [{atom(), erl_syntax:syntaxTree()}]}
| {atom(), atom()} | atom().
-spec analyze_record_expr(erl_syntax:syntaxTree()) -> {atom(), info()} | atom().
analyze_record_expr(Node) ->
case erl_syntax:type(Node) of
record_expr ->
A = erl_syntax:record_expr_type(Node),
case erl_syntax:type(A) of
atom ->
Fs0 = [analyze_record_field(F)
|| F <- erl_syntax:record_expr_fields(Node)],
Fs = [{N, D} || {N, {D, _T}} <- Fs0],
{record_expr, {erl_syntax:atom_value(A), Fs}};
_ ->
throw(syntax_error)
end;
record_access ->
F = erl_syntax:record_access_field(Node),
case erl_syntax:type(F) of
atom ->
A = erl_syntax:record_access_type(Node),
case erl_syntax:type(A) of
atom ->
{record_access,
{erl_syntax:atom_value(A),
erl_syntax:atom_value(F)}};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
record_index_expr ->
F = erl_syntax:record_index_expr_field(Node),
case erl_syntax:type(F) of
atom ->
A = erl_syntax:record_index_expr_type(Node),
case erl_syntax:type(A) of
atom ->
{record_index_expr,
{erl_syntax:atom_value(A),
erl_syntax:atom_value(F)}};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
Type ->
Type
end.
%% =====================================================================
( ) ) - > { atom ( ) , { Default , Type } }
%%
%% Default = none | syntaxTree()
%% Type = none | syntaxTree()
%%
%% @doc Returns the label, value-expression, and type of a record field
%% specifier. The result is a pair `{Label, {Default, Type}}', if
` Node ' represents " ` Label ' " , " ` Label = Default ' " ,
" ` Label : : Type ' " , or " ` Label = Default : : Type ' " .
%% If the field has no value-expression, the value for
%% `Default' will be the atom `none'. If the field has no type,
%% the value for `Type' will be the atom `none'.
%%
%% The evaluation throws `syntax_error' if
` Node ' does not represent a well - formed record field
%% specifier.
%%
%% @see analyze_record_attribute/1
%% @see analyze_record_expr/1
-spec analyze_record_field(erl_syntax:syntaxTree()) -> field().
analyze_record_field(Node) ->
case erl_syntax:type(Node) of
record_field ->
A = erl_syntax:record_field_name(Node),
case erl_syntax:type(A) of
atom ->
T = erl_syntax:record_field_value(Node),
{erl_syntax:atom_value(A), {T, none}};
_ ->
throw(syntax_error)
end;
typed_record_field ->
F = erl_syntax:typed_record_field_body(Node),
{N, {V, _none}} = analyze_record_field(F),
T = erl_syntax:typed_record_field_type(Node),
{N, {V, T}};
_ ->
throw(syntax_error)
end.
%% =====================================================================
( ) ) - >
%% {string(), integer()}
%%
%% @doc Returns the file name and line number of a `file'
%% attribute. The result is the pair `{File, Line}' if
` Node ' represents " ` -file(File , Line ) . ' " .
%%
%% The evaluation throws `syntax_error' if
` Node ' does not represent a well - formed ` file '
%% attribute.
%%
%% @see analyze_attribute/1
-spec analyze_file_attribute(erl_syntax:syntaxTree()) -> {string(), integer()}.
analyze_file_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[F, N] ->
case (erl_syntax:type(F) =:= string)
and (erl_syntax:type(N) =:= integer) of
true ->
{erl_syntax:string_value(F),
erl_syntax:integer_value(N)};
false ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
%% =====================================================================
( ) ) - > { atom ( ) , integer ( ) }
%%
%% @doc Returns the name and arity of a function definition. The result
%% is a pair `{Name, A}' if `Node' represents a
function definition " ` Name(P_1 , ... , P_A ) - >
%% ...'".
%%
%% The evaluation throws `syntax_error' if
` Node ' does not represent a well - formed function
%% definition.
-spec analyze_function(erl_syntax:syntaxTree()) -> {atom(), arity()}.
analyze_function(Node) ->
case erl_syntax:type(Node) of
function ->
N = erl_syntax:function_name(Node),
case erl_syntax:type(N) of
atom ->
{erl_syntax:atom_value(N),
erl_syntax:function_arity(Node)};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
%% =====================================================================
%% @spec analyze_implicit_fun(Node::syntaxTree()) -> FunctionName
%%
%% FunctionName = atom() | {atom(), integer()}
| { ModuleName , FunctionName }
ModuleName = atom ( )
%%
%% @doc Returns the name of an implicit fun expression "`fun
%% F'". The result is a representation of the function
%% name `F'. (Cf. `analyze_function_name/1'.)
%%
%% The evaluation throws `syntax_error' if
` Node ' does not represent a well - formed implicit fun .
%%
%% @see analyze_function_name/1
-spec analyze_implicit_fun(erl_syntax:syntaxTree()) -> functionName().
analyze_implicit_fun(Node) ->
case erl_syntax:type(Node) of
implicit_fun ->
analyze_function_name(erl_syntax:implicit_fun_name(Node));
_ ->
throw(syntax_error)
end.
%% =====================================================================
%% @spec analyze_application(Node::syntaxTree()) -> FunctionName | Arity
%%
%% FunctionName = {atom(), Arity}
| { ModuleName , FunctionName }
%% Arity = integer()
ModuleName = atom ( )
%%
%% @doc Returns the name of a called function. The result is a
%% representation of the name of the applied function `F/A',
%% if `Node' represents a function application
" ` F(X_1 , ... , ) ' " . If the
%% function is not explicitly named (i.e., `F' is given by
%% some expression), only the arity `A' is returned.
%%
%% The evaluation throws `syntax_error' if `Node' does not represent a
%% well-formed application expression.
%%
%% @see analyze_function_name/1
-type appFunName() :: {atom(), arity()} | {atom(), {atom(), arity()}}.
-spec analyze_application(erl_syntax:syntaxTree()) -> appFunName() | arity().
analyze_application(Node) ->
case erl_syntax:type(Node) of
application ->
A = length(erl_syntax:application_arguments(Node)),
F = erl_syntax:application_operator(Node),
case catch {ok, analyze_function_name(F)} of
syntax_error ->
A;
{ok, N} ->
append_arity(A, N);
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
%% =====================================================================
%% @spec analyze_type_application(Node::syntaxTree()) -> TypeName
%%
%% TypeName = {atom(), integer()}
| { ModuleName , { atom ( ) , integer ( ) } }
ModuleName = atom ( )
%%
%% @doc Returns the name of a used type. The result is a
%% representation of the name of the used pre-defined or local type `N/A',
%% if `Node' represents a local (user) type application
%% "`N(T_1, ..., T_A)'", or
%% a representation of the name of the used remote type `M:N/A'
%% if `Node' represents a remote user type application
%% "`M:N(T_1, ..., T_A)'".
%%
%% The evaluation throws `syntax_error' if `Node' does not represent a
%% well-formed (user) type application expression.
%%
@see analyze_type_name/1
-type typeName() :: atom() | {module(), {atom(), arity()}} | {atom(), arity()}.
-spec analyze_type_application(erl_syntax:syntaxTree()) -> typeName().
analyze_type_application(Node) ->
case erl_syntax:type(Node) of
type_application ->
A = length(erl_syntax:type_application_arguments(Node)),
N = erl_syntax:type_application_name(Node),
case catch {ok, analyze_type_name(N)} of
{ok, TypeName} ->
append_arity(A, TypeName);
_ ->
throw(syntax_error)
end;
user_type_application ->
A = length(erl_syntax:user_type_application_arguments(Node)),
N = erl_syntax:user_type_application_name(Node),
case catch {ok, analyze_type_name(N)} of
{ok, TypeName} ->
append_arity(A, TypeName);
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
%% =====================================================================
] ) - > [ { ShortName , Name } ]
%%
%% Name = ShortName | {atom(), Name}
%% ShortName = atom() | {atom(), integer()}
%%
%% @doc Creates a mapping from corresponding short names to full
%% function names. Names are represented by nested tuples of atoms and
%% integers (cf. `analyze_function_name/1'). The result is a
%% list containing a pair `{ShortName, Name}' for each
%% element `Name' in the given list, where the corresponding
%% `ShortName' is the rightmost-innermost part of
%% `Name'. The list thus represents a finite mapping from
%% unqualified names to the corresponding qualified names.
%%
Note : the resulting list can contain more than one tuple
%% `{ShortName, Name}' for the same `ShortName',
%% possibly with different values for `Name', depending on
%% the given list.
%%
%% @see analyze_function_name/1
-type shortname() :: atom() | {atom(), arity()}.
-type name() :: shortname() | {atom(), shortname()}.
-spec function_name_expansions([name()]) -> [{shortname(), name()}].
function_name_expansions(Fs) ->
function_name_expansions(Fs, []).
function_name_expansions([F | Fs], Ack) ->
function_name_expansions(Fs,
function_name_expansions(F, F, Ack));
function_name_expansions([], Ack) ->
Ack.
function_name_expansions({A, N}, Name, Ack) when is_integer(N) ->
[{{A, N}, Name} | Ack];
function_name_expansions({_, N}, Name, Ack) ->
function_name_expansions(N, Name, Ack);
function_name_expansions(A, Name, Ack) ->
[{A, Name} | Ack].
%% =====================================================================
( ) ) - > syntaxTree ( )
%%
%% @doc Removes all comments from all nodes of a syntax tree. All other
%% attributes (such as position information) remain unchanged.
Standalone comments in form lists are removed ; any other standalone
%% comments are changed into null-comments (no text, no indentation).
-spec strip_comments(erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
strip_comments(Tree) ->
map(fun strip_comments_1/1, Tree).
strip_comments_1(T) ->
case erl_syntax:type(T) of
form_list ->
Es = erl_syntax:form_list_elements(T),
Es1 = [E || E <- Es, erl_syntax:type(E) /= comment],
T1 = erl_syntax:copy_attrs(T, erl_syntax:form_list(Es1)),
erl_syntax:remove_comments(T1);
comment ->
erl_syntax:comment([]);
_ ->
erl_syntax:remove_comments(T)
end.
%% =====================================================================
) - > syntaxTree ( )
%% @equiv to_comment(Tree, "% ")
-spec to_comment(erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
to_comment(Tree) ->
to_comment(Tree, "% ").
%% =====================================================================
( ) , ( ) ) - >
%% syntaxTree()
%%
%% @doc Equivalent to `to_comment(Tree, Prefix, F)' for a
%% default formatting function `F'. The default
%% `F' simply calls `erl_prettypr:format/1'.
%%
@see to_comment/3
%% @see erl_prettypr:format/1
-spec to_comment(erl_syntax:syntaxTree(), string()) -> erl_syntax:syntaxTree().
to_comment(Tree, Prefix) ->
F = fun (T) -> erl_prettypr:format(T) end,
to_comment(Tree, Prefix, F).
%% =====================================================================
( ) , ( ) , Printer ) - >
%% syntaxTree()
%%
%% Printer = (syntaxTree()) -> string()
%%
%% @doc Transforms a syntax tree into an abstract comment. The lines of
%% the comment contain the text for `Node', as produced by
%% the given `Printer' function. Each line of the comment is
%% prefixed by the string `Prefix' (this does not include the
%% initial "`%'" character of the comment line).
%%
%% For example, the result of
%% `to_comment(erl_syntax:abstract([a,b,c]))' represents
%% <pre>
%% %% [a,b,c]</pre>
%% (cf. `to_comment/1').
%%
%% Note: the text returned by the formatting function will be split
%% automatically into separate comment lines at each line break. No
%% extra work is needed.
%%
%% @see to_comment/1
@see to_comment/2
-spec to_comment(erl_syntax:syntaxTree(), string(),
fun((erl_syntax:syntaxTree()) -> string())) ->
erl_syntax:syntaxTree().
to_comment(Tree, Prefix, F) ->
erl_syntax:comment(split_lines(F(Tree), Prefix)).
%% =====================================================================
, Depth ) - > syntaxTree ( )
%%
%% @doc Equivalent to `limit(Tree, Depth, Text)' using the
%% text `"..."' as default replacement.
%%
@see limit/3
%% @see erl_syntax:text/1
-spec limit(erl_syntax:syntaxTree(), integer()) -> erl_syntax:syntaxTree().
limit(Tree, Depth) ->
limit(Tree, Depth, erl_syntax:text("...")).
%% =====================================================================
@spec limit(Tree::syntaxTree ( ) , ( ) ,
( ) ) - > syntaxTree ( )
%%
%% @doc Limits a syntax tree to a specified depth. Replaces all non-leaf
%% subtrees in `Tree' at the given `Depth' by
%% `Node'. If `Depth' is negative, the result is
%% always `Node', even if `Tree' has no subtrees.
%%
%% When a group of subtrees (as e.g., the argument list of an
%% `application' node) is at the specified depth, and there
are two or more subtrees in the group , these will be collectively
replaced by ` Node ' even if they are leaf nodes . Groups of
%% subtrees that are above the specified depth will be limited in size,
as if each subsequent tree in the group were one level deeper than
%% the previous. E.g., if `Tree' represents a list of
integers " ` [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ' " , the result
of ` limit(Tree , 5 ) ' will represent ` [ 1 , 2 , 3 , 4 ,
%% ...]'.
%%
%% The resulting syntax tree is typically only useful for
%% pretty-printing or similar visual formatting.
%%
%% @see limit/2
-spec limit(erl_syntax:syntaxTree(), integer(), erl_syntax:syntaxTree()) ->
erl_syntax:syntaxTree().
limit(_Tree, Depth, Node) when Depth < 0 ->
Node;
limit(Tree, Depth, Node) ->
limit_1(Tree, Depth, Node).
limit_1(Tree, Depth, Node) ->
%% Depth is nonnegative here.
case erl_syntax:subtrees(Tree) of
[] ->
if Depth > 0 ->
Tree;
true ->
case is_simple_leaf(Tree) of
true ->
Tree;
false ->
Node
end
end;
Gs ->
if Depth > 1 ->
Gs1 = [[limit_1(T, Depth - 1, Node)
|| T <- limit_list(G, Depth, Node)]
|| G <- Gs],
rewrite(Tree,
erl_syntax:make_tree(erl_syntax:type(Tree),
Gs1));
Depth =:= 0 ->
Depth is zero , and this is not a leaf node
%% so we always replace it.
Node;
true ->
Depth is 1 , so all subtrees are to be cut .
%% This is done groupwise.
Gs1 = [cut_group(G, Node) || G <- Gs],
rewrite(Tree,
erl_syntax:make_tree(erl_syntax:type(Tree),
Gs1))
end
end.
cut_group([], _Node) ->
[];
cut_group([T], Node) ->
%% Only if the group contains a single subtree do we try to
%% preserve it if suitable.
[limit_1(T, 0, Node)];
cut_group(_Ts, Node) ->
[Node].
is_simple_leaf(Tree) ->
case erl_syntax:type(Tree) of
atom -> true;
char -> true;
float -> true;
integer -> true;
nil -> true;
operator -> true;
tuple -> true;
underscore -> true;
variable -> true;
_ -> false
end.
%% If list has more than N elements, take the N - 1 first and
append ; otherwise return list as is .
limit_list(Ts, N, Node) ->
if length(Ts) > N ->
limit_list_1(Ts, N - 1, Node);
true ->
Ts
end.
limit_list_1([T | Ts], N, Node) ->
if N > 0 ->
[T | limit_list_1(Ts, N - 1, Node)];
true ->
[Node]
end;
limit_list_1([], _N, _Node) ->
[].
%% =====================================================================
%% Utility functions
rewrite(Tree, Tree1) ->
erl_syntax:copy_attrs(Tree, Tree1).
module_name_to_atom(M) ->
case erl_syntax:type(M) of
atom ->
erl_syntax:atom_value(M);
_ ->
throw(syntax_error)
end.
%% This splits lines at line terminators and expands tab characters to
spaces . The width of a tab is assumed to be 8 .
% split_lines(Cs) ->
% split_lines(Cs, "").
split_lines(Cs, Prefix) ->
split_lines(Cs, Prefix, 0).
split_lines(Cs, Prefix, N) ->
lists:reverse(split_lines(Cs, N, [], [], Prefix)).
split_lines([$\r, $\n | Cs], _N, Cs1, Ls, Prefix) ->
split_lines_1(Cs, Cs1, Ls, Prefix);
split_lines([$\r | Cs], _N, Cs1, Ls, Prefix) ->
split_lines_1(Cs, Cs1, Ls, Prefix);
split_lines([$\n | Cs], _N, Cs1, Ls, Prefix) ->
split_lines_1(Cs, Cs1, Ls, Prefix);
split_lines([$\t | Cs], N, Cs1, Ls, Prefix) ->
split_lines(Cs, 0, push(8 - (N rem 8), $\040, Cs1), Ls,
Prefix);
split_lines([C | Cs], N, Cs1, Ls, Prefix) ->
split_lines(Cs, N + 1, [C | Cs1], Ls, Prefix);
split_lines([], _, [], Ls, _) ->
Ls;
split_lines([], _N, Cs, Ls, Prefix) ->
[Prefix ++ lists:reverse(Cs) | Ls].
split_lines_1(Cs, Cs1, Ls, Prefix) ->
split_lines(Cs, 0, [], [Prefix ++ lists:reverse(Cs1) | Ls],
Prefix).
push(N, C, Cs) when N > 0 ->
push(N - 1, C, [C | Cs]);
push(0, _, Cs) ->
Cs.
| null | https://raw.githubusercontent.com/erlang/otp/31225cfcfd9c0dc8a22183e3d0a30ba5c1ed93e1/lib/syntax_tools/src/erl_syntax_lib.erl | erlang | =====================================================================
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.
Alternatively, you may use this file under the terms of the GNU Lesser
If you wish to allow use of your version of this file only under the
terms of the LGPL, you should delete the provisions above and replace
them with the notice and other provisions required by the LGPL; see
</>. If you do not delete the provisions
above, a recipient may use your version of this file under the terms of
@end
=====================================================================
This module contains utility functions for working with the
abstract data type defined in the module {@link erl_syntax}.
@type syntaxTree() = erl_syntax:syntaxTree(). An abstract syntax
tree. See the {@link erl_syntax} module for details.
=====================================================================
@spec map(Function, Tree::syntaxTree()) -> syntaxTree()
Function = (syntaxTree()) -> syntaxTree()
@doc Applies a function to each node of a syntax tree. The result of
each application replaces the corresponding original node. The order
of traversal is bottom-up.
@see map_subtrees/2
=====================================================================
Function = (Tree) -> Tree1
@doc Applies a function to each immediate subtree of a syntax tree.
The result of each application replaces the corresponding original
node.
=====================================================================
@spec fold(Function, Start::term(), Tree::syntaxTree()) -> term()
Function = (syntaxTree(), term()) -> term()
@doc Folds a function over all nodes of a syntax tree. The result is
`Tree' in a post-order traversal.
@see fold_subtrees/3
=====================================================================
@spec fold_subtrees(Function, Start::term(), Tree::syntaxTree()) ->
term()
Function = (syntaxTree(), term()) -> term()
@doc Folds a function over the immediate subtrees of a syntax tree.
This is similar to `fold/3', but only on the immediate
subtrees of `Tree', in left-to-right order; it does not
include the root node of `Tree'.
@see fold/3
=====================================================================
Function = (term(), term()) -> term()
@doc Like `lists:foldl/3', but over a list of lists.
@see fold/3
@see //stdlib/lists:foldl/3
=====================================================================
@spec mapfold(Function, Start::term(), Tree::syntaxTree()) ->
{syntaxTree(), term()}
Function = (syntaxTree(), term()) -> {syntaxTree(), term()}
@doc Combines map and fold in a single operation. This is similar to
`map/2', but also propagates an extra value from each
post-order traversal of the tree like `fold/3'. The value
the final result is the result of the last application.
@see fold/3
=====================================================================
@spec mapfold_subtrees(Function, Start::term(),
Tree::syntaxTree()) -> {syntaxTree(), term()}
Function = (syntaxTree(), term()) -> {syntaxTree(), term()}
@doc Does a mapfold operation over the immediate subtrees of a syntax
tree. This is similar to `mapfold/3', but only on the
immediate subtrees of `Tree', in left-to-right order; it
does not include the root node of `Tree'.
@see mapfold/3
=====================================================================
{[[term()]], term()}
Function = (term(), term()) -> {term(), term()}
@doc Like `lists:mapfoldl/3', but over a list of lists.
The list of lists in the result has the same structure as the given
list of lists.
=====================================================================
@type set(T) = //stdlib/sets:set(T)
@doc Returns the names of variables occurring in a syntax tree, The
are not included.
@see //stdlib/sets
macro names are ignored, even if represented by variables
retries before enlarging range
range enlargement enumerator
range enlargement denominator
=====================================================================
@spec new_variable_name(Used::set(atom())) -> atom()
@doc Returns an atom which is not already in the set `Used'. This is
equivalent to `new_variable_name(Function, Used)', where `Function'
maps a given integer `N' to the atom whose name consists of "`V'"
followed by the numeral for `N'.
@see new_variable_name/2
=====================================================================
Function = (integer()) -> atom()
@doc Returns a user-named atom which is not already in the set
`Used'. The atom is generated by applying the given
`Function' to a generated integer. Integers are generated
using an algorithm which tries to keep the names randomly distributed
within a reasonably small range relative to the number of elements in
the set.
This function uses the module `rand' to generate new
keys. The seed it uses may be initialized by calling
@see //stdlib/sets
@see //stdlib/random
Too many retries - enlarge the range and start over.
Note that we assume that it is very cheap to take the size of
the given set. This should be valid for the stdlib
implementation of `sets'.
The previous number might or might not be used to compute the
next number to be tried. It is currently not used.
It is important that this function does not generate values in
order, but (pseudo-)randomly distributed over the range.
works well
=====================================================================
`N' new names.
=====================================================================
Used::set(atom())) -> [atom()]
Function = (integer()) -> atom()
@doc Like `new_variable_name/2', but generates a list of
`N' new names.
@see new_variable_name/2
=====================================================================
@spec annotate_bindings(Tree::syntaxTree(),
Bindings::ordset(atom())) -> syntaxTree()
@type ordset(T) = //stdlib/ordsets:ordset(T)
@doc Adds or updates annotations on nodes in a syntax tree.
`Bindings' specifies the set of bound variables in the
environment of the top level node. The following annotations are
affected:
<ul>
of the subtree.</li>
are bound in the subtree.</li>
</ul>
(cf. module `ordsets') of atoms representing variable
names.
@see annotate_bindings/1
@see //stdlib/ordsets
=====================================================================
@spec annotate_bindings(Tree::syntaxTree()) -> syntaxTree()
@doc Adds or updates annotations on nodes in a syntax tree.
Equivalent to `annotate_bindings(Tree, Bindings)' where
the top-level environment `Bindings' is taken from the
annotation `{env, Bindings}' on the root node of
`Tree'. An exception is thrown if no such annotation
should exist.
@see annotate_bindings/2
Variable use
bindings in the body should be available in the success case,
the after part does not export anything, yet; this might change
The timeout action is treated as an extra clause.
Bindings in the expiry expression are local only.
Bindings in filters are not
exported to the rest of the
body.
Bindings in filters are not
exported to the rest of the
body.
In list comprehension generators, the pattern variables are always
viewed as new occurrences, shadowing whatever is in the input
environment (thus, the pattern contains no variable uses, only
bindings). Bindings in the generator body are not exported.
lexically speaking.
Variable use
Variable binding
The macro name must be ignored. The arguments are treated
as patterns.
Guards cannot add bindings
=====================================================================
@doc Returns `true' if `Tree' represents an
expression which never terminates normally. Note that the reverse
does not apply. Currently, the detected cases are calls to
@see //erts/erlang:throw/1
@see //erts/erlang:error/1
=====================================================================
@spec analyze_forms(Forms) -> [{Key, term()}]
Forms = syntaxTree() | [syntaxTree()]
Key = attributes | errors | exports | functions | imports
| module | records | warnings
@doc Analyzes a sequence of "program forms". The given
`Forms' may be a single syntax tree of type
`form_list', or a list of "program form" syntax trees. The
returned value is a list of pairs `{Key, Info}', where
each value of `Key' occurs at most once in the list; the
absence of a particular key indicates that there is no well-defined
value for that key.
Each entry in the resulting list contains the following
corresponding information about the program forms:
<dl>
<dt>`{attributes, Attributes}'</dt>
<dd><ul>
<li>`Attributes = [{atom(), term()}]'</li>
</ul>
`Attributes' is a list of pairs representing the
names and corresponding values of all so-called "wild"
attributes (as e.g. "`-compile(...)'") occurring in
`Forms' (cf. `analyze_wild_attribute/1').
We do not guarantee that each name occurs at most once in the
<dt>`{errors, Errors}'</dt>
<dd><ul>
<li>`Errors = [term()]'</li>
</ul>
`Errors' is the list of error descriptors of all
`error_marker' nodes that occur in
<dt>`{exports, Exports}'</dt>
<dd><ul>
<li>`Exports = [FunctionName]'</li>
<li>`FunctionName = atom()
| {atom(), integer()}
<li>`ModuleName = atom()'</li>
</ul>
`Exports' is a list of representations of those
function names that are listed by export declaration attributes
in `Forms' (cf.
`analyze_export_attribute/1'). We do not guarantee
that each name occurs at most once in the list. The order of
<dt>`{functions, Functions}'</dt>
<dd><ul>
</ul>
`Functions' is a list of the names of the functions
that are defined in `Forms' (cf.
`analyze_function/1'). We do not guarantee that each
name occurs at most once in the list. The order of listing is
<dt>`{imports, Imports}'</dt>
<dd><ul>
<li>`Imports = [{Module, Names}]'</li>
<li>`Names = [FunctionName]'</li>
<li>`FunctionName = atom()
| {atom(), integer()}
<li>`ModuleName = atom()'</li>
</ul>
`Imports' is a list of pairs representing those
module names and corresponding function names that are listed
by import declaration attributes in `Forms' (cf.
`analyze_import_attribute/1'), where each
`Module' occurs at most once in
`Imports'. We do not guarantee that each name occurs
at most once in the lists of function names. The order of
<dt>`{module, ModuleName}'</dt>
<dd><ul>
<li>`ModuleName = atom()'</li>
</ul>
attribute in `Forms'. If no module name is defined
in `Forms', the result will contain no entry for the
`module' key. If multiple module name declarations
<dt>`{records, Records}'</dt>
<dd><ul>
<li>`Records = [{atom(), Fields}]'</li>
<li>`Fields = [{atom(), {Default, Type}}]'</li>
<li>`Default = none | syntaxTree()'</li>
<li>`Type = none | syntaxTree()'</li>
</ul>
`Records' is a list of pairs representing the names
and corresponding field declarations of all record declaration
attributes occurring in `Forms'. For fields declared
without a default value, the corresponding value for
`Default' is the atom `none'. Similarly, for fields declared
without a type, the corresponding value for `Type' is the
atom `none' (cf.
`analyze_record_attribute/1'). We do not guarantee
that each record name occurs at most once in the list. The
<dt>`{warnings, Warnings}'</dt>
<dd><ul>
<li>`Warnings = [term()]'</li>
</ul>
`Warnings' is the list of error descriptors of all
`warning_marker' nodes that occur in
</dl>
The evaluation throws `syntax_error' if an ill-formed
@see analyze_wild_attribute/1
@see analyze_export_attribute/1
@see analyze_import_attribute/1
@see analyze_record_attribute/1
@see erl_syntax:warning_marker_info/1
Abstract datatype for collecting module information.
=====================================================================
@spec analyze_form(Node::syntaxTree()) -> {atom(), term()} | atom()
"form" type (cf. `erl_syntax:is_form/1'), the returned
value is a tuple `{Type, Info}' where `Type' is
the node type and `Info' depends on `Type', as
follows:
<dl>
<dt>`{attribute, Info}'</dt>
<dd>where `Info = analyze_attribute(Node)'.</dd>
<dt>`{error_marker, Info}'</dt>
<dd>where `Info =
erl_syntax:error_marker_info(Node)'.</dd>
<dt>`{function, Info}'</dt>
<dd>where `Info = analyze_function(Node)'.</dd>
<dt>`{warning_marker, Info}'</dt>
<dd>where `Info =
erl_syntax:warning_marker_info(Node)'.</dd>
</dl>
For other types of forms, only the node type is returned.
The evaluation throws `syntax_error' if
@see analyze_attribute/1
@see erl_syntax:is_form/1
@see erl_syntax:warning_marker_info/1
=====================================================================
@spec analyze_attribute(Node::syntaxTree()) ->
preprocessor | {atom(), atom()}
@doc Analyzes an attribute node. If `Node' represents a
preprocessor directive, the atom `preprocessor' is
returned. Otherwise, if `Node' represents a module
attribute "`-Name...'", a tuple `{Name,
Info}' is returned, where `Info' depends on
`Name', as follows:
<dl>
<dt>`{module, Info}'</dt>
<dd>where `Info =
analyze_module_attribute(Node)'.</dd>
<dd>where `Info =
analyze_export_attribute(Node)'.</dd>
<dd>where `Info =
analyze_import_attribute(Node)'.</dd>
<dt>`{file, Info}'</dt>
<dd>where `Info =
analyze_file_attribute(Node)'.</dd>
<dt>`{record, Info}'</dt>
<dd>where `Info =
analyze_record_attribute(Node)'.</dd>
<dt>`{Name, Info}'</dt>
<dd>where `{Name, Info} =
analyze_wild_attribute(Node)'.</dd>
</dl>
The evaluation throws `syntax_error' if `Node'
does not represent a well-formed module attribute.
@see analyze_export_attribute/1
@see analyze_import_attribute/1
@see analyze_file_attribute/1
@see analyze_record_attribute/1
@see analyze_wild_attribute/1
XXX: underspecified
A "wild" attribute (such as e.g. a `compile' directive).
=====================================================================
Name::atom() | {Name::atom(), Variables::[atom()]}
@doc Returns the module name and possible parameters declared by a
module attribute. If the attribute is a plain module declaration such
as `-module(name)', the result is the module name. If the attribute
is a parameterized module declaration, the result is a tuple
containing the module name and a list of the parameter variable
names.
The evaluation throws `syntax_error' if `Node' does not represent a
well-formed module attribute.
@see analyze_attribute/1
=====================================================================
FunctionName = atom() | {atom(), integer()}
@doc Returns the list of function names declared by an export
attribute. We do not guarantee that each name occurs at most once in
the list. The order of listing is not defined.
The evaluation throws `syntax_error' if `Node' does not represent a
well-formed export attribute.
@see analyze_attribute/1
=====================================================================
@spec analyze_function_name(Node::syntaxTree()) -> FunctionName
FunctionName = atom() | {atom(), integer()}
@doc Returns the function name represented by a syntax tree. If
"`foo/1'" or "`bloggs:fred/2'", a uniform
representation of that name is returned. Different nestings of arity
and module name qualifiers in the syntax tree does not affect the
result.
The evaluation throws `syntax_error' if
quietly drop extra arity in case of conflict
=====================================================================
@spec analyze_import_attribute(Node::syntaxTree()) ->
{atom(), [FunctionName]} | atom()
FunctionName = atom() | {atom(), integer()}
@doc Returns the module name and (if present) list of function names
declared by an import attribute. The returned value is an atom
`Module' or a pair `{Module, Names}', where
`Names' is a list of function names declared as imported
from the module named by `Module'. We do not guarantee
that each name occurs at most once in `Names'. The order
of listing is not defined.
The evaluation throws `syntax_error' if `Node' does not represent a
well-formed import attribute.
@see analyze_attribute/1
=====================================================================
TypeName = atom()
| {atom(), integer()}
@doc Returns the type name represented by a syntax tree. If
"`foo/1'" or "`bloggs:fred/2'", a uniform
representation of that name is returned.
The evaluation throws `syntax_error' if
=====================================================================
@doc Returns the name and value of a "wild" attribute. The result is
the pair `{Name, Value}', if `Node' represents "`-Name(Value)'".
Note that no checking is done whether `Name' is a
reserved attribute name such as `module' or
`export': it is assumed that the attribute is "wild".
The evaluation throws `syntax_error' if `Node' does not represent a
well-formed wild attribute.
@see analyze_attribute/1
Note: does not work well with macros.
=====================================================================
@spec analyze_record_attribute(Node::syntaxTree()) ->
{atom(), Fields}
Fields = [{atom(), {Default, Type}}]
Default = none | syntaxTree()
Type = none | syntaxTree()
@doc Returns the name and the list of fields of a record declaration
attribute. The result is a pair `{Name, Fields}', if
`Node' represents "`-record(Name, {...}).'",
where `Fields' is a list of pairs `{Label,
{Default, Type}}' for each field "`Label'", "`Label =
Default'", "`Label :: Type'", or
listed in left-to-right
order. If the field has no default-value declaration, the value for
`Default' will be the atom `none'. If the field has no type declaration,
the value for `Type' will be the atom `none'. We do not
guarantee that each label occurs at most once in the list.
The evaluation throws `syntax_error' if
attribute.
@see analyze_attribute/1
=====================================================================
@spec analyze_record_expr(Node::syntaxTree()) ->
{atom(), Info} | atom()
Info = {atom(), [{atom(), Value}]} | {atom(), atom()} | atom()
Value = syntaxTree()
@doc Returns the record name and field name/names of a record
expression. If `Node' has type `record_expr',
`record_index_expr' or `record_access', a pair
`{Type, Info}' is returned, otherwise an atom
`Type' is returned. `Type' is the node type of
`Node', and `Info' depends on
`Type', as follows:
<dl>
<dt>`record_expr':</dt>
<dt>`record_access':</dt>
<dd>`{atom(), atom()}'</dd>
<dt>`record_index_expr':</dt>
<dd>`{atom(), atom()}'</dd>
</dl>
For a `record_expr' node, `Info' represents
the record name and the list of descriptors for the involved fields,
listed in the order they appear. A field descriptor is a pair
For a `record_access' node,
`Info' represents the record name and the field name. For a
`record_index_expr' node, `Info' represents the
record name and the name field name.
The evaluation throws `syntax_error' if
well-formed.
@see analyze_record_attribute/1
=====================================================================
Default = none | syntaxTree()
Type = none | syntaxTree()
@doc Returns the label, value-expression, and type of a record field
specifier. The result is a pair `{Label, {Default, Type}}', if
If the field has no value-expression, the value for
`Default' will be the atom `none'. If the field has no type,
the value for `Type' will be the atom `none'.
The evaluation throws `syntax_error' if
specifier.
@see analyze_record_attribute/1
@see analyze_record_expr/1
=====================================================================
{string(), integer()}
@doc Returns the file name and line number of a `file'
attribute. The result is the pair `{File, Line}' if
The evaluation throws `syntax_error' if
attribute.
@see analyze_attribute/1
=====================================================================
@doc Returns the name and arity of a function definition. The result
is a pair `{Name, A}' if `Node' represents a
...'".
The evaluation throws `syntax_error' if
definition.
=====================================================================
@spec analyze_implicit_fun(Node::syntaxTree()) -> FunctionName
FunctionName = atom() | {atom(), integer()}
@doc Returns the name of an implicit fun expression "`fun
F'". The result is a representation of the function
name `F'. (Cf. `analyze_function_name/1'.)
The evaluation throws `syntax_error' if
@see analyze_function_name/1
=====================================================================
@spec analyze_application(Node::syntaxTree()) -> FunctionName | Arity
FunctionName = {atom(), Arity}
Arity = integer()
@doc Returns the name of a called function. The result is a
representation of the name of the applied function `F/A',
if `Node' represents a function application
function is not explicitly named (i.e., `F' is given by
some expression), only the arity `A' is returned.
The evaluation throws `syntax_error' if `Node' does not represent a
well-formed application expression.
@see analyze_function_name/1
=====================================================================
@spec analyze_type_application(Node::syntaxTree()) -> TypeName
TypeName = {atom(), integer()}
@doc Returns the name of a used type. The result is a
representation of the name of the used pre-defined or local type `N/A',
if `Node' represents a local (user) type application
"`N(T_1, ..., T_A)'", or
a representation of the name of the used remote type `M:N/A'
if `Node' represents a remote user type application
"`M:N(T_1, ..., T_A)'".
The evaluation throws `syntax_error' if `Node' does not represent a
well-formed (user) type application expression.
=====================================================================
Name = ShortName | {atom(), Name}
ShortName = atom() | {atom(), integer()}
@doc Creates a mapping from corresponding short names to full
function names. Names are represented by nested tuples of atoms and
integers (cf. `analyze_function_name/1'). The result is a
list containing a pair `{ShortName, Name}' for each
element `Name' in the given list, where the corresponding
`ShortName' is the rightmost-innermost part of
`Name'. The list thus represents a finite mapping from
unqualified names to the corresponding qualified names.
`{ShortName, Name}' for the same `ShortName',
possibly with different values for `Name', depending on
the given list.
@see analyze_function_name/1
=====================================================================
@doc Removes all comments from all nodes of a syntax tree. All other
attributes (such as position information) remain unchanged.
comments are changed into null-comments (no text, no indentation).
=====================================================================
@equiv to_comment(Tree, "% ")
=====================================================================
syntaxTree()
@doc Equivalent to `to_comment(Tree, Prefix, F)' for a
default formatting function `F'. The default
`F' simply calls `erl_prettypr:format/1'.
@see erl_prettypr:format/1
=====================================================================
syntaxTree()
Printer = (syntaxTree()) -> string()
@doc Transforms a syntax tree into an abstract comment. The lines of
the comment contain the text for `Node', as produced by
the given `Printer' function. Each line of the comment is
prefixed by the string `Prefix' (this does not include the
initial "`%'" character of the comment line).
For example, the result of
`to_comment(erl_syntax:abstract([a,b,c]))' represents
<pre>
%% [a,b,c]</pre>
(cf. `to_comment/1').
Note: the text returned by the formatting function will be split
automatically into separate comment lines at each line break. No
extra work is needed.
@see to_comment/1
=====================================================================
@doc Equivalent to `limit(Tree, Depth, Text)' using the
text `"..."' as default replacement.
@see erl_syntax:text/1
=====================================================================
@doc Limits a syntax tree to a specified depth. Replaces all non-leaf
subtrees in `Tree' at the given `Depth' by
`Node'. If `Depth' is negative, the result is
always `Node', even if `Tree' has no subtrees.
When a group of subtrees (as e.g., the argument list of an
`application' node) is at the specified depth, and there
subtrees that are above the specified depth will be limited in size,
the previous. E.g., if `Tree' represents a list of
...]'.
The resulting syntax tree is typically only useful for
pretty-printing or similar visual formatting.
@see limit/2
Depth is nonnegative here.
so we always replace it.
This is done groupwise.
Only if the group contains a single subtree do we try to
preserve it if suitable.
If list has more than N elements, take the N - 1 first and
=====================================================================
Utility functions
This splits lines at line terminators and expands tab characters to
split_lines(Cs) ->
split_lines(Cs, ""). | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may
distributed under the License is distributed on an " AS IS " BASIS ,
General Public License ( the " LGPL " ) as published by the Free Software
Foundation ; either version 2.1 , or ( at your option ) any later version .
either the Apache License or the LGPL .
1997 - 2006
@author < >
@doc Support library for abstract Erlang syntax trees .
-module(erl_syntax_lib).
-export([analyze_application/1, analyze_attribute/1,
analyze_export_attribute/1, analyze_file_attribute/1,
analyze_form/1, analyze_forms/1, analyze_function/1,
analyze_function_name/1, analyze_implicit_fun/1,
analyze_import_attribute/1, analyze_module_attribute/1,
analyze_record_attribute/1, analyze_record_expr/1,
analyze_record_field/1, analyze_wild_attribute/1, annotate_bindings/1,
analyze_type_application/1, analyze_type_name/1,
annotate_bindings/2, fold/3, fold_subtrees/3, foldl_listlist/3,
function_name_expansions/1, is_fail_expr/1, limit/2, limit/3,
map/2, map_subtrees/2, mapfold/3, mapfold_subtrees/3,
mapfoldl_listlist/3, new_variable_name/1, new_variable_name/2,
new_variable_names/2, new_variable_names/3, strip_comments/1,
to_comment/1, to_comment/2, to_comment/3, variables/1]).
-export_type([info_pair/0]).
-spec map(fun((erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree()),
erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
map(F, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
F(Tree);
Gs ->
Tree1 = erl_syntax:make_tree(erl_syntax:type(Tree),
[[map(F, T) || T <- G]
|| G <- Gs]),
F(erl_syntax:copy_attrs(Tree, Tree1))
end.
, syntaxTree ( ) ) - > syntaxTree ( )
@see map/2
-spec map_subtrees(fun((erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree()),
erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
map_subtrees(F, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
Tree;
Gs ->
Tree1 = erl_syntax:make_tree(erl_syntax:type(Tree),
[[F(T) || T <- G] || G <- Gs]),
erl_syntax:copy_attrs(Tree, Tree1)
end.
the value of ` Function(X1 , Function(X2 , ... , Start )
... ) ) ' , where ` [ X1 , X2 , ... , Xn ] ' are the nodes of
@see foldl_listlist/3
-spec fold(fun((erl_syntax:syntaxTree(), term()) -> term()),
term(), erl_syntax:syntaxTree()) -> term().
fold(F, S, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
F(Tree, S);
Gs ->
F(Tree, fold_1(F, S, Gs))
end.
fold_1(F, S, [L | Ls]) ->
fold_1(F, fold_2(F, S, L), Ls);
fold_1(_, S, []) ->
S.
fold_2(F, S, [T | Ts]) ->
fold_2(F, fold(F, S, T), Ts);
fold_2(_, S, []) ->
S.
-spec fold_subtrees(fun((erl_syntax:syntaxTree(), term()) -> term()),
term(), erl_syntax:syntaxTree()) -> term().
fold_subtrees(F, S, Tree) ->
foldl_listlist(F, S, erl_syntax:subtrees(Tree)).
, Start::term ( ) , [ [ term ( ) ] ] ) - > term ( )
-spec foldl_listlist(fun((term(), term()) -> term()),
term(), [[term()]]) -> term().
foldl_listlist(F, S, [L | Ls]) ->
foldl_listlist(F, foldl(F, S, L), Ls);
foldl_listlist(_, S, []) ->
S.
foldl(F, S, [T | Ts]) ->
foldl(F, F(T, S), Ts);
foldl(_, S, []) ->
S.
application of the ` Function ' to the next , while doing a
` Start ' is passed to the first function application , and
@see map/2
-spec mapfold(fun((erl_syntax:syntaxTree(), term()) -> {erl_syntax:syntaxTree(), term()}),
term(), erl_syntax:syntaxTree()) -> {erl_syntax:syntaxTree(), term()}.
mapfold(F, S, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
F(Tree, S);
Gs ->
{Gs1, S1} = mapfold_1(F, S, Gs),
Tree1 = erl_syntax:make_tree(erl_syntax:type(Tree), Gs1),
F(erl_syntax:copy_attrs(Tree, Tree1), S1)
end.
mapfold_1(F, S, [L | Ls]) ->
{L1, S1} = mapfold_2(F, S, L),
{Ls1, S2} = mapfold_1(F, S1, Ls),
{[L1 | Ls1], S2};
mapfold_1(_, S, []) ->
{[], S}.
mapfold_2(F, S, [T | Ts]) ->
{T1, S1} = mapfold(F, S, T),
{Ts1, S2} = mapfold_2(F, S1, Ts),
{[T1 | Ts1], S2};
mapfold_2(_, S, []) ->
{[], S}.
-spec mapfold_subtrees(fun((erl_syntax:syntaxTree(), term()) ->
{erl_syntax:syntaxTree(), term()}),
term(), erl_syntax:syntaxTree()) ->
{erl_syntax:syntaxTree(), term()}.
mapfold_subtrees(F, S, Tree) ->
case erl_syntax:subtrees(Tree) of
[] ->
{Tree, S};
Gs ->
{Gs1, S1} = mapfoldl_listlist(F, S, Gs),
Tree1 = erl_syntax:make_tree(erl_syntax:type(Tree), Gs1),
{erl_syntax:copy_attrs(Tree, Tree1), S1}
end.
, State , [ [ term ( ) ] ] ) - >
-spec mapfoldl_listlist(fun((term(), term()) -> {term(), term()}),
term(), [[term()]]) -> {[[term()]], term()}.
mapfoldl_listlist(F, S, [L | Ls]) ->
{L1, S1} = mapfoldl(F, S, L),
{Ls1, S2} = mapfoldl_listlist(F, S1, Ls),
{[L1 | Ls1], S2};
mapfoldl_listlist(_, S, []) ->
{[], S}.
mapfoldl(F, S, [L | Ls]) ->
{L1, S1} = F(L, S),
{Ls1, S2} = mapfoldl(F, S1, Ls),
{[L1 | Ls1], S2};
mapfoldl(_, S, []) ->
{[], S}.
( ) ) - > set(atom ( ) )
result is a set of variable names represented by atoms . Macro names
-spec variables(erl_syntax:syntaxTree()) -> sets:set(atom()).
variables(Tree) ->
variables(Tree, sets:new()).
variables(T, S) ->
case erl_syntax:type(T) of
variable ->
sets:add_element(erl_syntax:variable_name(T), S);
macro ->
case erl_syntax:macro_arguments(T) of
none -> S;
As ->
variables_2(As, S)
end;
_ ->
case erl_syntax:subtrees(T) of
[] ->
S;
Gs ->
variables_1(Gs, S)
end
end.
variables_1([L | Ls], S) ->
variables_1(Ls, variables_2(L, S));
variables_1([], S) ->
S.
variables_2([T | Ts], S) ->
variables_2(Ts, variables(T, S));
variables_2([], S) ->
S.
-define(MINIMUM_RANGE, 100).
-define(START_RANGE_FACTOR, 100).
default_variable_name(N) ->
list_to_atom("V" ++ integer_to_list(N)).
-spec new_variable_name(sets:set(atom())) -> atom().
new_variable_name(S) ->
new_variable_name(fun default_variable_name/1, S).
@spec new_variable_name(Function , Used::set(atom ( ) ) ) - > atom ( )
` rand : seed/1 ' or ` rand : seed/2 ' before this
function is first called .
@see
-spec new_variable_name(fun((integer()) -> atom()), sets:set(atom())) -> atom().
new_variable_name(F, S) ->
R = start_range(S),
new_variable_name(R, F, S).
new_variable_name(R, F, S) ->
new_variable_name(generate(R, R), R, 0, F, S).
new_variable_name(N, R, T, F, S) when T < ?MAX_RETRIES ->
A = F(N),
case sets:is_element(A, S) of
true ->
new_variable_name(generate(N, R), R, T + 1, F, S);
false ->
A
end;
new_variable_name(N, R, _T, F, S) ->
R1 = (R * ?ENLARGE_ENUM) div ?ENLARGE_DENOM,
new_variable_name(generate(N, R1), R1, 0, F, S).
start_range(S) ->
erlang:max(sets:size(S) * ?START_RANGE_FACTOR, ?MINIMUM_RANGE).
generate(_Key, Range) ->
_ = case rand:export_seed() of
undefined ->
rand:seed(exsplus, {753,8,73});
_ ->
ok
end,
( ) , Used::set(atom ( ) ) ) - > [ atom ( ) ]
@doc Like ` ' , but generates a list of
@see
-spec new_variable_names(integer(), sets:set(atom())) -> [atom()].
new_variable_names(N, S) ->
new_variable_names(N, fun default_variable_name/1, S).
( ) , Function ,
-spec new_variable_names(integer(), fun((integer()) -> atom()), sets:set(atom())) ->
[atom()].
new_variable_names(N, F, S) when is_integer(N) ->
R = start_range(S),
new_variable_names(N, [], R, F, S).
new_variable_names(N, Names, R, F, S) when N > 0 ->
Name = new_variable_name(R, F, S),
S1 = sets:add_element(Name, S),
new_variable_names(N - 1, [Name | Names], R, F, S1);
new_variable_names(0, Names, _, _, _) ->
Names.
< li>`{env , Vars } ' , representing the input environment
< li>`{bound , Vars } ' , representing the variables that
< li>`{free , Vars } ' , representing the free variables in
the subtree.</li >
` Bindings ' and ` Vars ' are ordered - set lists
-spec annotate_bindings(erl_syntax:syntaxTree(), ordsets:ordset(atom())) ->
erl_syntax:syntaxTree().
annotate_bindings(Tree, Env) ->
{Tree1, _, _} = vann(Tree, Env),
Tree1.
-spec annotate_bindings(erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
annotate_bindings(Tree) ->
As = erl_syntax:get_ann(Tree),
case lists:keyfind(env, 1, As) of
{env, InVars} ->
annotate_bindings(Tree, InVars);
_ ->
erlang:error(badarg)
end.
vann(Tree, Env) ->
case erl_syntax:type(Tree) of
variable ->
Bound = [],
Free = [erl_syntax:variable_name(Tree)],
{ann_bindings(Tree, Env, Bound, Free), Bound, Free};
match_expr ->
vann_match_expr(Tree, Env);
case_expr ->
vann_case_expr(Tree, Env);
if_expr ->
vann_if_expr(Tree, Env);
receive_expr ->
vann_receive_expr(Tree, Env);
catch_expr ->
vann_catch_expr(Tree, Env);
try_expr ->
vann_try_expr(Tree, Env);
function ->
vann_function(Tree, Env);
fun_expr ->
vann_fun_expr(Tree, Env);
named_fun_expr ->
vann_named_fun_expr(Tree, Env);
list_comp ->
vann_list_comp(Tree, Env);
binary_comp ->
vann_binary_comp(Tree, Env);
generator ->
vann_generator(Tree, Env);
binary_generator ->
vann_binary_generator(Tree, Env);
block_expr ->
vann_block_expr(Tree, Env);
macro ->
vann_macro(Tree, Env);
_Type ->
F = vann_list_join(Env),
{Tree1, {Bound, Free}} = mapfold_subtrees(F, {[], []},
Tree),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}
end.
vann_list_join(Env) ->
fun (T, {Bound, Free}) ->
{T1, Bound1, Free1} = vann(T, Env),
{T1, {ordsets:union(Bound, Bound1),
ordsets:union(Free, Free1)}}
end.
vann_list(Ts, Env) ->
lists:mapfoldl(vann_list_join(Env), {[], []}, Ts).
vann_function(Tree, Env) ->
Cs = erl_syntax:function_clauses(Tree),
{Cs1, {_, Free}} = vann_clauses(Cs, Env),
N = erl_syntax:function_name(Tree),
{N1, _, _} = vann(N, Env),
Tree1 = rewrite(Tree, erl_syntax:function(N1, Cs1)),
Bound = [],
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_fun_expr(Tree, Env) ->
Cs = erl_syntax:fun_expr_clauses(Tree),
{Cs1, {_, Free}} = vann_clauses(Cs, Env),
Tree1 = rewrite(Tree, erl_syntax:fun_expr(Cs1)),
Bound = [],
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_named_fun_expr(Tree, Env) ->
N = erl_syntax:named_fun_expr_name(Tree),
NBound = [erl_syntax:variable_name(N)],
NFree = [],
N1 = ann_bindings(N, Env, NBound, NFree),
Env1 = ordsets:union(Env, NBound),
Cs = erl_syntax:named_fun_expr_clauses(Tree),
{Cs1, {_, Free}} = vann_clauses(Cs, Env1),
Tree1 = rewrite(Tree, erl_syntax:named_fun_expr(N1,Cs1)),
Bound = [],
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_match_expr(Tree, Env) ->
E = erl_syntax:match_expr_body(Tree),
{E1, Bound1, Free1} = vann(E, Env),
Env1 = ordsets:union(Env, Bound1),
P = erl_syntax:match_expr_pattern(Tree),
{P1, Bound2, Free2} = vann_pattern(P, Env1),
Bound = ordsets:union(Bound1, Bound2),
Free = ordsets:union(Free1, Free2),
Tree1 = rewrite(Tree, erl_syntax:match_expr(P1, E1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_case_expr(Tree, Env) ->
E = erl_syntax:case_expr_argument(Tree),
{E1, Bound1, Free1} = vann(E, Env),
Env1 = ordsets:union(Env, Bound1),
Cs = erl_syntax:case_expr_clauses(Tree),
{Cs1, {Bound2, Free2}} = vann_clauses(Cs, Env1),
Bound = ordsets:union(Bound1, Bound2),
Free = ordsets:union(Free1, Free2),
Tree1 = rewrite(Tree, erl_syntax:case_expr(E1, Cs1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_if_expr(Tree, Env) ->
Cs = erl_syntax:if_expr_clauses(Tree),
{Cs1, {Bound, Free}} = vann_clauses(Cs, Env),
Tree1 = rewrite(Tree, erl_syntax:if_expr(Cs1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_catch_expr(Tree, Env) ->
E = erl_syntax:catch_expr_body(Tree),
{E1, _, Free} = vann(E, Env),
Tree1 = rewrite(Tree, erl_syntax:catch_expr(E1)),
Bound = [],
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_try_expr(Tree, Env) ->
Es = erl_syntax:try_expr_body(Tree),
{Es1, {Bound1, Free1}} = vann_body(Es, Env),
Cs = erl_syntax:try_expr_clauses(Tree),
{Cs1, {_, Free2}} = vann_clauses(Cs, ordsets:union(Env, Bound1)),
Hs = erl_syntax:try_expr_handlers(Tree),
{Hs1, {_, Free3}} = vann_clauses(Hs, Env),
As = erl_syntax:try_expr_after(Tree),
{As1, {_, Free4}} = vann_body(As, Env),
Tree1 = rewrite(Tree, erl_syntax:try_expr(Es1, Cs1, Hs1, As1)),
Bound = [],
Free = ordsets:union(Free1, ordsets:union(Free2, ordsets:union(Free3, Free4))),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_receive_expr(Tree, Env) ->
Cs = erl_syntax:receive_expr_clauses(Tree),
Es = erl_syntax:receive_expr_action(Tree),
C = erl_syntax:clause([], Es),
{[C1 | Cs1], {Bound, Free1}} = vann_clauses([C | Cs], Env),
Es1 = erl_syntax:clause_body(C1),
{T1, _, Free2} = case erl_syntax:receive_expr_timeout(Tree) of
none ->
{none, [], []};
T ->
vann(T, Env)
end,
Free = ordsets:union(Free1, Free2),
Tree1 = rewrite(Tree, erl_syntax:receive_expr(Cs1, T1, Es1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_list_comp(Tree, Env) ->
Es = erl_syntax:list_comp_body(Tree),
{Es1, {Bound1, Free1}} = vann_list_comp_body(Es, Env),
Env1 = ordsets:union(Env, Bound1),
T = erl_syntax:list_comp_template(Tree),
{T1, _, Free2} = vann(T, Env1),
Free = ordsets:union(Free1, ordsets:subtract(Free2, Bound1)),
Bound = [],
Tree1 = rewrite(Tree, erl_syntax:list_comp(T1, Es1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_list_comp_body_join() ->
fun (T, {Env, Bound, Free}) ->
{T1, Bound1, Free1} = case erl_syntax:type(T) of
binary_generator ->
vann_binary_generator(T,Env);
generator ->
vann_generator(T, Env);
_ ->
{T2, _, Free2} = vann(T, Env),
{T2, [], Free2}
end,
Env1 = ordsets:union(Env, Bound1),
{T1, {Env1, ordsets:union(Bound, Bound1),
ordsets:union(Free,
ordsets:subtract(Free1, Bound))}}
end.
vann_list_comp_body(Ts, Env) ->
F = vann_list_comp_body_join(),
{Ts1, {_, Bound, Free}} = lists:mapfoldl(F, {Env, [], []}, Ts),
{Ts1, {Bound, Free}}.
vann_binary_comp(Tree, Env) ->
Es = erl_syntax:binary_comp_body(Tree),
{Es1, {Bound1, Free1}} = vann_binary_comp_body(Es, Env),
Env1 = ordsets:union(Env, Bound1),
T = erl_syntax:binary_comp_template(Tree),
{T1, _, Free2} = vann(T, Env1),
Free = ordsets:union(Free1, ordsets:subtract(Free2, Bound1)),
Bound = [],
Tree1 = rewrite(Tree, erl_syntax:binary_comp(T1, Es1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_binary_comp_body_join() ->
fun (T, {Env, Bound, Free}) ->
{T1, Bound1, Free1} = case erl_syntax:type(T) of
binary_generator ->
vann_binary_generator(T, Env);
generator ->
vann_generator(T, Env);
_ ->
{T2, _, Free2} = vann(T, Env),
{T2, [], Free2}
end,
Env1 = ordsets:union(Env, Bound1),
{T1, {Env1, ordsets:union(Bound, Bound1),
ordsets:union(Free,
ordsets:subtract(Free1, Bound))}}
end.
vann_binary_comp_body(Ts, Env) ->
F = vann_binary_comp_body_join(),
{Ts1, {_, Bound, Free}} = lists:mapfoldl(F, {Env, [], []}, Ts),
{Ts1, {Bound, Free}}.
vann_generator(Tree, Env) ->
P = erl_syntax:generator_pattern(Tree),
{P1, Bound, _} = vann_pattern(P, []),
E = erl_syntax:generator_body(Tree),
{E1, _, Free} = vann(E, Env),
Tree1 = rewrite(Tree, erl_syntax:generator(P1, E1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_binary_generator(Tree, Env) ->
P = erl_syntax:binary_generator_pattern(Tree),
{P1, Bound, _} = vann_pattern(P, Env),
E = erl_syntax:binary_generator_body(Tree),
{E1, _, Free} = vann(E, Env),
Tree1 = rewrite(Tree, erl_syntax:binary_generator(P1, E1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_block_expr(Tree, Env) ->
Es = erl_syntax:block_expr_body(Tree),
{Es1, {Bound, Free}} = vann_body(Es, Env),
Tree1 = rewrite(Tree, erl_syntax:block_expr(Es1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_body_join() ->
fun (T, {Env, Bound, Free}) ->
{T1, Bound1, Free1} = vann(T, Env),
Env1 = ordsets:union(Env, Bound1),
{T1, {Env1, ordsets:union(Bound, Bound1),
ordsets:union(Free,
ordsets:subtract(Free1, Bound))}}
end.
vann_body(Ts, Env) ->
{Ts1, {_, Bound, Free}} = lists:mapfoldl(vann_body_join(),
{Env, [], []}, Ts),
{Ts1, {Bound, Free}}.
Macro names must be ignored even if they happen to be variables ,
vann_macro(Tree, Env) ->
{As, {Bound, Free}} = case erl_syntax:macro_arguments(Tree) of
none ->
{none, {[], []}};
As1 ->
vann_list(As1, Env)
end,
N = erl_syntax:macro_name(Tree),
Tree1 = rewrite(Tree, erl_syntax:macro(N, As)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_pattern(Tree, Env) ->
case erl_syntax:type(Tree) of
variable ->
V = erl_syntax:variable_name(Tree),
case ordsets:is_element(V, Env) of
true ->
Bound = [],
Free = [V],
{ann_bindings(Tree, Env, Bound, Free), Bound, Free};
false ->
Bound = [V],
Free = [],
{ann_bindings(Tree, Env, Bound, Free), Bound, Free}
end;
match_expr ->
pattern
P = erl_syntax:match_expr_pattern(Tree),
{P1, Bound1, Free1} = vann_pattern(P, Env),
E = erl_syntax:match_expr_body(Tree),
{E1, Bound2, Free2} = vann_pattern(E, Env),
Bound = ordsets:union(Bound1, Bound2),
Free = ordsets:union(Free1, Free2),
Tree1 = rewrite(Tree, erl_syntax:match_expr(P1, E1)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free};
macro ->
{As, {Bound, Free}} =
case erl_syntax:macro_arguments(Tree) of
none ->
{none, {[], []}};
As1 ->
vann_patterns(As1, Env)
end,
N = erl_syntax:macro_name(Tree),
Tree1 = rewrite(Tree, erl_syntax:macro(N, As)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free};
_Type ->
F = vann_patterns_join(Env),
{Tree1, {Bound, Free}} = mapfold_subtrees(F, {[], []},
Tree),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}
end.
vann_patterns_join(Env) ->
fun (T, {Bound, Free}) ->
{T1, Bound1, Free1} = vann_pattern(T, Env),
{T1, {ordsets:union(Bound, Bound1),
ordsets:union(Free, Free1)}}
end.
vann_patterns(Ps, Env) ->
lists:mapfoldl(vann_patterns_join(Env), {[], []}, Ps).
vann_clause(C, Env) ->
{Ps, {Bound1, Free1}} = vann_patterns(erl_syntax:clause_patterns(C),
Env),
Env1 = ordsets:union(Env, Bound1),
{G1, _, Free2} = case erl_syntax:clause_guard(C) of
none ->
{none, [], []};
G ->
vann(G, Env1)
end,
{Es, {Bound2, Free3}} = vann_body(erl_syntax:clause_body(C), Env1),
Bound = ordsets:union(Bound1, Bound2),
Free = ordsets:union(Free1,
ordsets:subtract(ordsets:union(Free2, Free3),
Bound1)),
Tree1 = rewrite(C, erl_syntax:clause(Ps, G1, Es)),
{ann_bindings(Tree1, Env, Bound, Free), Bound, Free}.
vann_clauses_join(Env) ->
fun (C, {Bound, Free}) ->
{C1, Bound1, Free1} = vann_clause(C, Env),
{C1, {ordsets:intersection(Bound, Bound1),
ordsets:union(Free, Free1)}}
end.
vann_clauses([C | Cs], Env) ->
{C1, Bound, Free} = vann_clause(C, Env),
{Cs1, BF} = lists:mapfoldl(vann_clauses_join(Env), {Bound, Free}, Cs),
{[C1 | Cs1], BF};
vann_clauses([], _Env) ->
{[], {[], []}}.
ann_bindings(Tree, Env, Bound, Free) ->
As0 = erl_syntax:get_ann(Tree),
As1 = [{env, Env},
{bound, Bound},
{free, Free}
| delete_binding_anns(As0)],
erl_syntax:set_ann(Tree, As1).
delete_binding_anns([{env, _} | As]) ->
delete_binding_anns(As);
delete_binding_anns([{bound, _} | As]) ->
delete_binding_anns(As);
delete_binding_anns([{free, _} | As]) ->
delete_binding_anns(As);
delete_binding_anns([A | As]) ->
[A | delete_binding_anns(As)];
delete_binding_anns([]) ->
[].
( ) ) - > boolean ( )
` exit/1 ' , ` throw/1 ' ,
` erlang : error/1 ' and ` erlang : error/2 ' .
@see //erts / erlang : exit/1
@see //erts / erlang : error/2
-spec is_fail_expr(erl_syntax:syntaxTree()) -> boolean().
is_fail_expr(E) ->
case erl_syntax:type(E) of
application ->
N = length(erl_syntax:application_arguments(E)),
F = erl_syntax:application_operator(E),
case catch {ok, analyze_function_name(F)} of
syntax_error ->
false;
{ok, exit} when N =:= 1 ->
true;
{ok, throw} when N =:= 1 ->
true;
{ok, {erlang, exit}} when N =:= 1 ->
true;
{ok, {erlang, throw}} when N =:= 1 ->
true;
{ok, {erlang, error}} when N =:= 1 ->
true;
{ok, {erlang, error}} when N =:= 2 ->
true;
{ok, {erlang, fault}} when N =:= 1 ->
true;
{ok, {erlang, fault}} when N =:= 2 ->
true;
_ ->
false
end;
_ ->
false
end.
list . The order of listing is not defined.</dd >
` Forms ' . The order of listing is not defined.</dd >
| { ModuleName , FunctionName}'</li >
listing is not defined.</dd >
< li>`Functions = [ { atom ( ) , integer()}]'</li >
not defined.</dd >
= atom()'</li >
| { ModuleName , FunctionName}'</li >
listing is not defined.</dd >
` ModuleName ' is the name declared by a module
should occur , all but the first will be ignored.</dd >
order of listing is not defined.</dd >
` Forms ' . The order of listing is not defined.</dd >
Erlang construct is encountered .
@see analyze_function/1
@see erl_syntax : error_marker_info/1
-type key() :: 'attributes' | 'errors' | 'exports' | 'functions' | 'imports'
| 'module' | 'records' | 'warnings'.
-type info_pair() :: {key(), term()}.
-spec analyze_forms(erl_syntax:forms()) -> [info_pair()].
analyze_forms(Forms) when is_list(Forms) ->
finfo_to_list(lists:foldl(fun collect_form/2, new_finfo(), Forms));
analyze_forms(Forms) ->
analyze_forms(
erl_syntax:form_list_elements(
erl_syntax:flatten_form_list(Forms))).
collect_form(Node, Info) ->
case analyze_form(Node) of
{attribute, {Name, Data}} ->
collect_attribute(Name, Data, Info);
{attribute, preprocessor} ->
Info;
{function, Name} ->
finfo_add_function(Name, Info);
{error_marker, Data} ->
finfo_add_error(Data, Info);
{warning_marker, Data} ->
finfo_add_warning(Data, Info);
_ ->
Info
end.
collect_attribute(module, M, Info) ->
finfo_set_module(M, Info);
collect_attribute(export, L, Info) ->
finfo_add_exports(L, Info);
collect_attribute(import, {M, L}, Info) ->
finfo_add_imports(M, L, Info);
collect_attribute(import, M, Info) ->
finfo_add_module_import(M, Info);
collect_attribute(file, _, Info) ->
Info;
collect_attribute(record, {R, L}, Info) ->
finfo_add_record(R, L, Info);
collect_attribute(N, V, Info) ->
finfo_add_attribute(N, V, Info).
-record(forms, {module = none :: 'none' | {'value', atom()},
exports = [] :: [{atom(), arity()}],
module_imports = [] :: [atom()],
imports = [] :: [{atom(), [{atom(), arity()}]}],
attributes = [] :: [{atom(), term()}],
records = [] :: [{atom(), [{atom(),
field_default(),
field_type()}]}],
errors = [] :: [term()],
warnings = [] :: [term()],
functions = [] :: [{atom(), arity()}]}).
-type field_default() :: 'none' | erl_syntax:syntaxTree().
-type field_type() :: 'none' | erl_syntax:syntaxTree().
new_finfo() ->
#forms{}.
finfo_set_module(Name, Info) ->
case Info#forms.module of
none ->
Info#forms{module = {value, Name}};
{value, _} ->
Info
end.
finfo_add_exports(L, Info) ->
Info#forms{exports = L ++ Info#forms.exports}.
finfo_add_module_import(M, Info) ->
Info#forms{module_imports = [M | Info#forms.module_imports]}.
finfo_add_imports(M, L, Info) ->
Es = Info#forms.imports,
case lists:keyfind(M, 1, Es) of
{_, L1} ->
Es1 = lists:keyreplace(M, 1, Es, {M, L ++ L1}),
Info#forms{imports = Es1};
false ->
Info#forms{imports = [{M, L} | Es]}
end.
finfo_add_attribute(Name, Val, Info) ->
Info#forms{attributes = [{Name, Val} | Info#forms.attributes]}.
finfo_add_record(R, L, Info) ->
Info#forms{records = [{R, L} | Info#forms.records]}.
finfo_add_error(R, Info) ->
Info#forms{errors = [R | Info#forms.errors]}.
finfo_add_warning(R, Info) ->
Info#forms{warnings = [R | Info#forms.warnings]}.
finfo_add_function(F, Info) ->
Info#forms{functions = [F | Info#forms.functions]}.
finfo_to_list(Info) ->
[{Key, Value}
|| {Key, {value, Value}} <-
[{module, Info#forms.module},
{exports, list_value(Info#forms.exports)},
{imports, list_value(Info#forms.imports)},
{module_imports, list_value(Info#forms.module_imports)},
{attributes, list_value(Info#forms.attributes)},
{records, list_value(Info#forms.records)},
{errors, list_value(Info#forms.errors)},
{warnings, list_value(Info#forms.warnings)},
{functions, list_value(Info#forms.functions)}
]].
list_value([]) ->
none;
list_value(List) ->
{value, List}.
@doc Analyzes a " source code form " node . If ` Node ' is a
` Node ' is not well - formed .
@see analyze_function/1
@see erl_syntax : error_marker_info/1
-spec analyze_form(erl_syntax:syntaxTree()) -> {atom(), term()} | atom().
analyze_form(Node) ->
case erl_syntax:type(Node) of
attribute ->
{attribute, analyze_attribute(Node)};
function ->
{function, analyze_function(Node)};
error_marker ->
{error_marker, erl_syntax:error_marker_info(Node)};
warning_marker ->
{warning_marker, erl_syntax:warning_marker_info(Node)};
_ ->
case erl_syntax:is_form(Node) of
true ->
erl_syntax:type(Node);
false ->
throw(syntax_error)
end
end.
< dt>`{export , Info}'</dt >
< dt>`{import , Info}'</dt >
@see analyze_module_attribute/1
-spec analyze_attribute(erl_syntax:syntaxTree()) ->
analyze_attribute(Node) ->
Name = erl_syntax:attribute_name(Node),
case erl_syntax:type(Name) of
atom ->
case erl_syntax:atom_value(Name) of
define -> preprocessor;
undef -> preprocessor;
include -> preprocessor;
include_lib -> preprocessor;
ifdef -> preprocessor;
ifndef -> preprocessor;
'if' -> preprocessor;
elif -> preprocessor;
'else' -> preprocessor;
endif -> preprocessor;
A ->
{A, analyze_attribute(A, Node)}
end;
_ ->
throw(syntax_error)
end.
analyze_attribute(module, Node) ->
analyze_module_attribute(Node);
analyze_attribute(export, Node) ->
analyze_export_attribute(Node);
analyze_attribute(import, Node) ->
analyze_import_attribute(Node);
analyze_attribute(file, Node) ->
analyze_file_attribute(Node);
analyze_attribute(record, Node) ->
analyze_record_attribute(Node);
analyze_attribute(_, Node) ->
{_, Info} = analyze_wild_attribute(Node),
Info.
( ) ) - >
-spec analyze_module_attribute(erl_syntax:syntaxTree()) ->
atom() | {atom(), [atom()]}.
analyze_module_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[M] ->
module_name_to_atom(M);
[M, L] ->
M1 = module_name_to_atom(M),
L1 = analyze_variable_list(L),
{M1, L1};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
analyze_variable_list(Node) ->
case erl_syntax:is_proper_list(Node) of
true ->
[erl_syntax:variable_name(V)
|| V <- erl_syntax:list_elements(Node)];
false ->
throw(syntax_error)
end.
( ) ) - > [ FunctionName ]
| { ModuleName , FunctionName }
ModuleName = atom ( )
-type functionN() :: atom() | {atom(), arity()}.
-type functionName() :: functionN() | {atom(), functionN()}.
-spec analyze_export_attribute(erl_syntax:syntaxTree()) -> [functionName()].
analyze_export_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[L] ->
analyze_function_name_list(L);
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
analyze_function_name_list(Node) ->
case erl_syntax:is_proper_list(Node) of
true ->
[analyze_function_name(F)
|| F <- erl_syntax:list_elements(Node)];
false ->
throw(syntax_error)
end.
| { ModuleName , FunctionName }
ModuleName = atom ( )
` Node ' represents a function name , such as
` Node ' does not represent a well - formed function name .
-spec analyze_function_name(erl_syntax:syntaxTree()) -> functionName().
analyze_function_name(Node) ->
case erl_syntax:type(Node) of
atom ->
erl_syntax:atom_value(Node);
arity_qualifier ->
A = erl_syntax:arity_qualifier_argument(Node),
case erl_syntax:type(A) of
integer ->
F = erl_syntax:arity_qualifier_body(Node),
F1 = analyze_function_name(F),
append_arity(erl_syntax:integer_value(A), F1);
_ ->
throw(syntax_error)
end;
module_qualifier ->
M = erl_syntax:module_qualifier_argument(Node),
case erl_syntax:type(M) of
atom ->
F = erl_syntax:module_qualifier_body(Node),
F1 = analyze_function_name(F),
{erl_syntax:atom_value(M), F1};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
append_arity(A, {Module, Name}) ->
{Module, append_arity(A, Name)};
append_arity(A, Name) when is_atom(Name) ->
{Name, A};
append_arity(A, A) ->
A;
append_arity(_A, Name) ->
| { ModuleName , FunctionName }
ModuleName = atom ( )
-spec analyze_import_attribute(erl_syntax:syntaxTree()) ->
{atom(), [functionName()]} | atom().
analyze_import_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[M] ->
module_name_to_atom(M);
[M, L] ->
M1 = module_name_to_atom(M),
L1 = analyze_function_name_list(L),
{M1, L1};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
@spec analyze_type_name(Node::syntaxTree ( ) ) - > TypeName
| { ModuleName , { atom ( ) , integer ( ) } }
ModuleName = atom ( )
` Node ' represents a type name , such as
` Node ' does not represent a well - formed type name .
-spec analyze_type_name(erl_syntax:syntaxTree()) -> typeName().
analyze_type_name(Node) ->
case erl_syntax:type(Node) of
atom ->
erl_syntax:atom_value(Node);
arity_qualifier ->
A = erl_syntax:arity_qualifier_argument(Node),
N = erl_syntax:arity_qualifier_body(Node),
case ((erl_syntax:type(A) =:= integer)
and (erl_syntax:type(N) =:= atom))
of
true ->
append_arity(erl_syntax:integer_value(A),
erl_syntax:atom_value(N));
_ ->
throw(syntax_error)
end;
module_qualifier ->
M = erl_syntax:module_qualifier_argument(Node),
case erl_syntax:type(M) of
atom ->
N = erl_syntax:module_qualifier_body(Node),
N1 = analyze_type_name(N),
{erl_syntax:atom_value(M), N1};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
( ) ) - > { atom ( ) , term ( ) }
-spec analyze_wild_attribute(erl_syntax:syntaxTree()) -> {atom(), term()}.
analyze_wild_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
N = erl_syntax:attribute_name(Node),
case erl_syntax:type(N) of
atom ->
case erl_syntax:attribute_arguments(Node) of
[V] ->
case catch {ok, erl_syntax:concrete(V)} of
{ok, Val} ->
{erl_syntax:atom_value(N), Val};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
" ` Label = Default : : Type ' " in the declaration ,
` Node ' does not represent a well - formed record declaration
@see analyze_record_field/1
-type field() :: {atom(), {field_default(), field_type()}}.
-type fields() :: [field()].
-spec analyze_record_attribute(erl_syntax:syntaxTree()) -> {atom(), fields()}.
analyze_record_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[R, T] ->
case erl_syntax:type(R) of
atom ->
Es = analyze_record_attribute_tuple(T),
{erl_syntax:atom_value(R), Es};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
analyze_record_attribute_tuple(Node) ->
case erl_syntax:type(Node) of
tuple ->
[analyze_record_field(F)
|| F <- erl_syntax:tuple_elements(Node)];
_ ->
throw(syntax_error)
end.
< dd>`{atom ( ) , [ { atom ( ) , Value}]}'</dd >
` { Label , Value } ' , if ` Node ' represents " ` Label = Value ' " .
` Node ' represents a record expression that is not
@see analyze_record_field/1
-type info() :: {atom(), [{atom(), erl_syntax:syntaxTree()}]}
| {atom(), atom()} | atom().
-spec analyze_record_expr(erl_syntax:syntaxTree()) -> {atom(), info()} | atom().
analyze_record_expr(Node) ->
case erl_syntax:type(Node) of
record_expr ->
A = erl_syntax:record_expr_type(Node),
case erl_syntax:type(A) of
atom ->
Fs0 = [analyze_record_field(F)
|| F <- erl_syntax:record_expr_fields(Node)],
Fs = [{N, D} || {N, {D, _T}} <- Fs0],
{record_expr, {erl_syntax:atom_value(A), Fs}};
_ ->
throw(syntax_error)
end;
record_access ->
F = erl_syntax:record_access_field(Node),
case erl_syntax:type(F) of
atom ->
A = erl_syntax:record_access_type(Node),
case erl_syntax:type(A) of
atom ->
{record_access,
{erl_syntax:atom_value(A),
erl_syntax:atom_value(F)}};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
record_index_expr ->
F = erl_syntax:record_index_expr_field(Node),
case erl_syntax:type(F) of
atom ->
A = erl_syntax:record_index_expr_type(Node),
case erl_syntax:type(A) of
atom ->
{record_index_expr,
{erl_syntax:atom_value(A),
erl_syntax:atom_value(F)}};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
Type ->
Type
end.
( ) ) - > { atom ( ) , { Default , Type } }
` Node ' represents " ` Label ' " , " ` Label = Default ' " ,
" ` Label : : Type ' " , or " ` Label = Default : : Type ' " .
` Node ' does not represent a well - formed record field
-spec analyze_record_field(erl_syntax:syntaxTree()) -> field().
analyze_record_field(Node) ->
case erl_syntax:type(Node) of
record_field ->
A = erl_syntax:record_field_name(Node),
case erl_syntax:type(A) of
atom ->
T = erl_syntax:record_field_value(Node),
{erl_syntax:atom_value(A), {T, none}};
_ ->
throw(syntax_error)
end;
typed_record_field ->
F = erl_syntax:typed_record_field_body(Node),
{N, {V, _none}} = analyze_record_field(F),
T = erl_syntax:typed_record_field_type(Node),
{N, {V, T}};
_ ->
throw(syntax_error)
end.
( ) ) - >
` Node ' represents " ` -file(File , Line ) . ' " .
` Node ' does not represent a well - formed ` file '
-spec analyze_file_attribute(erl_syntax:syntaxTree()) -> {string(), integer()}.
analyze_file_attribute(Node) ->
case erl_syntax:type(Node) of
attribute ->
case erl_syntax:attribute_arguments(Node) of
[F, N] ->
case (erl_syntax:type(F) =:= string)
and (erl_syntax:type(N) =:= integer) of
true ->
{erl_syntax:string_value(F),
erl_syntax:integer_value(N)};
false ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
( ) ) - > { atom ( ) , integer ( ) }
function definition " ` Name(P_1 , ... , P_A ) - >
` Node ' does not represent a well - formed function
-spec analyze_function(erl_syntax:syntaxTree()) -> {atom(), arity()}.
analyze_function(Node) ->
case erl_syntax:type(Node) of
function ->
N = erl_syntax:function_name(Node),
case erl_syntax:type(N) of
atom ->
{erl_syntax:atom_value(N),
erl_syntax:function_arity(Node)};
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
| { ModuleName , FunctionName }
ModuleName = atom ( )
` Node ' does not represent a well - formed implicit fun .
-spec analyze_implicit_fun(erl_syntax:syntaxTree()) -> functionName().
analyze_implicit_fun(Node) ->
case erl_syntax:type(Node) of
implicit_fun ->
analyze_function_name(erl_syntax:implicit_fun_name(Node));
_ ->
throw(syntax_error)
end.
| { ModuleName , FunctionName }
ModuleName = atom ( )
" ` F(X_1 , ... , ) ' " . If the
-type appFunName() :: {atom(), arity()} | {atom(), {atom(), arity()}}.
-spec analyze_application(erl_syntax:syntaxTree()) -> appFunName() | arity().
analyze_application(Node) ->
case erl_syntax:type(Node) of
application ->
A = length(erl_syntax:application_arguments(Node)),
F = erl_syntax:application_operator(Node),
case catch {ok, analyze_function_name(F)} of
syntax_error ->
A;
{ok, N} ->
append_arity(A, N);
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
| { ModuleName , { atom ( ) , integer ( ) } }
ModuleName = atom ( )
@see analyze_type_name/1
-type typeName() :: atom() | {module(), {atom(), arity()}} | {atom(), arity()}.
-spec analyze_type_application(erl_syntax:syntaxTree()) -> typeName().
analyze_type_application(Node) ->
case erl_syntax:type(Node) of
type_application ->
A = length(erl_syntax:type_application_arguments(Node)),
N = erl_syntax:type_application_name(Node),
case catch {ok, analyze_type_name(N)} of
{ok, TypeName} ->
append_arity(A, TypeName);
_ ->
throw(syntax_error)
end;
user_type_application ->
A = length(erl_syntax:user_type_application_arguments(Node)),
N = erl_syntax:user_type_application_name(Node),
case catch {ok, analyze_type_name(N)} of
{ok, TypeName} ->
append_arity(A, TypeName);
_ ->
throw(syntax_error)
end;
_ ->
throw(syntax_error)
end.
] ) - > [ { ShortName , Name } ]
Note : the resulting list can contain more than one tuple
-type shortname() :: atom() | {atom(), arity()}.
-type name() :: shortname() | {atom(), shortname()}.
-spec function_name_expansions([name()]) -> [{shortname(), name()}].
function_name_expansions(Fs) ->
function_name_expansions(Fs, []).
function_name_expansions([F | Fs], Ack) ->
function_name_expansions(Fs,
function_name_expansions(F, F, Ack));
function_name_expansions([], Ack) ->
Ack.
function_name_expansions({A, N}, Name, Ack) when is_integer(N) ->
[{{A, N}, Name} | Ack];
function_name_expansions({_, N}, Name, Ack) ->
function_name_expansions(N, Name, Ack);
function_name_expansions(A, Name, Ack) ->
[{A, Name} | Ack].
( ) ) - > syntaxTree ( )
Standalone comments in form lists are removed ; any other standalone
-spec strip_comments(erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
strip_comments(Tree) ->
map(fun strip_comments_1/1, Tree).
strip_comments_1(T) ->
case erl_syntax:type(T) of
form_list ->
Es = erl_syntax:form_list_elements(T),
Es1 = [E || E <- Es, erl_syntax:type(E) /= comment],
T1 = erl_syntax:copy_attrs(T, erl_syntax:form_list(Es1)),
erl_syntax:remove_comments(T1);
comment ->
erl_syntax:comment([]);
_ ->
erl_syntax:remove_comments(T)
end.
) - > syntaxTree ( )
-spec to_comment(erl_syntax:syntaxTree()) -> erl_syntax:syntaxTree().
to_comment(Tree) ->
to_comment(Tree, "% ").
( ) , ( ) ) - >
@see to_comment/3
-spec to_comment(erl_syntax:syntaxTree(), string()) -> erl_syntax:syntaxTree().
to_comment(Tree, Prefix) ->
F = fun (T) -> erl_prettypr:format(T) end,
to_comment(Tree, Prefix, F).
( ) , ( ) , Printer ) - >
@see to_comment/2
-spec to_comment(erl_syntax:syntaxTree(), string(),
fun((erl_syntax:syntaxTree()) -> string())) ->
erl_syntax:syntaxTree().
to_comment(Tree, Prefix, F) ->
erl_syntax:comment(split_lines(F(Tree), Prefix)).
, Depth ) - > syntaxTree ( )
@see limit/3
-spec limit(erl_syntax:syntaxTree(), integer()) -> erl_syntax:syntaxTree().
limit(Tree, Depth) ->
limit(Tree, Depth, erl_syntax:text("...")).
@spec limit(Tree::syntaxTree ( ) , ( ) ,
( ) ) - > syntaxTree ( )
are two or more subtrees in the group , these will be collectively
replaced by ` Node ' even if they are leaf nodes . Groups of
as if each subsequent tree in the group were one level deeper than
integers " ` [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] ' " , the result
of ` limit(Tree , 5 ) ' will represent ` [ 1 , 2 , 3 , 4 ,
-spec limit(erl_syntax:syntaxTree(), integer(), erl_syntax:syntaxTree()) ->
erl_syntax:syntaxTree().
limit(_Tree, Depth, Node) when Depth < 0 ->
Node;
limit(Tree, Depth, Node) ->
limit_1(Tree, Depth, Node).
limit_1(Tree, Depth, Node) ->
case erl_syntax:subtrees(Tree) of
[] ->
if Depth > 0 ->
Tree;
true ->
case is_simple_leaf(Tree) of
true ->
Tree;
false ->
Node
end
end;
Gs ->
if Depth > 1 ->
Gs1 = [[limit_1(T, Depth - 1, Node)
|| T <- limit_list(G, Depth, Node)]
|| G <- Gs],
rewrite(Tree,
erl_syntax:make_tree(erl_syntax:type(Tree),
Gs1));
Depth =:= 0 ->
Depth is zero , and this is not a leaf node
Node;
true ->
Depth is 1 , so all subtrees are to be cut .
Gs1 = [cut_group(G, Node) || G <- Gs],
rewrite(Tree,
erl_syntax:make_tree(erl_syntax:type(Tree),
Gs1))
end
end.
cut_group([], _Node) ->
[];
cut_group([T], Node) ->
[limit_1(T, 0, Node)];
cut_group(_Ts, Node) ->
[Node].
is_simple_leaf(Tree) ->
case erl_syntax:type(Tree) of
atom -> true;
char -> true;
float -> true;
integer -> true;
nil -> true;
operator -> true;
tuple -> true;
underscore -> true;
variable -> true;
_ -> false
end.
append ; otherwise return list as is .
limit_list(Ts, N, Node) ->
if length(Ts) > N ->
limit_list_1(Ts, N - 1, Node);
true ->
Ts
end.
limit_list_1([T | Ts], N, Node) ->
if N > 0 ->
[T | limit_list_1(Ts, N - 1, Node)];
true ->
[Node]
end;
limit_list_1([], _N, _Node) ->
[].
rewrite(Tree, Tree1) ->
erl_syntax:copy_attrs(Tree, Tree1).
module_name_to_atom(M) ->
case erl_syntax:type(M) of
atom ->
erl_syntax:atom_value(M);
_ ->
throw(syntax_error)
end.
spaces . The width of a tab is assumed to be 8 .
split_lines(Cs, Prefix) ->
split_lines(Cs, Prefix, 0).
split_lines(Cs, Prefix, N) ->
lists:reverse(split_lines(Cs, N, [], [], Prefix)).
split_lines([$\r, $\n | Cs], _N, Cs1, Ls, Prefix) ->
split_lines_1(Cs, Cs1, Ls, Prefix);
split_lines([$\r | Cs], _N, Cs1, Ls, Prefix) ->
split_lines_1(Cs, Cs1, Ls, Prefix);
split_lines([$\n | Cs], _N, Cs1, Ls, Prefix) ->
split_lines_1(Cs, Cs1, Ls, Prefix);
split_lines([$\t | Cs], N, Cs1, Ls, Prefix) ->
split_lines(Cs, 0, push(8 - (N rem 8), $\040, Cs1), Ls,
Prefix);
split_lines([C | Cs], N, Cs1, Ls, Prefix) ->
split_lines(Cs, N + 1, [C | Cs1], Ls, Prefix);
split_lines([], _, [], Ls, _) ->
Ls;
split_lines([], _N, Cs, Ls, Prefix) ->
[Prefix ++ lists:reverse(Cs) | Ls].
split_lines_1(Cs, Cs1, Ls, Prefix) ->
split_lines(Cs, 0, [], [Prefix ++ lists:reverse(Cs1) | Ls],
Prefix).
push(N, C, Cs) when N > 0 ->
push(N - 1, C, [C | Cs]);
push(0, _, Cs) ->
Cs.
|
cccea4d2497ab6bc2fae3c3ee5f48c63a2f23dedec029e836437673b17ef75f0 | exoscale/tools.project | git.clj | (ns exoscale.tools.project.api.git
(:require [clojure.tools.deps.alpha.util.dir :as td]
[exoscale.tools.project.api.version :as v]
[exoscale.tools.project.io :as pio]
[clojure.string :as str]))
(defn commit-version
[opts]
(pio/shell ["git add VERSION"
"git commit -m \"Version $VERSION\""]
{:dir td/*the-dir*
:env {"VERSION" (v/get-version opts)}}))
(defn tag-version
[opts]
(pio/shell ["git tag -a \"$VERSION\" --no-sign -m \"Release $VERSION\""]
{:dir td/*the-dir*
:env {"VERSION" (v/get-version opts)}}))
(defn push
[_]
(pio/shell ["git pull"
"git push --follow-tags"]
{:dir td/*the-dir*}))
(defn revision-sha
[_]
(-> (pio/shell ["git rev-parse HEAD"] {:dir td/*the-dir* :out :capture})
:out
str/trim-newline))
| null | https://raw.githubusercontent.com/exoscale/tools.project/4b97ccbd4a8460cdd7644cc3574a7ff6a21a5b30/src/exoscale/tools/project/api/git.clj | clojure | (ns exoscale.tools.project.api.git
(:require [clojure.tools.deps.alpha.util.dir :as td]
[exoscale.tools.project.api.version :as v]
[exoscale.tools.project.io :as pio]
[clojure.string :as str]))
(defn commit-version
[opts]
(pio/shell ["git add VERSION"
"git commit -m \"Version $VERSION\""]
{:dir td/*the-dir*
:env {"VERSION" (v/get-version opts)}}))
(defn tag-version
[opts]
(pio/shell ["git tag -a \"$VERSION\" --no-sign -m \"Release $VERSION\""]
{:dir td/*the-dir*
:env {"VERSION" (v/get-version opts)}}))
(defn push
[_]
(pio/shell ["git pull"
"git push --follow-tags"]
{:dir td/*the-dir*}))
(defn revision-sha
[_]
(-> (pio/shell ["git rev-parse HEAD"] {:dir td/*the-dir* :out :capture})
:out
str/trim-newline))
| |
334a4f23d09de3e71dc78b83ea6c482e8ce38054a65791dff38bc51903e71bbe | DomainDrivenArchitecture/dda-k8s-crate | networking.clj | Licensed to the Apache Software Foundation ( ASF ) under one
; or more contributor license agreements. See the NOTICE file
; distributed with this work for additional information
; regarding copyright ownership. The ASF licenses this file
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.
(ns dda.pallet.dda-k8s-crate.infra.networking
(:require
[schema.core :as s]
[pallet.actions :as actions]
[dda.provision :as p]
[dda.provision.pallet :as pp]))
(s/def Networking
{:advertise-ip s/Str
:os-version (s/enum :20.04 :18.04)})
(def module "networking")
(s/defn init
[facility
config :- Networking]
(let [facility-name (name facility)
{:keys [advertise-ip os-version]} config]
(p/provision-log ::pp/pallet facility-name module ::p/info "init")
(p/copy-resources-to-tmp
::pp/pallet facility-name module
[{:filename "99-loopback.cfg" :config {:ipv4 advertise-ip}}
{:filename "99-loopback.yaml" :config {:ipv4 advertise-ip}}
{:filename "init18_04.sh"}
{:filename "init20_04.sh"}])
(if (= :20.04 os-version)
(p/exec-file-on-target-as-root
::pp/pallet facility-name module "init20_04.sh")
(p/exec-file-on-target-as-root
::pp/pallet facility-name module "init18_04.sh"))))
| null | https://raw.githubusercontent.com/DomainDrivenArchitecture/dda-k8s-crate/eaeb4d965a63692973d3c1d98759fbdf756596b2/main/src/dda/pallet/dda_k8s_crate/infra/networking.clj | clojure | or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
"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
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. | Licensed to the Apache Software Foundation ( ASF ) under one
to you under the Apache License , Version 2.0 ( the
distributed under the License is distributed on an " AS IS " BASIS ,
(ns dda.pallet.dda-k8s-crate.infra.networking
(:require
[schema.core :as s]
[pallet.actions :as actions]
[dda.provision :as p]
[dda.provision.pallet :as pp]))
(s/def Networking
{:advertise-ip s/Str
:os-version (s/enum :20.04 :18.04)})
(def module "networking")
(s/defn init
[facility
config :- Networking]
(let [facility-name (name facility)
{:keys [advertise-ip os-version]} config]
(p/provision-log ::pp/pallet facility-name module ::p/info "init")
(p/copy-resources-to-tmp
::pp/pallet facility-name module
[{:filename "99-loopback.cfg" :config {:ipv4 advertise-ip}}
{:filename "99-loopback.yaml" :config {:ipv4 advertise-ip}}
{:filename "init18_04.sh"}
{:filename "init20_04.sh"}])
(if (= :20.04 os-version)
(p/exec-file-on-target-as-root
::pp/pallet facility-name module "init20_04.sh")
(p/exec-file-on-target-as-root
::pp/pallet facility-name module "init18_04.sh"))))
|
4041dc6fdb51ac1cbd7253b84a6c723ac83f156cd89a10f61d0c384391889a05 | digikar99/numericals | primitives.lisp | (in-package :dense-numericals.impl)
;; (numericals.common:compiler-in-package numericals.common:*compiler-package*)
(declaim (inline fast-empty))
(defun fast-empty (shape &key (type default-element-type)
(layout *array-layout*))
(declare (type (member :row-major :column-major) layout)
(optimize speed))
(when (listp (first shape))
(assert (null (rest shape)))
(setq shape (first shape)))
(let* ((total-size (loop :for s :of-type size :in shape
:with total-size :of-type size := 1
:do (setf total-size (cl:* total-size s))
:finally (return total-size)))
(rank (length (the list shape)))
(storage ;; Allocate, but do not fill
#+sbcl
(multiple-value-bind (widetag shift) (sb-vm::%vector-widetag-and-n-bits-shift type)
(sb-vm::allocate-vector-with-widetag widetag total-size shift))
#-sbcl
(cl:make-array total-size :element-type type)))
(make-instance 'standard-dense-array
:storage storage
:element-type (cl:array-element-type storage)
:dimensions shape
:strides (dimensions->strides shape layout)
:offsets (make-list rank :initial-element 0)
:total-size total-size
:root-array nil
:rank rank
:layout layout)))
(defun fast-full (shape &key (type default-element-type)
(layout *array-layout*)
value)
(declare (type (member :row-major :column-major) layout)
(optimize speed))
(when (listp (first shape))
(assert (null (rest shape)))
(setq shape (first shape)))
(let* ((total-size (loop :for s :of-type size :in shape
:with total-size :of-type size := 1
:do (setf total-size (cl:* total-size s))
:finally (return total-size)))
(rank (length (the list shape)))
(storage (cl:make-array total-size :element-type type
:initial-element value)))
(make-instance 'standard-dense-array
:storage storage
:element-type (cl:array-element-type storage)
:dimensions shape
:strides (dimensions->strides shape layout)
:offsets (make-list rank :initial-element 0)
:total-size total-size
:root-array nil
:rank rank
:layout layout)))
(define-splice-list-fn nu:full (shape &key (type default-element-type)
(layout *array-layout*)
value)
(fast-full shape :type type :layout layout :value value))
(define-splice-list-fn nu:empty (shape &key (type default-element-type)
(layout *array-layout*))
(fast-empty shape :type type :layout layout))
(define-splice-list-fn nu:zeros (shape &key (type default-element-type) (layout *array-layout*))
(fast-full shape :type type :layout layout :value (coerce 0 type)))
(define-splice-list-fn nu:ones (shape &key (type default-element-type) (layout *array-layout*))
(when (listp (first shape))
(assert (null (rest shape)))
(setq shape (first shape)))
(nu:full (the list shape) :type type :layout layout :value (coerce 1 type)))
(define-splice-list-fn nu:rand (shape &key (type default-element-type)
(layout *array-layout*)
(min (coerce 0 type))
(max (coerce 1 type)))
(when (listp (first shape))
(assert (null (rest shape)))
(setq shape (first shape)))
(let ((a (nu:full shape :type type :layout layout :value (coerce 0 type)))
(range (- max min))
(min (coerce min type)))
(declare (type simple-array a))
(do-arrays ((a-elt a))
(setf a-elt (+ min (random range))))
a))
(defun nu:empty-like (array-like)
(nu:empty (dimensions array-like) :type (element-type array-like)))
(defun nu:zeros-like (array-like)
(nu:zeros (dimensions array-like) :type (element-type array-like)))
(defun nu:ones-like (array-like)
(nu:ones (dimensions array-like) :type (element-type array-like)))
(defun nu:rand-like (array-like)
(nu:rand (dimensions array-like) :type (element-type array-like)))
(defun nu:full-like (array-like value)
(nu:full (dimensions array-like) :value value :type (element-type array-like)))
| null | https://raw.githubusercontent.com/digikar99/numericals/69bfa08401c512772069d74ac30325d49f19b65c/dense-numericals-src/primitives.lisp | lisp | (numericals.common:compiler-in-package numericals.common:*compiler-package*)
Allocate, but do not fill | (in-package :dense-numericals.impl)
(declaim (inline fast-empty))
(defun fast-empty (shape &key (type default-element-type)
(layout *array-layout*))
(declare (type (member :row-major :column-major) layout)
(optimize speed))
(when (listp (first shape))
(assert (null (rest shape)))
(setq shape (first shape)))
(let* ((total-size (loop :for s :of-type size :in shape
:with total-size :of-type size := 1
:do (setf total-size (cl:* total-size s))
:finally (return total-size)))
(rank (length (the list shape)))
#+sbcl
(multiple-value-bind (widetag shift) (sb-vm::%vector-widetag-and-n-bits-shift type)
(sb-vm::allocate-vector-with-widetag widetag total-size shift))
#-sbcl
(cl:make-array total-size :element-type type)))
(make-instance 'standard-dense-array
:storage storage
:element-type (cl:array-element-type storage)
:dimensions shape
:strides (dimensions->strides shape layout)
:offsets (make-list rank :initial-element 0)
:total-size total-size
:root-array nil
:rank rank
:layout layout)))
(defun fast-full (shape &key (type default-element-type)
(layout *array-layout*)
value)
(declare (type (member :row-major :column-major) layout)
(optimize speed))
(when (listp (first shape))
(assert (null (rest shape)))
(setq shape (first shape)))
(let* ((total-size (loop :for s :of-type size :in shape
:with total-size :of-type size := 1
:do (setf total-size (cl:* total-size s))
:finally (return total-size)))
(rank (length (the list shape)))
(storage (cl:make-array total-size :element-type type
:initial-element value)))
(make-instance 'standard-dense-array
:storage storage
:element-type (cl:array-element-type storage)
:dimensions shape
:strides (dimensions->strides shape layout)
:offsets (make-list rank :initial-element 0)
:total-size total-size
:root-array nil
:rank rank
:layout layout)))
(define-splice-list-fn nu:full (shape &key (type default-element-type)
(layout *array-layout*)
value)
(fast-full shape :type type :layout layout :value value))
(define-splice-list-fn nu:empty (shape &key (type default-element-type)
(layout *array-layout*))
(fast-empty shape :type type :layout layout))
(define-splice-list-fn nu:zeros (shape &key (type default-element-type) (layout *array-layout*))
(fast-full shape :type type :layout layout :value (coerce 0 type)))
(define-splice-list-fn nu:ones (shape &key (type default-element-type) (layout *array-layout*))
(when (listp (first shape))
(assert (null (rest shape)))
(setq shape (first shape)))
(nu:full (the list shape) :type type :layout layout :value (coerce 1 type)))
(define-splice-list-fn nu:rand (shape &key (type default-element-type)
(layout *array-layout*)
(min (coerce 0 type))
(max (coerce 1 type)))
(when (listp (first shape))
(assert (null (rest shape)))
(setq shape (first shape)))
(let ((a (nu:full shape :type type :layout layout :value (coerce 0 type)))
(range (- max min))
(min (coerce min type)))
(declare (type simple-array a))
(do-arrays ((a-elt a))
(setf a-elt (+ min (random range))))
a))
(defun nu:empty-like (array-like)
(nu:empty (dimensions array-like) :type (element-type array-like)))
(defun nu:zeros-like (array-like)
(nu:zeros (dimensions array-like) :type (element-type array-like)))
(defun nu:ones-like (array-like)
(nu:ones (dimensions array-like) :type (element-type array-like)))
(defun nu:rand-like (array-like)
(nu:rand (dimensions array-like) :type (element-type array-like)))
(defun nu:full-like (array-like value)
(nu:full (dimensions array-like) :value value :type (element-type array-like)))
|
0bb2b19862e3e6112e9a3de075b9a2bfdb3031966262f64023547639485ade4b | phadej/vec | Optics.hs | {-# LANGUAGE CPP #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - orphans #
module Data.RAList.NonEmpty.Optics (
-- * Indexing
ix,
) where
import Prelude (Int)
import qualified Optics.Core as L
import Data.RAList.NonEmpty
import Data.RAList.NonEmpty.Optics.Internal
-------------------------------------------------------------------------------
-- Indexing
-------------------------------------------------------------------------------
ix :: Int -> L.AffineTraversal' (NERAList a) a
ix i = L.atraversalVL (ixVL i)
-------------------------------------------------------------------------------
-- Instances
-------------------------------------------------------------------------------
#if !MIN_VERSION_optics_core(0,4,0)
instance L.FunctorWithIndex Int NERAList where
imap = imap
instance L.FoldableWithIndex Int NERAList where
ifoldMap = ifoldMap
instance L.TraversableWithIndex Int NERAList where
itraverse = itraverse
#endif
instance L.Each Int (NERAList a) (NERAList b) a b
type instance L.Index (NERAList a) = Int
type instance L.IxValue (NERAList a) = a
instance L.Ixed (NERAList a) where
ix = ix
| null | https://raw.githubusercontent.com/phadej/vec/a895ab79e054987938295d5a149758eb79d85683/ral-optics/src/Data/RAList/NonEmpty/Optics.hs | haskell | # LANGUAGE CPP #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
* Indexing
-----------------------------------------------------------------------------
Indexing
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Instances
----------------------------------------------------------------------------- | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - orphans #
module Data.RAList.NonEmpty.Optics (
ix,
) where
import Prelude (Int)
import qualified Optics.Core as L
import Data.RAList.NonEmpty
import Data.RAList.NonEmpty.Optics.Internal
ix :: Int -> L.AffineTraversal' (NERAList a) a
ix i = L.atraversalVL (ixVL i)
#if !MIN_VERSION_optics_core(0,4,0)
instance L.FunctorWithIndex Int NERAList where
imap = imap
instance L.FoldableWithIndex Int NERAList where
ifoldMap = ifoldMap
instance L.TraversableWithIndex Int NERAList where
itraverse = itraverse
#endif
instance L.Each Int (NERAList a) (NERAList b) a b
type instance L.Index (NERAList a) = Int
type instance L.IxValue (NERAList a) = a
instance L.Ixed (NERAList a) where
ix = ix
|
f22e2fb02336d9be1adacd72041c681a7ae3b6bc0ea4d378fe12cbaf8e182e4c | ingolia-lab/RiboSeq | QuantTable.hs | {-# LANGUAGE OverloadedStrings #-}
module Main
where
import Control.Applicative
import Control.Monad.Reader
import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.Maybe
import qualified Data.Set as S
import Numeric
import System.Console.GetOpt
import System.Environment
import System.FilePath
import System.IO
import qualified Data.Attoparsec as AP (parseOnly)
import qualified Data.Attoparsec.Char8 as AP
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import Statistics.Quantile
import qualified Bio.RiboSeq.QExpr as QE
main :: IO ()
main = getArgs >>= handleOpt . getOpt RequireOrder optDescrs
where handleOpt (_, _, errs@(_:_)) = usage (unlines errs)
handleOpt (args, [], []) = either usage doQuantTable $ argsToConf args
handleOpt (_, _, []) = usage "Unexpected non-option arguments"
usage errs = do prog <- getProgName
let progline = prog ++ " [OPTIONS]"
hPutStr stderr $ usageInfo progline optDescrs
hPutStrLn stderr errs
doQuantTable :: Conf -> IO ()
doQuantTable conf = do samples <- liftM transpose $! mapM (QE.read . snd) $ confQuantSample conf
wantedGenes <- readIsInIdList conf
let wantedSamples = mapMaybe (wantedFeature wantedGenes) samples
when (confQuantNorm conf) $ writeQuantFactors conf wantedSamples
writeTable conf wantedSamples
readIsInIdList :: Conf -> IO (BS.ByteString -> Bool)
readIsInIdList = maybe (return $ const True) (liftM isIn . BS.readFile) . confIdList
where isIn idfile = flip S.member (S.fromList $ BS.lines idfile)
wantedFeature :: (BS.ByteString -> Bool) -> [QE.QExpr] -> Maybe [QE.QExpr]
wantedFeature _ [] = error "No samples"
wantedFeature wantedGene ss@(s0:_) | any mismatchKey ss = error . unwords $ "Mismatch:" : map show ss
| wantedGene (QE.name s0) = Just ss
| otherwise = Nothing
where mismatchKey s' = (QE.name s' /= QE.name s0) ||
(QE.size s' /= QE.size s0)
writeTable :: Conf -> [[QE.QExpr]] -> IO ()
writeTable conf genes = writeFile (confOutput conf) $ QE.unparses qt ""
where qt = QE.QETable { QE.samples = V.fromList $ map (BS.pack . fst) $ confQuantSample conf
, QE.features = V.fromList $ map qtfeat genes
}
qtfeat [] = error "No samples"
qtfeat ss@(s0:_) = QE.FeatureQE { QE.feature = QE.name s0
, QE.fsize = QE.size s0
, QE.quant = U.fromList . map QE.count $ ss
}
writeQuantFactors :: Conf -> [[QE.QExpr]] -> IO ()
writeQuantFactors conf wantedSamples = withFile (confQuantOut conf) WriteMode $ \hout ->
let pquant name (q, f) = hPutStrLn hout qline
where qline = intercalate "\t" [ name, showf 0 q, showf 1 (q / 1e6), showf 6 f ]
showf sf x = showFFloat (Just sf) x ""
qs = QE.sampleQuants wantedSamples
names = map fst $ confQuantSample conf
in sequence_ $! zipWith pquant names qs
data Conf = Conf { confOutput :: !(FilePath)
, confQuantSample :: ![(String, FilePath)]
, confIdList :: !(Maybe FilePath)
, confQuantNorm :: !Bool
} deriving (Show)
confQuantOut :: Conf -> FilePath
confQuantOut conf = let (base, ext) = splitExtension . confOutput $ conf
in (base ++ "_qnorm") `addExtension` ext
data Arg = ArgOutput { unArgOutput :: !String }
| ArgQuantSample { unArgQuantSample :: !String }
| ArgIdList { unArgIdList :: !String }
| ArgQuantNorm
| ArgQuantDens
deriving (Show, Read, Eq, Ord)
argOutput :: Arg -> Maybe String
argOutput (ArgOutput del) = Just del
argOutput _ = Nothing
argQuantSample :: Arg -> Maybe String
argQuantSample (ArgQuantSample quantCf) = Just quantCf
argQuantSample _ = Nothing
argIdList :: Arg -> Maybe String
argIdList (ArgIdList idList) = Just idList
argIdList _ = Nothing
optDescrs :: [OptDescr Arg]
optDescrs = [ Option ['o'] ["output"] (ReqArg ArgOutput "OUTPUT") "Output filename"
, Option ['s'] ["sample"] (ReqArg ArgQuantSample "NAME,QEXPR") "Comparison sample name and qexpr file"
, Option ['l'] ["id-list"] (ReqArg ArgIdList "FILENAME") "Filename for list of gene IDs"
, Option ['q'] ["quantnorm"] (NoArg ArgQuantNorm) "Quantile normalization"
]
argsToConf :: [Arg] -> Either String Conf
argsToConf = runReaderT conf
where conf = Conf <$>
findOutput <*>
findQuantSample <*>
findIdList <*>
(ReaderT $ return . elem ArgQuantNorm)
findOutput = ReaderT $ maybe (Left "No out base") return . listToMaybe . mapMaybe argOutput
findQuantSample = ReaderT $ mapM parseQuant . mapMaybe argQuantSample
findIdList = ReaderT $ return . listToMaybe . mapMaybe argIdList
parseQuant :: String -> Either String (String, FilePath)
parseQuant = AP.parseOnly quant . BS.pack
where quant = ((,) <$>
(BS.unpack <$> AP.takeWhile (/= ',') <* AP.char ',') <*>
(BS.unpack <$> AP.takeByteString)) AP.<?> "quant sample"
unfields :: [String] -> String
unfields = intercalate "\t" | null | https://raw.githubusercontent.com/ingolia-lab/RiboSeq/a14390cd95528910a258434c7b84c787f5e1d119/src/QuantTable.hs | haskell | # LANGUAGE OverloadedStrings # |
module Main
where
import Control.Applicative
import Control.Monad.Reader
import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.Maybe
import qualified Data.Set as S
import Numeric
import System.Console.GetOpt
import System.Environment
import System.FilePath
import System.IO
import qualified Data.Attoparsec as AP (parseOnly)
import qualified Data.Attoparsec.Char8 as AP
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import Statistics.Quantile
import qualified Bio.RiboSeq.QExpr as QE
main :: IO ()
main = getArgs >>= handleOpt . getOpt RequireOrder optDescrs
where handleOpt (_, _, errs@(_:_)) = usage (unlines errs)
handleOpt (args, [], []) = either usage doQuantTable $ argsToConf args
handleOpt (_, _, []) = usage "Unexpected non-option arguments"
usage errs = do prog <- getProgName
let progline = prog ++ " [OPTIONS]"
hPutStr stderr $ usageInfo progline optDescrs
hPutStrLn stderr errs
doQuantTable :: Conf -> IO ()
doQuantTable conf = do samples <- liftM transpose $! mapM (QE.read . snd) $ confQuantSample conf
wantedGenes <- readIsInIdList conf
let wantedSamples = mapMaybe (wantedFeature wantedGenes) samples
when (confQuantNorm conf) $ writeQuantFactors conf wantedSamples
writeTable conf wantedSamples
readIsInIdList :: Conf -> IO (BS.ByteString -> Bool)
readIsInIdList = maybe (return $ const True) (liftM isIn . BS.readFile) . confIdList
where isIn idfile = flip S.member (S.fromList $ BS.lines idfile)
wantedFeature :: (BS.ByteString -> Bool) -> [QE.QExpr] -> Maybe [QE.QExpr]
wantedFeature _ [] = error "No samples"
wantedFeature wantedGene ss@(s0:_) | any mismatchKey ss = error . unwords $ "Mismatch:" : map show ss
| wantedGene (QE.name s0) = Just ss
| otherwise = Nothing
where mismatchKey s' = (QE.name s' /= QE.name s0) ||
(QE.size s' /= QE.size s0)
writeTable :: Conf -> [[QE.QExpr]] -> IO ()
writeTable conf genes = writeFile (confOutput conf) $ QE.unparses qt ""
where qt = QE.QETable { QE.samples = V.fromList $ map (BS.pack . fst) $ confQuantSample conf
, QE.features = V.fromList $ map qtfeat genes
}
qtfeat [] = error "No samples"
qtfeat ss@(s0:_) = QE.FeatureQE { QE.feature = QE.name s0
, QE.fsize = QE.size s0
, QE.quant = U.fromList . map QE.count $ ss
}
writeQuantFactors :: Conf -> [[QE.QExpr]] -> IO ()
writeQuantFactors conf wantedSamples = withFile (confQuantOut conf) WriteMode $ \hout ->
let pquant name (q, f) = hPutStrLn hout qline
where qline = intercalate "\t" [ name, showf 0 q, showf 1 (q / 1e6), showf 6 f ]
showf sf x = showFFloat (Just sf) x ""
qs = QE.sampleQuants wantedSamples
names = map fst $ confQuantSample conf
in sequence_ $! zipWith pquant names qs
data Conf = Conf { confOutput :: !(FilePath)
, confQuantSample :: ![(String, FilePath)]
, confIdList :: !(Maybe FilePath)
, confQuantNorm :: !Bool
} deriving (Show)
confQuantOut :: Conf -> FilePath
confQuantOut conf = let (base, ext) = splitExtension . confOutput $ conf
in (base ++ "_qnorm") `addExtension` ext
data Arg = ArgOutput { unArgOutput :: !String }
| ArgQuantSample { unArgQuantSample :: !String }
| ArgIdList { unArgIdList :: !String }
| ArgQuantNorm
| ArgQuantDens
deriving (Show, Read, Eq, Ord)
argOutput :: Arg -> Maybe String
argOutput (ArgOutput del) = Just del
argOutput _ = Nothing
argQuantSample :: Arg -> Maybe String
argQuantSample (ArgQuantSample quantCf) = Just quantCf
argQuantSample _ = Nothing
argIdList :: Arg -> Maybe String
argIdList (ArgIdList idList) = Just idList
argIdList _ = Nothing
optDescrs :: [OptDescr Arg]
optDescrs = [ Option ['o'] ["output"] (ReqArg ArgOutput "OUTPUT") "Output filename"
, Option ['s'] ["sample"] (ReqArg ArgQuantSample "NAME,QEXPR") "Comparison sample name and qexpr file"
, Option ['l'] ["id-list"] (ReqArg ArgIdList "FILENAME") "Filename for list of gene IDs"
, Option ['q'] ["quantnorm"] (NoArg ArgQuantNorm) "Quantile normalization"
]
argsToConf :: [Arg] -> Either String Conf
argsToConf = runReaderT conf
where conf = Conf <$>
findOutput <*>
findQuantSample <*>
findIdList <*>
(ReaderT $ return . elem ArgQuantNorm)
findOutput = ReaderT $ maybe (Left "No out base") return . listToMaybe . mapMaybe argOutput
findQuantSample = ReaderT $ mapM parseQuant . mapMaybe argQuantSample
findIdList = ReaderT $ return . listToMaybe . mapMaybe argIdList
parseQuant :: String -> Either String (String, FilePath)
parseQuant = AP.parseOnly quant . BS.pack
where quant = ((,) <$>
(BS.unpack <$> AP.takeWhile (/= ',') <* AP.char ',') <*>
(BS.unpack <$> AP.takeByteString)) AP.<?> "quant sample"
unfields :: [String] -> String
unfields = intercalate "\t" |
b35b0f82dfc5ffacf979f8055065e6402db8259902d7d4e54072a2a72d1562b8 | status-im/status-lib-archived | defaults.cljs | (ns status-im.protocol.defaults
(:require [cljs-time.core :as t]))
(def default-content-type "text/plain")
(def max-send-attempts 5)
(def check-delivery-interval 500)
(def status-message-ttl (* 60 10))
(def ack-wait-timeout (t/minutes 10))
(def sending-retry-timeout (t/seconds 10))
(def send-online-period (* 60 10))
| null | https://raw.githubusercontent.com/status-im/status-lib-archived/0b07f54a6b8dc17490a74797fa04dae75e5668ca/src/cljs/status_im/protocol/defaults.cljs | clojure | (ns status-im.protocol.defaults
(:require [cljs-time.core :as t]))
(def default-content-type "text/plain")
(def max-send-attempts 5)
(def check-delivery-interval 500)
(def status-message-ttl (* 60 10))
(def ack-wait-timeout (t/minutes 10))
(def sending-retry-timeout (t/seconds 10))
(def send-online-period (* 60 10))
| |
23c065e10f43bc24707e044ab7f1570866fe2804f372bb5f498b555af11c38ed | ekmett/category-extras | Futu.hs | {-# OPTIONS_GHC -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
Module : Control . Morphism . Futu
Copyright : ( C ) 2008
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable (rank-2 polymorphism)
--
-- Traditional operators, shown here to show how to roll your own
----------------------------------------------------------------------------
module Control.Morphism.Futu
( futu, g_futu
, postpro_futu, g_postpro_futu
, distFutu
) where
import Control.Functor.Algebra
import Control.Functor.Extras
import Control.Functor.Fix
import Control.Monad.Free
import Control.Morphism.Ana
import Control.Morphism.Postpro
| Generalized from @futu : : Functor f = > GCoalgebra f ( Free f ) a - > a - > FixF f@
futu :: (RunMonadFree f m) => GCoalgebra f m a -> a -> FixF f
futu = g_ana (distFutu id)
g_futu :: (Functor f, RunMonadFree h m) => Dist h f -> GCoalgebra f m a -> a -> FixF f
g_futu k = g_ana (distFutu k)
-- | A futumorphic postpromorphism
postpro_futu :: (RunMonadFree f m) => GCoalgebra f m a -> (f :~> f) -> a -> FixF f
postpro_futu = g_postpro (distFutu id)
-- | A generalized-futumorphic postpromorphism
g_postpro_futu :: (Functor f, RunMonadFree h m) => Dist h f -> GCoalgebra f m a -> (f :~> f) -> a -> FixF f
g_postpro_futu k = g_postpro (distFutu k)
-- | Turn a distributive law for a functor into a distributive law for the free monad of that functor.
-- This has been generalized to support generating distributive laws for a number of related free-monad-like
constructions such as the Codensity monad of the free monad of a functor .
distFutu :: (Functor f, RunMonadFree h m) => Dist h f -> Dist m f
distFutu k = cataFree (fmap return) (fmap inFree . k)
| null | https://raw.githubusercontent.com/ekmett/category-extras/f0f3ca38a3dfcb49d39aa2bb5b31b719f2a5b1ae/Control/Morphism/Futu.hs | haskell | # OPTIONS_GHC -fglasgow-exts #
---------------------------------------------------------------------------
|
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : non-portable (rank-2 polymorphism)
Traditional operators, shown here to show how to roll your own
--------------------------------------------------------------------------
| A futumorphic postpromorphism
| A generalized-futumorphic postpromorphism
| Turn a distributive law for a functor into a distributive law for the free monad of that functor.
This has been generalized to support generating distributive laws for a number of related free-monad-like | Module : Control . Morphism . Futu
Copyright : ( C ) 2008
Maintainer : < >
module Control.Morphism.Futu
( futu, g_futu
, postpro_futu, g_postpro_futu
, distFutu
) where
import Control.Functor.Algebra
import Control.Functor.Extras
import Control.Functor.Fix
import Control.Monad.Free
import Control.Morphism.Ana
import Control.Morphism.Postpro
| Generalized from @futu : : Functor f = > GCoalgebra f ( Free f ) a - > a - > FixF f@
futu :: (RunMonadFree f m) => GCoalgebra f m a -> a -> FixF f
futu = g_ana (distFutu id)
g_futu :: (Functor f, RunMonadFree h m) => Dist h f -> GCoalgebra f m a -> a -> FixF f
g_futu k = g_ana (distFutu k)
postpro_futu :: (RunMonadFree f m) => GCoalgebra f m a -> (f :~> f) -> a -> FixF f
postpro_futu = g_postpro (distFutu id)
g_postpro_futu :: (Functor f, RunMonadFree h m) => Dist h f -> GCoalgebra f m a -> (f :~> f) -> a -> FixF f
g_postpro_futu k = g_postpro (distFutu k)
constructions such as the Codensity monad of the free monad of a functor .
distFutu :: (Functor f, RunMonadFree h m) => Dist h f -> Dist m f
distFutu k = cataFree (fmap return) (fmap inFree . k)
|
10bc44dd3adcb538f65d645a3aa943e6646f3e9ba7ee5a90dbed19c4219523fb | DaMSL/K3 | Interactive.hs | # LANGUAGE LambdaCase #
module Language.K3.Driver.Interactive where
import Control.Monad
import System.Console.Readline
import System.Exit
import Language.K3.Interpreter
import Language.K3.Parser
import Language.K3.Pretty
-- | Run an interactive prompt, reading evaulating and printing at each step.
runInteractive :: IO ()
runInteractive = readline ">>> " >>= \case
Nothing -> exitSuccess
Just input -> addHistory input >> repl input >> runInteractive
-- | A single round of parsing, interpretation and pretty-printing.
repl :: String -> IO ()
repl input = do
case runK3Parser Nothing expr input of
Left e -> print e
Right t -> do
putStr $ pretty t
i <- runInterpretation [] $ expression t
print i
| null | https://raw.githubusercontent.com/DaMSL/K3/51749157844e76ae79dba619116fc5ad9d685643/src/Language/K3/Driver/Interactive.hs | haskell | | Run an interactive prompt, reading evaulating and printing at each step.
| A single round of parsing, interpretation and pretty-printing. | # LANGUAGE LambdaCase #
module Language.K3.Driver.Interactive where
import Control.Monad
import System.Console.Readline
import System.Exit
import Language.K3.Interpreter
import Language.K3.Parser
import Language.K3.Pretty
runInteractive :: IO ()
runInteractive = readline ">>> " >>= \case
Nothing -> exitSuccess
Just input -> addHistory input >> repl input >> runInteractive
repl :: String -> IO ()
repl input = do
case runK3Parser Nothing expr input of
Left e -> print e
Right t -> do
putStr $ pretty t
i <- runInterpretation [] $ expression t
print i
|
db5da067d89979f4adb4b890563ec09cd6532cc173b5f62193e86f39b3227131 | boomerang-lang/boomerang | tree_alignment.ml | open Stdlib
(** To be an ordered metric space, we require the space to have a distance
* metric (a function distance : X -> X -> double) and a total ordering (a function
* compare : X -> X -> int) we do not require any meaningful interaction
* between the metric and the ordering **)
module TreeAlignmentOf(D : Data) =
struct
type alignment_node =
{
perm : Permutation.t ;
pleft : int list ;
pright : int list ;
}
[@@deriving ord, show, hash]
let create_alignment_node
~perm:(perm:Permutation.t)
~pleft:(pleft:int list)
~pright:(pright:int list)
: alignment_node =
{
perm = perm ;
pleft = pleft ;
pright = pright ;
}
type t = (alignment_node tree) option
[@@deriving ord, show, hash]
let rec nonempty_cost
(Node(an,al):alignment_node nonempty_tree)
: float =
let mapped_count = List.length al in
let unmapped_left_count = List.length an.pleft in
let unmapped_right_count = List.length an.pright in
let total_size =
Float.of_int
(mapped_count
+ unmapped_left_count
+ unmapped_right_count
+ 1)
in
let unnormalized_unmapped_cost =
Float.of_int (unmapped_left_count + unmapped_right_count)
in
let unnormalized_recursive_cost =
List.fold_left
~f:(fun acc a' -> acc +. (nonempty_cost a'))
~init:0.0
al
in
let unnormalized_cost =
unnormalized_unmapped_cost +.
unnormalized_recursive_cost
in
(unnormalized_cost /. total_size)
let cost
(a:t)
: float =
begin match a with
| None -> 1.0
| Some EmptyTree -> 0.0
| Some NonemptyTree nea -> nonempty_cost nea
end
module DataTree = UnorderedNonemptyTreeOf(D)
module DataTreeIndexListDict = DictOf(DataTree)(ListOf(IntModule))
module PrioritiedDataTreePairs =
struct
include TripleOf(DataTree)(DataTree)(FloatModule)
let priority ((_,_,p):t) = p
end
module DataTreeDataTreePriorityPQueue = PriorityQueueOf(PrioritiedDataTreePairs)
let get_minimal_alignment
(t1:D.t tree)
(t2:D.t tree)
: t =
let rec get_nonempty_alignment_distance
(t1:D.t nonempty_tree)
(t2:D.t nonempty_tree)
: float =
begin match get_minimal_alignment_nonempty t1 t2 with
| None -> 1.0
| Some nea -> nonempty_cost nea
end
and get_minimal_alignment_nonempty
(Node(l1,t1s):D.t nonempty_tree)
(Node(l2,t2s):D.t nonempty_tree)
: alignment_node nonempty_tree option =
if (not (is_equal (D.compare l1 l2))) then
None
else
let list_to_dict
(ts:D.t nonempty_tree list)
: DataTreeIndexListDict.t =
List.foldi
~f:(fun i d t ->
DataTreeIndexListDict.insert_or_merge
~merge:(fun il1 il2 -> il2@il1)
d
t
[i])
~init:DataTreeIndexListDict.empty
ts
in
let d1 = list_to_dict t1s in
let d2 = list_to_dict t2s in
let t1_keys = DataTreeIndexListDict.key_list d1 in
let t2_keys = DataTreeIndexListDict.key_list d2 in
let pq =
DataTreeDataTreePriorityPQueue.from_list
(cartesian_map
~f:(fun t1 t2 -> (t1,t2,get_nonempty_alignment_distance t1 t2))
t1_keys
t2_keys)
in
let (indices_and_alignments,pleft,pright) =
fold_until_completion
~f:(fun (pq,d1,d2,indices_and_alignments) ->
begin match DataTreeDataTreePriorityPQueue.pop pq with
| None ->
let leftover_left =
List.concat
(DataTreeIndexListDict.value_list d1)
in
let leftover_right =
List.concat
(DataTreeIndexListDict.value_list d2)
in
Right(indices_and_alignments,leftover_left,leftover_right)
| Some ((t1,t2,_),_,pq) ->
let l1o = DataTreeIndexListDict.lookup d1 t1 in
let l2o = DataTreeIndexListDict.lookup d2 t2 in
begin match (l1o,l2o) with
| (None ,_ ) ->
Left (pq,d1,d2,indices_and_alignments)
| (_ , None) ->
Left (pq,d1,d2,indices_and_alignments)
| (Some l1, Some l2) ->
let index_to = max (List.length l1) (List.length l2) in
let (l11,l12) = split_at_index_exn l1 index_to in
let (l21,l22) = split_at_index_exn l2 index_to in
let new_indices_and_alignment_options =
List.map
~f:(fun (i,j) ->
let t1 = List.nth_exn t1s i in
let t2 = List.nth_exn t2s j in
let alignment_option =
get_minimal_alignment_nonempty
t1
t2
in
Option.map
~f:(fun a -> (i,j,a))
alignment_option)
(List.zip_exn l11 l21)
in
let new_indices_and_alignments_option =
distribute_option
new_indices_and_alignment_options
in
begin match new_indices_and_alignments_option with
| None ->
Left (DataTreeDataTreePriorityPQueue.empty,d1,d2,indices_and_alignments)
| Some new_indices_and_alignments ->
let indices_and_alignments =
new_indices_and_alignments@indices_and_alignments
in
let updater_with_replacement
(to_replace:int list)
(_:int list)
: (int list) option =
if (List.is_empty to_replace) then
None
else
Some to_replace
in
let d1 =
DataTreeIndexListDict.remove_or_update
~updater:(updater_with_replacement l12)
d1
t1
in
let d2 =
DataTreeIndexListDict.remove_or_update
~updater:(updater_with_replacement l22)
d2
t2
in
Left (pq,d1,d2,indices_and_alignments)
end
end
end)
(pq,d1,d2,[])
in
let (perm_doubles,alignments) =
List.unzip
(List.map
~f:(fun (x,y,z) -> ((x,y),z))
indices_and_alignments)
in
Some
(Node
(create_alignment_node
~perm:(Permutation.create_from_doubles perm_doubles)
~pleft:pleft
~pright:pright,
alignments))
in
begin match (t1,t2) with
| (EmptyTree, EmptyTree) -> Some EmptyTree
| (EmptyTree, NonemptyTree _) -> None
| (NonemptyTree _, EmptyTree) -> None
| (NonemptyTree nt1, NonemptyTree nt2) ->
Option.map
~f:(fun nea -> NonemptyTree nea)
(get_minimal_alignment_nonempty nt1 nt2)
end
let get_alignment_distance
(t1:D.t tree)
(t2:D.t tree)
: float =
cost (get_minimal_alignment t1 t2)
end
| null | https://raw.githubusercontent.com/boomerang-lang/boomerang/b42c2bfc72030bbe5c32752c236c0aad3b17d149/optician/tree_alignment.ml | ocaml | * To be an ordered metric space, we require the space to have a distance
* metric (a function distance : X -> X -> double) and a total ordering (a function
* compare : X -> X -> int) we do not require any meaningful interaction
* between the metric and the ordering * | open Stdlib
module TreeAlignmentOf(D : Data) =
struct
type alignment_node =
{
perm : Permutation.t ;
pleft : int list ;
pright : int list ;
}
[@@deriving ord, show, hash]
let create_alignment_node
~perm:(perm:Permutation.t)
~pleft:(pleft:int list)
~pright:(pright:int list)
: alignment_node =
{
perm = perm ;
pleft = pleft ;
pright = pright ;
}
type t = (alignment_node tree) option
[@@deriving ord, show, hash]
let rec nonempty_cost
(Node(an,al):alignment_node nonempty_tree)
: float =
let mapped_count = List.length al in
let unmapped_left_count = List.length an.pleft in
let unmapped_right_count = List.length an.pright in
let total_size =
Float.of_int
(mapped_count
+ unmapped_left_count
+ unmapped_right_count
+ 1)
in
let unnormalized_unmapped_cost =
Float.of_int (unmapped_left_count + unmapped_right_count)
in
let unnormalized_recursive_cost =
List.fold_left
~f:(fun acc a' -> acc +. (nonempty_cost a'))
~init:0.0
al
in
let unnormalized_cost =
unnormalized_unmapped_cost +.
unnormalized_recursive_cost
in
(unnormalized_cost /. total_size)
let cost
(a:t)
: float =
begin match a with
| None -> 1.0
| Some EmptyTree -> 0.0
| Some NonemptyTree nea -> nonempty_cost nea
end
module DataTree = UnorderedNonemptyTreeOf(D)
module DataTreeIndexListDict = DictOf(DataTree)(ListOf(IntModule))
module PrioritiedDataTreePairs =
struct
include TripleOf(DataTree)(DataTree)(FloatModule)
let priority ((_,_,p):t) = p
end
module DataTreeDataTreePriorityPQueue = PriorityQueueOf(PrioritiedDataTreePairs)
let get_minimal_alignment
(t1:D.t tree)
(t2:D.t tree)
: t =
let rec get_nonempty_alignment_distance
(t1:D.t nonempty_tree)
(t2:D.t nonempty_tree)
: float =
begin match get_minimal_alignment_nonempty t1 t2 with
| None -> 1.0
| Some nea -> nonempty_cost nea
end
and get_minimal_alignment_nonempty
(Node(l1,t1s):D.t nonempty_tree)
(Node(l2,t2s):D.t nonempty_tree)
: alignment_node nonempty_tree option =
if (not (is_equal (D.compare l1 l2))) then
None
else
let list_to_dict
(ts:D.t nonempty_tree list)
: DataTreeIndexListDict.t =
List.foldi
~f:(fun i d t ->
DataTreeIndexListDict.insert_or_merge
~merge:(fun il1 il2 -> il2@il1)
d
t
[i])
~init:DataTreeIndexListDict.empty
ts
in
let d1 = list_to_dict t1s in
let d2 = list_to_dict t2s in
let t1_keys = DataTreeIndexListDict.key_list d1 in
let t2_keys = DataTreeIndexListDict.key_list d2 in
let pq =
DataTreeDataTreePriorityPQueue.from_list
(cartesian_map
~f:(fun t1 t2 -> (t1,t2,get_nonempty_alignment_distance t1 t2))
t1_keys
t2_keys)
in
let (indices_and_alignments,pleft,pright) =
fold_until_completion
~f:(fun (pq,d1,d2,indices_and_alignments) ->
begin match DataTreeDataTreePriorityPQueue.pop pq with
| None ->
let leftover_left =
List.concat
(DataTreeIndexListDict.value_list d1)
in
let leftover_right =
List.concat
(DataTreeIndexListDict.value_list d2)
in
Right(indices_and_alignments,leftover_left,leftover_right)
| Some ((t1,t2,_),_,pq) ->
let l1o = DataTreeIndexListDict.lookup d1 t1 in
let l2o = DataTreeIndexListDict.lookup d2 t2 in
begin match (l1o,l2o) with
| (None ,_ ) ->
Left (pq,d1,d2,indices_and_alignments)
| (_ , None) ->
Left (pq,d1,d2,indices_and_alignments)
| (Some l1, Some l2) ->
let index_to = max (List.length l1) (List.length l2) in
let (l11,l12) = split_at_index_exn l1 index_to in
let (l21,l22) = split_at_index_exn l2 index_to in
let new_indices_and_alignment_options =
List.map
~f:(fun (i,j) ->
let t1 = List.nth_exn t1s i in
let t2 = List.nth_exn t2s j in
let alignment_option =
get_minimal_alignment_nonempty
t1
t2
in
Option.map
~f:(fun a -> (i,j,a))
alignment_option)
(List.zip_exn l11 l21)
in
let new_indices_and_alignments_option =
distribute_option
new_indices_and_alignment_options
in
begin match new_indices_and_alignments_option with
| None ->
Left (DataTreeDataTreePriorityPQueue.empty,d1,d2,indices_and_alignments)
| Some new_indices_and_alignments ->
let indices_and_alignments =
new_indices_and_alignments@indices_and_alignments
in
let updater_with_replacement
(to_replace:int list)
(_:int list)
: (int list) option =
if (List.is_empty to_replace) then
None
else
Some to_replace
in
let d1 =
DataTreeIndexListDict.remove_or_update
~updater:(updater_with_replacement l12)
d1
t1
in
let d2 =
DataTreeIndexListDict.remove_or_update
~updater:(updater_with_replacement l22)
d2
t2
in
Left (pq,d1,d2,indices_and_alignments)
end
end
end)
(pq,d1,d2,[])
in
let (perm_doubles,alignments) =
List.unzip
(List.map
~f:(fun (x,y,z) -> ((x,y),z))
indices_and_alignments)
in
Some
(Node
(create_alignment_node
~perm:(Permutation.create_from_doubles perm_doubles)
~pleft:pleft
~pright:pright,
alignments))
in
begin match (t1,t2) with
| (EmptyTree, EmptyTree) -> Some EmptyTree
| (EmptyTree, NonemptyTree _) -> None
| (NonemptyTree _, EmptyTree) -> None
| (NonemptyTree nt1, NonemptyTree nt2) ->
Option.map
~f:(fun nea -> NonemptyTree nea)
(get_minimal_alignment_nonempty nt1 nt2)
end
let get_alignment_distance
(t1:D.t tree)
(t2:D.t tree)
: float =
cost (get_minimal_alignment t1 t2)
end
|
68af2feb212f59cbb8250146dd2a07124453295a55f87f8c5829cb2905c6940b | mhayashi1120/Gauche-net-twitter | sample.test-settings.scm | ;; -*- mode: lisp -*-
1 . copy this " sample.test-settings.scm " to " .secret / test - settings.scm "
2 . create 2 twitter test account
3 . fill the following sexp . ` oauth - token ` fields are generated by ` twitauth ` .
(
(user . "***YOUR USERNAME***")
(password . "***YOUR PASSWORD***")
(consumer-key . "***YOUR CONSUMER KEY***")
(consumer-secret-key . "***YOUR CONSUMER SECRET KEY***")
;; temporary settings
(oauth-token . ((consumer-key . "")
(consumer-secret . "")
(access-token . "")
(access-token-secret . "")))
(user2 . "***YOUR SECOND USERNAME***")
(password2 . "***YOUR SECOND PASSWORD***")
(oauth-token2 . ((consumer-key . "")
(consumer-secret . "")
(access-token . "")
(access-token-secret . "")))
)
| null | https://raw.githubusercontent.com/mhayashi1120/Gauche-net-twitter/b9f4be3ca8459fc662f9c79481411aac03b51133/sample.test-settings.scm | scheme | -*- mode: lisp -*-
temporary settings | 1 . copy this " sample.test-settings.scm " to " .secret / test - settings.scm "
2 . create 2 twitter test account
3 . fill the following sexp . ` oauth - token ` fields are generated by ` twitauth ` .
(
(user . "***YOUR USERNAME***")
(password . "***YOUR PASSWORD***")
(consumer-key . "***YOUR CONSUMER KEY***")
(consumer-secret-key . "***YOUR CONSUMER SECRET KEY***")
(oauth-token . ((consumer-key . "")
(consumer-secret . "")
(access-token . "")
(access-token-secret . "")))
(user2 . "***YOUR SECOND USERNAME***")
(password2 . "***YOUR SECOND PASSWORD***")
(oauth-token2 . ((consumer-key . "")
(consumer-secret . "")
(access-token . "")
(access-token-secret . "")))
)
|
1c415e76e1ecc67978b810e732c94c60f35fe0234aad6f5e55bf836f2ffeeeab | coq-community/coqffi | mod.ml | open Cmi_format
open Entry
open Error
open Types
type t = {
mod_namespace : string list;
mod_name : string;
mod_intro : intro list;
mod_functions : function_entry list;
mod_primitives : primitive_entry list;
mod_lwt : lwt_entry list;
mod_exceptions : exception_entry list;
mod_loc : Location.t;
}
and intro = Right of mutually_recursive_types_entry | Left of t
let translate_mutually_recursive_types ~rev_namespace (tbl : Translation.t)
(mt : mutually_recursive_types_entry) : Translation.t * intro list =
let update_table rev_namespace tbl t =
Translation.preserve ~rev_namespace t.type_name tbl
in
To perform the translation , we do not use the namespace . This is
because we want coqffi to find an issue with the following entry :
module Z : sig
type t = Z.t
end
In OCaml , this is a shadowing of Z.t . But , from coqffi
perspective , if we were using [ tbl_future ] , then to translate
[ t ] , would first try [ t ] , then [ Z.t ] , something we do not
want . So we use two different tables .
because we want coqffi to find an issue with the following entry:
module Z : sig
type t = Z.t
end
In OCaml, this is a shadowing of Z.t. But, from coqffi
perspective, if we were using [tbl_future], then to translate
[t], coqffi would first try [t], then [Z.t], something we do not
want. So we use two different tables. *)
let tbl_translate = List.fold_left (update_table []) tbl mt in
let tbl_future = List.fold_left (update_table rev_namespace) tbl mt in
let res =
try [ Right (List.map (translate_type ~rev_namespace tbl_translate) mt) ]
with _ ->
Something went wrong when tried to translate the types
within a variant . As a consequence , we treat each type of [ mt ]
as if it were opaque .
within a variant. As a consequence, we treat each type of [mt]
as if it were opaque. *)
List.map
(fun t ->
Right
[
translate_type ~rev_namespace tbl_translate
{ t with type_value = Opaque };
])
mt
in
(tbl_future, res)
let dispatch f g = function Right mt -> f mt | Left m -> g m
let fold_intro_list for_mtyps for_mod =
List.fold_left (fun acc -> dispatch (for_mtyps acc) (for_mod acc))
let map_intro_list f g = List.map (dispatch f g)
let namespace_and_path modname =
let rec namespace_and_path acc = function
| [ x ] -> (List.rev acc, String.capitalize_ascii x)
| x :: rst -> namespace_and_path (String.capitalize_ascii x :: acc) rst
| _ -> assert false
in
namespace_and_path [] (Str.split (Str.regexp "__") modname)
let error_function f e =
{
error_loc = f.func_loc;
error_entry = f.func_name;
error_exn = error_kind_of_exn e;
}
let error_primitive p e =
{
error_loc = p.prim_loc;
error_entry = p.prim_name;
error_exn = error_kind_of_exn e;
}
let error_lwt p e =
{
error_loc = p.lwt_loc;
error_entry = p.lwt_name;
error_exn = error_kind_of_exn e;
}
let error_exception exn e =
{
error_loc = exn.exception_loc;
error_entry = exn.exception_name;
error_exn = error_kind_of_exn e;
}
let safe_translate error translate x =
try Some (translate x)
with e ->
pp_error Format.err_formatter (error x e);
None
let rec of_module_entry ?(rev_namespace = []) tbl (m : module_entry) :
Translation.t * t =
let tbl, mod_intro = segment_module_intro ~rev_namespace tbl m.module_intro in
let mod_functions =
List.filter_map
(safe_translate error_function @@ translate_function ~rev_namespace tbl)
m.module_functions
in
let mod_primitives =
List.filter_map
(safe_translate error_primitive @@ translate_primitive ~rev_namespace tbl)
m.module_primitives
in
let mod_lwt =
List.filter_map
(safe_translate error_lwt @@ translate_lwt ~rev_namespace tbl)
m.module_lwt
in
let mod_exceptions =
List.filter_map
(safe_translate error_exception @@ translate_exception ~rev_namespace tbl)
m.module_exceptions
in
( tbl,
{
mod_intro;
mod_name = m.module_name;
mod_functions;
mod_primitives;
mod_lwt;
mod_exceptions;
mod_loc = m.module_loc;
mod_namespace = m.module_namespace;
} )
and segment_module_intro ~rev_namespace tbl :
intro_entry list -> Translation.t * intro list = function
| [] -> (tbl, [])
| IntroMod m :: rst ->
let tbl, m =
of_module_entry ~rev_namespace:(m.module_name :: rev_namespace) tbl m
in
let tbl, rst = segment_module_intro ~rev_namespace tbl rst in
(tbl, Left m :: rst)
| l -> segment_module_intro_aux ~rev_namespace tbl [] l
and segment_module_intro_aux ~rev_namespace tbl acc = function
| IntroType t :: rst ->
segment_module_intro_aux ~rev_namespace tbl (t :: acc) rst
| l -> (
match acc with
| [] -> segment_module_intro ~rev_namespace tbl l
| typs ->
let segment_list fstart =
let aux acc entry =
match acc with
| x :: rst ->
if fstart entry then [ entry ] :: List.rev x :: rst
else (entry :: x) :: rst
| [] -> [ [ entry ] ]
in
List.fold_left aux []
in
let find_recursive_types typs =
let candidates =
List.rev
(segment_list
(fun t -> t.type_rec = Trec_first || t.type_rec = Trec_not)
typs)
in
Compat.concat_map find_mutually_recursive_types candidates
in
(* We have constructed the list backward, so we need to
reverse it before searching for mutually recursive
type, so that we do not need to perform a complex
analysis on types’ dependencies to decide their order
of declaration. *)
let typs = List.rev typs in
let tbl, typs =
Compat.fold_left_map
(translate_mutually_recursive_types ~rev_namespace)
tbl
(find_recursive_types typs)
in
let tbl, rst = segment_module_intro ~rev_namespace tbl l in
(tbl, List.concat typs @ rst))
let of_cmi_infos ~translations ~features ~lwt_module ~tezos_types
(info : cmi_infos) =
let namespace, name = namespace_and_path info.cmi_name in
module_of_signatures features lwt_module tezos_types namespace name
info.cmi_sign
|> of_module_entry translations
|> snd
let compute_conflicts =
(* always call with [rev_namesace], which is never empty *)
let modname = List.hd in
let cc_variant ~rev_namespace owner conflicts v =
Conflict.add_constructor rev_namespace ~owner v.variant_name conflicts
in
let cc_field ~rev_namespace owner conflicts f =
Conflict.add_field rev_namespace ~owner f.field_name conflicts
in
let cc_type ~rev_namespace conflicts t =
let conflicts = Conflict.add_type rev_namespace t.type_name conflicts in
match t.type_value with
| Variant vs ->
List.fold_left (cc_variant ~rev_namespace t.type_name) conflicts vs
| Record fs ->
List.fold_left (cc_field ~rev_namespace t.type_name) conflicts fs
| _ -> conflicts
in
let cc_types ~rev_namespace conflicts typs =
List.fold_left (cc_type ~rev_namespace) conflicts typs
in
let cc_functions ~rev_namespace funcs conflicts =
List.fold_left
(fun conflicts func ->
Conflict.add_value rev_namespace func.func_name conflicts)
conflicts funcs
in
let cc_prim ~rev_namespace conflicts prim =
let modname = modname rev_namespace in
let owner = prim.prim_name in
Conflict.add_value rev_namespace owner conflicts
|> Conflict.add_helper rev_namespace owner Name.io_helper
|> Conflict.add_helper rev_namespace owner Name.lwt_sync_helper
|> Conflict.add_helper rev_namespace ~owner:modname owner
Name.interface_cstr
|> Conflict.add_helper rev_namespace owner Name.inject_helper
|> Conflict.add_helper rev_namespace owner Name.semantics_helper
in
let cc_prims ~rev_namespace prims conflicts =
let owner = modname rev_namespace in
List.fold_left (cc_prim ~rev_namespace) conflicts prims
|> Conflict.add_helper rev_namespace owner Name.prim_monad
|> Conflict.add_helper rev_namespace owner Name.io_instance
|> Conflict.add_helper rev_namespace owner Name.lwt_sync_instance
|> Conflict.add_helper rev_namespace owner Name.interface_type
|> Conflict.add_helper rev_namespace owner Name.inject_instance
|> Conflict.add_helper rev_namespace owner Name.semantics
in
let cc_lwt ~rev_namespace conflicts lwt =
let modname = modname rev_namespace in
let owner = lwt.lwt_name in
Conflict.add_value rev_namespace lwt.lwt_name conflicts
|> Conflict.add_helper rev_namespace owner Name.lwt_async_helper
|> Conflict.add_helper rev_namespace ~owner:modname owner
Name.interface_cstr
|> Conflict.add_helper rev_namespace owner Name.inject_helper
|> Conflict.add_helper rev_namespace owner Name.inject_instance
in
let cc_lwts ~rev_namespace lwts conflicts =
let owner = modname rev_namespace in
List.fold_left (cc_lwt ~rev_namespace) conflicts lwts
|> Conflict.add_helper rev_namespace owner Name.async_monad
|> Conflict.add_helper rev_namespace owner Name.lwt_async_instance
|> Conflict.add_helper rev_namespace owner Name.async_interface_type
|> Conflict.add_helper rev_namespace owner Name.async_inject_instance
in
let cc_exn ~rev_namespace conflicts exn =
let owner = exn.exception_name in
Conflict.add_helper rev_namespace owner Name.to_exn conflicts
|> Conflict.add_helper rev_namespace owner Name.of_exn
|> Conflict.add_helper rev_namespace owner Name.exn_proxy_type
|> Conflict.add_helper rev_namespace owner Name.exn_proxy_cstr
|> Conflict.add_helper rev_namespace owner Name.exn_instance
in
let cc_exns ~rev_namespace exns conflicts =
List.fold_left (cc_exn ~rev_namespace) conflicts exns
in
let rec cc_module ~rev_namespace conflicts m =
let rev_namespace = m.mod_name :: rev_namespace in
fold_intro_list (cc_types ~rev_namespace) (cc_module ~rev_namespace)
conflicts m.mod_intro
|> cc_functions ~rev_namespace m.mod_functions
|> cc_prims ~rev_namespace m.mod_primitives
|> cc_lwts ~rev_namespace m.mod_lwt
|> cc_exns ~rev_namespace m.mod_exceptions
in
cc_module ~rev_namespace:[]
| null | https://raw.githubusercontent.com/coq-community/coqffi/2489d4e5b07f7e42eb89800531a7da57edb66b6b/src/mod.ml | ocaml | We have constructed the list backward, so we need to
reverse it before searching for mutually recursive
type, so that we do not need to perform a complex
analysis on types’ dependencies to decide their order
of declaration.
always call with [rev_namesace], which is never empty | open Cmi_format
open Entry
open Error
open Types
type t = {
mod_namespace : string list;
mod_name : string;
mod_intro : intro list;
mod_functions : function_entry list;
mod_primitives : primitive_entry list;
mod_lwt : lwt_entry list;
mod_exceptions : exception_entry list;
mod_loc : Location.t;
}
and intro = Right of mutually_recursive_types_entry | Left of t
let translate_mutually_recursive_types ~rev_namespace (tbl : Translation.t)
(mt : mutually_recursive_types_entry) : Translation.t * intro list =
let update_table rev_namespace tbl t =
Translation.preserve ~rev_namespace t.type_name tbl
in
To perform the translation , we do not use the namespace . This is
because we want coqffi to find an issue with the following entry :
module Z : sig
type t = Z.t
end
In OCaml , this is a shadowing of Z.t . But , from coqffi
perspective , if we were using [ tbl_future ] , then to translate
[ t ] , would first try [ t ] , then [ Z.t ] , something we do not
want . So we use two different tables .
because we want coqffi to find an issue with the following entry:
module Z : sig
type t = Z.t
end
In OCaml, this is a shadowing of Z.t. But, from coqffi
perspective, if we were using [tbl_future], then to translate
[t], coqffi would first try [t], then [Z.t], something we do not
want. So we use two different tables. *)
let tbl_translate = List.fold_left (update_table []) tbl mt in
let tbl_future = List.fold_left (update_table rev_namespace) tbl mt in
let res =
try [ Right (List.map (translate_type ~rev_namespace tbl_translate) mt) ]
with _ ->
Something went wrong when tried to translate the types
within a variant . As a consequence , we treat each type of [ mt ]
as if it were opaque .
within a variant. As a consequence, we treat each type of [mt]
as if it were opaque. *)
List.map
(fun t ->
Right
[
translate_type ~rev_namespace tbl_translate
{ t with type_value = Opaque };
])
mt
in
(tbl_future, res)
let dispatch f g = function Right mt -> f mt | Left m -> g m
let fold_intro_list for_mtyps for_mod =
List.fold_left (fun acc -> dispatch (for_mtyps acc) (for_mod acc))
let map_intro_list f g = List.map (dispatch f g)
let namespace_and_path modname =
let rec namespace_and_path acc = function
| [ x ] -> (List.rev acc, String.capitalize_ascii x)
| x :: rst -> namespace_and_path (String.capitalize_ascii x :: acc) rst
| _ -> assert false
in
namespace_and_path [] (Str.split (Str.regexp "__") modname)
let error_function f e =
{
error_loc = f.func_loc;
error_entry = f.func_name;
error_exn = error_kind_of_exn e;
}
let error_primitive p e =
{
error_loc = p.prim_loc;
error_entry = p.prim_name;
error_exn = error_kind_of_exn e;
}
let error_lwt p e =
{
error_loc = p.lwt_loc;
error_entry = p.lwt_name;
error_exn = error_kind_of_exn e;
}
let error_exception exn e =
{
error_loc = exn.exception_loc;
error_entry = exn.exception_name;
error_exn = error_kind_of_exn e;
}
let safe_translate error translate x =
try Some (translate x)
with e ->
pp_error Format.err_formatter (error x e);
None
let rec of_module_entry ?(rev_namespace = []) tbl (m : module_entry) :
Translation.t * t =
let tbl, mod_intro = segment_module_intro ~rev_namespace tbl m.module_intro in
let mod_functions =
List.filter_map
(safe_translate error_function @@ translate_function ~rev_namespace tbl)
m.module_functions
in
let mod_primitives =
List.filter_map
(safe_translate error_primitive @@ translate_primitive ~rev_namespace tbl)
m.module_primitives
in
let mod_lwt =
List.filter_map
(safe_translate error_lwt @@ translate_lwt ~rev_namespace tbl)
m.module_lwt
in
let mod_exceptions =
List.filter_map
(safe_translate error_exception @@ translate_exception ~rev_namespace tbl)
m.module_exceptions
in
( tbl,
{
mod_intro;
mod_name = m.module_name;
mod_functions;
mod_primitives;
mod_lwt;
mod_exceptions;
mod_loc = m.module_loc;
mod_namespace = m.module_namespace;
} )
and segment_module_intro ~rev_namespace tbl :
intro_entry list -> Translation.t * intro list = function
| [] -> (tbl, [])
| IntroMod m :: rst ->
let tbl, m =
of_module_entry ~rev_namespace:(m.module_name :: rev_namespace) tbl m
in
let tbl, rst = segment_module_intro ~rev_namespace tbl rst in
(tbl, Left m :: rst)
| l -> segment_module_intro_aux ~rev_namespace tbl [] l
and segment_module_intro_aux ~rev_namespace tbl acc = function
| IntroType t :: rst ->
segment_module_intro_aux ~rev_namespace tbl (t :: acc) rst
| l -> (
match acc with
| [] -> segment_module_intro ~rev_namespace tbl l
| typs ->
let segment_list fstart =
let aux acc entry =
match acc with
| x :: rst ->
if fstart entry then [ entry ] :: List.rev x :: rst
else (entry :: x) :: rst
| [] -> [ [ entry ] ]
in
List.fold_left aux []
in
let find_recursive_types typs =
let candidates =
List.rev
(segment_list
(fun t -> t.type_rec = Trec_first || t.type_rec = Trec_not)
typs)
in
Compat.concat_map find_mutually_recursive_types candidates
in
let typs = List.rev typs in
let tbl, typs =
Compat.fold_left_map
(translate_mutually_recursive_types ~rev_namespace)
tbl
(find_recursive_types typs)
in
let tbl, rst = segment_module_intro ~rev_namespace tbl l in
(tbl, List.concat typs @ rst))
let of_cmi_infos ~translations ~features ~lwt_module ~tezos_types
(info : cmi_infos) =
let namespace, name = namespace_and_path info.cmi_name in
module_of_signatures features lwt_module tezos_types namespace name
info.cmi_sign
|> of_module_entry translations
|> snd
let compute_conflicts =
let modname = List.hd in
let cc_variant ~rev_namespace owner conflicts v =
Conflict.add_constructor rev_namespace ~owner v.variant_name conflicts
in
let cc_field ~rev_namespace owner conflicts f =
Conflict.add_field rev_namespace ~owner f.field_name conflicts
in
let cc_type ~rev_namespace conflicts t =
let conflicts = Conflict.add_type rev_namespace t.type_name conflicts in
match t.type_value with
| Variant vs ->
List.fold_left (cc_variant ~rev_namespace t.type_name) conflicts vs
| Record fs ->
List.fold_left (cc_field ~rev_namespace t.type_name) conflicts fs
| _ -> conflicts
in
let cc_types ~rev_namespace conflicts typs =
List.fold_left (cc_type ~rev_namespace) conflicts typs
in
let cc_functions ~rev_namespace funcs conflicts =
List.fold_left
(fun conflicts func ->
Conflict.add_value rev_namespace func.func_name conflicts)
conflicts funcs
in
let cc_prim ~rev_namespace conflicts prim =
let modname = modname rev_namespace in
let owner = prim.prim_name in
Conflict.add_value rev_namespace owner conflicts
|> Conflict.add_helper rev_namespace owner Name.io_helper
|> Conflict.add_helper rev_namespace owner Name.lwt_sync_helper
|> Conflict.add_helper rev_namespace ~owner:modname owner
Name.interface_cstr
|> Conflict.add_helper rev_namespace owner Name.inject_helper
|> Conflict.add_helper rev_namespace owner Name.semantics_helper
in
let cc_prims ~rev_namespace prims conflicts =
let owner = modname rev_namespace in
List.fold_left (cc_prim ~rev_namespace) conflicts prims
|> Conflict.add_helper rev_namespace owner Name.prim_monad
|> Conflict.add_helper rev_namespace owner Name.io_instance
|> Conflict.add_helper rev_namespace owner Name.lwt_sync_instance
|> Conflict.add_helper rev_namespace owner Name.interface_type
|> Conflict.add_helper rev_namespace owner Name.inject_instance
|> Conflict.add_helper rev_namespace owner Name.semantics
in
let cc_lwt ~rev_namespace conflicts lwt =
let modname = modname rev_namespace in
let owner = lwt.lwt_name in
Conflict.add_value rev_namespace lwt.lwt_name conflicts
|> Conflict.add_helper rev_namespace owner Name.lwt_async_helper
|> Conflict.add_helper rev_namespace ~owner:modname owner
Name.interface_cstr
|> Conflict.add_helper rev_namespace owner Name.inject_helper
|> Conflict.add_helper rev_namespace owner Name.inject_instance
in
let cc_lwts ~rev_namespace lwts conflicts =
let owner = modname rev_namespace in
List.fold_left (cc_lwt ~rev_namespace) conflicts lwts
|> Conflict.add_helper rev_namespace owner Name.async_monad
|> Conflict.add_helper rev_namespace owner Name.lwt_async_instance
|> Conflict.add_helper rev_namespace owner Name.async_interface_type
|> Conflict.add_helper rev_namespace owner Name.async_inject_instance
in
let cc_exn ~rev_namespace conflicts exn =
let owner = exn.exception_name in
Conflict.add_helper rev_namespace owner Name.to_exn conflicts
|> Conflict.add_helper rev_namespace owner Name.of_exn
|> Conflict.add_helper rev_namespace owner Name.exn_proxy_type
|> Conflict.add_helper rev_namespace owner Name.exn_proxy_cstr
|> Conflict.add_helper rev_namespace owner Name.exn_instance
in
let cc_exns ~rev_namespace exns conflicts =
List.fold_left (cc_exn ~rev_namespace) conflicts exns
in
let rec cc_module ~rev_namespace conflicts m =
let rev_namespace = m.mod_name :: rev_namespace in
fold_intro_list (cc_types ~rev_namespace) (cc_module ~rev_namespace)
conflicts m.mod_intro
|> cc_functions ~rev_namespace m.mod_functions
|> cc_prims ~rev_namespace m.mod_primitives
|> cc_lwts ~rev_namespace m.mod_lwt
|> cc_exns ~rev_namespace m.mod_exceptions
in
cc_module ~rev_namespace:[]
|
5bc6a087412ad941bcab307ee839002b50d4fb7dedcbb3bc16544a59359dd279 | katcipis/sicp | stream.rkt | #lang racket
(require "cons.rkt")
;kstream instead of stream because racket already has a stream
;a stream is basically lazy evaluation done manually
;when evaluated the tail of stream should produce another stream
;which is the next value + a promisse to calculate the rest
(define (kstream head tail)
(kons head tail))
(define (kstream-head s)
(kons-head s))
(define (kstream-tail s)
((kons-tail s)))
(define (kstream-nth s i)
(if (= i 0)
(kstream-head s)
(kstream-nth (kstream-tail s) (- i 1))))
(define (kstream-take s n)
(cond
[(<= n 0) '()]
[(null? (kstream-tail s)) (list (kstream-head s))]
[else (cons (kstream-head s)
(kstream-take (kstream-tail s)
(- n 1)))]))
(provide kstream kstream-head kstream-tail kstream-nth kstream-take)
| null | https://raw.githubusercontent.com/katcipis/sicp/d365de58e106d54f83d0ca236ea5ea666253da89/stream/stream.rkt | racket | kstream instead of stream because racket already has a stream
a stream is basically lazy evaluation done manually
when evaluated the tail of stream should produce another stream
which is the next value + a promisse to calculate the rest | #lang racket
(require "cons.rkt")
(define (kstream head tail)
(kons head tail))
(define (kstream-head s)
(kons-head s))
(define (kstream-tail s)
((kons-tail s)))
(define (kstream-nth s i)
(if (= i 0)
(kstream-head s)
(kstream-nth (kstream-tail s) (- i 1))))
(define (kstream-take s n)
(cond
[(<= n 0) '()]
[(null? (kstream-tail s)) (list (kstream-head s))]
[else (cons (kstream-head s)
(kstream-take (kstream-tail s)
(- n 1)))]))
(provide kstream kstream-head kstream-tail kstream-nth kstream-take)
|
878d27e9ba202c4fe4677282b509c5689ff8ae48b978a542ed3182a748835a4c | fpco/cache-s3 | Remote.hs | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE NoImplicitPrelude #
-- |
-- Module : Network.AWS.S3.Cache.Remote
Copyright : ( c ) FP Complete 2017
-- License : BSD3
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
--
module Network.AWS.S3.Cache.Remote where
import Control.Applicative
import Control.Lens hiding ((^.), to)
import Control.Monad.Reader
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Resource (liftResourceT)
import Crypto.Hash (Digest, HashAlgorithm, digestFromByteString)
import Data.ByteArray as BA
import Data.ByteString as S
import Data.ByteString.Base64 as S64
import Data.Conduit
import Data.Conduit.List as CL
import RIO.HashMap as HM
import Data.Ratio ((%))
import RIO.Text as T
import RIO.Time
import Network.AWS hiding (LogLevel)
import Network.AWS.Data.Body
import Network.AWS.Data.Text (toText)
import Network.AWS.S3.Cache.Types
import Network.AWS.S3.Cache.Local (restoreFilesFromCache)
import Network.AWS.S3.CreateMultipartUpload
import Network.AWS.S3.DeleteObject
import Network.AWS.S3.GetObject
import Network.AWS.S3.StreamingUpload
import Network.AWS.S3.Types
import Network.HTTP.Client
import Network.HTTP.Types.Status (Status(statusMessage), status404)
import RIO
import RIO.List as L
import Data.Conduit.Binary
-- | Returns the time when the cache object was created
getCreateTime :: GetObjectResponse -> Maybe UTCTime
getCreateTime resp =
(HM.lookup metaCreateTimeKey (resp ^. gorsMetadata) >>= parseISO8601) <|>
(resp ^. gorsLastModified)
| Will check if there is already cache up on AWS and checks if it 's contents has changed .
-- Returns create time date if new cache should be uploaded.
hasCacheChanged ::
( MonadReader r m
, MonadIO m
, MonadThrow m
, HasBucketName r BucketName
, HasLogFunc r
, HasObjectKey r ObjectKey
, HasNumRetries r Int
, HasEnv r
, HasMinLogLevel r LogLevel
, HashAlgorithm h
, Typeable h
)
=> Digest h
-> m (Maybe UTCTime)
hasCacheChanged newHash = do
c <- ask
let getObjReq = getObject (c ^. bucketName) (c ^. objectKey)
hashKey = getHashMetaKey newHash
onErr status
| status == status404 = do
logAWS LevelInfo "No previously stored cache was found."
return (Nothing, (Nothing, Nothing))
| otherwise = return (Just LevelError, (Nothing, Nothing))
onSucc resp = do
logAWS LevelDebug "Discovered previous cache."
let mOldHash = HM.lookup hashKey (resp ^. gorsMetadata)
mCreateTime = getCreateTime resp
case mOldHash of
Just oldHash ->
logAWS LevelDebug $
"Hash value for previous cache is " <> display hashKey <> ": " <> display oldHash
Nothing ->
logAWS LevelWarn $ "Previous cache is missing a hash value '" <> display hashKey <> "'"
return (mOldHash, mCreateTime)
(mOldHashTxt, mCreateTime) <- sendAWS getObjReq onErr onSucc
createTime <- maybe getCurrentTime return mCreateTime
mOldHash <- maybe (return Nothing) decodeHash mOldHashTxt
return
(if Just newHash /= mOldHash
then Just createTime
else Nothing)
encodeHash :: HashAlgorithm h => Digest h -> Utf8Builder
encodeHash hash = displayBytesUtf8 (S64.encode (BA.convert hash))
decodeHash ::
(MonadIO m, MonadReader env m, HashAlgorithm h, HasLogFunc env, HasObjectKey env ObjectKey)
=> Text
-> m (Maybe (Digest h))
decodeHash hashTxt =
case S64.decode (T.encodeUtf8 hashTxt) of
Left err -> do
logAWS LevelError $
"Problem decoding cache's hash value: " <> display hashTxt <> " Decoding Error: " <>
fromString err
return Nothing
Right bstr -> return $ digestFromByteString bstr
uploadCache ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasMinLogLevel r LogLevel
, HasObjectKey r ObjectKey
, HasBucketName r BucketName
, HasLogFunc r
, HasMaxSize r (Maybe Integer)
, HasNumRetries r Int
, MonadThrow m
, HashAlgorithm h
, Typeable h
)
=> Bool
-> TempFile -- ^ Temporary file where cache has been written to
-> (Word64, Digest h) -- ^ Size and hash of the temporary file with cache
-> m ()
uploadCache isPublic tmpFile (cSize, newHash) =
void $
runMaybeT $ do
c <- ask
when (maybe False (fromIntegral cSize >=) (c ^. maxSize)) $ do
logAWS LevelInfo $ "Refusing to save, cache is too big: " <> formatBytes (fromIntegral cSize)
MaybeT $ return Nothing
mCreatedTime <- hasCacheChanged newHash
createTime <- mCreatedTime `onNothing` logAWS LevelInfo "No change to cache was detected."
let newHashTxt = textDisplay $ encodeHash newHash
hashKey = getHashMetaKey newHash
cmu =
createMultipartUpload (c ^. bucketName) (c ^. objectKey) &
cmuMetadata .~
HM.fromList
[ (metaHashAlgorithmKey, hashKey)
, (metaCreateTimeKey, textDisplay $ formatISO8601 createTime)
, (hashKey, newHashTxt)
, (compressionMetaKey, getCompressionName (tempFileCompression tmpFile))
] &
if isPublic
then cmuACL ?~ OPublicRead
else id
logAWS LevelInfo $
mconcat
[ "Data change detected, caching "
, formatBytes (fromIntegral cSize)
, " with "
, display hashKey
, ": "
, display newHashTxt
]
startTime <- getCurrentTime
runLoggingAWS_ $
runConduit $
sourceHandle (tempFileHandle tmpFile) .|
passthroughSink (streamUpload (Just (100 * 2 ^ (20 :: Int))) cmu) (void . pure) .|
transPipe (runRIO c) (getProgressReporter cSize) .|
sinkNull
-- Disabled due to: -s3/issues/26
-- hClose (tempFileHandle tmpFile)
-- runLoggingAWS_ $
-- void $
-- concurrentUpload
( Just ( 8 * 1024 ^ ( 2 : : Int ) ) )
-- (Just 10)
( FP ( tempFilePath tmpFile ) )
-- cmu
endTime <- getCurrentTime
reportSpeed cSize $ diffUTCTime endTime startTime
logAWS LevelInfo "Finished uploading. Files are cached on S3."
reportSpeed ::
(MonadIO m, MonadReader env m, HasLogFunc env, HasObjectKey env ObjectKey, Real p1, Real p2)
=> p1
-> p2
-> m ()
reportSpeed cSize delta = logAWS LevelInfo $ "Average speed: " <> formatBytes speed <> "/s"
where
speed
| delta == 0 = 0
| otherwise = round (toRational cSize / toRational delta)
onNothing :: Monad m => Maybe b -> m a -> MaybeT m b
onNothing mArg whenNothing =
case mArg of
Nothing -> do
_ <- lift whenNothing
MaybeT $ return Nothing
Just res -> MaybeT $ return $ Just res
deleteCache ::
( MonadReader c m
, MonadThrow m
, MonadIO m
, HasEnv c
, HasLogFunc c
, HasMinLogLevel c LogLevel
, HasNumRetries c Int
, HasObjectKey c ObjectKey
, HasBucketName c BucketName
)
=> m ()
deleteCache = do
c <- ask
sendAWS_
(deleteObject (c ^. bucketName) (c ^. objectKey))
(const $ logAWS LevelInfo "Clear cache request was successfully submitted.")
-- | Download an object from S3 and handle its content using the supplied sink.
restoreCache ::
(MonadIO m, MonadReader Config m, MonadThrow m, PrimMonad m, MonadUnliftIO m)
=> FileOverwrite
-> m Bool
restoreCache fileOverwrite =
fmap isJust $
runMaybeT $ do
c <- ask
let getObjReq = getObject (c ^. bucketName) (c ^. objectKey)
onErr status
| status == status404 = do
logAWS LevelInfo "No previously stored cache was found."
MaybeT $ return Nothing
| otherwise = pure (Just LevelError, ())
logAWS LevelDebug "Checking for previously stored cache."
sendAWS getObjReq onErr $ \resp -> do
logAWS LevelDebug "Starting to download previous cache."
compAlgTxt <-
HM.lookup compressionMetaKey (resp ^. gorsMetadata) `onNothing`
logAWS LevelWarn "Missing information on compression algorithm."
compAlg <-
readCompression compAlgTxt `onNothing`
logAWS LevelWarn ("Compression algorithm is not supported: " <> display compAlgTxt)
logAWS LevelDebug $ "Compression algorithm used: " <> display compAlgTxt
hashAlgName <-
HM.lookup metaHashAlgorithmKey (resp ^. gorsMetadata) `onNothing`
logAWS LevelWarn "Missing information on hashing algorithm."
logAWS LevelDebug $ "Hashing algorithm used: " <> display hashAlgName
hashTxt <-
HM.lookup hashAlgName (resp ^. gorsMetadata) `onNothing`
logAWS LevelWarn ("Cache is missing a hash value '" <> display hashAlgName <> "'")
logAWS LevelDebug $ "Hash value is " <> display hashAlgName <> ": " <> display hashTxt
createTime <-
getCreateTime resp `onNothing` logAWS LevelWarn "Cache is missing creation time info."
logAWS LevelDebug $ "Cache creation timestamp: " <> formatRFC822 createTime
case c ^. maxAge of
Nothing -> return ()
Just timeDelta -> do
curTime <- getCurrentTime
when (curTime >= addUTCTime timeDelta createTime) $ do
logAWS LevelInfo $
"Refusing to restore, cache is too old: " <>
formatDiffTime (diffUTCTime curTime createTime)
deleteCache
MaybeT $ return Nothing
case (,) <$> (resp ^. gorsContentLength) <*> (c ^. maxSize) of
Nothing -> return ()
Just (len, maxLen) ->
when (len >= maxLen) $ do
logAWS LevelInfo $ "Refusing to restore, cache is too big: " <> formatBytes len
deleteCache
MaybeT $ return Nothing
let noHashAlgSupport _ =
logAWS LevelWarn $
"Hash algorithm used for the cache is not supported: " <> display hashAlgName
withHashAlgorithm_ hashAlgName noHashAlgSupport $ \hashAlg -> do
mHashExpected <- decodeHash hashTxt
hashExpected <-
mHashExpected `onNothing`
logAWS LevelError ("Problem decoding cache's hash value: " <> display hashTxt)
len <-
(resp ^. gorsContentLength) `onNothing`
logAWS LevelError "Did not receive expected cache size form AWS"
logAWS LevelInfo $
"Restoring cache from " <> formatRFC822 (fromMaybe createTime (resp ^. gorsLastModified)) <>
" with total size: " <>
formatBytes len
hashComputed <-
lift $
runConduitRes $
transPipe liftResourceT (resp ^. gorsBody ^. to _streamBody) .|
getProgressReporter (fromInteger len) .|
restoreFilesFromCache fileOverwrite compAlg hashAlg
if hashComputed == hashExpected
then logAWS LevelInfo $
"Successfully restored previous cache with hash: " <> encodeHash hashComputed
else do
logAWS LevelError $
mconcat
[ "Computed '"
, display hashAlgName
, "' hash mismatch: '"
, encodeHash hashComputed
, "' /= '"
, encodeHash hashExpected
, "'"
]
MaybeT $ return Nothing
| Send request to AWS and process the response with a handler . A separate error handler will be
-- invoked whenever an error occurs, which suppose to return some sort of default value and the
` LogLevel ` this error corresponds to .
sendAWS ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasLogFunc r
, HasMinLogLevel r LogLevel
, HasObjectKey r ObjectKey
, HasNumRetries r Int
, AWSRequest a
, MonadThrow m
)
=> a
-> (Status -> m (Maybe LogLevel, b))
-> (Rs a -> m b)
-> m b
sendAWS req = runLoggingAWS (send req)
-- | Same as `sendAWS`, but discard the response and simply error out on any received AWS error
-- responses.
sendAWS_ ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasLogFunc r
, HasMinLogLevel r LogLevel
, HasNumRetries r Int
, HasObjectKey r ObjectKey
, AWSRequest a
, MonadThrow m
)
=> a
-> (Rs a -> m ())
-> m ()
sendAWS_ req = sendAWS req (const $ pure (Just LevelError, ()))
| Report every problem as ` LevelError ` and discard the result .
runLoggingAWS_ ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasLogFunc r
, HasMinLogLevel r LogLevel
, HasNumRetries r Int
, HasObjectKey r ObjectKey
, MonadThrow m
)
=> AWS ()
-> m ()
runLoggingAWS_ action = runLoggingAWS action (const $ pure (Just LevelError, ())) return
-- | General helper for calling AWS and conditionally log the outcome upon a received error.
runLoggingAWS ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasLogFunc r
, HasMinLogLevel r LogLevel
, HasNumRetries r Int
, HasObjectKey r ObjectKey
, MonadThrow m
)
=> AWS t
-> (Status -> m (Maybe LogLevel, b))
-> (t -> m b)
-> m b
runLoggingAWS action onErr onSucc = do
conf <- ask
eResp <- retryWith (liftIO $ runResourceT $ runAWS conf $ trying _Error action)
case eResp of
Left err -> do
(errMsg, status) <-
case err of
TransportError exc -> do
unless ((conf ^. minLogLevel) == LevelDebug) $
logAWS LevelError $ "Critical HTTPException: " <> toErrorMessage exc
throwM exc
SerializeError serr ->
return (fromString (serr ^. serializeMessage), serr ^. serializeStatus)
ServiceError serr -> do
let status = serr ^. serviceStatus
errMsg =
display $
maybe
(T.decodeUtf8With T.lenientDecode $ statusMessage status)
toText
(serr ^. serviceMessage)
return (errMsg, status)
(mLevel, def) <- onErr status
case mLevel of
Just level -> logAWS level errMsg
Nothing -> return ()
return def
Right suc -> onSucc suc
-- | Convert an HTTP exception into a readable error message
toErrorMessage :: HttpException -> Utf8Builder
toErrorMessage exc =
case exc of
HttpExceptionRequest _ httpExcContent ->
case httpExcContent of
StatusCodeException resp _ -> "StatusCodeException: " <> displayShow (responseStatus resp)
TooManyRedirects rs -> "TooManyRedirects: " <> display (L.length rs)
InvalidHeader _ -> "InvalidHeader"
InvalidRequestHeader _ -> "InvalidRequestHeader"
InvalidProxyEnvironmentVariable name _ ->
"InvalidProxyEnvironmentVariable: " <> display name
_ -> displayShow httpExcContent
_ -> fromString (displayException exc)
-- | Retry the provided action
retryWith ::
( HasNumRetries r Int
, HasLogFunc r
, HasObjectKey r ObjectKey
, MonadIO m
, MonadReader r m
)
=> m (Either Error a)
-> m (Either Error a)
retryWith action = do
conf <- ask
let n = conf ^. numRetries
go i eResp =
case eResp of
Left (TransportError exc)
| i > n -> pure eResp
| otherwise -> do
exponential backoff with at most 9 seconds
logAWS LevelWarn $ "TransportError - " <> toErrorMessage exc
logAWS LevelWarn $
"Retry " <> display i <> "/" <> display n <> ". Waiting for " <> display s <>
" seconds"
liftIO $ threadDelay (s * 1000000) -- microseconds
eResp' <- action
go (i + 1) eResp'
_ -> pure eResp
action >>= go 1
-- | Logger that will add object info to the entry.
logAWS :: (MonadIO m, MonadReader a m, HasLogFunc a, HasObjectKey a ObjectKey) =>
LogLevel -> Utf8Builder -> m ()
logAWS ll msg = do
c <- ask
let ObjectKey objKeyTxt = c ^. objectKey
logGeneric "" ll $ "<" <> display objKeyTxt <> "> - " <> msg
-- | Compute chunk thresholds and report progress.
reportProgress ::
(MonadIO m)
=> (Word64 -> Word64 -> m a)
-> ([(Word64, Word64)], Word64, Word64, UTCTime)
-> Word64
-> m ([(Word64, Word64)], Word64, Word64, UTCTime)
reportProgress reporter (thresh, stepSum, prevSum, prevTime) chunkSize
| L.null thresh || curSum < curThresh = return (thresh, stepSum + chunkSize, curSum, prevTime)
| otherwise = do
curTime <- liftIO getCurrentTime
let delta = diffUTCTime curTime prevTime
speed = if delta == 0
then 0
else (toInteger (stepSum + chunkSize) % 1) / toRational delta
_ <- reporter perc $ round (fromRational @Double speed)
return (restThresh, 0, curSum, curTime)
where
curSum = prevSum + chunkSize
(perc, curThresh):restThresh = thresh
| Creates a conduit that will execute supplied action 10 time each for every 10 % of the data is
-- being passed through it. Supplied action will receive `Text` with status and speed of processing.
getProgressReporter ::
(MonadIO m, MonadReader r m, HasLogFunc r) => Word64 -> ConduitM S.ByteString S.ByteString m ()
getProgressReporter totalSize = do
let thresh = [(p, (totalSize * p) `div` 100) | p <- [10,20 .. 100]]
reporter perc speed =
logInfo $
"Progress: " <> display perc <> "%, speed: " <> formatBytes (fromIntegral speed) <>
"/s"
reportProgressAccum chunk acc = do
acc' <- reportProgress reporter acc (fromIntegral (S.length chunk))
return (acc', chunk)
curTime <- getCurrentTime
void $ CL.mapAccumM reportProgressAccum (thresh, 0, 0, curTime)
| null | https://raw.githubusercontent.com/fpco/cache-s3/2d68e6a5aa1c60d3785420adff24f028ac82ae15/src/Network/AWS/S3/Cache/Remote.hs | haskell | # LANGUAGE OverloadedStrings #
|
Module : Network.AWS.S3.Cache.Remote
License : BSD3
Stability : experimental
Portability : non-portable
| Returns the time when the cache object was created
Returns create time date if new cache should be uploaded.
^ Temporary file where cache has been written to
^ Size and hash of the temporary file with cache
Disabled due to: -s3/issues/26
hClose (tempFileHandle tmpFile)
runLoggingAWS_ $
void $
concurrentUpload
(Just 10)
cmu
| Download an object from S3 and handle its content using the supplied sink.
invoked whenever an error occurs, which suppose to return some sort of default value and the
| Same as `sendAWS`, but discard the response and simply error out on any received AWS error
responses.
| General helper for calling AWS and conditionally log the outcome upon a received error.
| Convert an HTTP exception into a readable error message
| Retry the provided action
microseconds
| Logger that will add object info to the entry.
| Compute chunk thresholds and report progress.
being passed through it. Supplied action will receive `Text` with status and speed of processing. | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE NoImplicitPrelude #
Copyright : ( c ) FP Complete 2017
Maintainer : < >
module Network.AWS.S3.Cache.Remote where
import Control.Applicative
import Control.Lens hiding ((^.), to)
import Control.Monad.Reader
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Resource (liftResourceT)
import Crypto.Hash (Digest, HashAlgorithm, digestFromByteString)
import Data.ByteArray as BA
import Data.ByteString as S
import Data.ByteString.Base64 as S64
import Data.Conduit
import Data.Conduit.List as CL
import RIO.HashMap as HM
import Data.Ratio ((%))
import RIO.Text as T
import RIO.Time
import Network.AWS hiding (LogLevel)
import Network.AWS.Data.Body
import Network.AWS.Data.Text (toText)
import Network.AWS.S3.Cache.Types
import Network.AWS.S3.Cache.Local (restoreFilesFromCache)
import Network.AWS.S3.CreateMultipartUpload
import Network.AWS.S3.DeleteObject
import Network.AWS.S3.GetObject
import Network.AWS.S3.StreamingUpload
import Network.AWS.S3.Types
import Network.HTTP.Client
import Network.HTTP.Types.Status (Status(statusMessage), status404)
import RIO
import RIO.List as L
import Data.Conduit.Binary
getCreateTime :: GetObjectResponse -> Maybe UTCTime
getCreateTime resp =
(HM.lookup metaCreateTimeKey (resp ^. gorsMetadata) >>= parseISO8601) <|>
(resp ^. gorsLastModified)
| Will check if there is already cache up on AWS and checks if it 's contents has changed .
hasCacheChanged ::
( MonadReader r m
, MonadIO m
, MonadThrow m
, HasBucketName r BucketName
, HasLogFunc r
, HasObjectKey r ObjectKey
, HasNumRetries r Int
, HasEnv r
, HasMinLogLevel r LogLevel
, HashAlgorithm h
, Typeable h
)
=> Digest h
-> m (Maybe UTCTime)
hasCacheChanged newHash = do
c <- ask
let getObjReq = getObject (c ^. bucketName) (c ^. objectKey)
hashKey = getHashMetaKey newHash
onErr status
| status == status404 = do
logAWS LevelInfo "No previously stored cache was found."
return (Nothing, (Nothing, Nothing))
| otherwise = return (Just LevelError, (Nothing, Nothing))
onSucc resp = do
logAWS LevelDebug "Discovered previous cache."
let mOldHash = HM.lookup hashKey (resp ^. gorsMetadata)
mCreateTime = getCreateTime resp
case mOldHash of
Just oldHash ->
logAWS LevelDebug $
"Hash value for previous cache is " <> display hashKey <> ": " <> display oldHash
Nothing ->
logAWS LevelWarn $ "Previous cache is missing a hash value '" <> display hashKey <> "'"
return (mOldHash, mCreateTime)
(mOldHashTxt, mCreateTime) <- sendAWS getObjReq onErr onSucc
createTime <- maybe getCurrentTime return mCreateTime
mOldHash <- maybe (return Nothing) decodeHash mOldHashTxt
return
(if Just newHash /= mOldHash
then Just createTime
else Nothing)
encodeHash :: HashAlgorithm h => Digest h -> Utf8Builder
encodeHash hash = displayBytesUtf8 (S64.encode (BA.convert hash))
decodeHash ::
(MonadIO m, MonadReader env m, HashAlgorithm h, HasLogFunc env, HasObjectKey env ObjectKey)
=> Text
-> m (Maybe (Digest h))
decodeHash hashTxt =
case S64.decode (T.encodeUtf8 hashTxt) of
Left err -> do
logAWS LevelError $
"Problem decoding cache's hash value: " <> display hashTxt <> " Decoding Error: " <>
fromString err
return Nothing
Right bstr -> return $ digestFromByteString bstr
uploadCache ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasMinLogLevel r LogLevel
, HasObjectKey r ObjectKey
, HasBucketName r BucketName
, HasLogFunc r
, HasMaxSize r (Maybe Integer)
, HasNumRetries r Int
, MonadThrow m
, HashAlgorithm h
, Typeable h
)
=> Bool
-> m ()
uploadCache isPublic tmpFile (cSize, newHash) =
void $
runMaybeT $ do
c <- ask
when (maybe False (fromIntegral cSize >=) (c ^. maxSize)) $ do
logAWS LevelInfo $ "Refusing to save, cache is too big: " <> formatBytes (fromIntegral cSize)
MaybeT $ return Nothing
mCreatedTime <- hasCacheChanged newHash
createTime <- mCreatedTime `onNothing` logAWS LevelInfo "No change to cache was detected."
let newHashTxt = textDisplay $ encodeHash newHash
hashKey = getHashMetaKey newHash
cmu =
createMultipartUpload (c ^. bucketName) (c ^. objectKey) &
cmuMetadata .~
HM.fromList
[ (metaHashAlgorithmKey, hashKey)
, (metaCreateTimeKey, textDisplay $ formatISO8601 createTime)
, (hashKey, newHashTxt)
, (compressionMetaKey, getCompressionName (tempFileCompression tmpFile))
] &
if isPublic
then cmuACL ?~ OPublicRead
else id
logAWS LevelInfo $
mconcat
[ "Data change detected, caching "
, formatBytes (fromIntegral cSize)
, " with "
, display hashKey
, ": "
, display newHashTxt
]
startTime <- getCurrentTime
runLoggingAWS_ $
runConduit $
sourceHandle (tempFileHandle tmpFile) .|
passthroughSink (streamUpload (Just (100 * 2 ^ (20 :: Int))) cmu) (void . pure) .|
transPipe (runRIO c) (getProgressReporter cSize) .|
sinkNull
( Just ( 8 * 1024 ^ ( 2 : : Int ) ) )
( FP ( tempFilePath tmpFile ) )
endTime <- getCurrentTime
reportSpeed cSize $ diffUTCTime endTime startTime
logAWS LevelInfo "Finished uploading. Files are cached on S3."
reportSpeed ::
(MonadIO m, MonadReader env m, HasLogFunc env, HasObjectKey env ObjectKey, Real p1, Real p2)
=> p1
-> p2
-> m ()
reportSpeed cSize delta = logAWS LevelInfo $ "Average speed: " <> formatBytes speed <> "/s"
where
speed
| delta == 0 = 0
| otherwise = round (toRational cSize / toRational delta)
onNothing :: Monad m => Maybe b -> m a -> MaybeT m b
onNothing mArg whenNothing =
case mArg of
Nothing -> do
_ <- lift whenNothing
MaybeT $ return Nothing
Just res -> MaybeT $ return $ Just res
deleteCache ::
( MonadReader c m
, MonadThrow m
, MonadIO m
, HasEnv c
, HasLogFunc c
, HasMinLogLevel c LogLevel
, HasNumRetries c Int
, HasObjectKey c ObjectKey
, HasBucketName c BucketName
)
=> m ()
deleteCache = do
c <- ask
sendAWS_
(deleteObject (c ^. bucketName) (c ^. objectKey))
(const $ logAWS LevelInfo "Clear cache request was successfully submitted.")
restoreCache ::
(MonadIO m, MonadReader Config m, MonadThrow m, PrimMonad m, MonadUnliftIO m)
=> FileOverwrite
-> m Bool
restoreCache fileOverwrite =
fmap isJust $
runMaybeT $ do
c <- ask
let getObjReq = getObject (c ^. bucketName) (c ^. objectKey)
onErr status
| status == status404 = do
logAWS LevelInfo "No previously stored cache was found."
MaybeT $ return Nothing
| otherwise = pure (Just LevelError, ())
logAWS LevelDebug "Checking for previously stored cache."
sendAWS getObjReq onErr $ \resp -> do
logAWS LevelDebug "Starting to download previous cache."
compAlgTxt <-
HM.lookup compressionMetaKey (resp ^. gorsMetadata) `onNothing`
logAWS LevelWarn "Missing information on compression algorithm."
compAlg <-
readCompression compAlgTxt `onNothing`
logAWS LevelWarn ("Compression algorithm is not supported: " <> display compAlgTxt)
logAWS LevelDebug $ "Compression algorithm used: " <> display compAlgTxt
hashAlgName <-
HM.lookup metaHashAlgorithmKey (resp ^. gorsMetadata) `onNothing`
logAWS LevelWarn "Missing information on hashing algorithm."
logAWS LevelDebug $ "Hashing algorithm used: " <> display hashAlgName
hashTxt <-
HM.lookup hashAlgName (resp ^. gorsMetadata) `onNothing`
logAWS LevelWarn ("Cache is missing a hash value '" <> display hashAlgName <> "'")
logAWS LevelDebug $ "Hash value is " <> display hashAlgName <> ": " <> display hashTxt
createTime <-
getCreateTime resp `onNothing` logAWS LevelWarn "Cache is missing creation time info."
logAWS LevelDebug $ "Cache creation timestamp: " <> formatRFC822 createTime
case c ^. maxAge of
Nothing -> return ()
Just timeDelta -> do
curTime <- getCurrentTime
when (curTime >= addUTCTime timeDelta createTime) $ do
logAWS LevelInfo $
"Refusing to restore, cache is too old: " <>
formatDiffTime (diffUTCTime curTime createTime)
deleteCache
MaybeT $ return Nothing
case (,) <$> (resp ^. gorsContentLength) <*> (c ^. maxSize) of
Nothing -> return ()
Just (len, maxLen) ->
when (len >= maxLen) $ do
logAWS LevelInfo $ "Refusing to restore, cache is too big: " <> formatBytes len
deleteCache
MaybeT $ return Nothing
let noHashAlgSupport _ =
logAWS LevelWarn $
"Hash algorithm used for the cache is not supported: " <> display hashAlgName
withHashAlgorithm_ hashAlgName noHashAlgSupport $ \hashAlg -> do
mHashExpected <- decodeHash hashTxt
hashExpected <-
mHashExpected `onNothing`
logAWS LevelError ("Problem decoding cache's hash value: " <> display hashTxt)
len <-
(resp ^. gorsContentLength) `onNothing`
logAWS LevelError "Did not receive expected cache size form AWS"
logAWS LevelInfo $
"Restoring cache from " <> formatRFC822 (fromMaybe createTime (resp ^. gorsLastModified)) <>
" with total size: " <>
formatBytes len
hashComputed <-
lift $
runConduitRes $
transPipe liftResourceT (resp ^. gorsBody ^. to _streamBody) .|
getProgressReporter (fromInteger len) .|
restoreFilesFromCache fileOverwrite compAlg hashAlg
if hashComputed == hashExpected
then logAWS LevelInfo $
"Successfully restored previous cache with hash: " <> encodeHash hashComputed
else do
logAWS LevelError $
mconcat
[ "Computed '"
, display hashAlgName
, "' hash mismatch: '"
, encodeHash hashComputed
, "' /= '"
, encodeHash hashExpected
, "'"
]
MaybeT $ return Nothing
| Send request to AWS and process the response with a handler . A separate error handler will be
` LogLevel ` this error corresponds to .
sendAWS ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasLogFunc r
, HasMinLogLevel r LogLevel
, HasObjectKey r ObjectKey
, HasNumRetries r Int
, AWSRequest a
, MonadThrow m
)
=> a
-> (Status -> m (Maybe LogLevel, b))
-> (Rs a -> m b)
-> m b
sendAWS req = runLoggingAWS (send req)
sendAWS_ ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasLogFunc r
, HasMinLogLevel r LogLevel
, HasNumRetries r Int
, HasObjectKey r ObjectKey
, AWSRequest a
, MonadThrow m
)
=> a
-> (Rs a -> m ())
-> m ()
sendAWS_ req = sendAWS req (const $ pure (Just LevelError, ()))
| Report every problem as ` LevelError ` and discard the result .
runLoggingAWS_ ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasLogFunc r
, HasMinLogLevel r LogLevel
, HasNumRetries r Int
, HasObjectKey r ObjectKey
, MonadThrow m
)
=> AWS ()
-> m ()
runLoggingAWS_ action = runLoggingAWS action (const $ pure (Just LevelError, ())) return
runLoggingAWS ::
( MonadReader r m
, MonadIO m
, HasEnv r
, HasLogFunc r
, HasMinLogLevel r LogLevel
, HasNumRetries r Int
, HasObjectKey r ObjectKey
, MonadThrow m
)
=> AWS t
-> (Status -> m (Maybe LogLevel, b))
-> (t -> m b)
-> m b
runLoggingAWS action onErr onSucc = do
conf <- ask
eResp <- retryWith (liftIO $ runResourceT $ runAWS conf $ trying _Error action)
case eResp of
Left err -> do
(errMsg, status) <-
case err of
TransportError exc -> do
unless ((conf ^. minLogLevel) == LevelDebug) $
logAWS LevelError $ "Critical HTTPException: " <> toErrorMessage exc
throwM exc
SerializeError serr ->
return (fromString (serr ^. serializeMessage), serr ^. serializeStatus)
ServiceError serr -> do
let status = serr ^. serviceStatus
errMsg =
display $
maybe
(T.decodeUtf8With T.lenientDecode $ statusMessage status)
toText
(serr ^. serviceMessage)
return (errMsg, status)
(mLevel, def) <- onErr status
case mLevel of
Just level -> logAWS level errMsg
Nothing -> return ()
return def
Right suc -> onSucc suc
toErrorMessage :: HttpException -> Utf8Builder
toErrorMessage exc =
case exc of
HttpExceptionRequest _ httpExcContent ->
case httpExcContent of
StatusCodeException resp _ -> "StatusCodeException: " <> displayShow (responseStatus resp)
TooManyRedirects rs -> "TooManyRedirects: " <> display (L.length rs)
InvalidHeader _ -> "InvalidHeader"
InvalidRequestHeader _ -> "InvalidRequestHeader"
InvalidProxyEnvironmentVariable name _ ->
"InvalidProxyEnvironmentVariable: " <> display name
_ -> displayShow httpExcContent
_ -> fromString (displayException exc)
retryWith ::
( HasNumRetries r Int
, HasLogFunc r
, HasObjectKey r ObjectKey
, MonadIO m
, MonadReader r m
)
=> m (Either Error a)
-> m (Either Error a)
retryWith action = do
conf <- ask
let n = conf ^. numRetries
go i eResp =
case eResp of
Left (TransportError exc)
| i > n -> pure eResp
| otherwise -> do
exponential backoff with at most 9 seconds
logAWS LevelWarn $ "TransportError - " <> toErrorMessage exc
logAWS LevelWarn $
"Retry " <> display i <> "/" <> display n <> ". Waiting for " <> display s <>
" seconds"
eResp' <- action
go (i + 1) eResp'
_ -> pure eResp
action >>= go 1
logAWS :: (MonadIO m, MonadReader a m, HasLogFunc a, HasObjectKey a ObjectKey) =>
LogLevel -> Utf8Builder -> m ()
logAWS ll msg = do
c <- ask
let ObjectKey objKeyTxt = c ^. objectKey
logGeneric "" ll $ "<" <> display objKeyTxt <> "> - " <> msg
reportProgress ::
(MonadIO m)
=> (Word64 -> Word64 -> m a)
-> ([(Word64, Word64)], Word64, Word64, UTCTime)
-> Word64
-> m ([(Word64, Word64)], Word64, Word64, UTCTime)
reportProgress reporter (thresh, stepSum, prevSum, prevTime) chunkSize
| L.null thresh || curSum < curThresh = return (thresh, stepSum + chunkSize, curSum, prevTime)
| otherwise = do
curTime <- liftIO getCurrentTime
let delta = diffUTCTime curTime prevTime
speed = if delta == 0
then 0
else (toInteger (stepSum + chunkSize) % 1) / toRational delta
_ <- reporter perc $ round (fromRational @Double speed)
return (restThresh, 0, curSum, curTime)
where
curSum = prevSum + chunkSize
(perc, curThresh):restThresh = thresh
| Creates a conduit that will execute supplied action 10 time each for every 10 % of the data is
getProgressReporter ::
(MonadIO m, MonadReader r m, HasLogFunc r) => Word64 -> ConduitM S.ByteString S.ByteString m ()
getProgressReporter totalSize = do
let thresh = [(p, (totalSize * p) `div` 100) | p <- [10,20 .. 100]]
reporter perc speed =
logInfo $
"Progress: " <> display perc <> "%, speed: " <> formatBytes (fromIntegral speed) <>
"/s"
reportProgressAccum chunk acc = do
acc' <- reportProgress reporter acc (fromIntegral (S.length chunk))
return (acc', chunk)
curTime <- getCurrentTime
void $ CL.mapAccumM reportProgressAccum (thresh, 0, 0, curTime)
|
d6fc155e26733e3c9680cb4551018d0aa9fe15cd238a47e5b430790aa7a74476 | timbertson/passe | tuple.ml | let snd (_, x) = x
let fst (x, _) = x
| null | https://raw.githubusercontent.com/timbertson/passe/467a79ea0cd7b08a97b52be3bd1307a3bdf55799/src/common/tuple.ml | ocaml | let snd (_, x) = x
let fst (x, _) = x
| |
69e5846a003e31a15191412bac8aea66a556048cbb0288a7759a2fbdb4beb68f | janestreet/core | option.mli | * This module extends { { ! Base . Option}[Base . Option ] } with bin_io , quickcheck , and support
for ppx_optional .
for ppx_optional. *)
type 'a t = 'a Base.Option.t [@@deriving bin_io, typerep]
* @inline
include module type of struct
include Base.Option
end
with type 'a t := 'a option
include Comparator.Derived with type 'a t := 'a t
include Quickcheckable.S1 with type 'a t := 'a t
val validate : none:unit Validate.check -> some:'a Validate.check -> 'a t Validate.check
module Stable : sig
module V1 : sig
type nonrec 'a t = 'a t
[@@deriving bin_io, compare, equal, hash, sexp, sexp_grammar, stable_witness]
end
end
* You might think that it 's pointless to have [ Optional_syntax ] on options because OCaml
already has nice syntax for matching on options . The reason to have this here is that
you might have , for example , a tuple of an option and some other type that supports
[ Optional_syntax ] . Since [ Optional_syntax ] can only be opted into at the granularity
of the whole match expression , we need this [ Optional_syntax ] support for options in
order to use it for the other half of the tuple .
already has nice syntax for matching on options. The reason to have this here is that
you might have, for example, a tuple of an option and some other type that supports
[Optional_syntax]. Since [Optional_syntax] can only be opted into at the granularity
of the whole match expression, we need this [Optional_syntax] support for options in
order to use it for the other half of the tuple. *)
module Optional_syntax : Optional_syntax.S1 with type 'a t := 'a t and type 'a value := 'a
| null | https://raw.githubusercontent.com/janestreet/core/f382131ccdcb4a8cd21ebf9a49fa42dcf8183de6/core/src/option.mli | ocaml | * This module extends { { ! Base . Option}[Base . Option ] } with bin_io , quickcheck , and support
for ppx_optional .
for ppx_optional. *)
type 'a t = 'a Base.Option.t [@@deriving bin_io, typerep]
* @inline
include module type of struct
include Base.Option
end
with type 'a t := 'a option
include Comparator.Derived with type 'a t := 'a t
include Quickcheckable.S1 with type 'a t := 'a t
val validate : none:unit Validate.check -> some:'a Validate.check -> 'a t Validate.check
module Stable : sig
module V1 : sig
type nonrec 'a t = 'a t
[@@deriving bin_io, compare, equal, hash, sexp, sexp_grammar, stable_witness]
end
end
* You might think that it 's pointless to have [ Optional_syntax ] on options because OCaml
already has nice syntax for matching on options . The reason to have this here is that
you might have , for example , a tuple of an option and some other type that supports
[ Optional_syntax ] . Since [ Optional_syntax ] can only be opted into at the granularity
of the whole match expression , we need this [ Optional_syntax ] support for options in
order to use it for the other half of the tuple .
already has nice syntax for matching on options. The reason to have this here is that
you might have, for example, a tuple of an option and some other type that supports
[Optional_syntax]. Since [Optional_syntax] can only be opted into at the granularity
of the whole match expression, we need this [Optional_syntax] support for options in
order to use it for the other half of the tuple. *)
module Optional_syntax : Optional_syntax.S1 with type 'a t := 'a t and type 'a value := 'a
| |
93567d001230d3798318358a599be9716835816babc709f9381b59843489d493 | snoyberg/mono-traversable | URef.hs | # LANGUAGE TypeFamilies #
| Use 1 - length mutable unboxed vectors for mutable references .
--
Motivated by : < -is-my-little-stref-int-require-allocating-gigabytes > and ArrayRef .
module Data.Mutable.URef
( -- * Types
URef
, IOURef
-- * Functions
, asURef
, MutableRef (..)
) where
import Control.Monad (liftM)
import Data.Mutable.Class
import qualified Data.Vector.Generic.Mutable as V
import qualified Data.Vector.Unboxed.Mutable as VU
-- | An unboxed vector reference, supporting any monad.
--
Since 0.2.0
newtype URef s a = URef (VU.MVector s a)
-- |
Since 0.2.0
asURef :: URef s a -> URef s a
asURef x = x
# INLINE asURef #
-- | An unboxed IO vector reference.
type IOURef = URef (PrimState IO)
instance MutableContainer (URef s a) where
type MCState (URef s a) = s
instance VU.Unbox a => MutableRef (URef s a) where
type RefElement (URef s a) = a
newRef = liftM URef . V.replicate 1
# INLINE newRef #
readRef (URef v) = V.unsafeRead v 0
# INLINE readRef #
writeRef (URef v) = V.unsafeWrite v 0
# INLINE writeRef #
modifyRef (URef v) f = V.unsafeRead v 0 >>= V.unsafeWrite v 0 . f
# INLINE modifyRef #
modifyRef' = modifyRef
# INLINE modifyRef ' #
| null | https://raw.githubusercontent.com/snoyberg/mono-traversable/7f763974fd312c75b74374bed889a0ee07b21428/mutable-containers/src/Data/Mutable/URef.hs | haskell |
* Types
* Functions
| An unboxed vector reference, supporting any monad.
|
| An unboxed IO vector reference. | # LANGUAGE TypeFamilies #
| Use 1 - length mutable unboxed vectors for mutable references .
Motivated by : < -is-my-little-stref-int-require-allocating-gigabytes > and ArrayRef .
module Data.Mutable.URef
URef
, IOURef
, asURef
, MutableRef (..)
) where
import Control.Monad (liftM)
import Data.Mutable.Class
import qualified Data.Vector.Generic.Mutable as V
import qualified Data.Vector.Unboxed.Mutable as VU
Since 0.2.0
newtype URef s a = URef (VU.MVector s a)
Since 0.2.0
asURef :: URef s a -> URef s a
asURef x = x
# INLINE asURef #
type IOURef = URef (PrimState IO)
instance MutableContainer (URef s a) where
type MCState (URef s a) = s
instance VU.Unbox a => MutableRef (URef s a) where
type RefElement (URef s a) = a
newRef = liftM URef . V.replicate 1
# INLINE newRef #
readRef (URef v) = V.unsafeRead v 0
# INLINE readRef #
writeRef (URef v) = V.unsafeWrite v 0
# INLINE writeRef #
modifyRef (URef v) f = V.unsafeRead v 0 >>= V.unsafeWrite v 0 . f
# INLINE modifyRef #
modifyRef' = modifyRef
# INLINE modifyRef ' #
|
da9bcb45000cc6f1fb70980eb6ca0f25a3ea32d7e9395222245dd0512be742a9 | bennn/dissertation | sequencer.rkt | #lang typed/racket/base #:transient
(require require-typed-check
"typed-data.rkt")
(require/typed/check "array-struct.rkt"
[build-array (-> Indexes (-> Indexes Flonum) Array)])
(require/typed/check "array-transform.rkt"
[array-append* ((Listof Array) -> Array)])
(require/typed/check "synth.rkt"
[fs Natural])
(require/typed/check "mixer.rkt"
[mix (-> Weighted-Signal * Array)])
(provide sequence note)
details at /~suits/notefreqs.html
(: note-freq (-> Natural Float))
(define (note-freq note)
A4 ( 440Hz ) is 57 semitones above C0 , which is our base .
(: res Real)
(define res (* 440 (expt (expt 2 1/12) (- note 57))))
(if (flonum? res) res (error "not real")))
;; A note is represented using the number of semitones from C0.
(: name+octave->note (-> Symbol Natural Natural))
(define (name+octave->note name octave)
(+ (* 12 octave)
(case name
[(C) 0]
[(C# Db) 1]
[(D) 2]
[(D# Eb) 3]
[(E) 4]
[(F) 5]
[(F# Gb) 6]
[(G) 7]
[(G# Ab) 8]
[(A) 9]
[(A# Bb) 10]
[(B) 11]
[else 0])))
;; Single note.
(: note (-> Symbol Natural Natural (Pairof Natural Natural)))
(define (note name octave duration)
(cons (name+octave->note name octave) duration))
;; Accepts notes or pauses, but not chords.
(: synthesize-note (-> (U #f Natural)
Natural
(-> Float (-> Indexes Float))
Array))
(define (synthesize-note note n-samples function)
(build-array (vector n-samples)
(if note
(function (note-freq note))
(lambda (x) 0.0)))) ; pause
;; repeats n times the sequence encoded by the pattern, at tempo bpm
;; pattern is a list of either single notes (note . duration) or
;; chords ((note ...) . duration) or pauses (#f . duration)
(: sequence (-> Natural
(Listof (Pairof (U Natural #f) Natural))
Natural
(-> Float (-> Indexes Float)) Array))
(define (sequence n pattern tempo function)
(: samples-per-beat Natural)
(define samples-per-beat (quotient (* fs 60) tempo))
(array-append*
(for*/list : (Listof Array) ([i (in-range n)] ; repeat the whole pattern
[note : (Pairof (U Natural #f) Natural) (in-list pattern)])
(: nsamples Natural)
(define nsamples (* samples-per-beat (cdr note)))
(synthesize-note (car note) nsamples function))))
| null | https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/QA/math-test/synth/d-s/sequencer.rkt | racket | A note is represented using the number of semitones from C0.
Single note.
Accepts notes or pauses, but not chords.
pause
repeats n times the sequence encoded by the pattern, at tempo bpm
pattern is a list of either single notes (note . duration) or
chords ((note ...) . duration) or pauses (#f . duration)
repeat the whole pattern | #lang typed/racket/base #:transient
(require require-typed-check
"typed-data.rkt")
(require/typed/check "array-struct.rkt"
[build-array (-> Indexes (-> Indexes Flonum) Array)])
(require/typed/check "array-transform.rkt"
[array-append* ((Listof Array) -> Array)])
(require/typed/check "synth.rkt"
[fs Natural])
(require/typed/check "mixer.rkt"
[mix (-> Weighted-Signal * Array)])
(provide sequence note)
details at /~suits/notefreqs.html
(: note-freq (-> Natural Float))
(define (note-freq note)
A4 ( 440Hz ) is 57 semitones above C0 , which is our base .
(: res Real)
(define res (* 440 (expt (expt 2 1/12) (- note 57))))
(if (flonum? res) res (error "not real")))
(: name+octave->note (-> Symbol Natural Natural))
(define (name+octave->note name octave)
(+ (* 12 octave)
(case name
[(C) 0]
[(C# Db) 1]
[(D) 2]
[(D# Eb) 3]
[(E) 4]
[(F) 5]
[(F# Gb) 6]
[(G) 7]
[(G# Ab) 8]
[(A) 9]
[(A# Bb) 10]
[(B) 11]
[else 0])))
(: note (-> Symbol Natural Natural (Pairof Natural Natural)))
(define (note name octave duration)
(cons (name+octave->note name octave) duration))
(: synthesize-note (-> (U #f Natural)
Natural
(-> Float (-> Indexes Float))
Array))
(define (synthesize-note note n-samples function)
(build-array (vector n-samples)
(if note
(function (note-freq note))
(: sequence (-> Natural
(Listof (Pairof (U Natural #f) Natural))
Natural
(-> Float (-> Indexes Float)) Array))
(define (sequence n pattern tempo function)
(: samples-per-beat Natural)
(define samples-per-beat (quotient (* fs 60) tempo))
(array-append*
[note : (Pairof (U Natural #f) Natural) (in-list pattern)])
(: nsamples Natural)
(define nsamples (* samples-per-beat (cdr note)))
(synthesize-note (car note) nsamples function))))
|
baea3d11f241d55e692766fb7f5d95a4039089578ae96029272d2a53a36186ab | chrisfarnham/diceandclocks | subs.cljs | (ns dice-and-clocks.subs
(:require
[re-frame.core :as re-frame]))
(re-frame/reg-sub
::name
(fn [db]
(:name db)))
(re-frame/reg-sub
::channel
(fn [db]
(:channel db)))
| null | https://raw.githubusercontent.com/chrisfarnham/diceandclocks/56662eb18e2c97afaba3582c1c585dc6c0d22b72/src/dice_and_clocks/subs.cljs | clojure | (ns dice-and-clocks.subs
(:require
[re-frame.core :as re-frame]))
(re-frame/reg-sub
::name
(fn [db]
(:name db)))
(re-frame/reg-sub
::channel
(fn [db]
(:channel db)))
| |
e09c3c7da1ce71e2093e52062e8ae2760f2aee6ceace4103d1938de6a7a0ff70 | tlaplus/tlapm | proof.mli |
* Copyright ( C ) 2011 INRIA and Microsoft Corporation
* Copyright (C) 2011 INRIA and Microsoft Corporation
*)
module T : sig
open Property
open Expr.T
type omission =
| Implicit
| Explicit
| Elsewhere of Loc.locus
type proof = proof_ wrapped
and proof_ =
| Obvious
| Omitted of omission
| By of usable * bool
| Steps of step list * qed_step
| Error of string
and step = step_ wrapped
and step_ =
| Hide of usable
| Define of defn list
| Assert of sequent * proof
| Suffices of sequent * proof
| Pcase of expr * proof
| Pick of bound list * expr * proof
| Use of usable * bool
| Have of expr
| Take of bound list
| Witness of expr list
| Forget of int
and qed_step = qed_step_ wrapped
and qed_step_ =
| Qed of proof
and usable = { facts : expr list
; defs : use_def wrapped list }
and use_def =
| Dvar of string
| Dx of int
type obligation_kind = Ob_main | Ob_support | Ob_error of string
type obligation = {
id : int option;
obl : sequent wrapped;
fingerprint : string option;
kind : obligation_kind;
}
type stepno =
| Named of int * string * bool
| Unnamed of int * int
module Props : sig
val step : stepno Property.pfuncs
val goal : sequent pfuncs
val supp : unit pfuncs
val obs : obligation list pfuncs
val meth : Method.t list pfuncs
val orig_step : step Property.pfuncs
val orig_proof : proof Property.pfuncs
val use_location : Loc.locus Property.pfuncs
end
val string_of_stepno: ?anonid:bool -> stepno -> string
val get_qed_proof: qed_step_ Property.wrapped -> proof
val step_number: stepno -> int
end
module Fmt : sig
open Ctx
open T
val pp_print_obligation : Format.formatter -> obligation -> unit
val pp_print_proof : Expr.Fmt.ctx -> Format.formatter -> proof -> unit
val pp_print_step : Expr.Fmt.ctx -> Format.formatter -> step -> Expr.Fmt.ctx
val pp_print_usable : Expr.Fmt.ctx -> Format.formatter -> usable -> unit
val string_of_step : Expr.T.hyp Deque.dq -> step -> string
end
module Subst : sig
open Expr.Subst
open T
val app_proof : sub -> proof -> proof
val app_step : sub -> step -> sub * step
val app_inits : sub -> step list -> sub * step list
val app_usable : sub -> usable -> usable
end
module Visit : sig
open Deque
open Expr.T
open T
open Expr.Visit
val bump : 's scx -> int -> 's scx
class virtual ['s] map : object
inherit ['s] Expr.Visit.map
method proof : 's scx -> proof -> proof
method steps : 's scx -> step list -> 's scx * step list
method step : 's scx -> step -> 's scx * step
method usable : 's scx -> usable -> usable
end
class virtual ['s] iter : object
inherit ['s] Expr.Visit.iter
method proof : 's scx -> proof -> unit
method steps : 's scx -> step list -> 's scx
method step : 's scx -> step -> 's scx
method usable : 's scx -> usable -> unit
end
end
module Simplify : sig
open Property
open Deque
open Expr.T
open T
val simplify : hyp dq -> expr -> proof -> time -> proof
end
module Anon : sig
class anon : [string list] Visit.map
val anon : anon
end
module Gen : sig
open Deque
open Property
open Expr.T
open T
val prove_assertion :
suffices:bool ->
hyp dq -> expr -> sequent wrapped -> time -> hyp dq * expr * time
val use_assertion :
suffices:bool ->
hyp dq -> expr -> sequent wrapped -> time -> hyp dq * expr
val get_steps_proof : proof -> step list
val generate : sequent -> proof -> time -> proof
val collect : proof -> obligation list * proof
val mutate : hyp Deque.dq ->
[`Use of bool | `Hide] -> usable wrapped -> time -> hyp Deque.dq * obligation list
type stats = {
total : int ;
checked : int ;
absent : Loc.locus list ;
omitted : Loc.locus list ;
suppressed : Loc.locus list ;
}
val get_stats : unit -> stats
val reset_stats : unit -> unit
end
module Parser : sig
type supp = Emit | Suppress
val usebody : T.usable Tla_parser.lprs
val proof : T.proof Tla_parser.lprs
val suppress : supp Tla_parser.lprs
end
| null | https://raw.githubusercontent.com/tlaplus/tlapm/158386319f5b6cd299f95385a216ade2b85c9f72/src/proof.mli | ocaml |
* Copyright ( C ) 2011 INRIA and Microsoft Corporation
* Copyright (C) 2011 INRIA and Microsoft Corporation
*)
module T : sig
open Property
open Expr.T
type omission =
| Implicit
| Explicit
| Elsewhere of Loc.locus
type proof = proof_ wrapped
and proof_ =
| Obvious
| Omitted of omission
| By of usable * bool
| Steps of step list * qed_step
| Error of string
and step = step_ wrapped
and step_ =
| Hide of usable
| Define of defn list
| Assert of sequent * proof
| Suffices of sequent * proof
| Pcase of expr * proof
| Pick of bound list * expr * proof
| Use of usable * bool
| Have of expr
| Take of bound list
| Witness of expr list
| Forget of int
and qed_step = qed_step_ wrapped
and qed_step_ =
| Qed of proof
and usable = { facts : expr list
; defs : use_def wrapped list }
and use_def =
| Dvar of string
| Dx of int
type obligation_kind = Ob_main | Ob_support | Ob_error of string
type obligation = {
id : int option;
obl : sequent wrapped;
fingerprint : string option;
kind : obligation_kind;
}
type stepno =
| Named of int * string * bool
| Unnamed of int * int
module Props : sig
val step : stepno Property.pfuncs
val goal : sequent pfuncs
val supp : unit pfuncs
val obs : obligation list pfuncs
val meth : Method.t list pfuncs
val orig_step : step Property.pfuncs
val orig_proof : proof Property.pfuncs
val use_location : Loc.locus Property.pfuncs
end
val string_of_stepno: ?anonid:bool -> stepno -> string
val get_qed_proof: qed_step_ Property.wrapped -> proof
val step_number: stepno -> int
end
module Fmt : sig
open Ctx
open T
val pp_print_obligation : Format.formatter -> obligation -> unit
val pp_print_proof : Expr.Fmt.ctx -> Format.formatter -> proof -> unit
val pp_print_step : Expr.Fmt.ctx -> Format.formatter -> step -> Expr.Fmt.ctx
val pp_print_usable : Expr.Fmt.ctx -> Format.formatter -> usable -> unit
val string_of_step : Expr.T.hyp Deque.dq -> step -> string
end
module Subst : sig
open Expr.Subst
open T
val app_proof : sub -> proof -> proof
val app_step : sub -> step -> sub * step
val app_inits : sub -> step list -> sub * step list
val app_usable : sub -> usable -> usable
end
module Visit : sig
open Deque
open Expr.T
open T
open Expr.Visit
val bump : 's scx -> int -> 's scx
class virtual ['s] map : object
inherit ['s] Expr.Visit.map
method proof : 's scx -> proof -> proof
method steps : 's scx -> step list -> 's scx * step list
method step : 's scx -> step -> 's scx * step
method usable : 's scx -> usable -> usable
end
class virtual ['s] iter : object
inherit ['s] Expr.Visit.iter
method proof : 's scx -> proof -> unit
method steps : 's scx -> step list -> 's scx
method step : 's scx -> step -> 's scx
method usable : 's scx -> usable -> unit
end
end
module Simplify : sig
open Property
open Deque
open Expr.T
open T
val simplify : hyp dq -> expr -> proof -> time -> proof
end
module Anon : sig
class anon : [string list] Visit.map
val anon : anon
end
module Gen : sig
open Deque
open Property
open Expr.T
open T
val prove_assertion :
suffices:bool ->
hyp dq -> expr -> sequent wrapped -> time -> hyp dq * expr * time
val use_assertion :
suffices:bool ->
hyp dq -> expr -> sequent wrapped -> time -> hyp dq * expr
val get_steps_proof : proof -> step list
val generate : sequent -> proof -> time -> proof
val collect : proof -> obligation list * proof
val mutate : hyp Deque.dq ->
[`Use of bool | `Hide] -> usable wrapped -> time -> hyp Deque.dq * obligation list
type stats = {
total : int ;
checked : int ;
absent : Loc.locus list ;
omitted : Loc.locus list ;
suppressed : Loc.locus list ;
}
val get_stats : unit -> stats
val reset_stats : unit -> unit
end
module Parser : sig
type supp = Emit | Suppress
val usebody : T.usable Tla_parser.lprs
val proof : T.proof Tla_parser.lprs
val suppress : supp Tla_parser.lprs
end
| |
47a0b47a6bd9cbdfd8390e1f4d003a22505db791de4eeefe44d686a780d013ee | camlp5/camlp5 | calc.ml | (* camlp5r *)
(* calc.ml,v *)
value g = Grammar.gcreate (Plexer.gmake ());
value e = Grammar.Entry.create g "expression";
EXTEND
e:
[ [ x = e; "+"; y = e -> x + y
| x = e; "-"; y = e -> x - y ]
| [ x = e; "*"; y = e -> x * y
| x = e; "/"; y = e -> x / y ]
| [ x = INT -> int_of_string x
| "("; x = e; ")" -> x ] ]
;
END;
open Printf;
try
for i = 1 to Array.length Sys.argv - 1 do {
let r = Grammar.Entry.parse e (Stream.of_string Sys.argv.(i)) in
printf "%s = %d\n" Sys.argv.(i) r;
flush stdout;
}
with [ Ploc.Exc loc exc ->
Fmt.(pf stderr "%s%a@.%!" (Ploc.string_of_location loc) exn exc)
| exc -> Fmt.(pf stderr "%a@.%!" exn exc)
]
;
| null | https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/tutorials/calc/calc.ml | ocaml | camlp5r
calc.ml,v |
value g = Grammar.gcreate (Plexer.gmake ());
value e = Grammar.Entry.create g "expression";
EXTEND
e:
[ [ x = e; "+"; y = e -> x + y
| x = e; "-"; y = e -> x - y ]
| [ x = e; "*"; y = e -> x * y
| x = e; "/"; y = e -> x / y ]
| [ x = INT -> int_of_string x
| "("; x = e; ")" -> x ] ]
;
END;
open Printf;
try
for i = 1 to Array.length Sys.argv - 1 do {
let r = Grammar.Entry.parse e (Stream.of_string Sys.argv.(i)) in
printf "%s = %d\n" Sys.argv.(i) r;
flush stdout;
}
with [ Ploc.Exc loc exc ->
Fmt.(pf stderr "%s%a@.%!" (Ploc.string_of_location loc) exn exc)
| exc -> Fmt.(pf stderr "%a@.%!" exn exc)
]
;
|
fe0bcbb044c1835e74c4b017c4e3c1893bb41b98624f4076e65f0a305dd0c619 | psholtz/MIT-SICP | exercise2-07.scm | ;;
Exercise 2.7
;;
's program is incomplete because she has not specified the implementation of
;; the interval abstraction. Here is a definition of the interval constructor:
;;
;; (define (make-interval a b) (cons a b))
;;
;; Define selectors "upper-bound" and "lower-bound" to complete the implementation.
;;
;;
;; Constructor:
;;
(define (make-interval a b) (cons a b))
;;
;; Selectors:
;;
(define (lower-bound x) (car x))
(define (upper-bound x) (cdr x)) | null | https://raw.githubusercontent.com/psholtz/MIT-SICP/01e9b722ac5008e26f386624849117ca8fa80906/Section-2.1/mit-scheme/exercise2-07.scm | scheme |
the interval abstraction. Here is a definition of the interval constructor:
(define (make-interval a b) (cons a b))
Define selectors "upper-bound" and "lower-bound" to complete the implementation.
Constructor:
Selectors:
| Exercise 2.7
's program is incomplete because she has not specified the implementation of
(define (make-interval a b) (cons a b))
(define (lower-bound x) (car x))
(define (upper-bound x) (cdr x)) |
06da2c76e5f41d53bc526f63e6b1944dde3ec0d14a088c0cab69c5deec9ecbbd | ghcjs/ghcjs | TestData.hs |
module TestData where
Test Data Data Type
Operation Tokens
data Op a = Find a | Delete a | Insert a deriving Show
A test Data .
-- t_name : Name of the test data.
-- t_threads : Number of concurrent threads to run
-- t_modes : Concurrent modes selected. Multiple modes
-- will be batch tested in specified sequence
-- t_repeats : Number of runs to conduct on each mode.
-- t_init_list : Elements of the initial list
-- t_tasks : Sequence of operation each node
-- executes. Note this must correspond to
-- number of threads.
data TestData a = TestData { t_name :: String
, t_threads :: Int
, t_init_list :: [a]
, t_tasks :: [[Op a]] }
instance Show a => Show (TestData a) where
show tc = "Name: " ++ (t_name tc) ++ "\n" ++
"Threads: " ++ (show $ t_threads tc) ++ "\n" ++
"Initial-List:\n" ++ (show $ t_init_list tc) ++ "\n" ++
"Tasks:\n" ++ (printOps $ t_tasks tc)
where
printOps (op:ops) = (show op) ++ "\n" ++ (printOps ops)
printOps [] = ""
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/concurrent/prog003/TestData.hs | haskell | t_name : Name of the test data.
t_threads : Number of concurrent threads to run
t_modes : Concurrent modes selected. Multiple modes
will be batch tested in specified sequence
t_repeats : Number of runs to conduct on each mode.
t_init_list : Elements of the initial list
t_tasks : Sequence of operation each node
executes. Note this must correspond to
number of threads. |
module TestData where
Test Data Data Type
Operation Tokens
data Op a = Find a | Delete a | Insert a deriving Show
A test Data .
data TestData a = TestData { t_name :: String
, t_threads :: Int
, t_init_list :: [a]
, t_tasks :: [[Op a]] }
instance Show a => Show (TestData a) where
show tc = "Name: " ++ (t_name tc) ++ "\n" ++
"Threads: " ++ (show $ t_threads tc) ++ "\n" ++
"Initial-List:\n" ++ (show $ t_init_list tc) ++ "\n" ++
"Tasks:\n" ++ (printOps $ t_tasks tc)
where
printOps (op:ops) = (show op) ++ "\n" ++ (printOps ops)
printOps [] = ""
|
6fc6a02b75a0896ec834f8b607625e4b2ee0bff96116ce404f55004f22ca7e9b | blt/port_compiler | pc_prv_clean.erl | %% -------------------------------------------------------------------
%%
rebar3 port compiler cleaner , in the manner of .
%%
%% -------------------------------------------------------------------
-module(pc_prv_clean).
-behaviour(provider).
-export([init/1, do/1, format_error/1]).
-define(NAMESPACE, pc).
-define(PROVIDER, clean).
-define(DEPS, [{default, app_discovery}]).
%%%===================================================================
%%% API
%%%===================================================================
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
Provider = providers:create([
{name, ?PROVIDER}, %% The 'user friendly' name of the task
{module, ?MODULE}, %% The module implementation of the task
{bare, true}, %% The task can be run by the user, always true
{deps, ?DEPS}, %% The list of dependencies
{example, "rebar pc clean"}, %% How to use the plugin
{opts, []}, %% list of options understood by the plugin
{short_desc, "clean the results of port compilation"},
{desc, ""},
{namespace, pc}
]),
{ok, rebar_state:add_provider(State, Provider)}.
-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
Cwd = rebar_state:dir(State),
Providers = rebar_state:providers(State),
rebar_hooks:run_all_hooks(
Cwd, pre, {?NAMESPACE, ?PROVIDER}, Providers, State),
{ok, PortSpecs} = pc_port_specs:construct(State),
ok = pc_compilation:clean(State, PortSpecs),
rebar_hooks:run_all_hooks(
Cwd, post, {?NAMESPACE, ?PROVIDER}, Providers, State),
{ok, State}.
-spec format_error(any()) -> iolist().
format_error(Reason) ->
io_lib:format("~p", [Reason]).
| null | https://raw.githubusercontent.com/blt/port_compiler/f791c40bfa9ca8ebfc82bd8fc241b1584fbfac26/src/pc_prv_clean.erl | erlang | -------------------------------------------------------------------
-------------------------------------------------------------------
===================================================================
API
===================================================================
The 'user friendly' name of the task
The module implementation of the task
The task can be run by the user, always true
The list of dependencies
How to use the plugin
list of options understood by the plugin | rebar3 port compiler cleaner , in the manner of .
-module(pc_prv_clean).
-behaviour(provider).
-export([init/1, do/1, format_error/1]).
-define(NAMESPACE, pc).
-define(PROVIDER, clean).
-define(DEPS, [{default, app_discovery}]).
-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
Provider = providers:create([
{short_desc, "clean the results of port compilation"},
{desc, ""},
{namespace, pc}
]),
{ok, rebar_state:add_provider(State, Provider)}.
-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
Cwd = rebar_state:dir(State),
Providers = rebar_state:providers(State),
rebar_hooks:run_all_hooks(
Cwd, pre, {?NAMESPACE, ?PROVIDER}, Providers, State),
{ok, PortSpecs} = pc_port_specs:construct(State),
ok = pc_compilation:clean(State, PortSpecs),
rebar_hooks:run_all_hooks(
Cwd, post, {?NAMESPACE, ?PROVIDER}, Providers, State),
{ok, State}.
-spec format_error(any()) -> iolist().
format_error(Reason) ->
io_lib:format("~p", [Reason]).
|
76c0a2d5d0956b669a7332c16990e29f3bdf217dc45270e49ed855b644b22380 | johnlawrenceaspden/hobby-code | binomial.clj | The Binomial Distribution
;; Example 1.1 of ItILA
;; A bent coin has probability f of coming up heads. The coin is tossed N times.
;; What is the probability distribution of the number of heads, r? What are the
;; mean and variance of r?
Suppose f is 1/3 , and we toss the coin once
1/3 of the time r is 1 , and 2/3 of the time , r is 0
;; If we toss it twice, then those probabilities split
1/3 - > 1/3 * 1/3 and 1/3 * 2/3
2/3 - > 1/3 * 2/3 and 1/3 * 2/3
So there are four separate sets of universes
In 1/9 ths of them , the coin came up heads twice
In 2/9 ths of them , the coin came up heads and then tails
In 2/9 ths of them , the coin came up tails and then heads
In 4/9 ths of them , the coin came up heads then heads
Ignoring the order , then we can unite the two 2/9ths possibilities to say that in 4/9ths
;; of the possible worlds, the coin has come up heads once.
So , 1/9 of the time r is 2 , 4/9ths of the time it is 1 , 4/9ths of the time it is 0
;; P(2)=1/9
;; P(1)=4/9
P(0)=4/9
If we call f 1/3 and g = 2/3 = 1 - f
Then ) + g P(2 ) from the previous distribution
;; Let us call P(r, N, f) the probability of r heads in N trials given
;; probability f of a head in a single trial.
;; We see a recursion. What do we know so far?
P(0,0,f ) = 1
P(r,0,f ) = 0 for any r < > 1
;; P(0,1,f) = 1-f
;; P(1,1,f) = f
P(0,2,f ) = ( 1 - f)*P(0,1,f)+ [ f*P(-1,1,f ) ]
P(1,2,f ) = ( 1 - f)*P(1,1,f)+f*P(0,1,f )
;; P(2,2,f) = [(1-f)*P(2,1,f) ]+ f*P(1,1,f)
;; That's enough information to write the recursion:
(defn P[r,N,f]
(if (= N 0) (if (= r 0) 1 0)
(+ (* f (P (dec r) (dec N) f)) (* (- 1 f) (P r (dec N) f)))))
;; since it's a tree recursion we'll memoize it
(def P (memoize P))
;; Test it by seeing whether it reproduces our old knowledge
0
1
0
(P -1 1 1/3) ; 0N
2/3
1/3
(P 2 1 1/3) ; 0N
(P -1 2 1/3) ; 0N
4/9
4/9
1/9
(P 3 2 1/3) ; 0N
;; And now try to create some new knowledge
(P -1 3 1/3) ; 0N
8/27
4/9
2/9
1/27
(P 4 3 1/3) ; 0N
;; What about an explicit formula?
;; If we have a sequences of H and T which are N long, how many have r H's?
;; The answer is N choose r, by definition. Each one has probability f^r*(1-f)^(N-r)
;; But how to calculate N choose r?
Well , if we take all the sequences of length 2 , and add H , and all the
sequences of length 2 and add T , then we 'll have all the sequences of length
3 .
And if we know 2 choose r for all r , then we can see that 3 choose r must be 2 choose r + 2 choose r-1 , by the recursion above .
1
1 1
;; 1 2 1
;; 1 3 3 1
;; 1 4 6 4 1
;; etc
;; What would an explicit formula look like?
;; The total number of sequences doubles at every pass.
How many different ways are there of mixing 3 H and 2 T ?
We have 5 ! permutations of a b c d e
If we say that a = b = c = H and d = e = T , how many of these 5 ! permutations are the same ?
;; Ah! we can permute a b c and we can independently permute d e without affecting the
sequence , so each sequence must have 3!2 ! aliases in the 5 ! permutations
;; Thus we may define
(defn factorial [n] (if (= n 0) 1 (* n (factorial (dec n)))))
(defn choose [N r]
(/ (factorial N) (factorial (- N r)) (factorial r)))
;; or
(defn ways [heads tails]
(/ (factorial (+ heads tails))
(factorial heads) (factorial tails)))
(defn power [a n]
(if (= n 0) 1 (* a (power a (dec n)))))
(defn probability [heads tails f]
(* (power f heads) (power (- 1N f) tails) (ways heads tails)))
1/9
4/9
4/9
(probability 10 5 1/3) ; 32032/4782969
;; But anyway we are going to define
(defn binomial [r f N] = (* (choose N r) (power f r) (power (- 1 f) (- N r))))
3/8 chance of 1 head in three tosses of a fair coin
63/256 chance of 4 heads in nine tosses of a fair coin
;; What is the mean of the binomial distribution?
(defn binomial-mean [f N]
(reduce + (map (fn [r] (* r (binomial r f N) )) (range 0 (inc N)))))
5N hooray !
(binomial-mean 1/3 10) ; 10/3
;; Postulate on intuitive grounds that the mean of the binomial distribution is N*f
;; Indeed it seems that this is so.
2/3
2 * 1/9 + 1 * 4/9 + 0 * 4/9 = 2/9 + 4/9 = 6/9 = 2/3 1/3 chance , 2 tosses
;; But why?
;; Let's look at a single toss of a fair coin
P(1 ) = 1/2 P(0 ) = 1/2
Expectation = 1 * 1/2 + 0 * 1/2 = 1/2
Two tosses
P(0 ) = 1/4 P(1 ) = 1/2 P(2 ) = 1/4
Expectation = 0 * 1/4 + 1 * 1/2 * 2 * 1/4 = 1/2 + 1/2 = 1
or alternatively 1/2 * ( 0 * 1/2 + 1 * 1/2 )
+ 1/2 * ( 1 * 1/2 + 2 * 1/2 )
2 * 1/2 * ( 0 * 1/2 + 1 * 1/2 )
;; What about generating samples from this distribution?
(defn binomial-sample [f N]
(if (= N 1)
(if (< (rand) f) 1 0)
(+ (binomial-sample f 1) (binomial-sample f (dec N)))))
(binomial-sample 0.3 10)
(defmacro sample-seq [sexp]
`(map #(%) (repeat (fn[] ~sexp))))
(def myseq (sample-seq (binomial-sample 0.3 10)))
(defn seq-sums [sq] (reductions (fn [a x] (+ a x)) 0 sq))
(defn seq-sqsums [sq] (reductions (fn [a x] (+ a (* x x))) 0 sq))
(defn scaledown [sq] (map / sq (drop 1 (range))))
(def samplemeans (map float (scaledown (seq-sums myseq))))
(def samplesqmeans (map float (scaledown (seq-sqsums myseq))))
(def ssq-smeans (map - samplesqmeans (map #(* % %) samplemeans)))
(take 10 (drop 100000 ssq-smeans))
(defn sample-mean [sq] (/ (reduce + sq) (count sq)))
(defn sample-var [sq]
(let [sm (sample-mean sq)]
(/ (reduce + (map #(* (- % sm) (- % sm)) sq)) (count sq))))
(sample-mean (take 100 (map #(* % %) (map #(- % 3) myseq))))
Sample mean should head for 3 = 10 * 0.3
(map float (map #(sample-mean (take % myseq)) (drop 1 (range))))
Sample variance should head for 2.1 = 10 * 0.3 ( 1 - 0.3 ) = 3 * 0.7
(map float (map #(sample-var (take % myseq)) (drop 1 (range))))
(* 10 0.3 (- 1 0.3))
(sample-mean (take 100 myseq))
| null | https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/binomial.clj | clojure | Example 1.1 of ItILA
A bent coin has probability f of coming up heads. The coin is tossed N times.
What is the probability distribution of the number of heads, r? What are the
mean and variance of r?
If we toss it twice, then those probabilities split
of the possible worlds, the coin has come up heads once.
P(2)=1/9
P(1)=4/9
Let us call P(r, N, f) the probability of r heads in N trials given
probability f of a head in a single trial.
We see a recursion. What do we know so far?
P(0,1,f) = 1-f
P(1,1,f) = f
P(2,2,f) = [(1-f)*P(2,1,f) ]+ f*P(1,1,f)
That's enough information to write the recursion:
since it's a tree recursion we'll memoize it
Test it by seeing whether it reproduces our old knowledge
0N
0N
0N
0N
And now try to create some new knowledge
0N
0N
What about an explicit formula?
If we have a sequences of H and T which are N long, how many have r H's?
The answer is N choose r, by definition. Each one has probability f^r*(1-f)^(N-r)
But how to calculate N choose r?
1 2 1
1 3 3 1
1 4 6 4 1
etc
What would an explicit formula look like?
The total number of sequences doubles at every pass.
Ah! we can permute a b c and we can independently permute d e without affecting the
Thus we may define
or
32032/4782969
But anyway we are going to define
What is the mean of the binomial distribution?
10/3
Postulate on intuitive grounds that the mean of the binomial distribution is N*f
Indeed it seems that this is so.
But why?
Let's look at a single toss of a fair coin
What about generating samples from this distribution? | The Binomial Distribution
Suppose f is 1/3 , and we toss the coin once
1/3 of the time r is 1 , and 2/3 of the time , r is 0
1/3 - > 1/3 * 1/3 and 1/3 * 2/3
2/3 - > 1/3 * 2/3 and 1/3 * 2/3
So there are four separate sets of universes
In 1/9 ths of them , the coin came up heads twice
In 2/9 ths of them , the coin came up heads and then tails
In 2/9 ths of them , the coin came up tails and then heads
In 4/9 ths of them , the coin came up heads then heads
Ignoring the order , then we can unite the two 2/9ths possibilities to say that in 4/9ths
So , 1/9 of the time r is 2 , 4/9ths of the time it is 1 , 4/9ths of the time it is 0
P(0)=4/9
If we call f 1/3 and g = 2/3 = 1 - f
Then ) + g P(2 ) from the previous distribution
P(0,0,f ) = 1
P(r,0,f ) = 0 for any r < > 1
P(0,2,f ) = ( 1 - f)*P(0,1,f)+ [ f*P(-1,1,f ) ]
P(1,2,f ) = ( 1 - f)*P(1,1,f)+f*P(0,1,f )
(defn P[r,N,f]
(if (= N 0) (if (= r 0) 1 0)
(+ (* f (P (dec r) (dec N) f)) (* (- 1 f) (P r (dec N) f)))))
(def P (memoize P))
0
1
0
2/3
1/3
4/9
4/9
1/9
8/27
4/9
2/9
1/27
Well , if we take all the sequences of length 2 , and add H , and all the
sequences of length 2 and add T , then we 'll have all the sequences of length
3 .
And if we know 2 choose r for all r , then we can see that 3 choose r must be 2 choose r + 2 choose r-1 , by the recursion above .
1
1 1
How many different ways are there of mixing 3 H and 2 T ?
We have 5 ! permutations of a b c d e
If we say that a = b = c = H and d = e = T , how many of these 5 ! permutations are the same ?
sequence , so each sequence must have 3!2 ! aliases in the 5 ! permutations
(defn factorial [n] (if (= n 0) 1 (* n (factorial (dec n)))))
(defn choose [N r]
(/ (factorial N) (factorial (- N r)) (factorial r)))
(defn ways [heads tails]
(/ (factorial (+ heads tails))
(factorial heads) (factorial tails)))
(defn power [a n]
(if (= n 0) 1 (* a (power a (dec n)))))
(defn probability [heads tails f]
(* (power f heads) (power (- 1N f) tails) (ways heads tails)))
1/9
4/9
4/9
(defn binomial [r f N] = (* (choose N r) (power f r) (power (- 1 f) (- N r))))
3/8 chance of 1 head in three tosses of a fair coin
63/256 chance of 4 heads in nine tosses of a fair coin
(defn binomial-mean [f N]
(reduce + (map (fn [r] (* r (binomial r f N) )) (range 0 (inc N)))))
5N hooray !
2/3
2 * 1/9 + 1 * 4/9 + 0 * 4/9 = 2/9 + 4/9 = 6/9 = 2/3 1/3 chance , 2 tosses
P(1 ) = 1/2 P(0 ) = 1/2
Expectation = 1 * 1/2 + 0 * 1/2 = 1/2
Two tosses
P(0 ) = 1/4 P(1 ) = 1/2 P(2 ) = 1/4
Expectation = 0 * 1/4 + 1 * 1/2 * 2 * 1/4 = 1/2 + 1/2 = 1
or alternatively 1/2 * ( 0 * 1/2 + 1 * 1/2 )
+ 1/2 * ( 1 * 1/2 + 2 * 1/2 )
2 * 1/2 * ( 0 * 1/2 + 1 * 1/2 )
(defn binomial-sample [f N]
(if (= N 1)
(if (< (rand) f) 1 0)
(+ (binomial-sample f 1) (binomial-sample f (dec N)))))
(binomial-sample 0.3 10)
(defmacro sample-seq [sexp]
`(map #(%) (repeat (fn[] ~sexp))))
(def myseq (sample-seq (binomial-sample 0.3 10)))
(defn seq-sums [sq] (reductions (fn [a x] (+ a x)) 0 sq))
(defn seq-sqsums [sq] (reductions (fn [a x] (+ a (* x x))) 0 sq))
(defn scaledown [sq] (map / sq (drop 1 (range))))
(def samplemeans (map float (scaledown (seq-sums myseq))))
(def samplesqmeans (map float (scaledown (seq-sqsums myseq))))
(def ssq-smeans (map - samplesqmeans (map #(* % %) samplemeans)))
(take 10 (drop 100000 ssq-smeans))
(defn sample-mean [sq] (/ (reduce + sq) (count sq)))
(defn sample-var [sq]
(let [sm (sample-mean sq)]
(/ (reduce + (map #(* (- % sm) (- % sm)) sq)) (count sq))))
(sample-mean (take 100 (map #(* % %) (map #(- % 3) myseq))))
Sample mean should head for 3 = 10 * 0.3
(map float (map #(sample-mean (take % myseq)) (drop 1 (range))))
Sample variance should head for 2.1 = 10 * 0.3 ( 1 - 0.3 ) = 3 * 0.7
(map float (map #(sample-var (take % myseq)) (drop 1 (range))))
(* 10 0.3 (- 1 0.3))
(sample-mean (take 100 myseq))
|
326744791b31bd078fa50685c4ecdde73fd5d5a2bf547c3e532471133a288214 | witan-org/witan | intmap.ml | (*************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2017
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
(* See the GNU Lesser General Public License version 2.1 *)
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(*************************************************************************)
(* -------------------------------------------------------------------------- *)
(* --- Bit library --- *)
(* -------------------------------------------------------------------------- *)
let hsb =
let hsb p = if p land 2 != 0 then 1 else 0
in let hsb p = let n = p lsr 2 in if n != 0 then 2 + hsb n else hsb p
in let hsb p = let n = p lsr 4 in if n != 0 then 4 + hsb n else hsb p
in let hsb = Array.init 256 hsb
in let hsb p = let n = p lsr 8 in if n != 0 then 8 + hsb.(n) else hsb.(p)
in let hsb p = let n = p lsr 16 in if n != 0 then 16 + hsb n else hsb p
in match Sys.word_size with
| 32 -> hsb
| 64 -> (function p -> let n = p lsr 32 in
if n != 0 then 32 + hsb n else hsb p)
* absurd : No other possible achitecture supported
let highest_bit x = 1 lsl (hsb x)
let lowest_bit x = x land (-x)
(* -------------------------------------------------------------------------- *)
(* --- Bit utilities --- *)
(* -------------------------------------------------------------------------- *)
let decode_mask p = lowest_bit (lnot p)
let branching_bit p0 p1 = highest_bit (p0 lxor p1)
let mask p m = (p lor (m-1)) land (lnot m)
let zero_bit_int k m = (k land m) == 0
let zero_bit k p = zero_bit_int k (decode_mask p)
let match_prefix_int k p m = (mask k m) == p
let match_prefix k p = match_prefix_int k p (decode_mask p)
let included_mask_int m n =
(* m mask is strictly included into n *)
can not use ( m < n ) when n is ( 1 lsl 62 ) = min_int < 0
(* must use (0 < (n-m) instead *)
0 > n - m
(* let included_mask p q = included_mask_int (decode_mask p) (decode_mask q) *)
let included_prefix p q =
let m = decode_mask p in
let n = decode_mask q in
included_mask_int m n && match_prefix_int q p m
(* -------------------------------------------------------------------------- *)
(* --- Debug --- *)
(* -------------------------------------------------------------------------- *)
let pp_mask m fmt p =
begin
let bits = Array.make 63 false in
let last = ref 0 in
for i = 0 to 62 do
let u = 1 lsl i in
if u land p <> 0 then
bits.(i) <- true ;
if u == m then last := i ;
done ;
Format.pp_print_char fmt '*' ;
for i = !last - 1 downto 0 do
Format.pp_print_char fmt (if bits.(i) then '1' else '0') ;
done ;
end
let pp_bits fmt k =
begin
let bits = Array.make 63 false in
let last = ref 0 in
for i = 0 to 62 do
if (1 lsl i) land k <> 0 then
( bits.(i) <- true ;
if i > !last then last := i ) ;
done ;
for i = !last downto 0 do
Format.pp_print_char fmt (if bits.(i) then '1' else '0') ;
done ;
end
(* ---------------------------------------------------------------------- *)
--- L. Correnson & P. Baudin & ---
(* ---------------------------------------------------------------------- *)
module Make(K:Map_intf.TaggedEqualType) :
Map_intf.Gen_Map_hashcons with type NT.key = K.t = struct
module Gen(G:sig
type (+'a) t
type 'a data
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
val ktag : 'a data t -> int
end)
= struct
open G
type key = K.t
type 'a data = 'a G.data
type 'a t = 'a G.t
(* ---------------------------------------------------------------------- *)
--- Smart Constructors ---
(* ---------------------------------------------------------------------- *)
let empty = mk_Empty
let singleton = mk_Lf
let br p t0 t1 = match view t0 , view t1 with
| Empty,_ -> t1
| _,Empty -> t0
| _ -> mk_Br p t0 t1
let lf k = function None -> mk_Empty | Some x -> mk_Lf k x
(* good sharing *)
let lf0 k x' t' = function
| None -> mk_Empty
| Some x -> if x == x' then t' else mk_Lf k x
(* good sharing *)
let br0 p t0' t1' t' t0 = match view t0 with
| Empty -> t1'
| _ -> if t0' == t0 then t' else mk_Br p t0 t1'
(* good sharing *)
let br1 p t0' t1' t' t1 = match view t1 with
| Empty -> t0'
| _ -> if t1' == t1 then t' else mk_Br p t0' t1
let join p t0 q t1 =
let m = branching_bit p q in
let r = mask p m in
if zero_bit p r
then mk_Br r t0 t1
else mk_Br r t1 t0
let side p q = (* true this side, false inverse *)
let m = branching_bit p q in
let r = mask p m in
zero_bit p r
(* t0 and t1 has different prefix, but best common prefix is unknown *)
let glue t0 t1 =
match view t0 , view t1 with
| Empty,_ -> t1
| _,Empty -> t0
| _,_ -> join (ktag t0) t0 (ktag t1) t1
let glue' ~old ~cur ~other ~all =
if old == cur then all else glue cur other
let glue0 t0 t0' t1' t' =
if t0 == t0' then t' else glue t0 t1'
let glue1 t1 t0' t1' t' =
if t1 == t1' then t' else glue t0' t1
let glue01 t0 t1 t0' t1' t' =
if t0 == t0' && t1 == t1' then t' else glue t0 t1
let glue2 t0 t1 t0' t1' t' s0' s1' s' =
if t0 == s0' && t1 == s1' then s' else
if t0 == t0' && t1 == t1' then t' else glue t0 t1
(* ---------------------------------------------------------------------- *)
(* --- Access API --- *)
(* ---------------------------------------------------------------------- *)
let is_empty x = match view x with
| Empty -> true
| Lf _ | Br _ -> false
let size t =
let rec walk n t = match view t with
| Empty -> n
| Lf _ -> succ n
| Br(_,a,b) -> walk (walk n a) b
in walk 0 t
let cardinal = size
let rec mem k t = match view t with
| Empty -> false
| Lf(i,_) -> K.equal i k
| Br(p,t0,t1) ->
match_prefix (K.tag k) p &&
mem k (if zero_bit (K.tag k) p then t0 else t1)
let rec findq k t = match view t with
| Empty -> raise Not_found
| Lf(i,x) -> if K.equal k i then (x,t) else raise Not_found
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
findq k (if zero_bit (K.tag k) p then t0 else t1)
else
raise Not_found
let rec find_exn exn k t = match view t with
| Empty -> raise exn
| Lf(i,x) -> if K.equal k i then x else raise exn
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_exn exn k (if zero_bit (K.tag k) p then t0 else t1)
else
raise exn
let find k m = find_exn Not_found k m
let rec find_opt k t = match view t with
| Empty -> None
| Lf(i,x) -> if K.equal k i then Some x else None
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_opt k (if zero_bit (K.tag k) p then t0 else t1)
else
None
let rec find_def def k t = match view t with
| Empty -> def
| Lf(i,x) -> if K.equal k i then x else def
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_def def k (if zero_bit (K.tag k) p then t0 else t1)
else
def
(* good sharing *)
let rec find_remove k t = match view t with
| Empty -> mk_Empty, None
| Lf(i,y) ->
if K.equal i k then
mk_Empty, Some y
else
t, None
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
(* k belongs to tree *)
if zero_bit (K.tag k) p
then let t0', r = find_remove k t0 in
br0 p t0 t1 t t0', r (* k is in t0 *)
else let t1', r = find_remove k t1 in
br1 p t0 t1 t t1', r (* k is in t1 *)
else
(* k is disjoint from tree *)
t, None
(** shouldn't be used at top *)
let rec max_binding_opt t = match view t with
| Empty -> None
| Lf(k,x) -> Some(k,x)
| Br(_,_,t1) -> max_binding_opt t1
let rec find_smaller_opt' cand k t = match view t with
| Empty -> assert false
| Lf(i,y) ->
let c = Pervasives.compare (K.tag i) (K.tag k) in
if c <= 0 then Some(i,y)
c > 0
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
(* k belongs to tree *)
if zero_bit (K.tag k) p
then find_smaller_opt' cand k t0
else find_smaller_opt' t0 k t1
else
(* k is disjoint from tree *)
if side (K.tag k) p
then (* k p *) max_binding_opt cand
else (* p k *) max_binding_opt t1
let find_smaller_opt k t = match view t with
| Empty -> None
| Br(p,t0,t1) when p = max_int ->
(* k belongs to tree *)
if zero_bit (K.tag k) p
then find_smaller_opt' t1 k t0
else find_smaller_opt' mk_Empty k t1
| _ ->
find_smaller_opt' mk_Empty k t
(* ---------------------------------------------------------------------- *)
(* --- Comparison --- *)
(* ---------------------------------------------------------------------- *)
let rec compare cmp s t =
if (Obj.magic s) == t then 0 else
match view s , view t with
| Empty , Empty -> 0
| Empty , _ -> (-1)
| _ , Empty -> 1
| Lf(i,x) , Lf(j,y) ->
let ck = Pervasives.compare (K.tag i) (K.tag j) in
if ck = 0 then cmp x y else ck
| Lf _ , _ -> (-1)
| _ , Lf _ -> 1
| Br(p,s0,s1) , Br(q,t0,t1) ->
let cp = Pervasives.compare p q in
if cp <> 0 then cp else
let c0 = compare cmp s0 t0 in
if c0 <> 0 then c0 else
compare cmp s1 t1
let rec equal eq s t =
if (Obj.magic s) == t then true else
match view s , view t with
| Empty , Empty -> true
| Lf(i,x) , Lf(j,y) -> K.equal i j && eq x y
| Br(p,s0,s1) , Br(q,t0,t1) ->
p==q && equal eq s0 t0 && equal eq s1 t1
| _ -> false
(* ---------------------------------------------------------------------- *)
(* --- Addition, Insert, Change, Remove --- *)
(* ---------------------------------------------------------------------- *)
(* good sharing *)
let rec change phi k x t = match view t with
| Empty -> (match phi k x None with
| None -> t
| Some w -> mk_Lf k w)
| Lf(i,y) ->
if K.equal i k then
lf0 k y t (phi k x (Some y))
else
(match phi k x None with
| None -> t
| Some w -> let s = mk_Lf k w in
join (K.tag k) s (K.tag i) t)
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
(* k belongs to tree *)
if zero_bit (K.tag k) p
then br0 p t0 t1 t (change phi k x t0) (* k is in t0 *)
else br1 p t0 t1 t (change phi k x t1) (* k is in t1 *)
else
(* k is disjoint from tree *)
(match phi k x None with
| None -> t
| Some w -> let s = mk_Lf k w in
join (K.tag k) s p t)
(* good sharing *)
let insert f k x = change (fun _k x -> function
| None -> Some x
| Some old -> Some (f k x old)) k x
(* good sharing *)
let add k x m = change (fun _k x _old -> Some x) k x m
(* good sharing *)
let remove k m = change (fun _k () _old -> None) k () m
(* good sharing *)
let add_new e x v m = change (fun _k (e,v) -> function
| Some _ -> raise e
| None -> Some v) x (e,v) m
(* good sharing *)
let rec add_change empty add k b t = match view t with
| Empty -> mk_Lf k (empty b)
| Lf(i,y) ->
if K.equal i k then
let y' = (add b y) in
if y == y' then t else mk_Lf i y'
else
let s = mk_Lf k (empty b) in
join (K.tag k) s (K.tag i) t
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
(* k belongs to tree *)
if zero_bit (K.tag k) p
then mk_Br p (add_change empty add k b t0) t1 (* k is in t0 *)
else mk_Br p t0 (add_change empty add k b t1) (* k is in t1 *)
else
(* k is disjoint from tree *)
let s = mk_Lf k (empty b) in
join (K.tag k) s p t
(* ---------------------------------------------------------------------- *)
(* --- Map --- *)
(* ---------------------------------------------------------------------- *)
let mapi phi t =
let rec mapi phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> mk_Lf k (phi k x)
| Br(p,t0,t1) ->
let t0 = mapi phi t0 in
let t1 = mapi phi t1 in
mk_Br p t0 t1
in match view t with (* in order to be sorted *)
| Empty -> mk_Empty
| Lf(k,x) -> mk_Lf k (phi k x)
| Br(p,t0,t1) when p = max_int -> let t1 = mapi phi t1 in
let t0 = mapi phi t0 in mk_Br p t0 t1
| Br(p,t0,t1) -> let t0 = mapi phi t0 in
let t1 = mapi phi t1 in mk_Br p t0 t1
let map phi = mapi (fun _ x -> phi x)
let mapf phi t =
let rec mapf phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(_,t0,t1) -> glue (mapf phi t0) (mapf phi t1)
in match view t with (* in order to be sorted *)
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(p,t0,t1) when p = max_int -> let t1 = mapf phi t1 in
let t0 = mapf phi t0 in glue t0 t1
| Br(_,t0,t1) -> let t0 = mapf phi t0 in
let t1 = mapf phi t1 in glue t0 t1
(* good sharing *)
let mapq phi t =
let rec mapq phi t = match view t with
| Empty -> t
| Lf(k,x) -> lf0 k x t (phi k x)
| Br(_,t0,t1) ->
let t0' = mapq phi t0 in
let t1' = mapq phi t1 in
glue01 t0' t1' t0 t1 t
in match view t with (* to be sorted *)
| Empty -> t
| Lf(k,x) -> lf0 k x t (phi k x)
| Br(p,t0,t1) when p = max_int ->
let t1' = mapq phi t1 in
let t0' = mapq phi t0 in
glue01 t0' t1' t0 t1 t
| Br(_,t0,t1) ->
let t0' = mapq phi t0 in
let t1' = mapq phi t1 in
glue01 t0' t1' t0 t1 t
(** bad sharing but polymorph *)
let mapq' :
type a b. (key -> a data -> b data option) -> a data t -> b data t=
fun phi t ->
let rec aux phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(_,t0,t1) ->
let t0' = aux phi t0 in
let t1' = aux phi t1 in
glue t0' t1'
in match view t with (* to be sorted *)
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(p,t0,t1) when p = max_int ->
let t1' = aux phi t1 in
let t0' = aux phi t0 in
glue t0' t1'
| Br(_,t0,t1) ->
let t0' = aux phi t0 in
let t1' = aux phi t1 in
glue t0' t1'
let filter f m = mapq' (fun k v -> if f k v then Some v else None) m
let mapi_filter = mapq'
let map_filter f m = mapq' (fun _ v -> f v) m
(*
bad sharing because the input type can be differente of the
output type it is possible but currently too many Obj.magic are
needed in lf0 and glue01
*)
let mapi_filter_fold:
type a b acc. (key -> a data -> acc -> acc * b data option) ->
a data t -> acc -> acc * b data t
= fun phi t acc ->
let rec aux phi t acc = match view t with
| Empty -> acc, mk_Empty
| Lf(k,x) -> let acc,x = (phi k x acc) in acc, lf k x
| Br(_,t0,t1) ->
let acc, t0' = aux phi t0 acc in
let acc, t1' = aux phi t1 acc in
acc, glue t0' t1'
in match view t with (* to be sorted *)
| Empty -> acc, mk_Empty
| Lf(k,x) -> let acc,x = (phi k x acc) in acc, lf k x
| Br(p,t0,t1) when p = max_int ->
let acc, t1' = aux phi t1 acc in
let acc, t0' = aux phi t0 acc in
acc, glue t0' t1'
| Br(_,t0,t1) ->
let acc, t0' = aux phi t0 acc in
let acc, t1' = aux phi t1 acc in
acc, glue t0' t1'
let mapi_fold phi t acc =
mapi_filter_fold (fun k v acc ->
let acc, v' = phi k v acc in
acc, Some v') t acc
(* good sharing *)
let rec partition p t = match view t with
| Empty -> (t,t)
| Lf(k,x) -> if p k x then t,mk_Empty else mk_Empty,t
| Br(_,t0,t1) ->
let (t0',u0') = partition p t0 in
let (t1',u1') = partition p t1 in
if t0'==t0 && t1'==t1 then (t, u0') (* u0' and u1' are empty *)
else if u0'==t0 && u1'==t1 then (t0', t) (* t0' and t1' are empty *)
else (glue t0' t1'),(glue u0' u1')
(* good sharing *)
let split k t =
let rec aux k t = match view t with
| Empty -> assert false (** absurd: only at top *)
| Lf(k',x) -> let c = Pervasives.compare (K.tag k) (K.tag k') in
if c = 0 then (mk_Empty,Some x,mk_Empty)
else if c < 0 then (mk_Empty, None, t)
c > 0
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then
let (t0',r,t1') = aux k t0 in
(t0',r,glue' ~old:t0 ~cur:t1' ~other:t1 ~all:t )
else
let (t0',r,t1') = aux k t1 in
(glue' ~old:t1 ~cur:t0' ~other:t0 ~all:t,r,t1')
else
if side (K.tag k) p
then (* k p *) (mk_Empty, None, t)
else (* p k *) (t, None, mk_Empty)
in match view t with
| Empty -> mk_Empty, None, mk_Empty
| Br(p,t0,t1) when p = max_int -> (** inverted *)
if zero_bit (K.tag k) p
then
let (t0',r,t1') = aux k t0 in
(glue' ~old:t0 ~cur:t0' ~other:t1 ~all:t,r,t1' )
else
let (t0',r,t1') = aux k t1 in
(t0',r,glue' ~old:t1 ~cur:t1' ~other:t0 ~all:t)
| _ -> aux k t
(* good sharing *)
let rec partition_split p t = match view t with
| Empty -> (t,t)
| Lf(k,x) -> let u,v = p k x in (lf0 k x t u), (lf0 k x t v)
| Br(_,t0,t1) ->
let t0',u0' = partition_split p t0 in
let t1',u1' = partition_split p t1 in
if t0'==t0 && t1'==t1 then (t, u0') (* u0' and u1' are empty *)
else if u0'==t0 && u1'==t1 then (t0', t) (* t0' and t1' are empty *)
else (glue t0' t1'),(glue u0' u1')
(* ---------------------------------------------------------------------- *)
(* --- Iter --- *)
(* ---------------------------------------------------------------------- *)
let iteri phi t =
let rec aux t = match view t with
| Empty -> ()
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 ; aux t1
in match view t with (* in order to be sorted *)
| Empty -> ()
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 ; aux t0
| Br(_,t0,t1) -> aux t0 ; aux t1
let iter = iteri
let foldi phi t e = (* increasing order *)
let rec aux t e = match view t with
| Empty -> e
| Lf(i,x) -> phi i x e
| Br(_,t0,t1) -> aux t1 (aux t0 e)
in match view t with (* to be sorted *)
| Empty -> e
| Lf(i,x) -> phi i x e
| Br(p,t0,t1) when p = max_int -> aux t0 (aux t1 e)
| Br(_,t0,t1) -> aux t1 (aux t0 e)
let fold = foldi
let fold_left phi e t = (* increasing order *)
let rec aux t e = match view t with
| Empty -> e
| Lf(k,x) -> phi e k x
| Br(_,t0,t1) -> aux t1 (aux t0 e)
in match view t with (* to be sorted *)
| Empty -> e
| Lf(k,x) -> phi e k x
| Br(p,t0,t1) when p = max_int -> aux t0 (aux t1 e)
| Br(_,t0,t1) -> aux t1 (aux t0 e)
let foldd phi e t = (* decreasing order *)
let rec aux t e = match view t with
| Empty -> e
| Lf(i,x) -> phi e i x
| Br(_,t0,t1) -> aux t0 (aux t1 e)
in match view t with (* to be sorted *)
| Empty -> e
| Lf(i,x) -> phi e i x
| Br(p,t0,t1) when p = max_int -> aux t1 (aux t0 e)
| Br(_,t0,t1) -> aux t0 (aux t1 e)
let fold_decr = foldd
(* decreasing order on f to have the list in increasing order *)
let mapl f m = foldd (fun a k v -> (f k v)::a) [] m
let bindings m = mapl (fun k v -> (k,v)) m
let values m = mapl (fun _ v -> v) m
let keys m = mapl (fun k _ -> k) m
let for_all phi t = (* increasing order *)
let rec aux t = match view t with
| Empty -> true
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 && aux t1
in match view t with (* in order to be sorted *)
| Empty -> true
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 && aux t0
| Br(_,t0,t1) -> aux t0 && aux t1
let exists phi t = (* increasing order *)
let rec aux t = match view t with
| Empty -> false
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 || aux t1
in match view t with (* in order to be sorted *)
| Empty -> false
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 || aux t0
| Br(_,t0,t1) -> aux t0 || aux t1
let min_binding t = (* increasing order *)
let rec aux t = match view t with
| Empty -> assert false (** absurd: only at top *)
| Lf(k,x) -> (k,x)
| Br(_,t0,_) -> aux t0
in match view t with (* in order to be sorted *)
| Empty -> raise Not_found
| Lf(k,x) -> (k,x)
| Br(p,_,t1) when p = max_int -> aux t1
| Br(_,t0,_) -> aux t0
let max_binding t = (* increasing order *)
let rec aux t = match view t with
| Empty -> assert false (** absurd: only at top *)
| Lf(k,x) -> (k,x)
| Br(_,_,t1) -> aux t1
in match view t with (* in order to be sorted *)
| Empty -> raise Not_found
| Lf(k,x) -> (k,x)
| Br(p,t0,_) when p = max_int -> aux t0
| Br(_,_,t1) -> aux t1
let choose = min_binding
(* ---------------------------------------------------------------------- *)
(* --- Inter --- *)
(* ---------------------------------------------------------------------- *)
let occur i t = try Some (find i t) with Not_found -> None
let rec interi lf_phi s t =
match view s , view t with
| Empty , _ -> mk_Empty
| _ , Empty -> mk_Empty
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lf_phi i x y
else mk_Empty
| Lf(i,x) , Br _ ->
(match occur i t with None -> mk_Empty | Some y -> lf_phi i x y)
| Br _ , Lf(j,y) ->
(match occur j s with None -> mk_Empty | Some x -> lf_phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue (interi lf_phi s0 t0) (interi lf_phi s1 t1)
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then interi lf_phi s0 t (* t has bit m = 0 => t is inside s0 *)
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
then interi lf_phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
mk_Empty
let interf phi = interi (fun i x y -> mk_Lf i (phi i x y))
let inter phi = interi (fun i x y -> lf i (phi i x y))
(* good sharing with s *)
let lfq phi i x y s t =
match phi i x y with
| None -> mk_Empty
| Some w -> if w == x then s else if w == y then t else mk_Lf i w
let occur0 phi i x s t =
try let (y,t) = findq i t in lfq phi i x y s t
with Not_found -> mk_Empty
let occur1 phi j y s t =
try let (x,s) = findq j s in lfq phi j x y s t
with Not_found -> mk_Empty
(* good sharing with s *)
let rec interq phi s t =
match view s , view t with
| Empty , _ -> s
| _ , Empty -> t
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lfq phi i x y s t
else mk_Empty
| Lf(i,x) , Br _ -> occur0 phi i x s t
| Br _ , Lf(j,y) -> occur1 phi j y s t
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue2 (interq phi s0 t0) (interq phi s1 t1) s0 s1 s t0 t1 t
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then interq phi s0 t (* t has bit m = 0 => t is inside s0 *)
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
then interq phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
mk_Empty
(* ---------------------------------------------------------------------- *)
(* --- Union --- *)
(* ---------------------------------------------------------------------- *)
(* good sharing with s *)
let br2u p s0' s1' s' t0' t1' t' t0 t1=
if s0'==t0 && s1'== t1 then s' else
if t0'==t0 && t1'== t1 then t' else
mk_Br p t0 t1
(* good sharing with s *)
let br0u p t0' t1' t' t0 = if t0'==t0 then t' else mk_Br p t0 t1'
let br1u p t0' t1' t' t1 = if t1'==t1 then t' else mk_Br p t0' t1
(* good sharing with s *)
let rec unionf phi s t =
match view s , view t with
| Empty , _ -> t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then let w = phi i x y in
if w == x then s else if w == y then t else mk_Lf i w
else join (K.tag i) s (K.tag j) t
| Lf(i,x) , Br _ -> insert phi i x t
| Br _ , Lf(j,y) -> insert (fun j y x -> phi j x y) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
br2u p s0 s1 s t0 t1 t (unionf phi s0 t0) (unionf phi s1 t1)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then
(* t has bit m = 0 => t is inside s0 *)
br0u p s0 s1 s (unionf phi s0 t)
else
t has bit m = 1 = > t is inside s1
br1u p s0 s1 s (unionf phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then
(* s has bit n = 0 => s is inside t0 *)
br0u q t0 t1 t (unionf phi s t0)
else
t has bit n = 1 = > s is inside t1
br1u q t0 t1 t (unionf phi s t1)
else
(* prefix disagree *)
join p s q t
(* good sharing with s *)
let rec union phi s t =
match view s , view t with
| Empty , _ -> t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then match phi i x y with
| Some w when w == x -> s
| Some w when w == y -> t
| Some w -> mk_Lf i w
| None -> mk_Empty
else join (K.tag i) s (K.tag j) t
| Lf(i,x) , Br _ ->
change (fun i x -> function | None -> Some x
| Some old -> (phi i x old)) i x t
| Br _ , Lf(j,y) ->
change (fun j y -> function | None -> Some y
| Some old -> (phi j old y)) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue2 (union phi s0 t0) (union phi s1 t1) s0 s1 s t0 t1 t
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then
(* t has bit m = 0 => t is inside s0 *)
br0 p s0 s1 s (union phi s0 t)
else
t has bit m = 1 = > t is inside s1
br1 p s0 s1 s (union phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then
(* s has bit n = 0 => s is inside t0 *)
br0 q t0 t1 t (union phi s t0)
else
t has bit n = 1 = > s is inside t1
br1 q t0 t1 t (union phi s t1)
else
(* prefix disagree *)
join p s q t
(* ---------------------------------------------------------------------- *)
(* --- Merge --- *)
(* ---------------------------------------------------------------------- *)
let map1 phi s = mapf (fun i x -> phi i (Some x) None) s
let map2 phi t = mapf (fun j y -> phi j None (Some y)) t
let rec merge phi s t =
match view s , view t with
| Empty , _ -> map2 phi t
| _ , Empty -> map1 phi s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j then lf i (phi i (Some x) (Some y))
else
let a = lf i (phi i (Some x) None) in
let b = lf j (phi j None (Some y)) in
glue a b
| Lf(i,x) , Br(q,t0,t1) ->
if match_prefix (K.tag i) q then
(* leaf i is in tree t *)
if zero_bit (K.tag i) q
then glue (merge phi s t0) (map2 phi t1) (* s=i is in t0 *)
else glue (map2 phi t0) (merge phi s t1) (* s=i is in t1 *)
else
(* leaf i does not appear in t *)
glue (lf i (phi i (Some x) None)) (map2 phi t)
| Br(p,s0,s1) , Lf(j,y) ->
if match_prefix (K.tag j) p then
(* leaf j is in tree s *)
if zero_bit (K.tag j) p
then glue (merge phi s0 t) (map1 phi s1) (* t=j is in s0 *)
else glue (map1 phi s0) (merge phi s1 t) (* t=j is in s1 *)
else
(* leaf j does not appear in s *)
glue (map1 phi s) (lf j (phi j None (Some y)))
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue (merge phi s0 t0) (merge phi s1 t1)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then (* t has bit m = 0 => t is inside s0 *)
glue (merge phi s0 t) (map1 phi s1)
t has bit m = 1 = > t is inside s1
glue (map1 phi s0) (merge phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then (* s has bit n = 0 => s is inside t0 *)
glue (merge phi s t0) (map2 phi t1)
s has bit n = 1 = > s is inside t1
glue (map2 phi t0) (merge phi s t1)
else
glue (map1 phi s) (map2 phi t)
let map2 phi t = mapf (fun j y -> phi j None y) t
let rec union_merge phi s t =
match view s , view t with
| Empty , _ -> map2 phi t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j then lf i (phi i (Some x) y)
else
let b = lf j (phi j None y) in
glue s b
| Lf(i,_) , Br(q,t0,t1) ->
if match_prefix (K.tag i) q then
(* leaf i is in tree t *)
if zero_bit (K.tag i) q
then glue (union_merge phi s t0) (map2 phi t1) (* s=i is in t0 *)
else glue (map2 phi t0) (union_merge phi s t1) (* s=i is in t1 *)
else
(* leaf i does not appear in t *)
glue s (map2 phi t)
| Br(p,s0,s1) , Lf(j,y) ->
if match_prefix (K.tag j) p then
(* leaf j is in tree s *)
if zero_bit (K.tag j) p
then glue (union_merge phi s0 t) s1 (* t=j is in s0 *)
else glue s0 (union_merge phi s1 t) (* t=j is in s1 *)
else
(* leaf j does not appear in s *)
glue s (lf j (phi j None y))
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue (union_merge phi s0 t0) (union_merge phi s1 t1)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then (* t has bit m = 0 => t is inside s0 *)
glue (union_merge phi s0 t) s1
t has bit m = 1 = > t is inside s1
glue s0 (union_merge phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then (* s has bit n = 0 => s is inside t0 *)
glue (union_merge phi s t0) (map2 phi t1)
s has bit n = 1 = > s is inside t1
glue (map2 phi t0) (union_merge phi s t1)
else
glue s (map2 phi t)
(* good sharing with s *)
let rec diffq phi s t =
match view s , view t with
| Empty , _ -> s
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lfq phi i x y s t
else s
| Lf(i,x) , Br _ ->
(match occur i t with None -> s | Some y -> lfq phi i x y s t)
| Br _ , Lf(j,y) -> change (fun j y x -> match x with
| None -> None
| Some x -> phi j x y) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
let t0' = (diffq phi s0 t0) in
let t1' = (diffq phi s1 t1) in
glue01 t0' t1' s0 s1 s
else if included_prefix p q then
(* q contains p. *)
if zero_bit q p
then (* t has bit m = 0 => t is inside s0 *)
let s0' = (diffq phi s0 t) in
glue0 s0' s0 s1 s
t has bit m = 1 = > t is inside s1
let s1' = (diffq phi s1 t) in
glue1 s1' s0 s1 s
else if included_prefix q p then
(* p contains q. *)
if zero_bit p q
then diffq phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
s
(* good sharing with s *)
let rec diff :
type a b. (key -> a data -> b data -> a data option) ->
a data t -> b data t -> a data t
= fun phi s t ->
match view s , view t with
| Empty , _ -> s
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lf0 i x s (phi i x y)
else s
| Lf(i,x) , Br _ ->
(match occur i t with None -> s | Some y -> lf0 i x s (phi i x y))
| Br _ , Lf(j,y) -> change (fun j y x -> match x with
| None -> None
| Some x -> phi j x y) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
let t0' = (diff phi s0 t0) in
let t1' = (diff phi s1 t1) in
glue01 t0' t1' s0 s1 s
else if included_prefix p q then
(* q contains p. *)
if zero_bit q p
then (* t has bit m = 0 => t is inside s0 *)
let s0' = (diff phi s0 t) in
glue0 s0' s0 s1 s
t has bit m = 1 = > t is inside s1
let s1' = (diff phi s1 t) in
glue1 s1' s0 s1 s
else if included_prefix q p then
(* p contains q. *)
if zero_bit p q
then diff phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
s
(* ---------------------------------------------------------------------- *)
(* --- Iter Kernel --- *)
(* ---------------------------------------------------------------------- *)
let rec iterk phi s t =
match view s , view t with
| Empty , _ | _ , Empty -> ()
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y
| Lf(i,x) , Br _ ->
(match occur i t with None -> () | Some y -> phi i x y)
| Br _ , Lf(j,y) ->
(match occur j s with None -> () | Some x -> phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
(iterk phi s0 t0 ; iterk phi s1 t1)
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then iterk phi s0 t (* t has bit m = 0 => t is inside s0 *)
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
then iterk phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
()
(* ---------------------------------------------------------------------- *)
(* --- Iter2 --- *)
(* ---------------------------------------------------------------------- *)
let iter21 phi s = iteri (fun i x -> phi i (Some x) None) s
let iter22 phi t = iteri (fun j y -> phi j None (Some y)) t
let rec iter2 phi s t =
match view s , view t with
| Empty , _ -> iter22 phi t
| _ , Empty -> iter21 phi s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j then phi i (Some x) (Some y)
else ( phi i (Some x) None ; phi j None (Some y) )
| Lf(i,x) , Br(q,t0,t1) ->
if match_prefix (K.tag i) q then
(* leaf i is in tree t *)
if zero_bit (K.tag i) q
then (iter2 phi s t0 ; iter22 phi t1) (* s=i is in t0 *)
else (iter22 phi t0 ; iter2 phi s t1) (* s=i is in t1 *)
else
(* leaf i does not appear in t *)
(phi i (Some x) None ; iter22 phi t)
| Br(p,s0,s1) , Lf(j,y) ->
if match_prefix (K.tag j) p then
(* leaf j is in tree s *)
if zero_bit (K.tag j) p
then (iter2 phi s0 t ; iter21 phi s1) (* t=j is in s0 *)
else (iter21 phi s0 ; iter2 phi s1 t) (* t=j is in s1 *)
else
(* leaf j does not appear in s *)
(iter21 phi s ; phi j None (Some y))
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
(iter2 phi s0 t0 ; iter2 phi s1 t1)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then (* t has bit m = 0 => t is inside s0 *)
(iter2 phi s0 t ; iter21 phi s1)
t has bit m = 1 = > t is inside s1
(iter21 phi s0 ; iter2 phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then (* s has bit n = 0 => s is inside t0 *)
(iter2 phi s t0 ; iter22 phi t1)
s has bit n = 1 = > s is inside t1
(iter22 phi t0 ; iter2 phi s t1)
else
(iter21 phi s ; iter22 phi t)
(* ---------------------------------------------------------------------- *)
(* --- Intersects --- *)
(* ---------------------------------------------------------------------- *)
(** TODO seems wrong *)
let rec intersectf phi s t =
match view s , view t with
| Empty , _ -> false
| _ , Empty -> false
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else false
| Lf(i,x) , Br _ -> (match occur i t with None -> false
| Some y -> phi i x y)
| Br _ , Lf(j,y) -> (match occur j s with None -> false
| Some x -> phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
(intersectf phi s0 t0) || (intersectf phi s1 t1)
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then intersectf phi s0 t (* t has bit m = 0 => t is inside s0 *)
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
then intersectf phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
false
let rec disjoint phi s t =
match view s , view t with
| Empty , _ -> true
| _ , Empty -> true
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else true
| Lf(i,x) , Br _ -> (match occur i t with None -> true
| Some y -> phi i x y)
| Br _ , Lf(j,y) -> (match occur j s with None -> true
| Some x -> phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
(disjoint phi s0 t0) && (disjoint phi s1 t1)
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then disjoint phi s0 t (* t has bit m = 0 => t is inside s0 *)
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
then disjoint phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
true
(** fold2 *)
let fold21 phi m acc = fold (fun i x acc -> phi i (Some x) None acc) m acc
let fold22 phi m acc = fold (fun j y acc -> phi j None (Some y) acc) m acc
(* good sharing with s *)
let rec fold2_union:
type a b c.
(key -> a data option -> b data option -> c -> c) ->
a data t -> b data t -> c -> c
= fun phi s t acc ->
match view s , view t with
| Empty , _ -> fold22 phi t acc
| _ , Empty -> fold21 phi s acc
| Lf(i,x) , Lf(j,y) ->
let c = Pervasives.compare (K.tag i) (K.tag j) in
if c = 0
then phi i (Some x) (Some y) acc
else if c < 0 then phi j None (Some y) (phi i (Some x) None acc)
c > 0
| Lf(k,x) , Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then fold22 phi t2 (fold2_union phi s t1 acc)
else fold2_union phi s t2 (fold22 phi t1 acc)
else
if side (K.tag k) p
then (* k p *) fold22 phi t (phi k (Some x) None acc)
else (* p k *) phi k (Some x) None (fold22 phi t acc)
| Br(p,s1,s2) , Lf(k,y) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then fold21 phi s2 (fold2_union phi s1 t acc)
else fold2_union phi s2 t (fold21 phi s1 acc)
else
if side (K.tag k) p
then (* k p *) fold21 phi s (phi k None (Some y) acc)
else (* p k *) phi k None (Some y) (fold21 phi s acc)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
fold2_union phi s1 t1 (fold2_union phi s0 t0 acc)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then
(* t has bit m = 0 => t is inside s0 *)
fold21 phi s1 (fold2_union phi s0 t acc)
else
t has bit m = 1 = > t is inside s1
fold2_union phi s1 t (fold21 phi s0 acc)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then
(* s has bit n = 0 => s is inside t0 *)
fold22 phi t1 (fold2_union phi s t0 acc)
else
t has bit n = 1 = > s is inside t1
fold2_union phi s t1 (fold22 phi t0 acc)
else
(* prefix disagree *)
if side p q
then (* p q *) fold22 phi t (fold21 phi s acc)
else (* q p *) fold21 phi s (fold22 phi t acc)
(* good sharing with s *)
let rec fold2_inter phi s t acc =
match view s , view t with
| Empty , _ -> acc
| _ , Empty -> acc
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then phi i x y acc
else acc
| Lf(k,x) , Br _ ->
begin match find_opt k t with
| Some y -> phi k x y acc
| None -> acc
end
| Br _ , Lf(k,y) ->
begin match find_opt k s with
| Some x -> phi k x y acc
| None -> acc
end
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
fold2_inter phi s1 t1 (fold2_inter phi s0 t0 acc)
else if included_prefix p q then
(* q contains p. Merge t with a subtree of s *)
if zero_bit q p
then
(* t has bit m = 0 => t is inside s0 *)
fold2_inter phi s0 t acc
else
t has bit m = 1 = > t is inside s1
fold2_inter phi s1 t acc
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then
(* s has bit n = 0 => s is inside t0 *)
fold2_inter phi s t0 acc
else
t has bit n = 1 = > s is inside t1
fold2_inter phi s t1 acc
else
(* prefix disagree *)
acc
(* ---------------------------------------------------------------------- *)
(* --- Subset --- *)
(* ---------------------------------------------------------------------- *)
let rec subsetf phi s t =
match view s , view t with
| Empty , _ -> true
| _ , Empty -> false
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else false
| Lf(i,x) , Br _ ->
(match occur i t with None -> false | Some y -> phi i x y)
| Br _ , Lf _ -> false
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
(subsetf phi s0 t0 && subsetf phi s1 t1)
else if included_prefix p q then
(* q contains p: t is included in a (strict) subtree of s *)
false
else if included_prefix q p then
(* p contains q: s is included in a subtree of t *)
if zero_bit p q
then subsetf phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
false
let subset = subsetf
let subsetk s t = subsetf (fun _i _x _y -> true) s t
let submap = subsetf
(* ---------------------------------------------------------------------- *)
let rec _pp_tree tab fmt t =
match view t with
| Empty -> ()
| Lf(k,_) ->
let k = K.tag k in
Format.fprintf fmt "%sL%a=%d" tab pp_bits k k
| Br(p,l,r) ->
let next = tab ^ " " in
_pp_tree next fmt l ;
Format.fprintf fmt "%s@@%a" tab (pp_mask (decode_mask p)) p ;
_pp_tree next fmt r
let is_num_elt n m =
try
fold (fun _ _ n -> if n < 0 then raise Exit else n-1) m n = 0
with Exit -> false
let of_list l =
List.fold_left (fun acc (k,d) -> add k d acc) empty l
let translate f m =
fold (fun k v acc -> add (f k) v acc) m empty
(** set_* *)
let set_union m1 m2 = unionf (fun _ x _ -> x) m1 m2
let set_inter m1 m2 = interf (fun _ x _ -> x) m1 m2
let set_diff m1 m2 = diff (fun _ _ _ -> None) m1 m2
let set_submap m1 m2 = submap (fun _ _ _ -> true) m1 m2
let set_disjoint m1 m2 = disjoint (fun _ _ _ -> false) m1 m2
let set_compare m1 m2 = compare (fun _ _ -> 0) m1 m2
let set_equal m1 m2 = equal (fun _ _ -> true) m1 m2
(** the goal is to choose randomly but often the same than [choose] *)
let choose_rnd f m =
let rec aux f m ret =
match view m with
| Empty -> ()
| Lf(k,v) -> if f () then (ret := (k,v); raise Exit)
| Br(_,t1,t2) ->
aux f t1 ret; aux f t2 ret
in
let ret = ref (Obj.magic 0) in
try
begin match view m with (* in order to be sorted *)
| Empty -> raise Not_found
| Br(p,_,t1) when p = max_int -> aux f t1 ret
| _ -> aux f m ret
end;
choose m
with Exit -> !ret
(** Enumeration *)
type 'a enumeration =
| EEmpty
| ELf of K.t * 'a * 'a enum2
and 'a enum2 =
| End
| EBr of 'a t * 'a enum2
let rec cons_enum m e =
match view m with
| Empty -> assert false (** absurd: Empty can appear only a toplevel *)
| Lf(i,x) -> ELf(i,x,e)
| Br(_,t1,t2) -> cons_enum t1 (EBr(t2,e))
let start_enum m = (* in order to be sorted *)
match view m with
| Empty -> EEmpty
| Lf(i,x) -> ELf(i,x,End)
| Br(p,t1,t2) when p = max_int -> cons_enum t2 (EBr(t1, End))
| Br(_,t1,t2) -> cons_enum t1 (EBr(t2, End))
let val_enum = function
| EEmpty -> None
| ELf(i,x,_) -> Some (i,x)
let next_enum_br = function
| End -> EEmpty
| EBr(t2,e) -> cons_enum t2 e
let next_enum = function
| EEmpty -> EEmpty
| ELf(_,_,e) -> next_enum_br e
let rec cons_ge_enum k m e =
match view m with
| Empty -> assert false (** absurd: Empty can appear only a toplevel *)
| Lf(i,x) ->
if side (K.tag i) (K.tag k)
then (* i k *) next_enum_br e
else (* k i *) ELf(i,x,e)
| Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then cons_ge_enum k t1 (EBr(t2,e))
else cons_ge_enum k t2 e
else
if side (K.tag k) p
then (* k p *) cons_enum t1 (EBr(t2,e))
else (* p k *) next_enum_br e
let start_ge_enum k m =
match view m with
| Empty -> EEmpty
| Br(p,t1,t2) when p = max_int ->
if zero_bit (K.tag k) p
then cons_ge_enum k t1 End
else cons_ge_enum k t2 (EBr(t1,End))
| _ -> cons_ge_enum k m End
let rec next_ge_enum_br k = function
| End -> EEmpty
| EBr(t,e) -> match view t with
| Empty -> assert false (** absurd: Empty only at top *)
| Lf(i,d) when (K.tag k) <= (K.tag i) -> ELf(i,d,e)
| Lf(_,_) -> next_ge_enum_br k e
| Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then cons_ge_enum k t1 (EBr(t2,e))
else cons_ge_enum k t2 e
else
if side (K.tag k) p
then (* k p *) cons_enum t1 (EBr(t2,e))
else (* p k *) next_ge_enum_br k e
let next_ge_enum k = function
| EEmpty -> EEmpty
| ELf(i,_,_) as e when (K.tag k) <= (K.tag i)-> e
| ELf(_,_,e) -> next_ge_enum_br k e
let change f k m = change (fun _ () v -> f v) k () m
let add_opt x o m =
match o with
| None -> remove x m
| Some y -> add x y m
(** TODO more checks? *)
let check_invariant m =
match view m with
| Empty -> true
| _ ->
let rec aux m =
match view m with
| Empty -> false
| Lf _ -> true
| Br (_,t1,t2) -> aux t1 && aux t2 in
aux m
let pp pp fmt m =
Pp.iter2 iter Pp.arrow Pp.colon
K.pp pp fmt m
end
module Def = struct
type 'a t =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
end
module NT = struct
module M : sig
type 'a t = 'a Def.t
type 'a data = 'a
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val ktag : 'a data t -> int
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
end = struct
type 'a t = 'a Def.t
type 'a data = 'a
let ktag = function
| Def.Empty -> assert false (** absurd: precondition: not Empty *)
| Def.Lf(i,_) -> K.tag i
| Def.Br(i,_,_) -> i
let mk_Empty = Def.Empty
let mk_Lf k d = Def.Lf(k,d)
let mk_Br i t1 t2 =
assert ( t1 ! = Def . Empty & & t2 ! = Def . Empty ) ;
Def.Br(i,t1,t2)
type 'a view = 'a Def.t =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
let view x = x
end
include Gen(M)
end
module Make(Data: Map_intf.HashType) :
Map_intf.Map_hashcons with type 'a data = Data.t
and type 'a poly := 'a NT.t
and type key = K.t = struct
(** Tag *)
module Tag: sig
type t
type gen
val mk_gen: unit -> gen
val to_int: t -> int
val dtag : t
val next_tag: gen -> t
val incr_tag: gen -> unit
* all of them are different from dtag
end = struct
type t = int
type gen = int ref
let to_int x = x
let dtag = min_int (** tag used in the polymorphic non hashconsed case *)
let mk_gen () = ref (min_int + 1)
let next_tag gen = !gen
let incr_tag gen = incr gen; assert (!gen != dtag)
end
module M : sig
type (+'a) t
type 'a data = Data.t
val nt: 'a data t -> 'a data NT.t
val rebuild: 'a data NT.t -> 'a data t
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val tag : 'a data t -> int
val ktag : 'a data t -> int
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
end = struct
module Check = struct
type 'a def = 'a Def.t = (** check the type of Def.t *)
| Empty
| Lf of K.t * 'a
| Br of int * 'a def * 'a def
end
type 'a t =
| Empty
| Lf of K.t * 'a * Tag.t
| Br of int * 'a t * 'a t * Tag.t
type 'a data = Data.t
(** This obj.magic "just" hide the last field *)
let nt x = (Obj.magic (x : 'a t) : 'a Check.def)
let tag = function
| Empty -> Tag.to_int Tag.dtag
| Lf(_,_,tag) | Br(_,_,_,tag) -> Tag.to_int tag
let ktag = function
* absurd : be used on Empty
| Lf(k,_,_) -> K.tag k
| Br(i,_,_,_) -> i
module WH = Weak.Make(struct
type 'a t' = 'a t
type t = Data.t t'
let equal x y =
match x, y with
| Empty, Empty -> true
| Lf(i1,d1,_), Lf(i2,d2,_) ->
K.equal i1 i2 && Data.equal d1 d2
| Br(_,l1,r1,_), Br(_,l2,r2,_) -> l1 == l2 && r1 == r2
| _ -> false
let hash = function
| Empty -> 0
| Lf(i1,d1,_) ->
65599 * ((K.tag i1) + (Data.hash d1 * 65599 + 31))
| Br(_,l,r,_) ->
65599 * ((tag l) + ((tag r) * 65599 + 17))
end)
let gentag = Tag.mk_gen ()
let htable = WH.create 5003
let hashcons d =
let o = WH.merge htable d in
if o == d then Tag.incr_tag gentag;
o
let mk_Empty = Empty
let mk_Lf k x = hashcons (Lf(k,x,Tag.next_tag gentag))
let mk_Br k t0 t1 =
assert ( t0 ! = Empty & & t1 ! = Empty ) ;
hashcons (Br(k,t0,t1,Tag.next_tag gentag))
let rec rebuild t = match t with
| Def.Empty -> mk_Empty
| Def.Lf(i,d) -> mk_Lf i d
| Def.Br(i,l,r) -> mk_Br i (rebuild l) (rebuild r)
type 'a view =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
(** implemntation without obj bust with copy of the next function *)
let view_ : 'a t -> 'a view = function
| Empty -> Empty
| Lf(k,v,_) -> Lf(k,v)
| Br(i,t1,t2,_) -> Br(i,t1,t2)
(** This obj.magic "just" hide the last field of the root node *)
let view x = (Obj.magic (x : 'a t): 'a view)
end
include Gen(M)
let mk_Empty = M.mk_Empty
let mk_Lf = M.mk_Lf
let nt = M.nt
let rebuild = M.rebuild
let compare_t s t = Pervasives.compare (M.tag s) (M.tag t)
let equal_t (s:'a data t) t = s == t
(** with Def.t *)
let rec interi_nt lf_phi s t =
match M.view s , t with
| M.Empty , _ -> mk_Empty
| _ , Def.Empty -> mk_Empty
| M.Lf(i,x) , Def.Lf(j,y) ->
if K.equal i j
then lf_phi i x y
else mk_Empty
| M.Lf(i,x) , Def.Br _ ->
(match NT.occur i t with None -> mk_Empty | Some y -> lf_phi i x y)
| M.Br _ , Def.Lf(j,y) ->
(match occur j s with None -> mk_Empty | Some x -> lf_phi j x y)
| M.Br(p,s0,s1) , Def.Br(q,t0,t1) ->
if p == q then
(* prefixes agree *)
glue (interi_nt lf_phi s0 t0) (interi_nt lf_phi s1 t1)
else if included_prefix p q then
(* q contains p. Intersect t with a subtree of s *)
if zero_bit q p
then interi_nt lf_phi s0 t (* t has bit m = 0 => t is inside s0 *)
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
then interi_nt lf_phi s t0 (* s has bit n = 0 => s is inside t0 *)
t has bit n = 1 = > s is inside t1
else
(* prefix disagree *)
mk_Empty
let inter_nt phi = interi_nt (fun i x y -> mk_Lf i (phi i x y))
let interf_nt phi = interi_nt (fun i x y -> lf i (phi i x y))
let set_inter_nt m1 m2 = interi_nt (fun i x _ -> mk_Lf i x) m1 m2
end
end
| null | https://raw.githubusercontent.com/witan-org/witan/d26f9f810fc34bf44daccb91f71ad3258eb62037/src/popop_lib/intmap.ml | ocaml | ***********************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
See the GNU Lesser General Public License version 2.1
***********************************************************************
--------------------------------------------------------------------------
--- Bit library ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Bit utilities ---
--------------------------------------------------------------------------
m mask is strictly included into n
must use (0 < (n-m) instead
let included_mask p q = included_mask_int (decode_mask p) (decode_mask q)
--------------------------------------------------------------------------
--- Debug ---
--------------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
good sharing
good sharing
good sharing
true this side, false inverse
t0 and t1 has different prefix, but best common prefix is unknown
----------------------------------------------------------------------
--- Access API ---
----------------------------------------------------------------------
good sharing
k belongs to tree
k is in t0
k is in t1
k is disjoint from tree
* shouldn't be used at top
k belongs to tree
k is disjoint from tree
k p
p k
k belongs to tree
----------------------------------------------------------------------
--- Comparison ---
----------------------------------------------------------------------
----------------------------------------------------------------------
--- Addition, Insert, Change, Remove ---
----------------------------------------------------------------------
good sharing
k belongs to tree
k is in t0
k is in t1
k is disjoint from tree
good sharing
good sharing
good sharing
good sharing
good sharing
k belongs to tree
k is in t0
k is in t1
k is disjoint from tree
----------------------------------------------------------------------
--- Map ---
----------------------------------------------------------------------
in order to be sorted
in order to be sorted
good sharing
to be sorted
* bad sharing but polymorph
to be sorted
bad sharing because the input type can be differente of the
output type it is possible but currently too many Obj.magic are
needed in lf0 and glue01
to be sorted
good sharing
u0' and u1' are empty
t0' and t1' are empty
good sharing
* absurd: only at top
k p
p k
* inverted
good sharing
u0' and u1' are empty
t0' and t1' are empty
----------------------------------------------------------------------
--- Iter ---
----------------------------------------------------------------------
in order to be sorted
increasing order
to be sorted
increasing order
to be sorted
decreasing order
to be sorted
decreasing order on f to have the list in increasing order
increasing order
in order to be sorted
increasing order
in order to be sorted
increasing order
* absurd: only at top
in order to be sorted
increasing order
* absurd: only at top
in order to be sorted
----------------------------------------------------------------------
--- Inter ---
----------------------------------------------------------------------
prefixes agree
q contains p. Intersect t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
good sharing with s
good sharing with s
prefixes agree
q contains p. Intersect t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
----------------------------------------------------------------------
--- Union ---
----------------------------------------------------------------------
good sharing with s
good sharing with s
good sharing with s
prefixes agree
q contains p. Merge t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
good sharing with s
prefixes agree
q contains p. Merge t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
----------------------------------------------------------------------
--- Merge ---
----------------------------------------------------------------------
leaf i is in tree t
s=i is in t0
s=i is in t1
leaf i does not appear in t
leaf j is in tree s
t=j is in s0
t=j is in s1
leaf j does not appear in s
prefixes agree
q contains p. Merge t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
leaf i is in tree t
s=i is in t0
s=i is in t1
leaf i does not appear in t
leaf j is in tree s
t=j is in s0
t=j is in s1
leaf j does not appear in s
prefixes agree
q contains p. Merge t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
good sharing with s
prefixes agree
q contains p.
t has bit m = 0 => t is inside s0
p contains q.
s has bit n = 0 => s is inside t0
prefix disagree
good sharing with s
prefixes agree
q contains p.
t has bit m = 0 => t is inside s0
p contains q.
s has bit n = 0 => s is inside t0
prefix disagree
----------------------------------------------------------------------
--- Iter Kernel ---
----------------------------------------------------------------------
prefixes agree
q contains p. Intersect t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
----------------------------------------------------------------------
--- Iter2 ---
----------------------------------------------------------------------
leaf i is in tree t
s=i is in t0
s=i is in t1
leaf i does not appear in t
leaf j is in tree s
t=j is in s0
t=j is in s1
leaf j does not appear in s
prefixes agree
q contains p. Merge t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
----------------------------------------------------------------------
--- Intersects ---
----------------------------------------------------------------------
* TODO seems wrong
prefixes agree
q contains p. Intersect t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
prefixes agree
q contains p. Intersect t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
* fold2
good sharing with s
k p
p k
k p
p k
prefixes agree
q contains p. Merge t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
p q
q p
good sharing with s
prefixes agree
q contains p. Merge t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree
----------------------------------------------------------------------
--- Subset ---
----------------------------------------------------------------------
prefixes agree
q contains p: t is included in a (strict) subtree of s
p contains q: s is included in a subtree of t
s has bit n = 0 => s is inside t0
prefix disagree
----------------------------------------------------------------------
* set_*
* the goal is to choose randomly but often the same than [choose]
in order to be sorted
* Enumeration
* absurd: Empty can appear only a toplevel
in order to be sorted
* absurd: Empty can appear only a toplevel
i k
k i
k p
p k
* absurd: Empty only at top
k p
p k
* TODO more checks?
* absurd: precondition: not Empty
* Tag
* tag used in the polymorphic non hashconsed case
* check the type of Def.t
* This obj.magic "just" hide the last field
* implemntation without obj bust with copy of the next function
* This obj.magic "just" hide the last field of the root node
* with Def.t
prefixes agree
q contains p. Intersect t with a subtree of s
t has bit m = 0 => t is inside s0
s has bit n = 0 => s is inside t0
prefix disagree | This file is part of Frama - C.
Copyright ( C ) 2007 - 2017
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
let hsb =
let hsb p = if p land 2 != 0 then 1 else 0
in let hsb p = let n = p lsr 2 in if n != 0 then 2 + hsb n else hsb p
in let hsb p = let n = p lsr 4 in if n != 0 then 4 + hsb n else hsb p
in let hsb = Array.init 256 hsb
in let hsb p = let n = p lsr 8 in if n != 0 then 8 + hsb.(n) else hsb.(p)
in let hsb p = let n = p lsr 16 in if n != 0 then 16 + hsb n else hsb p
in match Sys.word_size with
| 32 -> hsb
| 64 -> (function p -> let n = p lsr 32 in
if n != 0 then 32 + hsb n else hsb p)
* absurd : No other possible achitecture supported
let highest_bit x = 1 lsl (hsb x)
let lowest_bit x = x land (-x)
let decode_mask p = lowest_bit (lnot p)
let branching_bit p0 p1 = highest_bit (p0 lxor p1)
let mask p m = (p lor (m-1)) land (lnot m)
let zero_bit_int k m = (k land m) == 0
let zero_bit k p = zero_bit_int k (decode_mask p)
let match_prefix_int k p m = (mask k m) == p
let match_prefix k p = match_prefix_int k p (decode_mask p)
let included_mask_int m n =
can not use ( m < n ) when n is ( 1 lsl 62 ) = min_int < 0
0 > n - m
let included_prefix p q =
let m = decode_mask p in
let n = decode_mask q in
included_mask_int m n && match_prefix_int q p m
let pp_mask m fmt p =
begin
let bits = Array.make 63 false in
let last = ref 0 in
for i = 0 to 62 do
let u = 1 lsl i in
if u land p <> 0 then
bits.(i) <- true ;
if u == m then last := i ;
done ;
Format.pp_print_char fmt '*' ;
for i = !last - 1 downto 0 do
Format.pp_print_char fmt (if bits.(i) then '1' else '0') ;
done ;
end
let pp_bits fmt k =
begin
let bits = Array.make 63 false in
let last = ref 0 in
for i = 0 to 62 do
if (1 lsl i) land k <> 0 then
( bits.(i) <- true ;
if i > !last then last := i ) ;
done ;
for i = !last downto 0 do
Format.pp_print_char fmt (if bits.(i) then '1' else '0') ;
done ;
end
--- L. Correnson & P. Baudin & ---
module Make(K:Map_intf.TaggedEqualType) :
Map_intf.Gen_Map_hashcons with type NT.key = K.t = struct
module Gen(G:sig
type (+'a) t
type 'a data
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
val ktag : 'a data t -> int
end)
= struct
open G
type key = K.t
type 'a data = 'a G.data
type 'a t = 'a G.t
--- Smart Constructors ---
let empty = mk_Empty
let singleton = mk_Lf
let br p t0 t1 = match view t0 , view t1 with
| Empty,_ -> t1
| _,Empty -> t0
| _ -> mk_Br p t0 t1
let lf k = function None -> mk_Empty | Some x -> mk_Lf k x
let lf0 k x' t' = function
| None -> mk_Empty
| Some x -> if x == x' then t' else mk_Lf k x
let br0 p t0' t1' t' t0 = match view t0 with
| Empty -> t1'
| _ -> if t0' == t0 then t' else mk_Br p t0 t1'
let br1 p t0' t1' t' t1 = match view t1 with
| Empty -> t0'
| _ -> if t1' == t1 then t' else mk_Br p t0' t1
let join p t0 q t1 =
let m = branching_bit p q in
let r = mask p m in
if zero_bit p r
then mk_Br r t0 t1
else mk_Br r t1 t0
let m = branching_bit p q in
let r = mask p m in
zero_bit p r
let glue t0 t1 =
match view t0 , view t1 with
| Empty,_ -> t1
| _,Empty -> t0
| _,_ -> join (ktag t0) t0 (ktag t1) t1
let glue' ~old ~cur ~other ~all =
if old == cur then all else glue cur other
let glue0 t0 t0' t1' t' =
if t0 == t0' then t' else glue t0 t1'
let glue1 t1 t0' t1' t' =
if t1 == t1' then t' else glue t0' t1
let glue01 t0 t1 t0' t1' t' =
if t0 == t0' && t1 == t1' then t' else glue t0 t1
let glue2 t0 t1 t0' t1' t' s0' s1' s' =
if t0 == s0' && t1 == s1' then s' else
if t0 == t0' && t1 == t1' then t' else glue t0 t1
let is_empty x = match view x with
| Empty -> true
| Lf _ | Br _ -> false
let size t =
let rec walk n t = match view t with
| Empty -> n
| Lf _ -> succ n
| Br(_,a,b) -> walk (walk n a) b
in walk 0 t
let cardinal = size
let rec mem k t = match view t with
| Empty -> false
| Lf(i,_) -> K.equal i k
| Br(p,t0,t1) ->
match_prefix (K.tag k) p &&
mem k (if zero_bit (K.tag k) p then t0 else t1)
let rec findq k t = match view t with
| Empty -> raise Not_found
| Lf(i,x) -> if K.equal k i then (x,t) else raise Not_found
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
findq k (if zero_bit (K.tag k) p then t0 else t1)
else
raise Not_found
let rec find_exn exn k t = match view t with
| Empty -> raise exn
| Lf(i,x) -> if K.equal k i then x else raise exn
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_exn exn k (if zero_bit (K.tag k) p then t0 else t1)
else
raise exn
let find k m = find_exn Not_found k m
let rec find_opt k t = match view t with
| Empty -> None
| Lf(i,x) -> if K.equal k i then Some x else None
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_opt k (if zero_bit (K.tag k) p then t0 else t1)
else
None
let rec find_def def k t = match view t with
| Empty -> def
| Lf(i,x) -> if K.equal k i then x else def
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
find_def def k (if zero_bit (K.tag k) p then t0 else t1)
else
def
let rec find_remove k t = match view t with
| Empty -> mk_Empty, None
| Lf(i,y) ->
if K.equal i k then
mk_Empty, Some y
else
t, None
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then let t0', r = find_remove k t0 in
else let t1', r = find_remove k t1 in
else
t, None
let rec max_binding_opt t = match view t with
| Empty -> None
| Lf(k,x) -> Some(k,x)
| Br(_,_,t1) -> max_binding_opt t1
let rec find_smaller_opt' cand k t = match view t with
| Empty -> assert false
| Lf(i,y) ->
let c = Pervasives.compare (K.tag i) (K.tag k) in
if c <= 0 then Some(i,y)
c > 0
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then find_smaller_opt' cand k t0
else find_smaller_opt' t0 k t1
else
if side (K.tag k) p
let find_smaller_opt k t = match view t with
| Empty -> None
| Br(p,t0,t1) when p = max_int ->
if zero_bit (K.tag k) p
then find_smaller_opt' t1 k t0
else find_smaller_opt' mk_Empty k t1
| _ ->
find_smaller_opt' mk_Empty k t
let rec compare cmp s t =
if (Obj.magic s) == t then 0 else
match view s , view t with
| Empty , Empty -> 0
| Empty , _ -> (-1)
| _ , Empty -> 1
| Lf(i,x) , Lf(j,y) ->
let ck = Pervasives.compare (K.tag i) (K.tag j) in
if ck = 0 then cmp x y else ck
| Lf _ , _ -> (-1)
| _ , Lf _ -> 1
| Br(p,s0,s1) , Br(q,t0,t1) ->
let cp = Pervasives.compare p q in
if cp <> 0 then cp else
let c0 = compare cmp s0 t0 in
if c0 <> 0 then c0 else
compare cmp s1 t1
let rec equal eq s t =
if (Obj.magic s) == t then true else
match view s , view t with
| Empty , Empty -> true
| Lf(i,x) , Lf(j,y) -> K.equal i j && eq x y
| Br(p,s0,s1) , Br(q,t0,t1) ->
p==q && equal eq s0 t0 && equal eq s1 t1
| _ -> false
let rec change phi k x t = match view t with
| Empty -> (match phi k x None with
| None -> t
| Some w -> mk_Lf k w)
| Lf(i,y) ->
if K.equal i k then
lf0 k y t (phi k x (Some y))
else
(match phi k x None with
| None -> t
| Some w -> let s = mk_Lf k w in
join (K.tag k) s (K.tag i) t)
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
else
(match phi k x None with
| None -> t
| Some w -> let s = mk_Lf k w in
join (K.tag k) s p t)
let insert f k x = change (fun _k x -> function
| None -> Some x
| Some old -> Some (f k x old)) k x
let add k x m = change (fun _k x _old -> Some x) k x m
let remove k m = change (fun _k () _old -> None) k () m
let add_new e x v m = change (fun _k (e,v) -> function
| Some _ -> raise e
| None -> Some v) x (e,v) m
let rec add_change empty add k b t = match view t with
| Empty -> mk_Lf k (empty b)
| Lf(i,y) ->
if K.equal i k then
let y' = (add b y) in
if y == y' then t else mk_Lf i y'
else
let s = mk_Lf k (empty b) in
join (K.tag k) s (K.tag i) t
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
else
let s = mk_Lf k (empty b) in
join (K.tag k) s p t
let mapi phi t =
let rec mapi phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> mk_Lf k (phi k x)
| Br(p,t0,t1) ->
let t0 = mapi phi t0 in
let t1 = mapi phi t1 in
mk_Br p t0 t1
| Empty -> mk_Empty
| Lf(k,x) -> mk_Lf k (phi k x)
| Br(p,t0,t1) when p = max_int -> let t1 = mapi phi t1 in
let t0 = mapi phi t0 in mk_Br p t0 t1
| Br(p,t0,t1) -> let t0 = mapi phi t0 in
let t1 = mapi phi t1 in mk_Br p t0 t1
let map phi = mapi (fun _ x -> phi x)
let mapf phi t =
let rec mapf phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(_,t0,t1) -> glue (mapf phi t0) (mapf phi t1)
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(p,t0,t1) when p = max_int -> let t1 = mapf phi t1 in
let t0 = mapf phi t0 in glue t0 t1
| Br(_,t0,t1) -> let t0 = mapf phi t0 in
let t1 = mapf phi t1 in glue t0 t1
let mapq phi t =
let rec mapq phi t = match view t with
| Empty -> t
| Lf(k,x) -> lf0 k x t (phi k x)
| Br(_,t0,t1) ->
let t0' = mapq phi t0 in
let t1' = mapq phi t1 in
glue01 t0' t1' t0 t1 t
| Empty -> t
| Lf(k,x) -> lf0 k x t (phi k x)
| Br(p,t0,t1) when p = max_int ->
let t1' = mapq phi t1 in
let t0' = mapq phi t0 in
glue01 t0' t1' t0 t1 t
| Br(_,t0,t1) ->
let t0' = mapq phi t0 in
let t1' = mapq phi t1 in
glue01 t0' t1' t0 t1 t
let mapq' :
type a b. (key -> a data -> b data option) -> a data t -> b data t=
fun phi t ->
let rec aux phi t = match view t with
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(_,t0,t1) ->
let t0' = aux phi t0 in
let t1' = aux phi t1 in
glue t0' t1'
| Empty -> mk_Empty
| Lf(k,x) -> lf k (phi k x)
| Br(p,t0,t1) when p = max_int ->
let t1' = aux phi t1 in
let t0' = aux phi t0 in
glue t0' t1'
| Br(_,t0,t1) ->
let t0' = aux phi t0 in
let t1' = aux phi t1 in
glue t0' t1'
let filter f m = mapq' (fun k v -> if f k v then Some v else None) m
let mapi_filter = mapq'
let map_filter f m = mapq' (fun _ v -> f v) m
let mapi_filter_fold:
type a b acc. (key -> a data -> acc -> acc * b data option) ->
a data t -> acc -> acc * b data t
= fun phi t acc ->
let rec aux phi t acc = match view t with
| Empty -> acc, mk_Empty
| Lf(k,x) -> let acc,x = (phi k x acc) in acc, lf k x
| Br(_,t0,t1) ->
let acc, t0' = aux phi t0 acc in
let acc, t1' = aux phi t1 acc in
acc, glue t0' t1'
| Empty -> acc, mk_Empty
| Lf(k,x) -> let acc,x = (phi k x acc) in acc, lf k x
| Br(p,t0,t1) when p = max_int ->
let acc, t1' = aux phi t1 acc in
let acc, t0' = aux phi t0 acc in
acc, glue t0' t1'
| Br(_,t0,t1) ->
let acc, t0' = aux phi t0 acc in
let acc, t1' = aux phi t1 acc in
acc, glue t0' t1'
let mapi_fold phi t acc =
mapi_filter_fold (fun k v acc ->
let acc, v' = phi k v acc in
acc, Some v') t acc
let rec partition p t = match view t with
| Empty -> (t,t)
| Lf(k,x) -> if p k x then t,mk_Empty else mk_Empty,t
| Br(_,t0,t1) ->
let (t0',u0') = partition p t0 in
let (t1',u1') = partition p t1 in
else (glue t0' t1'),(glue u0' u1')
let split k t =
let rec aux k t = match view t with
| Lf(k',x) -> let c = Pervasives.compare (K.tag k) (K.tag k') in
if c = 0 then (mk_Empty,Some x,mk_Empty)
else if c < 0 then (mk_Empty, None, t)
c > 0
| Br(p,t0,t1) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then
let (t0',r,t1') = aux k t0 in
(t0',r,glue' ~old:t0 ~cur:t1' ~other:t1 ~all:t )
else
let (t0',r,t1') = aux k t1 in
(glue' ~old:t1 ~cur:t0' ~other:t0 ~all:t,r,t1')
else
if side (K.tag k) p
in match view t with
| Empty -> mk_Empty, None, mk_Empty
if zero_bit (K.tag k) p
then
let (t0',r,t1') = aux k t0 in
(glue' ~old:t0 ~cur:t0' ~other:t1 ~all:t,r,t1' )
else
let (t0',r,t1') = aux k t1 in
(t0',r,glue' ~old:t1 ~cur:t1' ~other:t0 ~all:t)
| _ -> aux k t
let rec partition_split p t = match view t with
| Empty -> (t,t)
| Lf(k,x) -> let u,v = p k x in (lf0 k x t u), (lf0 k x t v)
| Br(_,t0,t1) ->
let t0',u0' = partition_split p t0 in
let t1',u1' = partition_split p t1 in
else (glue t0' t1'),(glue u0' u1')
let iteri phi t =
let rec aux t = match view t with
| Empty -> ()
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 ; aux t1
| Empty -> ()
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 ; aux t0
| Br(_,t0,t1) -> aux t0 ; aux t1
let iter = iteri
let rec aux t e = match view t with
| Empty -> e
| Lf(i,x) -> phi i x e
| Br(_,t0,t1) -> aux t1 (aux t0 e)
| Empty -> e
| Lf(i,x) -> phi i x e
| Br(p,t0,t1) when p = max_int -> aux t0 (aux t1 e)
| Br(_,t0,t1) -> aux t1 (aux t0 e)
let fold = foldi
let rec aux t e = match view t with
| Empty -> e
| Lf(k,x) -> phi e k x
| Br(_,t0,t1) -> aux t1 (aux t0 e)
| Empty -> e
| Lf(k,x) -> phi e k x
| Br(p,t0,t1) when p = max_int -> aux t0 (aux t1 e)
| Br(_,t0,t1) -> aux t1 (aux t0 e)
let rec aux t e = match view t with
| Empty -> e
| Lf(i,x) -> phi e i x
| Br(_,t0,t1) -> aux t0 (aux t1 e)
| Empty -> e
| Lf(i,x) -> phi e i x
| Br(p,t0,t1) when p = max_int -> aux t1 (aux t0 e)
| Br(_,t0,t1) -> aux t0 (aux t1 e)
let fold_decr = foldd
let mapl f m = foldd (fun a k v -> (f k v)::a) [] m
let bindings m = mapl (fun k v -> (k,v)) m
let values m = mapl (fun _ v -> v) m
let keys m = mapl (fun k _ -> k) m
let rec aux t = match view t with
| Empty -> true
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 && aux t1
| Empty -> true
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 && aux t0
| Br(_,t0,t1) -> aux t0 && aux t1
let rec aux t = match view t with
| Empty -> false
| Lf(k,x) -> phi k x
| Br(_,t0,t1) -> aux t0 || aux t1
| Empty -> false
| Lf(k,x) -> phi k x
| Br(p,t0,t1) when p = max_int -> aux t1 || aux t0
| Br(_,t0,t1) -> aux t0 || aux t1
let rec aux t = match view t with
| Lf(k,x) -> (k,x)
| Br(_,t0,_) -> aux t0
| Empty -> raise Not_found
| Lf(k,x) -> (k,x)
| Br(p,_,t1) when p = max_int -> aux t1
| Br(_,t0,_) -> aux t0
let rec aux t = match view t with
| Lf(k,x) -> (k,x)
| Br(_,_,t1) -> aux t1
| Empty -> raise Not_found
| Lf(k,x) -> (k,x)
| Br(p,t0,_) when p = max_int -> aux t0
| Br(_,_,t1) -> aux t1
let choose = min_binding
let occur i t = try Some (find i t) with Not_found -> None
let rec interi lf_phi s t =
match view s , view t with
| Empty , _ -> mk_Empty
| _ , Empty -> mk_Empty
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lf_phi i x y
else mk_Empty
| Lf(i,x) , Br _ ->
(match occur i t with None -> mk_Empty | Some y -> lf_phi i x y)
| Br _ , Lf(j,y) ->
(match occur j s with None -> mk_Empty | Some x -> lf_phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
glue (interi lf_phi s0 t0) (interi lf_phi s1 t1)
else if included_prefix p q then
if zero_bit q p
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
mk_Empty
let interf phi = interi (fun i x y -> mk_Lf i (phi i x y))
let inter phi = interi (fun i x y -> lf i (phi i x y))
let lfq phi i x y s t =
match phi i x y with
| None -> mk_Empty
| Some w -> if w == x then s else if w == y then t else mk_Lf i w
let occur0 phi i x s t =
try let (y,t) = findq i t in lfq phi i x y s t
with Not_found -> mk_Empty
let occur1 phi j y s t =
try let (x,s) = findq j s in lfq phi j x y s t
with Not_found -> mk_Empty
let rec interq phi s t =
match view s , view t with
| Empty , _ -> s
| _ , Empty -> t
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lfq phi i x y s t
else mk_Empty
| Lf(i,x) , Br _ -> occur0 phi i x s t
| Br _ , Lf(j,y) -> occur1 phi j y s t
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
glue2 (interq phi s0 t0) (interq phi s1 t1) s0 s1 s t0 t1 t
else if included_prefix p q then
if zero_bit q p
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
mk_Empty
let br2u p s0' s1' s' t0' t1' t' t0 t1=
if s0'==t0 && s1'== t1 then s' else
if t0'==t0 && t1'== t1 then t' else
mk_Br p t0 t1
let br0u p t0' t1' t' t0 = if t0'==t0 then t' else mk_Br p t0 t1'
let br1u p t0' t1' t' t1 = if t1'==t1 then t' else mk_Br p t0' t1
let rec unionf phi s t =
match view s , view t with
| Empty , _ -> t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then let w = phi i x y in
if w == x then s else if w == y then t else mk_Lf i w
else join (K.tag i) s (K.tag j) t
| Lf(i,x) , Br _ -> insert phi i x t
| Br _ , Lf(j,y) -> insert (fun j y x -> phi j x y) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
br2u p s0 s1 s t0 t1 t (unionf phi s0 t0) (unionf phi s1 t1)
else if included_prefix p q then
if zero_bit q p
then
br0u p s0 s1 s (unionf phi s0 t)
else
t has bit m = 1 = > t is inside s1
br1u p s0 s1 s (unionf phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then
br0u q t0 t1 t (unionf phi s t0)
else
t has bit n = 1 = > s is inside t1
br1u q t0 t1 t (unionf phi s t1)
else
join p s q t
let rec union phi s t =
match view s , view t with
| Empty , _ -> t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then match phi i x y with
| Some w when w == x -> s
| Some w when w == y -> t
| Some w -> mk_Lf i w
| None -> mk_Empty
else join (K.tag i) s (K.tag j) t
| Lf(i,x) , Br _ ->
change (fun i x -> function | None -> Some x
| Some old -> (phi i x old)) i x t
| Br _ , Lf(j,y) ->
change (fun j y -> function | None -> Some y
| Some old -> (phi j old y)) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
glue2 (union phi s0 t0) (union phi s1 t1) s0 s1 s t0 t1 t
else if included_prefix p q then
if zero_bit q p
then
br0 p s0 s1 s (union phi s0 t)
else
t has bit m = 1 = > t is inside s1
br1 p s0 s1 s (union phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then
br0 q t0 t1 t (union phi s t0)
else
t has bit n = 1 = > s is inside t1
br1 q t0 t1 t (union phi s t1)
else
join p s q t
let map1 phi s = mapf (fun i x -> phi i (Some x) None) s
let map2 phi t = mapf (fun j y -> phi j None (Some y)) t
let rec merge phi s t =
match view s , view t with
| Empty , _ -> map2 phi t
| _ , Empty -> map1 phi s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j then lf i (phi i (Some x) (Some y))
else
let a = lf i (phi i (Some x) None) in
let b = lf j (phi j None (Some y)) in
glue a b
| Lf(i,x) , Br(q,t0,t1) ->
if match_prefix (K.tag i) q then
if zero_bit (K.tag i) q
else
glue (lf i (phi i (Some x) None)) (map2 phi t)
| Br(p,s0,s1) , Lf(j,y) ->
if match_prefix (K.tag j) p then
if zero_bit (K.tag j) p
else
glue (map1 phi s) (lf j (phi j None (Some y)))
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
glue (merge phi s0 t0) (merge phi s1 t1)
else if included_prefix p q then
if zero_bit q p
glue (merge phi s0 t) (map1 phi s1)
t has bit m = 1 = > t is inside s1
glue (map1 phi s0) (merge phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
glue (merge phi s t0) (map2 phi t1)
s has bit n = 1 = > s is inside t1
glue (map2 phi t0) (merge phi s t1)
else
glue (map1 phi s) (map2 phi t)
let map2 phi t = mapf (fun j y -> phi j None y) t
let rec union_merge phi s t =
match view s , view t with
| Empty , _ -> map2 phi t
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j then lf i (phi i (Some x) y)
else
let b = lf j (phi j None y) in
glue s b
| Lf(i,_) , Br(q,t0,t1) ->
if match_prefix (K.tag i) q then
if zero_bit (K.tag i) q
else
glue s (map2 phi t)
| Br(p,s0,s1) , Lf(j,y) ->
if match_prefix (K.tag j) p then
if zero_bit (K.tag j) p
else
glue s (lf j (phi j None y))
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
glue (union_merge phi s0 t0) (union_merge phi s1 t1)
else if included_prefix p q then
if zero_bit q p
glue (union_merge phi s0 t) s1
t has bit m = 1 = > t is inside s1
glue s0 (union_merge phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
glue (union_merge phi s t0) (map2 phi t1)
s has bit n = 1 = > s is inside t1
glue (map2 phi t0) (union_merge phi s t1)
else
glue s (map2 phi t)
let rec diffq phi s t =
match view s , view t with
| Empty , _ -> s
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lfq phi i x y s t
else s
| Lf(i,x) , Br _ ->
(match occur i t with None -> s | Some y -> lfq phi i x y s t)
| Br _ , Lf(j,y) -> change (fun j y x -> match x with
| None -> None
| Some x -> phi j x y) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
let t0' = (diffq phi s0 t0) in
let t1' = (diffq phi s1 t1) in
glue01 t0' t1' s0 s1 s
else if included_prefix p q then
if zero_bit q p
let s0' = (diffq phi s0 t) in
glue0 s0' s0 s1 s
t has bit m = 1 = > t is inside s1
let s1' = (diffq phi s1 t) in
glue1 s1' s0 s1 s
else if included_prefix q p then
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
s
let rec diff :
type a b. (key -> a data -> b data -> a data option) ->
a data t -> b data t -> a data t
= fun phi s t ->
match view s , view t with
| Empty , _ -> s
| _ , Empty -> s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then lf0 i x s (phi i x y)
else s
| Lf(i,x) , Br _ ->
(match occur i t with None -> s | Some y -> lf0 i x s (phi i x y))
| Br _ , Lf(j,y) -> change (fun j y x -> match x with
| None -> None
| Some x -> phi j x y) j y s
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
let t0' = (diff phi s0 t0) in
let t1' = (diff phi s1 t1) in
glue01 t0' t1' s0 s1 s
else if included_prefix p q then
if zero_bit q p
let s0' = (diff phi s0 t) in
glue0 s0' s0 s1 s
t has bit m = 1 = > t is inside s1
let s1' = (diff phi s1 t) in
glue1 s1' s0 s1 s
else if included_prefix q p then
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
s
let rec iterk phi s t =
match view s , view t with
| Empty , _ | _ , Empty -> ()
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y
| Lf(i,x) , Br _ ->
(match occur i t with None -> () | Some y -> phi i x y)
| Br _ , Lf(j,y) ->
(match occur j s with None -> () | Some x -> phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(iterk phi s0 t0 ; iterk phi s1 t1)
else if included_prefix p q then
if zero_bit q p
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
()
let iter21 phi s = iteri (fun i x -> phi i (Some x) None) s
let iter22 phi t = iteri (fun j y -> phi j None (Some y)) t
let rec iter2 phi s t =
match view s , view t with
| Empty , _ -> iter22 phi t
| _ , Empty -> iter21 phi s
| Lf(i,x) , Lf(j,y) ->
if K.equal i j then phi i (Some x) (Some y)
else ( phi i (Some x) None ; phi j None (Some y) )
| Lf(i,x) , Br(q,t0,t1) ->
if match_prefix (K.tag i) q then
if zero_bit (K.tag i) q
else
(phi i (Some x) None ; iter22 phi t)
| Br(p,s0,s1) , Lf(j,y) ->
if match_prefix (K.tag j) p then
if zero_bit (K.tag j) p
else
(iter21 phi s ; phi j None (Some y))
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(iter2 phi s0 t0 ; iter2 phi s1 t1)
else if included_prefix p q then
if zero_bit q p
(iter2 phi s0 t ; iter21 phi s1)
t has bit m = 1 = > t is inside s1
(iter21 phi s0 ; iter2 phi s1 t)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
(iter2 phi s t0 ; iter22 phi t1)
s has bit n = 1 = > s is inside t1
(iter22 phi t0 ; iter2 phi s t1)
else
(iter21 phi s ; iter22 phi t)
let rec intersectf phi s t =
match view s , view t with
| Empty , _ -> false
| _ , Empty -> false
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else false
| Lf(i,x) , Br _ -> (match occur i t with None -> false
| Some y -> phi i x y)
| Br _ , Lf(j,y) -> (match occur j s with None -> false
| Some x -> phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(intersectf phi s0 t0) || (intersectf phi s1 t1)
else if included_prefix p q then
if zero_bit q p
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
false
let rec disjoint phi s t =
match view s , view t with
| Empty , _ -> true
| _ , Empty -> true
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else true
| Lf(i,x) , Br _ -> (match occur i t with None -> true
| Some y -> phi i x y)
| Br _ , Lf(j,y) -> (match occur j s with None -> true
| Some x -> phi j x y)
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(disjoint phi s0 t0) && (disjoint phi s1 t1)
else if included_prefix p q then
if zero_bit q p
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
true
let fold21 phi m acc = fold (fun i x acc -> phi i (Some x) None acc) m acc
let fold22 phi m acc = fold (fun j y acc -> phi j None (Some y) acc) m acc
let rec fold2_union:
type a b c.
(key -> a data option -> b data option -> c -> c) ->
a data t -> b data t -> c -> c
= fun phi s t acc ->
match view s , view t with
| Empty , _ -> fold22 phi t acc
| _ , Empty -> fold21 phi s acc
| Lf(i,x) , Lf(j,y) ->
let c = Pervasives.compare (K.tag i) (K.tag j) in
if c = 0
then phi i (Some x) (Some y) acc
else if c < 0 then phi j None (Some y) (phi i (Some x) None acc)
c > 0
| Lf(k,x) , Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then fold22 phi t2 (fold2_union phi s t1 acc)
else fold2_union phi s t2 (fold22 phi t1 acc)
else
if side (K.tag k) p
| Br(p,s1,s2) , Lf(k,y) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then fold21 phi s2 (fold2_union phi s1 t acc)
else fold2_union phi s2 t (fold21 phi s1 acc)
else
if side (K.tag k) p
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
fold2_union phi s1 t1 (fold2_union phi s0 t0 acc)
else if included_prefix p q then
if zero_bit q p
then
fold21 phi s1 (fold2_union phi s0 t acc)
else
t has bit m = 1 = > t is inside s1
fold2_union phi s1 t (fold21 phi s0 acc)
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then
fold22 phi t1 (fold2_union phi s t0 acc)
else
t has bit n = 1 = > s is inside t1
fold2_union phi s t1 (fold22 phi t0 acc)
else
if side p q
let rec fold2_inter phi s t acc =
match view s , view t with
| Empty , _ -> acc
| _ , Empty -> acc
| Lf(i,x) , Lf(j,y) ->
if K.equal i j
then phi i x y acc
else acc
| Lf(k,x) , Br _ ->
begin match find_opt k t with
| Some y -> phi k x y acc
| None -> acc
end
| Br _ , Lf(k,y) ->
begin match find_opt k s with
| Some x -> phi k x y acc
| None -> acc
end
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
fold2_inter phi s1 t1 (fold2_inter phi s0 t0 acc)
else if included_prefix p q then
if zero_bit q p
then
fold2_inter phi s0 t acc
else
t has bit m = 1 = > t is inside s1
fold2_inter phi s1 t acc
else if included_prefix q p then
p contains q. Merge s with a subtree of t
if zero_bit p q
then
fold2_inter phi s t0 acc
else
t has bit n = 1 = > s is inside t1
fold2_inter phi s t1 acc
else
acc
let rec subsetf phi s t =
match view s , view t with
| Empty , _ -> true
| _ , Empty -> false
| Lf(i,x) , Lf(j,y) -> if K.equal i j then phi i x y else false
| Lf(i,x) , Br _ ->
(match occur i t with None -> false | Some y -> phi i x y)
| Br _ , Lf _ -> false
| Br(p,s0,s1) , Br(q,t0,t1) ->
if p == q then
(subsetf phi s0 t0 && subsetf phi s1 t1)
else if included_prefix p q then
false
else if included_prefix q p then
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
false
let subset = subsetf
let subsetk s t = subsetf (fun _i _x _y -> true) s t
let submap = subsetf
let rec _pp_tree tab fmt t =
match view t with
| Empty -> ()
| Lf(k,_) ->
let k = K.tag k in
Format.fprintf fmt "%sL%a=%d" tab pp_bits k k
| Br(p,l,r) ->
let next = tab ^ " " in
_pp_tree next fmt l ;
Format.fprintf fmt "%s@@%a" tab (pp_mask (decode_mask p)) p ;
_pp_tree next fmt r
let is_num_elt n m =
try
fold (fun _ _ n -> if n < 0 then raise Exit else n-1) m n = 0
with Exit -> false
let of_list l =
List.fold_left (fun acc (k,d) -> add k d acc) empty l
let translate f m =
fold (fun k v acc -> add (f k) v acc) m empty
let set_union m1 m2 = unionf (fun _ x _ -> x) m1 m2
let set_inter m1 m2 = interf (fun _ x _ -> x) m1 m2
let set_diff m1 m2 = diff (fun _ _ _ -> None) m1 m2
let set_submap m1 m2 = submap (fun _ _ _ -> true) m1 m2
let set_disjoint m1 m2 = disjoint (fun _ _ _ -> false) m1 m2
let set_compare m1 m2 = compare (fun _ _ -> 0) m1 m2
let set_equal m1 m2 = equal (fun _ _ -> true) m1 m2
let choose_rnd f m =
let rec aux f m ret =
match view m with
| Empty -> ()
| Lf(k,v) -> if f () then (ret := (k,v); raise Exit)
| Br(_,t1,t2) ->
aux f t1 ret; aux f t2 ret
in
let ret = ref (Obj.magic 0) in
try
| Empty -> raise Not_found
| Br(p,_,t1) when p = max_int -> aux f t1 ret
| _ -> aux f m ret
end;
choose m
with Exit -> !ret
type 'a enumeration =
| EEmpty
| ELf of K.t * 'a * 'a enum2
and 'a enum2 =
| End
| EBr of 'a t * 'a enum2
let rec cons_enum m e =
match view m with
| Lf(i,x) -> ELf(i,x,e)
| Br(_,t1,t2) -> cons_enum t1 (EBr(t2,e))
match view m with
| Empty -> EEmpty
| Lf(i,x) -> ELf(i,x,End)
| Br(p,t1,t2) when p = max_int -> cons_enum t2 (EBr(t1, End))
| Br(_,t1,t2) -> cons_enum t1 (EBr(t2, End))
let val_enum = function
| EEmpty -> None
| ELf(i,x,_) -> Some (i,x)
let next_enum_br = function
| End -> EEmpty
| EBr(t2,e) -> cons_enum t2 e
let next_enum = function
| EEmpty -> EEmpty
| ELf(_,_,e) -> next_enum_br e
let rec cons_ge_enum k m e =
match view m with
| Lf(i,x) ->
if side (K.tag i) (K.tag k)
| Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then cons_ge_enum k t1 (EBr(t2,e))
else cons_ge_enum k t2 e
else
if side (K.tag k) p
let start_ge_enum k m =
match view m with
| Empty -> EEmpty
| Br(p,t1,t2) when p = max_int ->
if zero_bit (K.tag k) p
then cons_ge_enum k t1 End
else cons_ge_enum k t2 (EBr(t1,End))
| _ -> cons_ge_enum k m End
let rec next_ge_enum_br k = function
| End -> EEmpty
| EBr(t,e) -> match view t with
| Lf(i,d) when (K.tag k) <= (K.tag i) -> ELf(i,d,e)
| Lf(_,_) -> next_ge_enum_br k e
| Br(p,t1,t2) ->
if match_prefix (K.tag k) p then
if zero_bit (K.tag k) p
then cons_ge_enum k t1 (EBr(t2,e))
else cons_ge_enum k t2 e
else
if side (K.tag k) p
let next_ge_enum k = function
| EEmpty -> EEmpty
| ELf(i,_,_) as e when (K.tag k) <= (K.tag i)-> e
| ELf(_,_,e) -> next_ge_enum_br k e
let change f k m = change (fun _ () v -> f v) k () m
let add_opt x o m =
match o with
| None -> remove x m
| Some y -> add x y m
let check_invariant m =
match view m with
| Empty -> true
| _ ->
let rec aux m =
match view m with
| Empty -> false
| Lf _ -> true
| Br (_,t1,t2) -> aux t1 && aux t2 in
aux m
let pp pp fmt m =
Pp.iter2 iter Pp.arrow Pp.colon
K.pp pp fmt m
end
module Def = struct
type 'a t =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
end
module NT = struct
module M : sig
type 'a t = 'a Def.t
type 'a data = 'a
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val ktag : 'a data t -> int
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
end = struct
type 'a t = 'a Def.t
type 'a data = 'a
let ktag = function
| Def.Lf(i,_) -> K.tag i
| Def.Br(i,_,_) -> i
let mk_Empty = Def.Empty
let mk_Lf k d = Def.Lf(k,d)
let mk_Br i t1 t2 =
assert ( t1 ! = Def . Empty & & t2 ! = Def . Empty ) ;
Def.Br(i,t1,t2)
type 'a view = 'a Def.t =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
let view x = x
end
include Gen(M)
end
module Make(Data: Map_intf.HashType) :
Map_intf.Map_hashcons with type 'a data = Data.t
and type 'a poly := 'a NT.t
and type key = K.t = struct
module Tag: sig
type t
type gen
val mk_gen: unit -> gen
val to_int: t -> int
val dtag : t
val next_tag: gen -> t
val incr_tag: gen -> unit
* all of them are different from dtag
end = struct
type t = int
type gen = int ref
let to_int x = x
let mk_gen () = ref (min_int + 1)
let next_tag gen = !gen
let incr_tag gen = incr gen; assert (!gen != dtag)
end
module M : sig
type (+'a) t
type 'a data = Data.t
val nt: 'a data t -> 'a data NT.t
val rebuild: 'a data NT.t -> 'a data t
type 'a view = private
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
val view: 'a data t -> 'a data view
val tag : 'a data t -> int
val ktag : 'a data t -> int
val mk_Empty: 'a data t
val mk_Lf: K.t -> 'a data -> 'a data t
val mk_Br: int -> 'a data t -> 'a data t -> 'a data t
end = struct
module Check = struct
| Empty
| Lf of K.t * 'a
| Br of int * 'a def * 'a def
end
type 'a t =
| Empty
| Lf of K.t * 'a * Tag.t
| Br of int * 'a t * 'a t * Tag.t
type 'a data = Data.t
let nt x = (Obj.magic (x : 'a t) : 'a Check.def)
let tag = function
| Empty -> Tag.to_int Tag.dtag
| Lf(_,_,tag) | Br(_,_,_,tag) -> Tag.to_int tag
let ktag = function
* absurd : be used on Empty
| Lf(k,_,_) -> K.tag k
| Br(i,_,_,_) -> i
module WH = Weak.Make(struct
type 'a t' = 'a t
type t = Data.t t'
let equal x y =
match x, y with
| Empty, Empty -> true
| Lf(i1,d1,_), Lf(i2,d2,_) ->
K.equal i1 i2 && Data.equal d1 d2
| Br(_,l1,r1,_), Br(_,l2,r2,_) -> l1 == l2 && r1 == r2
| _ -> false
let hash = function
| Empty -> 0
| Lf(i1,d1,_) ->
65599 * ((K.tag i1) + (Data.hash d1 * 65599 + 31))
| Br(_,l,r,_) ->
65599 * ((tag l) + ((tag r) * 65599 + 17))
end)
let gentag = Tag.mk_gen ()
let htable = WH.create 5003
let hashcons d =
let o = WH.merge htable d in
if o == d then Tag.incr_tag gentag;
o
let mk_Empty = Empty
let mk_Lf k x = hashcons (Lf(k,x,Tag.next_tag gentag))
let mk_Br k t0 t1 =
assert ( t0 ! = Empty & & t1 ! = Empty ) ;
hashcons (Br(k,t0,t1,Tag.next_tag gentag))
let rec rebuild t = match t with
| Def.Empty -> mk_Empty
| Def.Lf(i,d) -> mk_Lf i d
| Def.Br(i,l,r) -> mk_Br i (rebuild l) (rebuild r)
type 'a view =
| Empty
| Lf of K.t * 'a
| Br of int * 'a t * 'a t
let view_ : 'a t -> 'a view = function
| Empty -> Empty
| Lf(k,v,_) -> Lf(k,v)
| Br(i,t1,t2,_) -> Br(i,t1,t2)
let view x = (Obj.magic (x : 'a t): 'a view)
end
include Gen(M)
let mk_Empty = M.mk_Empty
let mk_Lf = M.mk_Lf
let nt = M.nt
let rebuild = M.rebuild
let compare_t s t = Pervasives.compare (M.tag s) (M.tag t)
let equal_t (s:'a data t) t = s == t
let rec interi_nt lf_phi s t =
match M.view s , t with
| M.Empty , _ -> mk_Empty
| _ , Def.Empty -> mk_Empty
| M.Lf(i,x) , Def.Lf(j,y) ->
if K.equal i j
then lf_phi i x y
else mk_Empty
| M.Lf(i,x) , Def.Br _ ->
(match NT.occur i t with None -> mk_Empty | Some y -> lf_phi i x y)
| M.Br _ , Def.Lf(j,y) ->
(match occur j s with None -> mk_Empty | Some x -> lf_phi j x y)
| M.Br(p,s0,s1) , Def.Br(q,t0,t1) ->
if p == q then
glue (interi_nt lf_phi s0 t0) (interi_nt lf_phi s1 t1)
else if included_prefix p q then
if zero_bit q p
t has bit m = 1 = > t is inside s1
else if included_prefix q p then
p contains q. Intersect s with a subtree of t
if zero_bit p q
t has bit n = 1 = > s is inside t1
else
mk_Empty
let inter_nt phi = interi_nt (fun i x y -> mk_Lf i (phi i x y))
let interf_nt phi = interi_nt (fun i x y -> lf i (phi i x y))
let set_inter_nt m1 m2 = interi_nt (fun i x _ -> mk_Lf i x) m1 m2
end
end
|
d1c9efe4b1629e7aa8eb9ba277afcdc3978eecc57e925574696af3af8f2d7df8 | michiakig/LispInSmallPieces | pp.scm | File : " pp.scm " ( c ) 1991 ,
;;; [QNC] unified case to lower-case.
;;; Define the string to be emitted between lines.
(define *inter-line-string* (make-string 1 #\newline))
(set! *inter-line-string* *inter-line-string*)
; 'generic-write' is a procedure that transforms a Scheme data value (or
; Scheme program expression) into its textual representation. The interface
; to the procedure is sufficiently general to easily implement other useful
; formatting procedures such as pretty printing, output to a string and
; truncated output.
;
; Parameters:
;
; OBJ Scheme data value to transform.
; DISPLAY? Boolean, controls whether characters and strings are quoted.
; WIDTH Extended boolean, selects format:
; #f = single line format
; integer > 0 = pretty-print (value = max nb of chars per line)
OUTPUT Procedure of 1 argument of string type , called repeatedly
; with successive substrings of the textual representation.
; This procedure can return #f to stop the transformation.
;
; The value returned by 'generic-write' is undefined.
;
; Examples:
;
( write obj ) = ( generic - write obj # f # f display - string )
; (display obj) = (generic-write obj #t #f display-string)
;
; where display-string = (lambda (s) (for-each write-char (string->list s)) #t)
(define (generic-write obj display? width output)
(define (read-macro? l)
(define (length1? l) (and (pair? l) (null? (cdr l))))
(let ((head (car l)) (tail (cdr l)))
(case head
((quote quasiquote unquote unquote-splicing) (length1? tail))
(else #f))))
(define (read-macro-body l)
(cadr l))
(define (read-macro-prefix l)
(let ((head (car l)) (tail (cdr l)))
(case head
((quote) "'")
((quasiquote) "`")
((unquote) ",")
((unquote-splicing) ",@"))))
(define (out str col)
(and col (output str) (+ col (string-length str))))
(define (wr obj col)
(define (wr-expr expr col)
(if (read-macro? expr)
(wr (read-macro-body expr) (out (read-macro-prefix expr) col))
(wr-lst expr col)))
(define (wr-lst l col)
(if (pair? l)
(let loop ((l (cdr l)) (col (wr (car l) (out "(" col))))
(and col
(cond ((pair? l) (loop (cdr l) (wr (car l) (out " " col))))
((null? l) (out ")" col))
(else (out ")" (wr l (out " . " col)))))))
(out "()" col)))
(cond ((pair? obj) (wr-expr obj col))
((null? obj) (wr-lst obj col))
((vector? obj) (wr-lst (vector->list obj) (out "#" col)))
((boolean? obj) (out (if obj "#t" "#f") col))
((number? obj) (out (number->string obj) col))
((symbol? obj) (out (symbol->string obj) col))
((procedure? obj) (out "#[procedure]" col))
((string? obj) (if display?
(out obj col)
(let loop ((i 0) (j 0) (col (out "\"" col)))
(if (and col (< j (string-length obj)))
(let ((c (string-ref obj j)))
(if (or (char=? c #\\)
(char=? c #\"))
(loop j
(+ j 1)
(out "\\"
(out (substring obj i j)
col)))
(loop i (+ j 1) col)))
(out "\""
(out (substring obj i j) col))))))
((char? obj) (if display?
(out (make-string 1 obj) col)
(out (case obj
((#\space) "space")
((#\newline) "newline")
(else (make-string 1 obj)))
(out "#\\" col))))
((input-port? obj) (out "#[input-port]" col))
((output-port? obj) (out "#[output-port]" col))
((eof-object? obj) (out "#[eof-object]" col))
(else (out "#[unknown]" col))))
(define (pp obj col)
(define (spaces n col)
(if (> n 0)
(if (> n 7)
(spaces (- n 8) (out " " col))
(out (substring " " 0 n) col))
col))
(define (indent to col)
(and col
(if (< to col)
( and ( out ( make - string 1 # \newline ) col ) ( spaces to 0 ) )
(and (out *inter-line-string* col) (spaces to 0))
(spaces (- to col) col))))
(define (pr obj col extra pp-pair)
(if (or (pair? obj) (vector? obj)) ; may have to split on multiple lines
(let ((result '())
(left (min (+ (- (- width col) extra) 1) max-expr-width)))
(generic-write obj display? #f
(lambda (str)
(set! result (cons str result))
(set! left (- left (string-length str)))
(> left 0)))
all can be printed on one line
(out (reverse-string-append result) col)
(if (pair? obj)
(pp-pair obj col extra)
(pp-list (vector->list obj) (out "#" col) extra pp-expr))))
(wr obj col)))
(define (pp-expr expr col extra)
(if (read-macro? expr)
(pr (read-macro-body expr)
(out (read-macro-prefix expr) col)
extra
pp-expr)
(let ((head (car expr)))
(if (symbol? head)
(let ((proc (style head)))
(if proc
(proc expr col extra)
(if (> (string-length (symbol->string head))
max-call-head-width)
(pp-general expr col extra #f #f #f pp-expr)
(pp-call expr col extra pp-expr))))
(pp-list expr col extra pp-expr)))))
( head
; item3)
(define (pp-call expr col extra pp-item)
(let ((col* (wr (car expr) (out "(" col))))
(and col
(pp-down (cdr expr) col* (+ col* 1) extra pp-item))))
(
; item3)
(define (pp-list l col extra pp-item)
(let ((col (out "(" col)))
(pp-down l col col extra pp-item)))
(define (pp-down l col1 col2 extra pp-item)
(let loop ((l l) (col col1))
(and col
(cond ((pair? l)
(let ((rest (cdr l)))
(let ((extra (if (null? rest) (+ extra 1) 0)))
(loop rest
(pr (car l) (indent col2 col) extra pp-item)))))
((null? l)
(out ")" col))
(else
(out ")"
(pr l
(indent col2 (out "." (indent col2 col)))
(+ extra 1)
pp-item)))))))
(define (pp-general expr col extra named? pp-1 pp-2 pp-3)
(define (tail1 rest col1 col2 col3)
(if (and pp-1 (pair? rest))
(let* ((val1 (car rest))
(rest (cdr rest))
(extra (if (null? rest) (+ extra 1) 0)))
(tail2 rest col1 (pr val1 (indent col3 col2) extra pp-1) col3))
(tail2 rest col1 col2 col3)))
(define (tail2 rest col1 col2 col3)
(if (and pp-2 (pair? rest))
(let* ((val1 (car rest))
(rest (cdr rest))
(extra (if (null? rest) (+ extra 1) 0)))
(tail3 rest col1 (pr val1 (indent col3 col2) extra pp-2)))
(tail3 rest col1 col2)))
(define (tail3 rest col1 col2)
(pp-down rest col2 col1 extra pp-3))
(let* ((head (car expr))
(rest (cdr expr))
(col* (wr head (out "(" col))))
(if (and named? (pair? rest))
(let* ((name (car rest))
(rest (cdr rest))
(col** (wr name (out " " col*))))
(tail1 rest (+ col indent-general) col** (+ col** 1)))
(tail1 rest (+ col indent-general) col* (+ col* 1)))))
(define (pp-expr-list l col extra)
(pp-list l col extra pp-expr))
(define (pp-lambda expr col extra)
(pp-general expr col extra #f pp-expr-list #f pp-expr))
(define (pp-if expr col extra)
(pp-general expr col extra #f pp-expr #f pp-expr))
(define (pp-cond expr col extra)
(pp-call expr col extra pp-expr-list))
(define (pp-case expr col extra)
(pp-general expr col extra #f pp-expr #f pp-expr-list))
(define (pp-and expr col extra)
(pp-call expr col extra pp-expr))
(define (pp-let expr col extra)
(let* ((rest (cdr expr))
(named? (and (pair? rest) (symbol? (car rest)))))
(pp-general expr col extra named? pp-expr-list #f pp-expr)))
(define (pp-begin expr col extra)
(pp-general expr col extra #f #f #f pp-expr))
(define (pp-do expr col extra)
(pp-general expr col extra #f pp-expr-list pp-expr-list pp-expr))
; define formatting style (change these to suit your style)
(define indent-general 2)
(define max-call-head-width 5)
(define max-expr-width 50)
(define (style head)
(case head
((lambda let* letrec define) pp-lambda)
((if set!) pp-if)
((cond) pp-cond)
((case) pp-case)
((and or) pp-and)
((let) pp-let)
((begin) pp-begin)
((do) pp-do)
(else #f)))
(pr obj col 0 pp-expr))
(if width
( out ( make - string 1 # \newline ) ( pp obj 0 ) )
(out "" (pp obj 0)) ;; QNC Hacked for LiSP2TeX
(wr obj 0)))
; (reverse-string-append l) = (apply string-append (reverse l))
(define (reverse-string-append l)
(define (rev-string-append l i)
(if (pair? l)
(let* ((str (car l))
(len (string-length str))
(result (rev-string-append (cdr l) (+ i len))))
(let loop ((j 0) (k (- (- (string-length result) i) len)))
(if (< j len)
(begin
(string-set! result k (string-ref str j))
(loop (+ j 1) (+ k 1)))
result)))
(make-string i)))
(rev-string-append l 0))
; (object->string obj) returns the textual representation of 'obj' as a
; string.
;
; Note: (write obj) = (display (object->string obj))
(define (object->string obj)
(let ((result '()))
(generic-write obj #f #f (lambda (str) (set! result (cons str result)) #t))
(reverse-string-append result)))
( object->limited - string obj limit ) returns a string containing the first
; 'limit' characters of the textual representation of 'obj'.
(define (object->limited-string obj limit)
(let ((result '()) (left limit))
(generic-write obj #f #f
(lambda (str)
(let ((len (string-length str)))
(if (> len left)
(begin
(set! result (cons (substring str 0 left) result))
(set! left 0)
#f)
(begin
(set! result (cons str result))
(set! left (- left len))
#t)))))
(reverse-string-append result)))
; (pretty-print obj port) pretty prints 'obj' on 'port'. The current
; output port is used if 'port' is not specified.
(define (pretty-print obj . opt)
(let ((port (if (pair? opt) (car opt) (current-output-port))))
(generic-write obj #f 79 (lambda (s) (display s port) #t))))
; (pretty-print-to-string obj) returns a string with the pretty-printed
; textual representation of 'obj'.
(define (pretty-print-to-string obj)
(let ((result '()))
(generic-write obj #f 79 (lambda (str) (set! result (cons str result)) #t))
(reverse-string-append result)))
| null | https://raw.githubusercontent.com/michiakig/LispInSmallPieces/0a2762d539a5f4c7488fffe95722790ac475c2ea/gambit/pp.scm | scheme | [QNC] unified case to lower-case.
Define the string to be emitted between lines.
'generic-write' is a procedure that transforms a Scheme data value (or
Scheme program expression) into its textual representation. The interface
to the procedure is sufficiently general to easily implement other useful
formatting procedures such as pretty printing, output to a string and
truncated output.
Parameters:
OBJ Scheme data value to transform.
DISPLAY? Boolean, controls whether characters and strings are quoted.
WIDTH Extended boolean, selects format:
#f = single line format
integer > 0 = pretty-print (value = max nb of chars per line)
with successive substrings of the textual representation.
This procedure can return #f to stop the transformation.
The value returned by 'generic-write' is undefined.
Examples:
(display obj) = (generic-write obj #t #f display-string)
where display-string = (lambda (s) (for-each write-char (string->list s)) #t)
may have to split on multiple lines
item3)
item3)
define formatting style (change these to suit your style)
QNC Hacked for LiSP2TeX
(reverse-string-append l) = (apply string-append (reverse l))
(object->string obj) returns the textual representation of 'obj' as a
string.
Note: (write obj) = (display (object->string obj))
'limit' characters of the textual representation of 'obj'.
(pretty-print obj port) pretty prints 'obj' on 'port'. The current
output port is used if 'port' is not specified.
(pretty-print-to-string obj) returns a string with the pretty-printed
textual representation of 'obj'. | File : " pp.scm " ( c ) 1991 ,
(define *inter-line-string* (make-string 1 #\newline))
(set! *inter-line-string* *inter-line-string*)
OUTPUT Procedure of 1 argument of string type , called repeatedly
( write obj ) = ( generic - write obj # f # f display - string )
(define (generic-write obj display? width output)
(define (read-macro? l)
(define (length1? l) (and (pair? l) (null? (cdr l))))
(let ((head (car l)) (tail (cdr l)))
(case head
((quote quasiquote unquote unquote-splicing) (length1? tail))
(else #f))))
(define (read-macro-body l)
(cadr l))
(define (read-macro-prefix l)
(let ((head (car l)) (tail (cdr l)))
(case head
((quote) "'")
((quasiquote) "`")
((unquote) ",")
((unquote-splicing) ",@"))))
(define (out str col)
(and col (output str) (+ col (string-length str))))
(define (wr obj col)
(define (wr-expr expr col)
(if (read-macro? expr)
(wr (read-macro-body expr) (out (read-macro-prefix expr) col))
(wr-lst expr col)))
(define (wr-lst l col)
(if (pair? l)
(let loop ((l (cdr l)) (col (wr (car l) (out "(" col))))
(and col
(cond ((pair? l) (loop (cdr l) (wr (car l) (out " " col))))
((null? l) (out ")" col))
(else (out ")" (wr l (out " . " col)))))))
(out "()" col)))
(cond ((pair? obj) (wr-expr obj col))
((null? obj) (wr-lst obj col))
((vector? obj) (wr-lst (vector->list obj) (out "#" col)))
((boolean? obj) (out (if obj "#t" "#f") col))
((number? obj) (out (number->string obj) col))
((symbol? obj) (out (symbol->string obj) col))
((procedure? obj) (out "#[procedure]" col))
((string? obj) (if display?
(out obj col)
(let loop ((i 0) (j 0) (col (out "\"" col)))
(if (and col (< j (string-length obj)))
(let ((c (string-ref obj j)))
(if (or (char=? c #\\)
(char=? c #\"))
(loop j
(+ j 1)
(out "\\"
(out (substring obj i j)
col)))
(loop i (+ j 1) col)))
(out "\""
(out (substring obj i j) col))))))
((char? obj) (if display?
(out (make-string 1 obj) col)
(out (case obj
((#\space) "space")
((#\newline) "newline")
(else (make-string 1 obj)))
(out "#\\" col))))
((input-port? obj) (out "#[input-port]" col))
((output-port? obj) (out "#[output-port]" col))
((eof-object? obj) (out "#[eof-object]" col))
(else (out "#[unknown]" col))))
(define (pp obj col)
(define (spaces n col)
(if (> n 0)
(if (> n 7)
(spaces (- n 8) (out " " col))
(out (substring " " 0 n) col))
col))
(define (indent to col)
(and col
(if (< to col)
( and ( out ( make - string 1 # \newline ) col ) ( spaces to 0 ) )
(and (out *inter-line-string* col) (spaces to 0))
(spaces (- to col) col))))
(define (pr obj col extra pp-pair)
(let ((result '())
(left (min (+ (- (- width col) extra) 1) max-expr-width)))
(generic-write obj display? #f
(lambda (str)
(set! result (cons str result))
(set! left (- left (string-length str)))
(> left 0)))
all can be printed on one line
(out (reverse-string-append result) col)
(if (pair? obj)
(pp-pair obj col extra)
(pp-list (vector->list obj) (out "#" col) extra pp-expr))))
(wr obj col)))
(define (pp-expr expr col extra)
(if (read-macro? expr)
(pr (read-macro-body expr)
(out (read-macro-prefix expr) col)
extra
pp-expr)
(let ((head (car expr)))
(if (symbol? head)
(let ((proc (style head)))
(if proc
(proc expr col extra)
(if (> (string-length (symbol->string head))
max-call-head-width)
(pp-general expr col extra #f #f #f pp-expr)
(pp-call expr col extra pp-expr))))
(pp-list expr col extra pp-expr)))))
( head
(define (pp-call expr col extra pp-item)
(let ((col* (wr (car expr) (out "(" col))))
(and col
(pp-down (cdr expr) col* (+ col* 1) extra pp-item))))
(
(define (pp-list l col extra pp-item)
(let ((col (out "(" col)))
(pp-down l col col extra pp-item)))
(define (pp-down l col1 col2 extra pp-item)
(let loop ((l l) (col col1))
(and col
(cond ((pair? l)
(let ((rest (cdr l)))
(let ((extra (if (null? rest) (+ extra 1) 0)))
(loop rest
(pr (car l) (indent col2 col) extra pp-item)))))
((null? l)
(out ")" col))
(else
(out ")"
(pr l
(indent col2 (out "." (indent col2 col)))
(+ extra 1)
pp-item)))))))
(define (pp-general expr col extra named? pp-1 pp-2 pp-3)
(define (tail1 rest col1 col2 col3)
(if (and pp-1 (pair? rest))
(let* ((val1 (car rest))
(rest (cdr rest))
(extra (if (null? rest) (+ extra 1) 0)))
(tail2 rest col1 (pr val1 (indent col3 col2) extra pp-1) col3))
(tail2 rest col1 col2 col3)))
(define (tail2 rest col1 col2 col3)
(if (and pp-2 (pair? rest))
(let* ((val1 (car rest))
(rest (cdr rest))
(extra (if (null? rest) (+ extra 1) 0)))
(tail3 rest col1 (pr val1 (indent col3 col2) extra pp-2)))
(tail3 rest col1 col2)))
(define (tail3 rest col1 col2)
(pp-down rest col2 col1 extra pp-3))
(let* ((head (car expr))
(rest (cdr expr))
(col* (wr head (out "(" col))))
(if (and named? (pair? rest))
(let* ((name (car rest))
(rest (cdr rest))
(col** (wr name (out " " col*))))
(tail1 rest (+ col indent-general) col** (+ col** 1)))
(tail1 rest (+ col indent-general) col* (+ col* 1)))))
(define (pp-expr-list l col extra)
(pp-list l col extra pp-expr))
(define (pp-lambda expr col extra)
(pp-general expr col extra #f pp-expr-list #f pp-expr))
(define (pp-if expr col extra)
(pp-general expr col extra #f pp-expr #f pp-expr))
(define (pp-cond expr col extra)
(pp-call expr col extra pp-expr-list))
(define (pp-case expr col extra)
(pp-general expr col extra #f pp-expr #f pp-expr-list))
(define (pp-and expr col extra)
(pp-call expr col extra pp-expr))
(define (pp-let expr col extra)
(let* ((rest (cdr expr))
(named? (and (pair? rest) (symbol? (car rest)))))
(pp-general expr col extra named? pp-expr-list #f pp-expr)))
(define (pp-begin expr col extra)
(pp-general expr col extra #f #f #f pp-expr))
(define (pp-do expr col extra)
(pp-general expr col extra #f pp-expr-list pp-expr-list pp-expr))
(define indent-general 2)
(define max-call-head-width 5)
(define max-expr-width 50)
(define (style head)
(case head
((lambda let* letrec define) pp-lambda)
((if set!) pp-if)
((cond) pp-cond)
((case) pp-case)
((and or) pp-and)
((let) pp-let)
((begin) pp-begin)
((do) pp-do)
(else #f)))
(pr obj col 0 pp-expr))
(if width
( out ( make - string 1 # \newline ) ( pp obj 0 ) )
(wr obj 0)))
(define (reverse-string-append l)
(define (rev-string-append l i)
(if (pair? l)
(let* ((str (car l))
(len (string-length str))
(result (rev-string-append (cdr l) (+ i len))))
(let loop ((j 0) (k (- (- (string-length result) i) len)))
(if (< j len)
(begin
(string-set! result k (string-ref str j))
(loop (+ j 1) (+ k 1)))
result)))
(make-string i)))
(rev-string-append l 0))
(define (object->string obj)
(let ((result '()))
(generic-write obj #f #f (lambda (str) (set! result (cons str result)) #t))
(reverse-string-append result)))
( object->limited - string obj limit ) returns a string containing the first
(define (object->limited-string obj limit)
(let ((result '()) (left limit))
(generic-write obj #f #f
(lambda (str)
(let ((len (string-length str)))
(if (> len left)
(begin
(set! result (cons (substring str 0 left) result))
(set! left 0)
#f)
(begin
(set! result (cons str result))
(set! left (- left len))
#t)))))
(reverse-string-append result)))
(define (pretty-print obj . opt)
(let ((port (if (pair? opt) (car opt) (current-output-port))))
(generic-write obj #f 79 (lambda (s) (display s port) #t))))
(define (pretty-print-to-string obj)
(let ((result '()))
(generic-write obj #f 79 (lambda (str) (set! result (cons str result)) #t))
(reverse-string-append result)))
|
49d75426606b0e40e3305d9d186b68b0f4e1312c5210766100e9476046eb3163 | billstclair/trubanc-lisp | packages.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
$ Header : /usr / local / cvsrep / flexi - streams / test / packages.lisp , v 1.8 2008/08/01 10:12:43 edi Exp $
Copyright ( c ) 2006 - 2008 , Dr. . 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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage :flexi-streams-test
(:use :cl :flexi-streams)
(:import-from :flexi-streams
:with-unique-names
:with-rebinding
:char*
:normalize-external-format)
(:export :run-all-tests))
| null | https://raw.githubusercontent.com/billstclair/trubanc-lisp/5436d2eca5b1ed10bc47eec7080f6cb90f98ca65/systems/flexi-streams-1.0.7/test/packages.lisp | lisp | Syntax : COMMON - LISP ; Package : CL - USER ; Base : 10 -*-
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 AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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. | $ Header : /usr / local / cvsrep / flexi - streams / test / packages.lisp , v 1.8 2008/08/01 10:12:43 edi Exp $
Copyright ( c ) 2006 - 2008 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :cl-user)
(defpackage :flexi-streams-test
(:use :cl :flexi-streams)
(:import-from :flexi-streams
:with-unique-names
:with-rebinding
:char*
:normalize-external-format)
(:export :run-all-tests))
|
4bba5e39e73af57ef73a124175284372bdef71402e917ad55afd3f312bfd9378 | minoki/haskell-floating-point | Internal.hs | # OPTIONS_HADDOCK not - home #
{-# OPTIONS -Wno-unused-imports #-}
module Numeric.Rounded.Hardware.Internal
( module Internal
) where
import Numeric.Rounded.Hardware.Backend.Default ()
import Numeric.Rounded.Hardware.Internal.Class as Internal
import Numeric.Rounded.Hardware.Internal.Constants as Internal
import Numeric.Rounded.Hardware.Internal.Conversion as Internal
import Numeric.Rounded.Hardware.Internal.FloatUtil as Internal
import Numeric.Rounded.Hardware.Internal.Rounding as Internal
import Numeric.Rounded.Hardware.Internal.Show as Internal
| null | https://raw.githubusercontent.com/minoki/haskell-floating-point/7d7bb31bb2b07c637a5eaeda92fc622566e9b141/rounded-hw/src/Numeric/Rounded/Hardware/Internal.hs | haskell | # OPTIONS -Wno-unused-imports # | # OPTIONS_HADDOCK not - home #
module Numeric.Rounded.Hardware.Internal
( module Internal
) where
import Numeric.Rounded.Hardware.Backend.Default ()
import Numeric.Rounded.Hardware.Internal.Class as Internal
import Numeric.Rounded.Hardware.Internal.Constants as Internal
import Numeric.Rounded.Hardware.Internal.Conversion as Internal
import Numeric.Rounded.Hardware.Internal.FloatUtil as Internal
import Numeric.Rounded.Hardware.Internal.Rounding as Internal
import Numeric.Rounded.Hardware.Internal.Show as Internal
|
7410ad4fa1a64032f0ae279abc197dfd21f1087bdc248c921a9183e5bbef7692 | unclebob/wator | cell.clj | (ns wator.cell)
(defmulti tick (fn [cell & args] (::type cell)))
| null | https://raw.githubusercontent.com/unclebob/wator/3c45455647deb1364e3102e189d0cf10340ceeb4/src/wator/cell.clj | clojure | (ns wator.cell)
(defmulti tick (fn [cell & args] (::type cell)))
| |
1726b03fdb31cb20e6b1e00a19cd053df2309cdc76b596c9394dbe8ab75b95dd | ekmett/categories | Discrete.hs | {-# LANGUAGE GADTs, TypeOperators #-}
-------------------------------------------------------------------------------------------
-- |
-- Module : Control.Category.Discrete
Copyright : 2008 - 2010
-- License : BSD
--
Maintainer : < >
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------------------
module Control.Category.Discrete
( Discrete(Refl)
, liftDiscrete
, cast
, inverse
) where
import Prelude ()
import Control.Category
-- | Category of discrete objects. The only arrows are identity arrows.
data Discrete a b where
Refl :: Discrete a a
instance Category Discrete where
id = Refl
Refl . Refl = Refl
instance Groupoid Discrete where
= Refl
-- | Discrete a b acts as a proof that a = b, lift that proof into something of kind * -> *
liftDiscrete :: Discrete a b -> Discrete (f a) (f b)
liftDiscrete Refl = Refl
-- | Lower the proof that a ~ b to an arbitrary category.
cast :: Category k => Discrete a b -> k a b
cast Refl = id
-- |
inverse :: Discrete a b -> Discrete b a
inverse Refl = Refl
| null | https://raw.githubusercontent.com/ekmett/categories/4a02808d28b275f59d9d6c08f0c2d329ee567a97/old/src/Control/Category/Discrete.hs | haskell | # LANGUAGE GADTs, TypeOperators #
-----------------------------------------------------------------------------------------
|
Module : Control.Category.Discrete
License : BSD
Stability : experimental
Portability : portable
-----------------------------------------------------------------------------------------
| Category of discrete objects. The only arrows are identity arrows.
| Discrete a b acts as a proof that a = b, lift that proof into something of kind * -> *
| Lower the proof that a ~ b to an arbitrary category.
| | Copyright : 2008 - 2010
Maintainer : < >
module Control.Category.Discrete
( Discrete(Refl)
, liftDiscrete
, cast
, inverse
) where
import Prelude ()
import Control.Category
data Discrete a b where
Refl :: Discrete a a
instance Category Discrete where
id = Refl
Refl . Refl = Refl
instance Groupoid Discrete where
= Refl
liftDiscrete :: Discrete a b -> Discrete (f a) (f b)
liftDiscrete Refl = Refl
cast :: Category k => Discrete a b -> k a b
cast Refl = id
inverse :: Discrete a b -> Discrete b a
inverse Refl = Refl
|
c96a53d67ba912fb40179a58dc03f685a78968743dfd459ef4c3eba164655dd3 | hamler-lang/hamler | Digraph.erl | %%---------------------------------------------------------------------------
%% |
Module :
Copyright : ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd.
%% License : BSD-style (see the LICENSE file)
%%
Maintainer : ,
,
%% Stability : experimental
%% Portability : portable
%%
The Digraph FFI Module .
%%
%%---------------------------------------------------------------------------
-module('Digraph').
-include("../Foreign.hrl").
FFI
-export([ edgeOf/1
, vertexOf/1
, edgeID/1
, vertexID/1
, new/1
, addEdge/4
, modifyEdge/5
, addVertex/2
, edge/2
, vertex/2
, getCycle/2
, getPath/3
, getShortCycle/2
, getShortPath/3
, info/1
, eqImpl/2
]).
-define(Left(V), {'Left', V}).
-define(Right(V), {'Right', V}).
edgeOf(ID) -> ['$e' | ID].
vertexOf(ID) -> ['$v' | ID].
edgeID(['$e' | ID]) -> ID.
vertexID(['$v' | ID]) -> ID.
eqImpl(X, Y) -> X =:= Y.
trans([]) -> [];
trans([X | Xs]) ->
[case X of
{'Cyclic'} -> digraph:cyclic();
{'Acyclic'} -> digraph:acyclic();
{'Protected'} -> digraph:protected();
{'Private'} -> digraph:private()
end | trans(Xs)].
new(Type) -> ?IO(digraph:new(trans(Type))).
addEdge(G, V1, V2, Labal) -> ?IO(
case digraph:add_edge(G, V1, V2, Labal) of
{error, {bad_edge, Path}} -> ?Left({'BadEdge', Path});
{error, {bad_vertex, V}} -> ?Left({'BadVertex', V});
V -> ?Right(V)
end).
modifyEdge(G, E, V1, V2, Labal) -> ?IO(
case digraph:add_edge(G, E, V1, V2, Labal) of
{error, {bad_edge, Path}} -> ?Left({'BadEdge', Path});
{error, {bad_vertex, V}} -> ?Left({'BadVertex', V});
V -> ?Right(V)
end).
addVertex(G, Labal) -> ?IO(
digraph:add_vertex(G, digraph:add_vertex(G), Labal)).
edge(G, E) -> ?IO(
case digraph:edge(G, E) of
{E, V1, V2, Labal} -> ?Just({V1, V2, Labal});
false -> ?Nothing
end).
vertex(G, V) -> ?IO(
case digraph:vertex(G, V) of
{V, Labal} -> ?Just(Labal);
false -> ?Nothing
end).
getCycle(G, V) -> ?IO(
case digraph:get_cycle(G, V) of
false -> [];
Else -> Else
end).
getPath(G, V1, V2) -> ?IO(
case digraph:get_path(G, V1, V2) of
false -> [];
Else -> Else
end).
getShortCycle(G, V) -> ?IO(
case digraph:get_short_cycle(G, V) of
false -> [];
Else -> Else
end).
getShortPath(G, V1, V2) -> ?IO(
case digraph:get_short_path(G, V1, V2) of
false -> [];
Else -> Else
end).
info(G) -> ?IO(
lists:map(fun({memory, M}) ->
{'GraphMemoryInfo', M};
({cyclicity, Y}) ->
{'GraphTypeInfo', {case Y of cyclic -> 'Cyclic'; acyclic -> 'Acyclic' end}};
({portection, Y}) ->
{'GraphTypeInfo', {case Y of protected -> 'Protected'; private -> 'Private' end}}
end, digraph:info(G))).
| null | https://raw.githubusercontent.com/hamler-lang/hamler/3ba89dde3067076e112c60351b019eeed6c97dd7/lib/Data/Digraph.erl | erlang | ---------------------------------------------------------------------------
|
License : BSD-style (see the LICENSE file)
Stability : experimental
Portability : portable
--------------------------------------------------------------------------- | Module :
Copyright : ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd.
Maintainer : ,
,
The Digraph FFI Module .
-module('Digraph').
-include("../Foreign.hrl").
FFI
-export([ edgeOf/1
, vertexOf/1
, edgeID/1
, vertexID/1
, new/1
, addEdge/4
, modifyEdge/5
, addVertex/2
, edge/2
, vertex/2
, getCycle/2
, getPath/3
, getShortCycle/2
, getShortPath/3
, info/1
, eqImpl/2
]).
-define(Left(V), {'Left', V}).
-define(Right(V), {'Right', V}).
edgeOf(ID) -> ['$e' | ID].
vertexOf(ID) -> ['$v' | ID].
edgeID(['$e' | ID]) -> ID.
vertexID(['$v' | ID]) -> ID.
eqImpl(X, Y) -> X =:= Y.
trans([]) -> [];
trans([X | Xs]) ->
[case X of
{'Cyclic'} -> digraph:cyclic();
{'Acyclic'} -> digraph:acyclic();
{'Protected'} -> digraph:protected();
{'Private'} -> digraph:private()
end | trans(Xs)].
new(Type) -> ?IO(digraph:new(trans(Type))).
addEdge(G, V1, V2, Labal) -> ?IO(
case digraph:add_edge(G, V1, V2, Labal) of
{error, {bad_edge, Path}} -> ?Left({'BadEdge', Path});
{error, {bad_vertex, V}} -> ?Left({'BadVertex', V});
V -> ?Right(V)
end).
modifyEdge(G, E, V1, V2, Labal) -> ?IO(
case digraph:add_edge(G, E, V1, V2, Labal) of
{error, {bad_edge, Path}} -> ?Left({'BadEdge', Path});
{error, {bad_vertex, V}} -> ?Left({'BadVertex', V});
V -> ?Right(V)
end).
addVertex(G, Labal) -> ?IO(
digraph:add_vertex(G, digraph:add_vertex(G), Labal)).
edge(G, E) -> ?IO(
case digraph:edge(G, E) of
{E, V1, V2, Labal} -> ?Just({V1, V2, Labal});
false -> ?Nothing
end).
vertex(G, V) -> ?IO(
case digraph:vertex(G, V) of
{V, Labal} -> ?Just(Labal);
false -> ?Nothing
end).
getCycle(G, V) -> ?IO(
case digraph:get_cycle(G, V) of
false -> [];
Else -> Else
end).
getPath(G, V1, V2) -> ?IO(
case digraph:get_path(G, V1, V2) of
false -> [];
Else -> Else
end).
getShortCycle(G, V) -> ?IO(
case digraph:get_short_cycle(G, V) of
false -> [];
Else -> Else
end).
getShortPath(G, V1, V2) -> ?IO(
case digraph:get_short_path(G, V1, V2) of
false -> [];
Else -> Else
end).
info(G) -> ?IO(
lists:map(fun({memory, M}) ->
{'GraphMemoryInfo', M};
({cyclicity, Y}) ->
{'GraphTypeInfo', {case Y of cyclic -> 'Cyclic'; acyclic -> 'Acyclic' end}};
({portection, Y}) ->
{'GraphTypeInfo', {case Y of protected -> 'Protected'; private -> 'Private' end}}
end, digraph:info(G))).
|
ce7134153dc083918b3a94dada3a38196862cd2f42bdf2dce5309ac83cb08c00 | rubenbarroso/EOPL | 2_17.scm | ;The new grammar production:
;
;(has-association? [f] s) = true if s=t and f(s)=k and [f] = (extend-env '(t) '(k) [g])
; or (has-association? [g] s)
; false if [f] = [0]
The new procedural implementation . As we saw in exercise 2.15 , with the addition of
;the new observer, has-association?, we need to extend the constructor with a new
;procedure that supports it.
(load "/Users/ruben/Dropbox/EOPL/src/interps/r5rs.scm")
(define empty-env
(lambda ()
(list
(lambda (sym)
(eopl:error 'apply-env "No binding for ~s" sym))
(lambda (sym) #f))))
(define extend-env
(lambda (syms vals env)
(list
(lambda (sym)
(let ((pos (list-find-position sym syms)))
(if (number? pos)
(list-ref vals pos)
(apply-env env sym))))
(lambda (sym)
(if (memv sym syms)
#t
(has-association? env sym))))))
(define has-association?
(lambda (env sym)
((cadr env) sym)))
(define apply-env
(lambda (env sym)
((car env) sym)))
(define list-find-position
(lambda (sym los)
(list-index (lambda (sym1) (eqv? sym1 sym)) los)))
(define list-index
(lambda (pred ls)
(cond
((null? ls) #f)
((pred (car ls)) 0)
(else (let ((list-index-r (list-index pred (cdr ls))))
(if (number? list-index-r)
(+ list-index-r 1)
#f))))))
> ( define dxy - env
( extend - env ' ( d x ) ' ( 6 7 )
; (extend-env '(y) '(8)
; (empty-env))))
;> (apply-env dxy-env 'x)
7
> ( has - association ? dxy - env ' x )
;#t
> ( has - association ? dxy - env ' y )
;#t
> ( has - association ? dxy - env 'd )
;#t
> ( has - association ? dxy - env ' z )
;#f
| null | https://raw.githubusercontent.com/rubenbarroso/EOPL/f9b3c03c2fcbaddf64694ee3243d54be95bfe31d/src/chapter2/2_17.scm | scheme | The new grammar production:
(has-association? [f] s) = true if s=t and f(s)=k and [f] = (extend-env '(t) '(k) [g])
or (has-association? [g] s)
false if [f] = [0]
the new observer, has-association?, we need to extend the constructor with a new
procedure that supports it.
(extend-env '(y) '(8)
(empty-env))))
> (apply-env dxy-env 'x)
#t
#t
#t
#f |
The new procedural implementation . As we saw in exercise 2.15 , with the addition of
(load "/Users/ruben/Dropbox/EOPL/src/interps/r5rs.scm")
(define empty-env
(lambda ()
(list
(lambda (sym)
(eopl:error 'apply-env "No binding for ~s" sym))
(lambda (sym) #f))))
(define extend-env
(lambda (syms vals env)
(list
(lambda (sym)
(let ((pos (list-find-position sym syms)))
(if (number? pos)
(list-ref vals pos)
(apply-env env sym))))
(lambda (sym)
(if (memv sym syms)
#t
(has-association? env sym))))))
(define has-association?
(lambda (env sym)
((cadr env) sym)))
(define apply-env
(lambda (env sym)
((car env) sym)))
(define list-find-position
(lambda (sym los)
(list-index (lambda (sym1) (eqv? sym1 sym)) los)))
(define list-index
(lambda (pred ls)
(cond
((null? ls) #f)
((pred (car ls)) 0)
(else (let ((list-index-r (list-index pred (cdr ls))))
(if (number? list-index-r)
(+ list-index-r 1)
#f))))))
> ( define dxy - env
( extend - env ' ( d x ) ' ( 6 7 )
7
> ( has - association ? dxy - env ' x )
> ( has - association ? dxy - env ' y )
> ( has - association ? dxy - env 'd )
> ( has - association ? dxy - env ' z )
|
9a1564b8838bb6ac8c5fd20933186c5534f019253e0fe3ef10019fe5929c24c5 | tmcgilchrist/postgresql-transactional | Tagged.hs | # LANGUAGE CPP #
{-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE ImplicitPrelude #-}
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
|
Module : Database . PostgreSQL.Tagged
Copyright : ( c ) Helium Systems , Inc.
License : MIT
Maintainer :
Stability : experimental
Portability : GHC
This module is similar to @Database . PostgreSQL.Simple@ , with one notable exception :
each function is tagged ( using DataKinds over the ' Effect ' type ) with information
as to whether it reads from or writes to the database . This is useful in conjunction
with Postgres setups that are replicated over multiple machines .
As with @Database . PostgreSQL.Transaction@ , the parameter order is reversed when compared to the functions
provided by postgresql - simple .
Module : Database.PostgreSQL.Tagged
Copyright : (c) Helium Systems, Inc.
License : MIT
Maintainer :
Stability : experimental
Portability : GHC
This module is similar to @Database.PostgreSQL.Simple@, with one notable exception:
each function is tagged (using DataKinds over the 'Effect' type) with information
as to whether it reads from or writes to the database. This is useful in conjunction
with Postgres setups that are replicated over multiple machines.
As with @Database.PostgreSQL.Transaction@, the parameter order is reversed when compared to the functions
provided by postgresql-simple.
-}
module Database.PostgreSQL.Tagged
( Effect (..)
, PGTaggedT
, PGTaggedIO
, whileWriting
, runPGWrite
, runPGRead
, query
, query_
, execute
, executeOne
, executeMany
, returning
, queryHead
, queryOnly
, formatQuery
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Coerce
import Data.Int
import qualified Database.PostgreSQL.Simple as Postgres
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToRow
import qualified Database.PostgreSQL.Transaction as T
-- | Postgres queries are either read-only or writing-enabled.
These values ' kinds are used as phantom types in the ' PGTaggedT '
-- monad transformer.
data Effect = Read | Write
-- | The tagged-effect Postgres monad transformer.
The parameter must be either ' Read ' or ' Write ' .
newtype PGTaggedT (e :: Effect) m a =
PGTagged (T.PGTransactionT m a)
deriving ( Functor
, Applicative
, Monad
, MonadTrans
, MonadIO)
| A convenient alias for PGTaggedT values taking place in IO .
type PGTaggedIO e a = PGTaggedT e IO a
-- | Run a writing-oriented PGTagged transaction.
runPGWrite :: MonadBaseControl IO m
=> PGTaggedT 'Write m a
-> Postgres.Connection
-> m a
runPGWrite = T.runPGTransactionT . coerce
-- | Run a read-only PGTagged transaction. Actions such as
-- these can take place on a read-only replica.
runPGRead :: MonadBaseControl IO m
=> PGTaggedT 'Read m a
-> Postgres.Connection
-> m a
runPGRead = T.runPGTransactionT . coerce
-- | Promote a reading operation to a writing operation.
-- Note that there is no way to go the opposite direction
-- (unless you use 'coerce'). This is by design: if you're
-- writing, it's safe to read, but the converse does not
-- necessarily hold true.
whileWriting :: PGTaggedT 'Read m a -> PGTaggedT 'Write m a
whileWriting = coerce
-- | Run an individual query. (read operation)
query :: (ToRow input, FromRow output, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Read m [output]
query i = PGTagged <$> T.query i
-- | As 'query', but without arguments. (read operation)
query_ :: (FromRow output, MonadIO m)
=> Postgres.Query
-> PGTaggedT 'Read m [output]
query_ = PGTagged <$> T.query_
-- | As 'Database.PostgreSQL.Simple.execute'. (write operation)
execute :: (ToRow input, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Write m Int64
execute i = PGTagged <$> T.execute i
-- | As 'Database.PostgreSQL.Simple.executeMany'. (write operation)
executeMany :: (ToRow input, MonadIO m)
=> [input]
-> Postgres.Query
-> PGTaggedT 'Write m Int64
executeMany is = PGTagged <$> T.executeMany is
-- | As 'Database.PostgreSQL.Simple.returning'. (write operation)
returning :: (ToRow input, FromRow output, MonadIO m)
=> [input]
-> Postgres.Query
-> PGTaggedT 'Write m [output]
returning is = PGTagged <$> T.returning is
-- | As 'Database.PostgreSQL.Transaction.queryOnly'. (read operation)
queryOnly :: (ToRow input, FromField f, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Read m (Maybe f)
queryOnly i = PGTagged <$> T.queryOnly i
-- | As 'Database.PostgreSQL.Transaction.queryHead'. (read operation)
queryHead :: (ToRow input, FromRow output, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Read m (Maybe output)
queryHead i = PGTagged <$> T.queryHead i
-- | As 'Database.PostgreSQL.Transaction.executeOne'. (write operation)
executeOne :: (ToRow input, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Write m Bool
executeOne i = PGTagged <$> T.executeOne i
-- | As 'Database.PostgreSQL.Simple.formatQuery'. (neutral)
formatQuery :: (ToRow input, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT e m Postgres.Query
formatQuery i = PGTagged <$> T.formatQuery i
| null | https://raw.githubusercontent.com/tmcgilchrist/postgresql-transactional/d53c6227c9ef7e5ab3ea255bb3351a4a0b7032be/src/Database/PostgreSQL/Tagged.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE ImplicitPrelude #
| Postgres queries are either read-only or writing-enabled.
monad transformer.
| The tagged-effect Postgres monad transformer.
| Run a writing-oriented PGTagged transaction.
| Run a read-only PGTagged transaction. Actions such as
these can take place on a read-only replica.
| Promote a reading operation to a writing operation.
Note that there is no way to go the opposite direction
(unless you use 'coerce'). This is by design: if you're
writing, it's safe to read, but the converse does not
necessarily hold true.
| Run an individual query. (read operation)
| As 'query', but without arguments. (read operation)
| As 'Database.PostgreSQL.Simple.execute'. (write operation)
| As 'Database.PostgreSQL.Simple.executeMany'. (write operation)
| As 'Database.PostgreSQL.Simple.returning'. (write operation)
| As 'Database.PostgreSQL.Transaction.queryOnly'. (read operation)
| As 'Database.PostgreSQL.Transaction.queryHead'. (read operation)
| As 'Database.PostgreSQL.Transaction.executeOne'. (write operation)
| As 'Database.PostgreSQL.Simple.formatQuery'. (neutral) | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE KindSignatures #
# LANGUAGE MultiParamTypeClasses #
|
Module : Database . PostgreSQL.Tagged
Copyright : ( c ) Helium Systems , Inc.
License : MIT
Maintainer :
Stability : experimental
Portability : GHC
This module is similar to @Database . PostgreSQL.Simple@ , with one notable exception :
each function is tagged ( using DataKinds over the ' Effect ' type ) with information
as to whether it reads from or writes to the database . This is useful in conjunction
with Postgres setups that are replicated over multiple machines .
As with @Database . PostgreSQL.Transaction@ , the parameter order is reversed when compared to the functions
provided by postgresql - simple .
Module : Database.PostgreSQL.Tagged
Copyright : (c) Helium Systems, Inc.
License : MIT
Maintainer :
Stability : experimental
Portability : GHC
This module is similar to @Database.PostgreSQL.Simple@, with one notable exception:
each function is tagged (using DataKinds over the 'Effect' type) with information
as to whether it reads from or writes to the database. This is useful in conjunction
with Postgres setups that are replicated over multiple machines.
As with @Database.PostgreSQL.Transaction@, the parameter order is reversed when compared to the functions
provided by postgresql-simple.
-}
module Database.PostgreSQL.Tagged
( Effect (..)
, PGTaggedT
, PGTaggedIO
, whileWriting
, runPGWrite
, runPGRead
, query
, query_
, execute
, executeOne
, executeMany
, returning
, queryHead
, queryOnly
, formatQuery
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.Coerce
import Data.Int
import qualified Database.PostgreSQL.Simple as Postgres
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToRow
import qualified Database.PostgreSQL.Transaction as T
These values ' kinds are used as phantom types in the ' PGTaggedT '
data Effect = Read | Write
The parameter must be either ' Read ' or ' Write ' .
newtype PGTaggedT (e :: Effect) m a =
PGTagged (T.PGTransactionT m a)
deriving ( Functor
, Applicative
, Monad
, MonadTrans
, MonadIO)
| A convenient alias for PGTaggedT values taking place in IO .
type PGTaggedIO e a = PGTaggedT e IO a
runPGWrite :: MonadBaseControl IO m
=> PGTaggedT 'Write m a
-> Postgres.Connection
-> m a
runPGWrite = T.runPGTransactionT . coerce
runPGRead :: MonadBaseControl IO m
=> PGTaggedT 'Read m a
-> Postgres.Connection
-> m a
runPGRead = T.runPGTransactionT . coerce
whileWriting :: PGTaggedT 'Read m a -> PGTaggedT 'Write m a
whileWriting = coerce
query :: (ToRow input, FromRow output, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Read m [output]
query i = PGTagged <$> T.query i
query_ :: (FromRow output, MonadIO m)
=> Postgres.Query
-> PGTaggedT 'Read m [output]
query_ = PGTagged <$> T.query_
execute :: (ToRow input, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Write m Int64
execute i = PGTagged <$> T.execute i
executeMany :: (ToRow input, MonadIO m)
=> [input]
-> Postgres.Query
-> PGTaggedT 'Write m Int64
executeMany is = PGTagged <$> T.executeMany is
returning :: (ToRow input, FromRow output, MonadIO m)
=> [input]
-> Postgres.Query
-> PGTaggedT 'Write m [output]
returning is = PGTagged <$> T.returning is
queryOnly :: (ToRow input, FromField f, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Read m (Maybe f)
queryOnly i = PGTagged <$> T.queryOnly i
queryHead :: (ToRow input, FromRow output, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Read m (Maybe output)
queryHead i = PGTagged <$> T.queryHead i
executeOne :: (ToRow input, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT 'Write m Bool
executeOne i = PGTagged <$> T.executeOne i
formatQuery :: (ToRow input, MonadIO m)
=> input
-> Postgres.Query
-> PGTaggedT e m Postgres.Query
formatQuery i = PGTagged <$> T.formatQuery i
|
f29143d2a9cdccaca103e5f84144320ab3181be660058faede94ea832519cc4a | acl2/acl2 | doc@useless-runes.lsp | (DM::PRIMEP204511953)
(DM::PRIMEP250269713
(6296 36 (:REWRITE MEMBER-OF-CONS))
(4356 100 (:REWRITE SET::EMPTY-SET-UNIQUE))
(4320 36 (:REWRITE MEMBER-EQUAL-OF-CONS-DROP))
(2052 50 (:REWRITE OMAP::SETP-WHEN-MAPP))
(1560 13 (:REWRITE MEMBER-EQUAL-WHEN-SINGLETON-IFF))
(470 50 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX))
(319 1 (:REWRITE R1CS::PSEUDO-VAR-LISTP-FORWARD-TO-TRUE-LISTP))
(316 1 (:REWRITE R1CS::PSEUDO-VAR-LISTP-WHEN-SYMBOL-LISTP))
(300 50 (:REWRITE BITCOIN::SETP-WHEN-BIP32-PATH-SETP))
(277 1 (:DEFINITION SYMBOL-LISTP))
(270 5 (:REWRITE CONSP-FROM-LEN-CHEAP))
(260 50 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM))
(252 50 (:REWRITE OMAP::MFIX-IMPLIES-MAPP))
(250 50 (:REWRITE C::MAPP-WHEN-SCOPEP))
(250 50 (:REWRITE OMAP::MAPP-WHEN-NOT-EMPTY))
(250 50 (:REWRITE PFCS::MAPP-WHEN-ASSIGNMENTP))
(202 100 (:REWRITE EQUAL-OF-BOOLEANS-CHEAP))
(200 200 (:TYPE-PRESCRIPTION OMAP::MAPP))
(200 50 (:REWRITE SET::NONEMPTY-MEANS-SET))
(187 2 (:REWRITE SYMBOL-LISTP-WHEN-NOT-CONSP))
(150 50 (:REWRITE C::SETP-WHEN-TYPE-SETP))
(150 50 (:REWRITE C::SETP-WHEN-TYPE-OPTION-SETP))
(150 50 (:REWRITE ABNF::SETP-WHEN-TREE-SETP))
(150 50 (:REWRITE ACL2PL::SETP-WHEN-SYMBOL-VALUE-SETP))
(150 50 (:REWRITE ABNF::SETP-WHEN-RULENAME-SETP))
(150 50 (:REWRITE SET::SETP-WHEN-NAT-SETP))
(150 50 (:REWRITE SET::SETP-WHEN-INTEGER-SETP))
(150 50 (:REWRITE C::SETP-WHEN-IDENT-SETP))
(150 50 (:REWRITE ACL2PL::SETP-WHEN-FUNCTION-SETP))
(150 50 (:REWRITE BITCOIN::SETP-WHEN-BIP44-COIN-TYPE-SETP))
(150 50 (:REWRITE C::MAPP-WHEN-VAR-TABLE-SCOPEP))
(150 50 (:REWRITE C::MAPP-WHEN-TAG-ENVP))
(150 50 (:REWRITE C::MAPP-WHEN-HEAPP))
(150 50 (:REWRITE C::MAPP-WHEN-FUN-TABLEP))
(150 50 (:REWRITE C::MAPP-WHEN-FUN-ENVP))
(150 50 (:REWRITE ACL2PL::MAPP-WHEN-BINDINGP))
(150 50 (:REWRITE BITCOIN::BIP32-PATH-SETP-WHEN-BIP32-INDEX-TREEP))
(102 100 (:TYPE-PRESCRIPTION OMAP::MFIX))
(101 101 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(101 99 (:REWRITE NOT-EQUAL-WHEN-LESS))
(100 100 (:TYPE-PRESCRIPTION C::VAR-TABLE-SCOPEP))
(100 100 (:TYPE-PRESCRIPTION C::TYPE-SETP))
(100 100 (:TYPE-PRESCRIPTION C::TYPE-OPTION-SETP))
(100 100 (:TYPE-PRESCRIPTION ABNF::TREE-SETP))
(100 100 (:TYPE-PRESCRIPTION C::TAG-ENVP))
(100 100 (:TYPE-PRESCRIPTION ACL2PL::SYMBOL-VALUE-SETP))
(100 100 (:TYPE-PRESCRIPTION C::SCOPEP))
(100 100 (:TYPE-PRESCRIPTION ABNF::RULENAME-SETP))
(100 100 (:TYPE-PRESCRIPTION SET::NAT-SETP))
(100 100 (:TYPE-PRESCRIPTION SET::INTEGER-SETP))
(100 100 (:TYPE-PRESCRIPTION C::IDENT-SETP))
(100 100 (:TYPE-PRESCRIPTION C::HEAPP))
(100 100 (:TYPE-PRESCRIPTION ACL2PL::FUNCTION-SETP))
(100 100 (:TYPE-PRESCRIPTION C::FUN-TABLEP))
(100 100 (:TYPE-PRESCRIPTION C::FUN-ENVP))
(100 100 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(100 100 (:TYPE-PRESCRIPTION OMAP::EMPTY))
(100 100 (:TYPE-PRESCRIPTION BOOLEANP))
(100 100 (:TYPE-PRESCRIPTION BITCOIN::BIP44-COIN-TYPE-SETP))
(100 100 (:TYPE-PRESCRIPTION BITCOIN::BIP32-PATH-SETP))
(100 100 (:TYPE-PRESCRIPTION BITCOIN::BIP32-INDEX-TREEP))
(100 100 (:TYPE-PRESCRIPTION ACL2PL::BINDINGP))
(100 100 (:TYPE-PRESCRIPTION PFCS::ASSIGNMENTP))
(100 100 (:REWRITE C::SCOPEP-WHEN-MEMBER-EQUAL-OF-SCOPE-LISTP))
(100 100 (:REWRITE CLR-DIFFERENTIAL))
(100 100 (:REWRITE PFCS::ASSIGNMENTP-WHEN-MEMBER-EQUAL-OF-ASSIGNMENT-LISTP))
(100 50 (:REWRITE OMAP::MFIX-WHEN-MAPP))
(100 50 (:REWRITE OMAP::MAPP-NON-NIL-IMPLIES-NON-EMPTY))
(99 99 (:REWRITE REFS-DIFFER-WHEN-ARRAY-DIMENSIONS-DIFFER-ALT))
(99 99 (:REWRITE REFS-DIFFER-WHEN-ARRAY-DIMENSIONS-DIFFER))
(99 99 (:REWRITE NOT-EQUAL-WHEN-NOT-EQUAL-BVCHOP))
(99 99 (:REWRITE NOT-EQUAL-OF-CONSTANT-AND-BV-TERM-ALT))
(99 99 (:REWRITE NOT-EQUAL-OF-CONSTANT-AND-BV-TERM))
(99 99 (:REWRITE NOT-EQUAL-FROM-BOUND))
(99 99 (:REWRITE NOT-EQUAL-CONSTANT-WHEN-UNSIGNED-BYTE-P-ALT))
(99 99 (:REWRITE NOT-EQUAL-CONSTANT-WHEN-UNSIGNED-BYTE-P))
(99 99 (:REWRITE JVM::NOT-EQUAL-CONSTANT-WHEN-CDR-WRONG))
(99 99 (:REWRITE JVM::NOT-EQUAL-CONSTANT-WHEN-CAR-WRONG))
(99 99 (:REWRITE NOT-EQUAL-CONSTANT-WHEN-BOUND-FORBIDS-IT2))
(99 99 (:REWRITE NOT-EQUAL-CONSTANT-WHEN-BOUND-FORBIDS-IT))
(99 99 (:REWRITE IMPOSSIBLE-VALUE-2))
(99 99 (:REWRITE IMPOSSIBLE-VALUE-1))
(99 99 (:REWRITE EQUAL-WHEN-BVLT-ALT))
(99 99 (:REWRITE EQUAL-WHEN-BVLT))
(99 99 (:REWRITE EQUAL-WHEN-<-OF-+-ALT))
(99 99 (:REWRITE EQUAL-WHEN-<-OF-+))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-SBVLT))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-NOT-BVLT-CONSTANT-2))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-NOT-BVLT-CONSTANT-1))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-BVLT-CONSTANT-2-ALT))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-BVLT-CONSTANT-2))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-BVLT-CONSTANT-1-ALT))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-BVLT-CONSTANT-1))
(99 99 (:REWRITE EQUAL-CONSTANT-WHEN-SLICE-EQUAL-CONSTANT))
(99 99 (:REWRITE EQUAL-CONSTANT-WHEN-NOT-SLICE-EQUAL-CONSTANT))
(99 99 (:REWRITE EQUAL-CONSTANT-WHEN-NOT-SBVLT))
(99 99 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE))
(98 2 (:REWRITE DEFAULT-CDR))
(74 37 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP))
(74 37 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP))
(53 1 (:REWRITE <-0-+-NEGATIVE-1))
(50 50 (:REWRITE SET::SETP-CONSTANT-OPENER))
(50 50 (:REWRITE DM::PERM-MEMBER))
(50 50 (:REWRITE SET::IN-SET))
(50 50 (:REWRITE SET::EMPTY-CONSTANT-OPENER))
(50 50 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY))
(47 5 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP))
(37 37 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL))
(37 37 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR))
(37 7 (:REWRITE LEN-OF-IF))
(36 36 (:REWRITE SUBSETP-MEMBER . 4))
(36 36 (:REWRITE SUBSETP-MEMBER . 3))
(36 36 (:REWRITE SUBSETP-MEMBER . 2))
(36 36 (:REWRITE SUBSETP-MEMBER . 1))
(36 36 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL))
(36 36 (:REWRITE MEMBER-EQUAL-OF-CONS-NON-CONSTANT))
(36 36 (:REWRITE INTERSECTP-MEMBER . 3))
(36 36 (:REWRITE INTERSECTP-MEMBER . 2))
(35 1 (:REWRITE TRUE-LISTP-WHEN-NOT-CONSP))
(26 1 (:REWRITE LEN-OF-CDR))
(17 17 (:REWRITE KECCAK::LEN-WHEN-K-STATE-ARRAY-P))
(17 17 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(16 16 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP))
(16 16 (:REWRITE LEN-WHEN-EQUAL-TAKE))
(16 16 (:META LEN-CONS-META-RULE))
(13 13 (:REWRITE ASSOC-EQUAL-WHEN-NOT-CONSP-CHEAP))
(12 7 (:REWRITE <-OF-IF-ARG2))
(9 9 (:REWRITE LEN-WHEN-PSEUDO-DAGP-AUX))
(9 9 (:REWRITE LEN-WHEN-DARGP-LESS-THAN))
(9 9 (:REWRITE LEN-WHEN-BV-ARRAYP))
(9 9 (:REWRITE LEN-WHEN-BOUNDED-DAG-EXPRP-AND-QUOTEP))
(8 4 (:TYPE-PRESCRIPTION INTEGERP-OF-NTH-WHEN-ALL-NATP))
(7 7 (:REWRITE ASSOC-EQUAL-OF-CONS-SAFE))
(6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL))
(6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(6 6 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(6 6 (:LINEAR LEN-WHEN-PREFIXP))
(6 2 (:REWRITE <-OF-LEN-WHEN-NTH-NON-NIL))
(6 2 (:REWRITE <-OF-LEN-WHEN-INTEGERP-OF-NTH))
(5 5 (:REWRITE USE-ALL-HEAPREF-TABLE-ENTRYP-2))
(5 5 (:REWRITE NOT-CONSP-WHEN-NUMBER-OF-ARRAY-DIMENSIONS-IS-0))
(5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-PSEUDOTERM-ALISTP . 2))
(5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-PSEUDOTERM-ALISTP . 1))
(5 5 (:REWRITE ISAR::CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-FACT-INFO-ALISTP . 2))
(5 5 (:REWRITE ISAR::CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-FACT-INFO-ALISTP . 1))
(5 5 (:REWRITE C::CONSP-WHEN-MEMBER-EQUAL-OF-ATC-STRING-OBJINFO-ALISTP . 2))
(5 5 (:REWRITE C::CONSP-WHEN-MEMBER-EQUAL-OF-ATC-STRING-OBJINFO-ALISTP . 1))
(5 5 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT))
(5 5 (:LINEAR INDEX-OF-<-LEN))
(4 4 (:TYPE-PRESCRIPTION ALL-NATP))
(4 2 (:REWRITE DEFAULT-<-2))
(3 3 (:REWRITE USE-ALL-CONSP-2))
(3 3 (:REWRITE USE-ALL-CONSP))
(3 3 (:REWRITE STRENGTHEN-<-OF-CONSTANT-WHEN-NOT-EQUAL))
(3 3 (:REWRITE LEN-GIVES-CONSP))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-TRUELIST-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-TRUELIST-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-TRUELIST-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-TRUELIST-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-ISODATA-SYMBOL-ISOMAP-ALISTP . 2))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-ISODATA-SYMBOL-ISOMAP-ALISTP . 1))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-ISODATA-POS-ISOMAP-ALISTP . 2))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-ISODATA-POS-ISOMAP-ALISTP . 1))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-EXPDATA-SYMBOL-SURJMAP-ALISTP . 2))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-EXPDATA-SYMBOL-SURJMAP-ALISTP . 1))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-EXPDATA-POS-SURJMAP-ALISTP . 2))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-EXPDATA-POS-SURJMAP-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-LEN-GREATER))
(3 3 (:REWRITE CONSP-FROM-LEN-BOUND))
(3 3 (:REWRITE <-WHEN-BOUNDED-AXE-TREEP))
(3 3 (:REWRITE <-TRANS))
(2 2 (:TYPE-PRESCRIPTION TRUE-LISTP))
(2 2 (:TYPE-PRESCRIPTION R1CS::PSEUDO-VAR-LISTP))
(2 2 (:REWRITE USE-ALL-<-2))
(2 2 (:REWRITE USE-ALL-<))
(2 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-SYMBOL-TRUELIST-ALISTP))
(2 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP))
(2 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-SYMBOL-PSEUDOTERM-ALISTP))
(2 2 (:REWRITE APT::SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-ISODATA-SYMBOL-ISOMAP-ALISTP))
(2 2 (:REWRITE APT::SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-EXPDATA-SYMBOL-SURJMAP-ALISTP))
(2 2 (:REWRITE SYMBOL-LISTP-OF-CDR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP))
(2 2 (:REWRITE NOT-PRIMEP-WHEN-DIVIDES))
(2 2 (:REWRITE MY-NON-INTEGERP-<-INTEGERP))
(2 2 (:REWRITE MY-INTEGERP-<-NON-INTEGERP))
(2 2 (:REWRITE FN-CHECK-DEF-FORMALS))
(2 2 (:REWRITE DROP-LINEAR-HYPS2))
(2 2 (:REWRITE DROP->-HYPS))
(2 2 (:REWRITE DROP-<-HYPS))
(2 2 (:REWRITE DEFAULT-CAR))
(2 2 (:REWRITE DEFAULT-<-1))
(2 2 (:REWRITE CAR-WHEN-EQUAL-NTHCDR))
(2 2 (:REWRITE BOUND-WHEN-USB2))
(2 2 (:REWRITE <-WHEN-SBVLT-CONSTANTS))
(2 2 (:REWRITE <-WHEN-BVLT))
(2 2 (:REWRITE <-WHEN-BOUNDED-DARG-LISTP-GEN))
(2 2 (:REWRITE <-TIGHTEN-WHEN-SLICE-IS-0))
(2 2 (:REWRITE <-OF-NON-INTEGERP-AND-INTEGERP))
(2 2 (:REWRITE <-OF-CONSTANT-WHEN-USB2))
(2 2 (:REWRITE <-OF-0-WHEN-<-FREE))
(2 2 (:REWRITE <-LEMMA-FOR-KNOWN-OPERATORS-NON-DAG))
(2 2 (:REWRITE <-FROM-<=-FREE))
(2 1 (:REWRITE TRUE-LISTP-WHEN-POSSIBLY-NEGATED-NODENUMSP))
(2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP))
(2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-AXE-TREEP-CHEAP))
(2 1 (:REWRITE SYMBOL-LISTP-OF-CDR-WHEN-SYMBOL-LISTP))
(2 1 (:REWRITE DEFAULT-+-2))
(1 1 (:TYPE-PRESCRIPTION POSSIBLY-NEGATED-NODENUMSP))
(1 1 (:TYPE-PRESCRIPTION AXE-TREEP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-THEOREM-SYMBOL-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-TERMFN-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-SIGNED-BYTE-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-PSEUDO-DAGP-AUX))
(1 1 (:REWRITE TRUE-LISTP-WHEN-MACRO-SYMBOL-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-LAMBDA-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-INTEGER-RANGE-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-FUNCTION-SYMBOL-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-DAB-DIGIT-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-BV-ARRAYP))
(1 1 (:REWRITE C::TRUE-LISTP-WHEN-ATC-FORMAL-POINTER-LISTP))
(1 1 (:REWRITE SYMBOLP-WHEN-MEMBER-EQUAL))
(1 1 (:REWRITE PFCS::SYMBOLP-WHEN-IN-ASSIGNMENTP-BINDS-FREE-X))
(1 1 (:REWRITE SYMBOLP-WHEN-BOUNDED-DAG-EXPRP))
(1 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-BOUNDED-DAG-EXPRP))
(1 1 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE LEN->-0-WEAKEN))
(1 1 (:REWRITE EQUAL-LEN-0))
(1 1 (:REWRITE DEFAULT-+-1))
(1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN))
(1 1 (:REWRITE +-OF-MINUS-CONSTANT-VERSION))
(1 1 (:REWRITE +-OF-MINUS))
)
| null | https://raw.githubusercontent.com/acl2/acl2/f64742cc6d41c35f9d3f94e154cd5fd409105d34/books/kestrel/.sys/doc%40useless-runes.lsp | lisp | (DM::PRIMEP204511953)
(DM::PRIMEP250269713
(6296 36 (:REWRITE MEMBER-OF-CONS))
(4356 100 (:REWRITE SET::EMPTY-SET-UNIQUE))
(4320 36 (:REWRITE MEMBER-EQUAL-OF-CONS-DROP))
(2052 50 (:REWRITE OMAP::SETP-WHEN-MAPP))
(1560 13 (:REWRITE MEMBER-EQUAL-WHEN-SINGLETON-IFF))
(470 50 (:REWRITE TRUE-LIST-LISTP-IMPLIES-TRUE-LISTP-XXX))
(319 1 (:REWRITE R1CS::PSEUDO-VAR-LISTP-FORWARD-TO-TRUE-LISTP))
(316 1 (:REWRITE R1CS::PSEUDO-VAR-LISTP-WHEN-SYMBOL-LISTP))
(300 50 (:REWRITE BITCOIN::SETP-WHEN-BIP32-PATH-SETP))
(277 1 (:DEFINITION SYMBOL-LISTP))
(270 5 (:REWRITE CONSP-FROM-LEN-CHEAP))
(260 50 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-TRIM))
(252 50 (:REWRITE OMAP::MFIX-IMPLIES-MAPP))
(250 50 (:REWRITE C::MAPP-WHEN-SCOPEP))
(250 50 (:REWRITE OMAP::MAPP-WHEN-NOT-EMPTY))
(250 50 (:REWRITE PFCS::MAPP-WHEN-ASSIGNMENTP))
(202 100 (:REWRITE EQUAL-OF-BOOLEANS-CHEAP))
(200 200 (:TYPE-PRESCRIPTION OMAP::MAPP))
(200 50 (:REWRITE SET::NONEMPTY-MEANS-SET))
(187 2 (:REWRITE SYMBOL-LISTP-WHEN-NOT-CONSP))
(150 50 (:REWRITE C::SETP-WHEN-TYPE-SETP))
(150 50 (:REWRITE C::SETP-WHEN-TYPE-OPTION-SETP))
(150 50 (:REWRITE ABNF::SETP-WHEN-TREE-SETP))
(150 50 (:REWRITE ACL2PL::SETP-WHEN-SYMBOL-VALUE-SETP))
(150 50 (:REWRITE ABNF::SETP-WHEN-RULENAME-SETP))
(150 50 (:REWRITE SET::SETP-WHEN-NAT-SETP))
(150 50 (:REWRITE SET::SETP-WHEN-INTEGER-SETP))
(150 50 (:REWRITE C::SETP-WHEN-IDENT-SETP))
(150 50 (:REWRITE ACL2PL::SETP-WHEN-FUNCTION-SETP))
(150 50 (:REWRITE BITCOIN::SETP-WHEN-BIP44-COIN-TYPE-SETP))
(150 50 (:REWRITE C::MAPP-WHEN-VAR-TABLE-SCOPEP))
(150 50 (:REWRITE C::MAPP-WHEN-TAG-ENVP))
(150 50 (:REWRITE C::MAPP-WHEN-HEAPP))
(150 50 (:REWRITE C::MAPP-WHEN-FUN-TABLEP))
(150 50 (:REWRITE C::MAPP-WHEN-FUN-ENVP))
(150 50 (:REWRITE ACL2PL::MAPP-WHEN-BINDINGP))
(150 50 (:REWRITE BITCOIN::BIP32-PATH-SETP-WHEN-BIP32-INDEX-TREEP))
(102 100 (:TYPE-PRESCRIPTION OMAP::MFIX))
(101 101 (:TYPE-PRESCRIPTION SET::SETP-TYPE))
(101 99 (:REWRITE NOT-EQUAL-WHEN-LESS))
(100 100 (:TYPE-PRESCRIPTION C::VAR-TABLE-SCOPEP))
(100 100 (:TYPE-PRESCRIPTION C::TYPE-SETP))
(100 100 (:TYPE-PRESCRIPTION C::TYPE-OPTION-SETP))
(100 100 (:TYPE-PRESCRIPTION ABNF::TREE-SETP))
(100 100 (:TYPE-PRESCRIPTION C::TAG-ENVP))
(100 100 (:TYPE-PRESCRIPTION ACL2PL::SYMBOL-VALUE-SETP))
(100 100 (:TYPE-PRESCRIPTION C::SCOPEP))
(100 100 (:TYPE-PRESCRIPTION ABNF::RULENAME-SETP))
(100 100 (:TYPE-PRESCRIPTION SET::NAT-SETP))
(100 100 (:TYPE-PRESCRIPTION SET::INTEGER-SETP))
(100 100 (:TYPE-PRESCRIPTION C::IDENT-SETP))
(100 100 (:TYPE-PRESCRIPTION C::HEAPP))
(100 100 (:TYPE-PRESCRIPTION ACL2PL::FUNCTION-SETP))
(100 100 (:TYPE-PRESCRIPTION C::FUN-TABLEP))
(100 100 (:TYPE-PRESCRIPTION C::FUN-ENVP))
(100 100 (:TYPE-PRESCRIPTION SET::EMPTY-TYPE))
(100 100 (:TYPE-PRESCRIPTION OMAP::EMPTY))
(100 100 (:TYPE-PRESCRIPTION BOOLEANP))
(100 100 (:TYPE-PRESCRIPTION BITCOIN::BIP44-COIN-TYPE-SETP))
(100 100 (:TYPE-PRESCRIPTION BITCOIN::BIP32-PATH-SETP))
(100 100 (:TYPE-PRESCRIPTION BITCOIN::BIP32-INDEX-TREEP))
(100 100 (:TYPE-PRESCRIPTION ACL2PL::BINDINGP))
(100 100 (:TYPE-PRESCRIPTION PFCS::ASSIGNMENTP))
(100 100 (:REWRITE C::SCOPEP-WHEN-MEMBER-EQUAL-OF-SCOPE-LISTP))
(100 100 (:REWRITE CLR-DIFFERENTIAL))
(100 100 (:REWRITE PFCS::ASSIGNMENTP-WHEN-MEMBER-EQUAL-OF-ASSIGNMENT-LISTP))
(100 50 (:REWRITE OMAP::MFIX-WHEN-MAPP))
(100 50 (:REWRITE OMAP::MAPP-NON-NIL-IMPLIES-NON-EMPTY))
(99 99 (:REWRITE REFS-DIFFER-WHEN-ARRAY-DIMENSIONS-DIFFER-ALT))
(99 99 (:REWRITE REFS-DIFFER-WHEN-ARRAY-DIMENSIONS-DIFFER))
(99 99 (:REWRITE NOT-EQUAL-WHEN-NOT-EQUAL-BVCHOP))
(99 99 (:REWRITE NOT-EQUAL-OF-CONSTANT-AND-BV-TERM-ALT))
(99 99 (:REWRITE NOT-EQUAL-OF-CONSTANT-AND-BV-TERM))
(99 99 (:REWRITE NOT-EQUAL-FROM-BOUND))
(99 99 (:REWRITE NOT-EQUAL-CONSTANT-WHEN-UNSIGNED-BYTE-P-ALT))
(99 99 (:REWRITE NOT-EQUAL-CONSTANT-WHEN-UNSIGNED-BYTE-P))
(99 99 (:REWRITE JVM::NOT-EQUAL-CONSTANT-WHEN-CDR-WRONG))
(99 99 (:REWRITE JVM::NOT-EQUAL-CONSTANT-WHEN-CAR-WRONG))
(99 99 (:REWRITE NOT-EQUAL-CONSTANT-WHEN-BOUND-FORBIDS-IT2))
(99 99 (:REWRITE NOT-EQUAL-CONSTANT-WHEN-BOUND-FORBIDS-IT))
(99 99 (:REWRITE IMPOSSIBLE-VALUE-2))
(99 99 (:REWRITE IMPOSSIBLE-VALUE-1))
(99 99 (:REWRITE EQUAL-WHEN-BVLT-ALT))
(99 99 (:REWRITE EQUAL-WHEN-BVLT))
(99 99 (:REWRITE EQUAL-WHEN-<-OF-+-ALT))
(99 99 (:REWRITE EQUAL-WHEN-<-OF-+))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-SBVLT))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-NOT-BVLT-CONSTANT-2))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-NOT-BVLT-CONSTANT-1))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-BVLT-CONSTANT-2-ALT))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-BVLT-CONSTANT-2))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-BVLT-CONSTANT-1-ALT))
(99 99 (:REWRITE EQUAL-OF-CONSTANT-WHEN-BVLT-CONSTANT-1))
(99 99 (:REWRITE EQUAL-CONSTANT-WHEN-SLICE-EQUAL-CONSTANT))
(99 99 (:REWRITE EQUAL-CONSTANT-WHEN-NOT-SLICE-EQUAL-CONSTANT))
(99 99 (:REWRITE EQUAL-CONSTANT-WHEN-NOT-SBVLT))
(99 99 (:REWRITE EQUAL-CONSTANT-WHEN-BVCHOP-EQUAL-CONSTANT-FALSE))
(98 2 (:REWRITE DEFAULT-CDR))
(74 37 (:REWRITE NOT-MEMBER-EQUAL-WHEN-NOT-MEMBER-EQUAL-OF-CDR-CHEAP))
(74 37 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-CDR-CHEAP))
(53 1 (:REWRITE <-0-+-NEGATIVE-1))
(50 50 (:REWRITE SET::SETP-CONSTANT-OPENER))
(50 50 (:REWRITE DM::PERM-MEMBER))
(50 50 (:REWRITE SET::IN-SET))
(50 50 (:REWRITE SET::EMPTY-CONSTANT-OPENER))
(50 50 (:REWRITE ALWAYS$-P-LST-IMPLIES-P-ELEMENT-COROLLARY))
(47 5 (:LINEAR LEN-POSITIVE-WHEN-CONSP-LINEAR-CHEAP))
(37 37 (:REWRITE MEMBER-EQUAL-WHEN-MEMBER-EQUAL-OF-MEMBER-EQUAL))
(37 37 (:REWRITE MEMBER-EQUAL-OF-CONSTANT-WHEN-NOT-EQUAL-CAR))
(37 7 (:REWRITE LEN-OF-IF))
(36 36 (:REWRITE SUBSETP-MEMBER . 4))
(36 36 (:REWRITE SUBSETP-MEMBER . 3))
(36 36 (:REWRITE SUBSETP-MEMBER . 2))
(36 36 (:REWRITE SUBSETP-MEMBER . 1))
(36 36 (:REWRITE NOT-MEMBER-EQUAL-WHEN-SUBSEQUENCEP-EQUAL-AND-MEMBER-EQUAL))
(36 36 (:REWRITE MEMBER-EQUAL-OF-CONS-NON-CONSTANT))
(36 36 (:REWRITE INTERSECTP-MEMBER . 3))
(36 36 (:REWRITE INTERSECTP-MEMBER . 2))
(35 1 (:REWRITE TRUE-LISTP-WHEN-NOT-CONSP))
(26 1 (:REWRITE LEN-OF-CDR))
(17 17 (:REWRITE KECCAK::LEN-WHEN-K-STATE-ARRAY-P))
(17 17 (:REWRITE LEN-MEMBER-EQUAL-LOOP$-AS))
(16 16 (:REWRITE LEN-WHEN-NOT-CONSP-CHEAP))
(16 16 (:REWRITE LEN-WHEN-EQUAL-TAKE))
(16 16 (:META LEN-CONS-META-RULE))
(13 13 (:REWRITE ASSOC-EQUAL-WHEN-NOT-CONSP-CHEAP))
(12 7 (:REWRITE <-OF-IF-ARG2))
(9 9 (:REWRITE LEN-WHEN-PSEUDO-DAGP-AUX))
(9 9 (:REWRITE LEN-WHEN-DARGP-LESS-THAN))
(9 9 (:REWRITE LEN-WHEN-BV-ARRAYP))
(9 9 (:REWRITE LEN-WHEN-BOUNDED-DAG-EXPRP-AND-QUOTEP))
(8 4 (:TYPE-PRESCRIPTION INTEGERP-OF-NTH-WHEN-ALL-NATP))
(7 7 (:REWRITE ASSOC-EQUAL-OF-CONS-SAFE))
(6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBSEQUENCEP-EQUAL))
(6 6 (:LINEAR LOWER-BOUND-OF-LEN-WHEN-SUBLISTP))
(6 6 (:LINEAR LISTPOS-UPPER-BOUND-STRONG-2))
(6 6 (:LINEAR LEN-WHEN-PREFIXP))
(6 2 (:REWRITE <-OF-LEN-WHEN-NTH-NON-NIL))
(6 2 (:REWRITE <-OF-LEN-WHEN-INTEGERP-OF-NTH))
(5 5 (:REWRITE USE-ALL-HEAPREF-TABLE-ENTRYP-2))
(5 5 (:REWRITE NOT-CONSP-WHEN-NUMBER-OF-ARRAY-DIMENSIONS-IS-0))
(5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-PSEUDOTERM-ALISTP . 2))
(5 5 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-PSEUDOTERM-ALISTP . 1))
(5 5 (:REWRITE ISAR::CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-FACT-INFO-ALISTP . 2))
(5 5 (:REWRITE ISAR::CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-FACT-INFO-ALISTP . 1))
(5 5 (:REWRITE C::CONSP-WHEN-MEMBER-EQUAL-OF-ATC-STRING-OBJINFO-ALISTP . 2))
(5 5 (:REWRITE C::CONSP-WHEN-MEMBER-EQUAL-OF-ATC-STRING-OBJINFO-ALISTP . 1))
(5 5 (:REWRITE CONSP-WHEN-LEN-EQUAL-CONSTANT))
(5 5 (:LINEAR INDEX-OF-<-LEN))
(4 4 (:TYPE-PRESCRIPTION ALL-NATP))
(4 2 (:REWRITE DEFAULT-<-2))
(3 3 (:REWRITE USE-ALL-CONSP-2))
(3 3 (:REWRITE USE-ALL-CONSP))
(3 3 (:REWRITE STRENGTHEN-<-OF-CONSTANT-WHEN-NOT-EQUAL))
(3 3 (:REWRITE LEN-GIVES-CONSP))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-TRUELIST-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-TRUELIST-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-TRUELIST-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-TRUELIST-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE CONSP-WHEN-MEMBER-EQUAL-OF-KEYWORD-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-ISODATA-SYMBOL-ISOMAP-ALISTP . 2))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-ISODATA-SYMBOL-ISOMAP-ALISTP . 1))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-ISODATA-POS-ISOMAP-ALISTP . 2))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-ISODATA-POS-ISOMAP-ALISTP . 1))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-EXPDATA-SYMBOL-SURJMAP-ALISTP . 2))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-EXPDATA-SYMBOL-SURJMAP-ALISTP . 1))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-EXPDATA-POS-SURJMAP-ALISTP . 2))
(3 3 (:REWRITE APT::CONSP-WHEN-MEMBER-EQUAL-OF-EXPDATA-POS-SURJMAP-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFTREEOPS-RULENAME-INFO-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-REP-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 2))
(3 3 (:REWRITE ABNF::CONSP-WHEN-MEMBER-EQUAL-OF-DEFDEFPARSE-ALT-SYMBOL-ALISTP . 1))
(3 3 (:REWRITE CONSP-WHEN-LEN-GREATER))
(3 3 (:REWRITE CONSP-FROM-LEN-BOUND))
(3 3 (:REWRITE <-WHEN-BOUNDED-AXE-TREEP))
(3 3 (:REWRITE <-TRANS))
(2 2 (:TYPE-PRESCRIPTION TRUE-LISTP))
(2 2 (:TYPE-PRESCRIPTION R1CS::PSEUDO-VAR-LISTP))
(2 2 (:REWRITE USE-ALL-<-2))
(2 2 (:REWRITE USE-ALL-<))
(2 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-SYMBOL-TRUELIST-ALISTP))
(2 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-SYMBOL-SYMBOL-ALISTP))
(2 2 (:REWRITE SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-SYMBOL-PSEUDOTERM-ALISTP))
(2 2 (:REWRITE APT::SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-ISODATA-SYMBOL-ISOMAP-ALISTP))
(2 2 (:REWRITE APT::SYMBOLP-OF-CAR-WHEN-MEMBER-EQUAL-OF-EXPDATA-SYMBOL-SURJMAP-ALISTP))
(2 2 (:REWRITE SYMBOL-LISTP-OF-CDR-WHEN-MEMBER-EQUAL-OF-STRING-SYMBOLLIST-ALISTP))
(2 2 (:REWRITE NOT-PRIMEP-WHEN-DIVIDES))
(2 2 (:REWRITE MY-NON-INTEGERP-<-INTEGERP))
(2 2 (:REWRITE MY-INTEGERP-<-NON-INTEGERP))
(2 2 (:REWRITE FN-CHECK-DEF-FORMALS))
(2 2 (:REWRITE DROP-LINEAR-HYPS2))
(2 2 (:REWRITE DROP->-HYPS))
(2 2 (:REWRITE DROP-<-HYPS))
(2 2 (:REWRITE DEFAULT-CAR))
(2 2 (:REWRITE DEFAULT-<-1))
(2 2 (:REWRITE CAR-WHEN-EQUAL-NTHCDR))
(2 2 (:REWRITE BOUND-WHEN-USB2))
(2 2 (:REWRITE <-WHEN-SBVLT-CONSTANTS))
(2 2 (:REWRITE <-WHEN-BVLT))
(2 2 (:REWRITE <-WHEN-BOUNDED-DARG-LISTP-GEN))
(2 2 (:REWRITE <-TIGHTEN-WHEN-SLICE-IS-0))
(2 2 (:REWRITE <-OF-NON-INTEGERP-AND-INTEGERP))
(2 2 (:REWRITE <-OF-CONSTANT-WHEN-USB2))
(2 2 (:REWRITE <-OF-0-WHEN-<-FREE))
(2 2 (:REWRITE <-LEMMA-FOR-KNOWN-OPERATORS-NON-DAG))
(2 2 (:REWRITE <-FROM-<=-FREE))
(2 1 (:REWRITE TRUE-LISTP-WHEN-POSSIBLY-NEGATED-NODENUMSP))
(2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-SYMBOL-LISTP))
(2 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-AXE-TREEP-CHEAP))
(2 1 (:REWRITE SYMBOL-LISTP-OF-CDR-WHEN-SYMBOL-LISTP))
(2 1 (:REWRITE DEFAULT-+-2))
(1 1 (:TYPE-PRESCRIPTION POSSIBLY-NEGATED-NODENUMSP))
(1 1 (:TYPE-PRESCRIPTION AXE-TREEP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-UNSIGNED-BYTE-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-THEOREM-SYMBOL-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-TERMFN-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-SIGNED-BYTE-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-PSEUDO-DAGP-AUX))
(1 1 (:REWRITE TRUE-LISTP-WHEN-MACRO-SYMBOL-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-LAMBDA-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-INTEGER-RANGE-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-FUNCTION-SYMBOL-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-DAB-DIGIT-LISTP))
(1 1 (:REWRITE TRUE-LISTP-WHEN-BV-ARRAYP))
(1 1 (:REWRITE C::TRUE-LISTP-WHEN-ATC-FORMAL-POINTER-LISTP))
(1 1 (:REWRITE SYMBOLP-WHEN-MEMBER-EQUAL))
(1 1 (:REWRITE PFCS::SYMBOLP-WHEN-IN-ASSIGNMENTP-BINDS-FREE-X))
(1 1 (:REWRITE SYMBOLP-WHEN-BOUNDED-DAG-EXPRP))
(1 1 (:REWRITE SYMBOLP-OF-CAR-WHEN-BOUNDED-DAG-EXPRP))
(1 1 (:REWRITE SYMBOL-LISTP-IMPLIES-SYMBOLP))
(1 1 (:REWRITE LEN->-0-WEAKEN))
(1 1 (:REWRITE EQUAL-LEN-0))
(1 1 (:REWRITE DEFAULT-+-1))
(1 1 (:REWRITE CONSP-OF-CDR-WHEN-LEN-KNOWN))
(1 1 (:REWRITE +-OF-MINUS-CONSTANT-VERSION))
(1 1 (:REWRITE +-OF-MINUS))
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.